Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(649)

Side by Side Diff: net/third_party/nss/ssl/ssl3con.c

Issue 1844813002: Uprev NSS to 3.23 on iOS (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Update patches Created 4 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ 1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /* 2 /*
3 * SSL3 Protocol 3 * SSL3 Protocol
4 * 4 *
5 * This Source Code Form is subject to the terms of the Mozilla Public 5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this 6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 7 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
8 8
9 /* TODO(ekr): Implement HelloVerifyRequest on server side. OK for now. */ 9 /* TODO(ekr): Implement HelloVerifyRequest on server side. OK for now. */
10 10
11 #define _GNU_SOURCE 1
12 #include "cert.h" 11 #include "cert.h"
13 #include "ssl.h" 12 #include "ssl.h"
14 #include "cryptohi.h"» /* for DSAU_ stuff */ 13 #include "cryptohi.h" /* for DSAU_ stuff */
15 #include "keyhi.h" 14 #include "keyhi.h"
16 #include "secder.h" 15 #include "secder.h"
17 #include "secitem.h" 16 #include "secitem.h"
18 #include "sechash.h" 17 #include "sechash.h"
19 18
20 #include "sslimpl.h" 19 #include "sslimpl.h"
21 #include "sslproto.h" 20 #include "sslproto.h"
22 #include "sslerr.h" 21 #include "sslerr.h"
23 #include "prtime.h" 22 #include "prtime.h"
24 #include "prinrval.h" 23 #include "prinrval.h"
25 #include "prerror.h" 24 #include "prerror.h"
26 #include "pratom.h" 25 #include "pratom.h"
27 #include "prthread.h" 26 #include "prthread.h"
28 #include "nss.h" 27 #include "nss.h"
29 #include "nssoptions.h" 28 #include "nssoptions.h"
30 29
31 #include "pk11func.h" 30 #include "pk11func.h"
32 #include "secmod.h" 31 #include "secmod.h"
33 #ifndef NO_PKCS11_BYPASS 32 #ifndef NO_PKCS11_BYPASS
34 #include "blapi.h" 33 #include "blapi.h"
35 #endif 34 #endif
36 35
37 /* This is a bodge to allow this code to be compiled against older NSS headers
38 * that don't contain the TLS 1.2 changes. */
39 #ifndef CKM_NSS_TLS_PRF_GENERAL_SHA256
40 #define CKM_NSS_TLS_PRF_GENERAL_SHA256 (CKM_NSS + 21)
41 #define CKM_NSS_TLS_MASTER_KEY_DERIVE_SHA256 (CKM_NSS + 22)
42 #define CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256 (CKM_NSS + 23)
43 #define CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256 (CKM_NSS + 24)
44 #endif
45
46 /* This is a bodge to allow this code to be compiled against older NSS
47 * headers. */
48 #ifndef CKM_NSS_CHACHA20_POLY1305
49 #define CKM_NSS_CHACHA20_POLY1305 (CKM_NSS + 26)
50
51 typedef struct CK_NSS_AEAD_PARAMS {
52 CK_BYTE_PTR pIv; /* This is the nonce. */
53 CK_ULONG ulIvLen;
54 CK_BYTE_PTR pAAD;
55 CK_ULONG ulAADLen;
56 CK_ULONG ulTagLen;
57 } CK_NSS_AEAD_PARAMS;
58
59 #endif
60
61 #include <stdio.h> 36 #include <stdio.h>
62 #ifdef NSS_ENABLE_ZLIB 37 #ifdef NSS_SSL_ENABLE_ZLIB
63 #include "zlib.h" 38 #include "zlib.h"
64 #endif 39 #endif
65 #ifdef LINUX
66 #include <dlfcn.h>
67 #endif
68 40
69 #ifndef PK11_SETATTRS 41 #ifndef PK11_SETATTRS
70 #define PK11_SETATTRS(x,id,v,l) (x)->type = (id); \ 42 #define PK11_SETATTRS(x, id, v, l) \
71 » » (x)->pValue=(v); (x)->ulValueLen = (l); 43 (x)->type = (id); \
44 (x)->pValue = (v); \
45 (x)->ulValueLen = (l);
72 #endif 46 #endif
73 47
74 static SECStatus ssl3_AuthCertificate(sslSocket *ss); 48 static SECStatus ssl3_AuthCertificate(sslSocket *ss);
75 static void ssl3_CleanupPeerCerts(sslSocket *ss); 49 static void ssl3_CleanupPeerCerts(sslSocket *ss);
76 static void ssl3_CopyPeerCertsFromSID(sslSocket *ss, sslSessionID *sid); 50 static void ssl3_CopyPeerCertsFromSID(sslSocket *ss, sslSessionID *sid);
77 static PK11SymKey *ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec, 51 static PK11SymKey *ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec,
78 PK11SlotInfo * serverKeySlot); 52 PK11SlotInfo *serverKeySlot);
79 static SECStatus ssl3_DeriveMasterSecret(sslSocket *ss, PK11SymKey *pms); 53 static SECStatus ssl3_DeriveMasterSecret(sslSocket *ss, PK11SymKey *pms);
80 static SECStatus ssl3_DeriveConnectionKeysPKCS11(sslSocket *ss); 54 static SECStatus ssl3_DeriveConnectionKeysPKCS11(sslSocket *ss);
81 static SECStatus ssl3_HandshakeFailure( sslSocket *ss); 55 static SECStatus ssl3_HandshakeFailure(sslSocket *ss);
82 static SECStatus ssl3_InitState( sslSocket *ss); 56 static SECStatus ssl3_InitState(sslSocket *ss);
83 static SECStatus ssl3_SendCertificate( sslSocket *ss); 57
84 static SECStatus ssl3_SendCertificateStatus( sslSocket *ss);
85 static SECStatus ssl3_SendEmptyCertificate( sslSocket *ss);
86 static SECStatus ssl3_SendCertificateRequest(sslSocket *ss); 58 static SECStatus ssl3_SendCertificateRequest(sslSocket *ss);
87 static SECStatus ssl3_SendNextProto( sslSocket *ss); 59 static SECStatus ssl3_SendNextProto(sslSocket *ss);
88 static SECStatus ssl3_SendEncryptedExtensions(sslSocket *ss); 60 static SECStatus ssl3_SendChannelIDEncryptedExtensions(sslSocket *ss);
89 static SECStatus ssl3_SendFinished( sslSocket *ss, PRInt32 flags); 61 static SECStatus ssl3_SendFinished(sslSocket *ss, PRInt32 flags);
90 static SECStatus ssl3_SendServerHello( sslSocket *ss); 62 static SECStatus ssl3_SendServerHelloDone(sslSocket *ss);
91 static SECStatus ssl3_SendServerHelloDone( sslSocket *ss); 63 static SECStatus ssl3_SendServerKeyExchange(sslSocket *ss);
92 static SECStatus ssl3_SendServerKeyExchange( sslSocket *ss); 64 static SECStatus ssl3_UpdateHandshakeHashes(sslSocket *ss,
93 static SECStatus ssl3_UpdateHandshakeHashes( sslSocket *ss, 65 const unsigned char *b,
94 const unsigned char *b, 66 unsigned int l);
95 unsigned int l); 67 static SECStatus ssl3_HandlePostHelloHandshakeMessage(sslSocket *ss,
96 static SECStatus ssl3_ComputeHandshakeHashes(sslSocket *ss, 68 SSL3Opaque *b,
97 ssl3CipherSpec *spec, 69 PRUint32 length,
98 SSL3Hashes *hashes, 70 SSL3Hashes *hashesPtr);
99 PRUint32 sender);
100 static SECStatus ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags); 71 static SECStatus ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags);
101 72
102 static SECStatus Null_Cipher(void *ctx, unsigned char *output, int *outputLen, 73 static SECStatus Null_Cipher(void *ctx, unsigned char *output, int *outputLen,
103 » » » int maxOutputLen, const unsigned char *input, 74 int maxOutputLen, const unsigned char *input,
104 » » » int inputLen); 75 int inputLen);
105 #ifndef NO_PKCS11_BYPASS 76 #ifndef NO_PKCS11_BYPASS
106 static SECStatus ssl3_AESGCMBypass(ssl3KeyMaterial *keys, PRBool doDecrypt, 77 static SECStatus ssl3_AESGCMBypass(ssl3KeyMaterial *keys, PRBool doDecrypt,
107 » » » » unsigned char *out, int *outlen, int maxout, 78 unsigned char *out, int *outlen, int maxout,
108 » » » » const unsigned char *in, int inlen, 79 const unsigned char *in, int inlen,
109 » » » » const unsigned char *additionalData, 80 const unsigned char *additionalData,
110 » » » » int additionalDataLen); 81 int additionalDataLen);
111 #endif 82 #endif
112 83
113 #define MAX_SEND_BUF_LENGTH 32000 /* watch for 16-bit integer overflow */ 84 #define MAX_SEND_BUF_LENGTH 32000 /* watch for 16-bit integer overflow */
114 #define MIN_SEND_BUF_LENGTH 4000 85 #define MIN_SEND_BUF_LENGTH 4000
115 86
116 /* This list of SSL3 cipher suites is sorted in descending order of 87 /* This list of SSL3 cipher suites is sorted in descending order of
117 * precedence (desirability). It only includes cipher suites we implement. 88 * precedence (desirability). It only includes cipher suites we implement.
118 * This table is modified by SSL3_SetPolicy(). The ordering of cipher suites 89 * This table is modified by SSL3_SetPolicy(). The ordering of cipher suites
119 * in this table must match the ordering in SSL_ImplementedCiphers (sslenum.c) 90 * in this table must match the ordering in SSL_ImplementedCiphers (sslenum.c)
120 * 91 *
121 * Important: See bug 946147 before enabling, reordering, or adding any cipher 92 * Important: See bug 946147 before enabling, reordering, or adding any cipher
122 * suites to this list. 93 * suites to this list.
123 */ 94 */
95 /* clang-format off */
124 static ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED] = { 96 static ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED] = {
125 /* cipher_suite policy enabled isPresent */ 97 /* cipher_suite policy enabled isPresent */
126 98
127 #ifndef NSS_DISABLE_ECC 99 #ifndef NSS_DISABLE_ECC
128 { TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, SSL_ALLOWED, PR_FALSE, PR_FALSE},
129 { TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, SSL_ALLOWED, PR_FALSE, PR_FALSE},
130 { TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 100 { TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
131 { TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 101 { TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
102 { TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE },
103 { TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE },
132 /* TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA is out of order to work around 104 /* TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA is out of order to work around
133 * bug 946147. 105 * bug 946147.
134 */ 106 */
135 { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 107 { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
136 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 108 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
137 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 109 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
138 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 110 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
139 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 111 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
140 { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 112 { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
141 { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 113 { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
142 { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 114 { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
143 { TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 115 { TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
144 { TLS_ECDHE_RSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 116 { TLS_ECDHE_RSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
145 #endif /* NSS_DISABLE_ECC */ 117 #endif /* NSS_DISABLE_ECC */
146 118
147 { TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 119 { TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
120 { TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256,SSL_ALLOWED,PR_TRUE, PR_FALSE},
148 { TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 121 { TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE},
149 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 122 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
150 { TLS_DHE_DSS_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 123 { TLS_DHE_DSS_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
151 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 124 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
152 { TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 125 { TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE},
153 { TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 126 { TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
154 { TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 127 { TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
155 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 128 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
156 { TLS_DHE_DSS_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 129 { TLS_DHE_DSS_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
157 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 130 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
(...skipping 47 matching lines...) Expand 10 before | Expand all | Expand 10 after
205 #ifndef NSS_DISABLE_ECC 178 #ifndef NSS_DISABLE_ECC
206 { TLS_ECDHE_ECDSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 179 { TLS_ECDHE_ECDSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
207 { TLS_ECDHE_RSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 180 { TLS_ECDHE_RSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
208 { TLS_ECDH_RSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 181 { TLS_ECDH_RSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
209 { TLS_ECDH_ECDSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 182 { TLS_ECDH_ECDSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
210 #endif /* NSS_DISABLE_ECC */ 183 #endif /* NSS_DISABLE_ECC */
211 { TLS_RSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 184 { TLS_RSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
212 { TLS_RSA_WITH_NULL_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 185 { TLS_RSA_WITH_NULL_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE},
213 { TLS_RSA_WITH_NULL_MD5, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 186 { TLS_RSA_WITH_NULL_MD5, SSL_ALLOWED, PR_FALSE, PR_FALSE},
214 }; 187 };
188 /* clang-format on */
215 189
216 static const SSLSignatureAndHashAlg defaultSignatureAlgorithms[] = { 190 static const SSLSignatureAndHashAlg defaultSignatureAlgorithms[] = {
217 {ssl_hash_sha256, ssl_sign_rsa}, 191 { ssl_hash_sha256, ssl_sign_rsa },
218 {ssl_hash_sha384, ssl_sign_rsa}, 192 { ssl_hash_sha384, ssl_sign_rsa },
219 {ssl_hash_sha512, ssl_sign_rsa}, 193 { ssl_hash_sha512, ssl_sign_rsa },
220 {ssl_hash_sha1, ssl_sign_rsa}, 194 { ssl_hash_sha1, ssl_sign_rsa },
221 #ifndef NSS_DISABLE_ECC 195 #ifndef NSS_DISABLE_ECC
222 {ssl_hash_sha256, ssl_sign_ecdsa}, 196 { ssl_hash_sha256, ssl_sign_ecdsa },
223 {ssl_hash_sha384, ssl_sign_ecdsa}, 197 { ssl_hash_sha384, ssl_sign_ecdsa },
224 {ssl_hash_sha512, ssl_sign_ecdsa}, 198 { ssl_hash_sha512, ssl_sign_ecdsa },
225 {ssl_hash_sha1, ssl_sign_ecdsa}, 199 { ssl_hash_sha1, ssl_sign_ecdsa },
226 #endif 200 #endif
227 {ssl_hash_sha256, ssl_sign_dsa}, 201 { ssl_hash_sha256, ssl_sign_dsa },
228 {ssl_hash_sha1, ssl_sign_dsa} 202 { ssl_hash_sha1, ssl_sign_dsa }
229 }; 203 };
230 PR_STATIC_ASSERT(PR_ARRAY_SIZE(defaultSignatureAlgorithms) <= 204 PR_STATIC_ASSERT(PR_ARRAY_SIZE(defaultSignatureAlgorithms) <=
231 MAX_SIGNATURE_ALGORITHMS); 205 MAX_SIGNATURE_ALGORITHMS);
232 206
233 /* Verify that SSL_ImplementedCiphers and cipherSuites are in consistent order. 207 /* Verify that SSL_ImplementedCiphers and cipherSuites are in consistent order.
234 */ 208 */
235 #ifdef DEBUG 209 #ifdef DEBUG
236 void ssl3_CheckCipherSuiteOrderConsistency() 210 void
211 ssl3_CheckCipherSuiteOrderConsistency()
237 { 212 {
238 unsigned int i; 213 unsigned int i;
239 214
240 /* Note that SSL_ImplementedCiphers has more elements than cipherSuites 215 /* Note that SSL_ImplementedCiphers has more elements than cipherSuites
241 * because it SSL_ImplementedCiphers includes SSL 2.0 cipher suites. 216 * because it SSL_ImplementedCiphers includes SSL 2.0 cipher suites.
242 */ 217 */
243 PORT_Assert(SSL_NumImplementedCiphers >= PR_ARRAY_SIZE(cipherSuites)); 218 PORT_Assert(SSL_NumImplementedCiphers >= PR_ARRAY_SIZE(cipherSuites));
244 219
245 for (i = 0; i < PR_ARRAY_SIZE(cipherSuites); ++i) { 220 for (i = 0; i < PR_ARRAY_SIZE(cipherSuites); ++i) {
246 PORT_Assert(SSL_ImplementedCiphers[i] == cipherSuites[i].cipher_suite); 221 PORT_Assert(SSL_ImplementedCiphers[i] == cipherSuites[i].cipher_suite);
247 } 222 }
248 } 223 }
249 #endif 224 #endif
250 225
251 /* This list of SSL3 compression methods is sorted in descending order of 226 /* This list of SSL3 compression methods is sorted in descending order of
252 * precedence (desirability). It only includes compression methods we 227 * precedence (desirability). It only includes compression methods we
253 * implement. 228 * implement.
254 */ 229 */
255 static const /*SSLCompressionMethod*/ PRUint8 compressions [] = { 230 static const /*SSLCompressionMethod*/ PRUint8 compressions[] = {
256 #ifdef NSS_ENABLE_ZLIB 231 #ifdef NSS_SSL_ENABLE_ZLIB
257 ssl_compression_deflate, 232 ssl_compression_deflate,
258 #endif 233 #endif
259 ssl_compression_null 234 ssl_compression_null
260 }; 235 };
261 236
262 static const int compressionMethodsCount = 237 static const int compressionMethodsCount =
263 sizeof(compressions) / sizeof(compressions[0]); 238 sizeof(compressions) / sizeof(compressions[0]);
264 239
265 /* compressionEnabled returns true iff the compression algorithm is enabled 240 /* compressionEnabled returns true iff the compression algorithm is enabled
266 * for the given SSL socket. */ 241 * for the given SSL socket. */
267 static PRBool 242 static PRBool
268 compressionEnabled(sslSocket *ss, SSLCompressionMethod compression) 243 compressionEnabled(sslSocket *ss, SSLCompressionMethod compression)
269 { 244 {
270 switch (compression) { 245 switch (compression) {
271 case ssl_compression_null: 246 case ssl_compression_null:
272 » return PR_TRUE; /* Always enabled */ 247 return PR_TRUE; /* Always enabled */
273 #ifdef NSS_ENABLE_ZLIB 248 #ifdef NSS_SSL_ENABLE_ZLIB
274 case ssl_compression_deflate: 249 case ssl_compression_deflate:
275 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { 250 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
276 return ss->opt.enableDeflate; 251 return ss->opt.enableDeflate;
277 } 252 }
278 return PR_FALSE; 253 return PR_FALSE;
279 #endif 254 #endif
280 default: 255 default:
281 » return PR_FALSE; 256 return PR_FALSE;
282 } 257 }
283 } 258 }
284 259
285 static const /*SSL3ClientCertificateType */ PRUint8 certificate_types [] = { 260 static const /*SSL3ClientCertificateType */ PRUint8 certificate_types[] = {
286 ct_RSA_sign, 261 ct_RSA_sign,
287 #ifndef NSS_DISABLE_ECC 262 #ifndef NSS_DISABLE_ECC
288 ct_ECDSA_sign, 263 ct_ECDSA_sign,
289 #endif /* NSS_DISABLE_ECC */ 264 #endif /* NSS_DISABLE_ECC */
290 ct_DSS_sign, 265 ct_DSS_sign,
291 }; 266 };
292 267
293 #define EXPORT_RSA_KEY_LENGTH 64» /* bytes */ 268 #define EXPORT_RSA_KEY_LENGTH 64 /* bytes */
294
295 269
296 /* This global item is used only in servers. It is is initialized by 270 /* This global item is used only in servers. It is is initialized by
297 ** SSL_ConfigSecureServer(), and is used in ssl3_SendCertificateRequest(). 271 ** SSL_ConfigSecureServer(), and is used in ssl3_SendCertificateRequest().
298 */ 272 */
299 CERTDistNames *ssl3_server_ca_list = NULL; 273 CERTDistNames *ssl3_server_ca_list = NULL;
300 static SSL3Statistics ssl3stats; 274 static SSL3Statistics ssl3stats;
301 275
302 /* indexed by SSL3BulkCipher */ 276 /* indexed by SSL3BulkCipher */
277 /* clang-format off */
303 static const ssl3BulkCipherDef bulk_cipher_defs[] = { 278 static const ssl3BulkCipherDef bulk_cipher_defs[] = {
304 /* |--------- Lengths --------| */ 279 /* |--------- Lengths --------| */
305 /* cipher calg k s type i b t n */ 280 /* cipher calg k s type i b t n o */
306 /* e e v l a o */ 281 /* e e v l a o i */
307 /* y c | o g n */ 282 /* y c | o g n d */
308 /* | r | c | c */ 283 /* | r | c | c | */
309 /* | e | k | e */ 284 /* | e | k | e | */
310 /* | t | | | | */ 285 /* | t | | | | | */
311 {cipher_null, calg_null, 0, 0, type_stream, 0, 0, 0, 0}, 286 {cipher_null, calg_null, 0, 0, type_stream, 0, 0, 0, 0, SEC_ OID_NULL_CIPHER},
312 {cipher_rc4, calg_rc4, 16,16, type_stream, 0, 0, 0, 0}, 287 {cipher_rc4, calg_rc4, 16,16, type_stream, 0, 0, 0, 0, SEC_ OID_RC4},
313 {cipher_rc4_40, calg_rc4, 16, 5, type_stream, 0, 0, 0, 0}, 288 {cipher_rc4_40, calg_rc4, 16, 5, type_stream, 0, 0, 0, 0, SEC_ OID_RC4_40},
314 {cipher_rc4_56, calg_rc4, 16, 7, type_stream, 0, 0, 0, 0}, 289 {cipher_rc4_56, calg_rc4, 16, 7, type_stream, 0, 0, 0, 0, SEC_ OID_RC4_56},
315 {cipher_rc2, calg_rc2, 16,16, type_block, 8, 8, 0, 0}, 290 {cipher_rc2, calg_rc2, 16,16, type_block, 8, 8, 0, 0, SEC_ OID_RC2_CBC},
316 {cipher_rc2_40, calg_rc2, 16, 5, type_block, 8, 8, 0, 0}, 291 {cipher_rc2_40, calg_rc2, 16, 5, type_block, 8, 8, 0, 0, SEC_ OID_RC2_40_CBC},
317 {cipher_des, calg_des, 8, 8, type_block, 8, 8, 0, 0}, 292 {cipher_des, calg_des, 8, 8, type_block, 8, 8, 0, 0, SEC_ OID_DES_CBC},
318 {cipher_3des, calg_3des, 24,24, type_block, 8, 8, 0, 0}, 293 {cipher_3des, calg_3des, 24,24, type_block, 8, 8, 0, 0, SEC_ OID_DES_EDE3_CBC},
319 {cipher_des40, calg_des, 8, 5, type_block, 8, 8, 0, 0}, 294 {cipher_des40, calg_des, 8, 5, type_block, 8, 8, 0, 0, SEC_ OID_DES_40_CBC},
320 {cipher_idea, calg_idea, 16,16, type_block, 8, 8, 0, 0}, 295 {cipher_idea, calg_idea, 16,16, type_block, 8, 8, 0, 0, SEC_ OID_IDEA_CBC},
321 {cipher_aes_128, calg_aes, 16,16, type_block, 16,16, 0, 0}, 296 {cipher_aes_128, calg_aes, 16,16, type_block, 16,16, 0, 0, SEC_ OID_AES_128_CBC},
322 {cipher_aes_256, calg_aes, 32,32, type_block, 16,16, 0, 0}, 297 {cipher_aes_256, calg_aes, 32,32, type_block, 16,16, 0, 0, SEC_ OID_AES_256_CBC},
323 {cipher_camellia_128, calg_camellia, 16,16, type_block, 16,16, 0, 0}, 298 {cipher_camellia_128, calg_camellia, 16,16, type_block, 16,16, 0, 0, SEC_ OID_CAMELLIA_128_CBC},
324 {cipher_camellia_256, calg_camellia, 32,32, type_block, 16,16, 0, 0}, 299 {cipher_camellia_256, calg_camellia, 32,32, type_block, 16,16, 0, 0, SEC_ OID_CAMELLIA_256_CBC},
325 {cipher_seed, calg_seed, 16,16, type_block, 16,16, 0, 0}, 300 {cipher_seed, calg_seed, 16,16, type_block, 16,16, 0, 0, SEC_ OID_SEED_CBC},
326 {cipher_aes_128_gcm, calg_aes_gcm, 16,16, type_aead, 4, 0,16, 8}, 301 {cipher_aes_128_gcm, calg_aes_gcm, 16,16, type_aead, 4, 0,16, 8, SEC_ OID_AES_128_GCM},
327 {cipher_chacha20, calg_chacha20, 32,32, type_aead, 0, 0,16, 0}, 302 {cipher_chacha20, calg_chacha20, 32,32, type_aead, 12, 0,16, 0, SEC_ OID_CHACHA20_POLY1305},
328 {cipher_missing, calg_null, 0, 0, type_stream, 0, 0, 0, 0}, 303 {cipher_missing, calg_null, 0, 0, type_stream, 0, 0, 0, 0, 0},
329 }; 304 };
330 305
331 static const ssl3KEADef kea_defs[] = 306 static const ssl3KEADef kea_defs[] =
332 { /* indexed by SSL3KeyExchangeAlgorithm */ 307 { /* indexed by SSL3KeyExchangeAlgorithm */
333 /* kea exchKeyType signKeyType is_limited limit tls_keygen epheme ral */ 308 /* kea exchKeyType signKeyType is_limited limit tls_keygen epheme ral oid */
334 {kea_null, kt_null, sign_null, PR_FALSE, 0, PR_FALSE, PR_FALSE} , 309 {kea_null, kt_null, ssl_sign_null, PR_FALSE, 0, PR_FALSE, PR_FA LSE, 0},
335 {kea_rsa, kt_rsa, sign_rsa, PR_FALSE, 0, PR_FALSE, PR_FALSE} , 310 {kea_rsa, kt_rsa, ssl_sign_rsa, PR_FALSE, 0, PR_FALSE, PR_FA LSE, SEC_OID_TLS_RSA},
336 {kea_rsa_export, kt_rsa, sign_rsa, PR_TRUE, 512, PR_FALSE, PR_FALSE} , 311 {kea_rsa_export, kt_rsa, ssl_sign_rsa, PR_TRUE, 512, PR_FALSE, PR_FA LSE, SEC_OID_TLS_RSA_EXPORT},
337 {kea_rsa_export_1024,kt_rsa, sign_rsa, PR_TRUE, 1024, PR_FALSE, PR_FALSE} , 312 {kea_rsa_export_1024,kt_rsa, ssl_sign_rsa, PR_TRUE, 1024, PR_FALSE, PR_FA LSE, SEC_OID_TLS_RSA_EXPORT},
338 {kea_dh_dss, kt_dh, sign_dsa, PR_FALSE, 0, PR_FALSE, PR_FALSE} , 313 {kea_dh_dss, kt_dh, ssl_sign_dsa, PR_FALSE, 0, PR_FALSE, PR_FA LSE, SEC_OID_TLS_DH_DSS},
339 {kea_dh_dss_export, kt_dh, sign_dsa, PR_TRUE, 512, PR_FALSE, PR_FALSE} , 314 {kea_dh_dss_export, kt_dh, ssl_sign_dsa, PR_TRUE, 512, PR_FALSE, PR_FA LSE, SEC_OID_TLS_DH_DSS_EXPORT},
340 {kea_dh_rsa, kt_dh, sign_rsa, PR_FALSE, 0, PR_FALSE, PR_FALSE} , 315 {kea_dh_rsa, kt_dh, ssl_sign_rsa, PR_FALSE, 0, PR_FALSE, PR_FA LSE, SEC_OID_TLS_DH_RSA},
341 {kea_dh_rsa_export, kt_dh, sign_rsa, PR_TRUE, 512, PR_FALSE, PR_FALSE} , 316 {kea_dh_rsa_export, kt_dh, ssl_sign_rsa, PR_TRUE, 512, PR_FALSE, PR_FA LSE, SEC_OID_TLS_DH_RSA_EXPORT},
342 {kea_dhe_dss, kt_dh, sign_dsa, PR_FALSE, 0, PR_FALSE, PR_TRUE}, 317 {kea_dhe_dss, kt_dh, ssl_sign_dsa, PR_FALSE, 0, PR_FALSE, PR_TR UE, SEC_OID_TLS_DHE_DSS},
343 {kea_dhe_dss_export, kt_dh, sign_dsa, PR_TRUE, 512, PR_FALSE, PR_TRUE}, 318 {kea_dhe_dss_export, kt_dh, ssl_sign_dsa, PR_TRUE, 512, PR_FALSE, PR_TR UE, SEC_OID_TLS_DHE_DSS_EXPORT},
344 {kea_dhe_rsa, kt_dh, sign_rsa, PR_FALSE, 0, PR_FALSE, PR_TRUE}, 319 {kea_dhe_rsa, kt_dh, ssl_sign_rsa, PR_FALSE, 0, PR_FALSE, PR_TR UE, SEC_OID_TLS_DHE_RSA},
345 {kea_dhe_rsa_export, kt_dh, sign_rsa, PR_TRUE, 512, PR_FALSE, PR_TRUE}, 320 {kea_dhe_rsa_export, kt_dh, ssl_sign_rsa, PR_TRUE, 512, PR_FALSE, PR_TR UE, SEC_OID_TLS_DHE_RSA_EXPORT},
346 {kea_dh_anon, kt_dh, sign_null, PR_FALSE, 0, PR_FALSE, PR_TRUE}, 321 {kea_dh_anon, kt_dh, ssl_sign_null, PR_FALSE, 0, PR_FALSE, PR_TR UE, SEC_OID_TLS_DH_ANON},
347 {kea_dh_anon_export, kt_dh, sign_null, PR_TRUE, 512, PR_FALSE, PR_TRUE}, 322 {kea_dh_anon_export, kt_dh, ssl_sign_null, PR_TRUE, 512, PR_FALSE, PR_TR UE, SEC_OID_TLS_DH_ANON_EXPORT},
348 {kea_rsa_fips, kt_rsa, sign_rsa, PR_FALSE, 0, PR_TRUE, PR_FALSE} , 323 {kea_rsa_fips, kt_rsa, ssl_sign_rsa, PR_FALSE, 0, PR_TRUE, PR_FA LSE, SEC_OID_TLS_RSA},
349 #ifndef NSS_DISABLE_ECC 324 #ifndef NSS_DISABLE_ECC
350 {kea_ecdh_ecdsa, kt_ecdh, sign_ecdsa, PR_FALSE, 0, PR_FALSE, PR_FALSE} , 325 {kea_ecdh_ecdsa, kt_ecdh, ssl_sign_ecdsa, PR_FALSE, 0, PR_FALSE, PR_FA LSE, SEC_OID_TLS_ECDH_ECDSA},
351 {kea_ecdhe_ecdsa, kt_ecdh, sign_ecdsa, PR_FALSE, 0, PR_FALSE, PR_TRUE}, 326 {kea_ecdhe_ecdsa, kt_ecdh, ssl_sign_ecdsa, PR_FALSE, 0, PR_FALSE, PR_TR UE, SEC_OID_TLS_ECDHE_ECDSA},
352 {kea_ecdh_rsa, kt_ecdh, sign_rsa, PR_FALSE, 0, PR_FALSE, PR_FALSE} , 327 {kea_ecdh_rsa, kt_ecdh, ssl_sign_rsa, PR_FALSE, 0, PR_FALSE, PR_FA LSE, SEC_OID_TLS_ECDH_RSA},
353 {kea_ecdhe_rsa, kt_ecdh, sign_rsa, PR_FALSE, 0, PR_FALSE, PR_TRUE}, 328 {kea_ecdhe_rsa, kt_ecdh, ssl_sign_rsa, PR_FALSE, 0, PR_FALSE, PR_TR UE, SEC_OID_TLS_ECDHE_RSA},
354 {kea_ecdh_anon, kt_ecdh, sign_null, PR_FALSE, 0, PR_FALSE, PR_TRUE}, 329 {kea_ecdh_anon, kt_ecdh, ssl_sign_null, PR_FALSE, 0, PR_FALSE, PR_TR UE, SEC_OID_TLS_ECDH_ANON},
355 #endif /* NSS_DISABLE_ECC */ 330 #endif /* NSS_DISABLE_ECC */
356 }; 331 };
357 332
358 /* must use ssl_LookupCipherSuiteDef to access */ 333 /* must use ssl_LookupCipherSuiteDef to access */
359 static const ssl3CipherSuiteDef cipher_suite_defs[] = 334 static const ssl3CipherSuiteDef cipher_suite_defs[] =
360 { 335 {
361 /* cipher_suite bulk_cipher_alg mac_alg key_exchange_alg */ 336 /* cipher_suite bulk_cipher_alg mac_alg key_exchange_alg */
362 337
363 {TLS_NULL_WITH_NULL_NULL, cipher_null, mac_null, kea_null}, 338 {TLS_NULL_WITH_NULL_NULL, cipher_null, mac_null, kea_null},
364 {TLS_RSA_WITH_NULL_MD5, cipher_null, mac_md5, kea_rsa}, 339 {TLS_RSA_WITH_NULL_MD5, cipher_null, mac_md5, kea_rsa},
365 {TLS_RSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_rsa}, 340 {TLS_RSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_rsa},
366 {TLS_RSA_WITH_NULL_SHA256, cipher_null, hmac_sha256, kea_rsa}, 341 {TLS_RSA_WITH_NULL_SHA256, cipher_null, hmac_sha256, kea_rsa},
367 {TLS_RSA_EXPORT_WITH_RC4_40_MD5,cipher_rc4_40, mac_md5, kea_rsa_export}, 342 {TLS_RSA_EXPORT_WITH_RC4_40_MD5,cipher_rc4_40, mac_md5, kea_rsa_export},
368 {TLS_RSA_WITH_RC4_128_MD5, cipher_rc4, mac_md5, kea_rsa}, 343 {TLS_RSA_WITH_RC4_128_MD5, cipher_rc4, mac_md5, kea_rsa},
369 {TLS_RSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_rsa}, 344 {TLS_RSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_rsa},
(...skipping 30 matching lines...) Expand all
400 #if 0 375 #if 0
401 {SSL_DH_ANON_EXPORT_RC4_40_MD5, cipher_rc4_40, mac_md5, kea_dh_anon_export}, 376 {SSL_DH_ANON_EXPORT_RC4_40_MD5, cipher_rc4_40, mac_md5, kea_dh_anon_export},
402 {TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA, 377 {TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA,
403 cipher_des40, mac_sha, kea_dh_anon_export}, 378 cipher_des40, mac_sha, kea_dh_anon_export},
404 {TLS_DH_anon_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_dh_anon}, 379 {TLS_DH_anon_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_dh_anon},
405 {TLS_DH_anon_WITH_3DES_CBC_SHA, cipher_3des, mac_sha, kea_dh_anon}, 380 {TLS_DH_anon_WITH_3DES_CBC_SHA, cipher_3des, mac_sha, kea_dh_anon},
406 #endif 381 #endif
407 382
408 383
409 /* New TLS cipher suites */ 384 /* New TLS cipher suites */
410 {TLS_RSA_WITH_AES_128_CBC_SHA, »cipher_aes_128, mac_sha, kea_rsa}, 385 {TLS_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_rsa},
411 {TLS_RSA_WITH_AES_128_CBC_SHA256,» cipher_aes_128, hmac_sha256, kea_rsa}, 386 {TLS_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_rsa},
412 {TLS_DHE_DSS_WITH_AES_128_CBC_SHA, »cipher_aes_128, mac_sha, kea_dhe_dss}, 387 {TLS_DHE_DSS_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dhe_dss},
413 {TLS_DHE_RSA_WITH_AES_128_CBC_SHA, »cipher_aes_128, mac_sha, kea_dhe_rsa}, 388 {TLS_DHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dhe_rsa},
414 {TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_dhe_r sa}, 389 {TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_dhe_r sa},
415 {TLS_RSA_WITH_AES_256_CBC_SHA, »cipher_aes_256, mac_sha, kea_rsa}, 390 {TLS_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_rsa},
416 {TLS_RSA_WITH_AES_256_CBC_SHA256,» cipher_aes_256, hmac_sha256, kea_rsa}, 391 {TLS_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, hmac_sha256, kea_rsa},
417 {TLS_DHE_DSS_WITH_AES_256_CBC_SHA, »cipher_aes_256, mac_sha, kea_dhe_dss}, 392 {TLS_DHE_DSS_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dhe_dss},
418 {TLS_DHE_RSA_WITH_AES_256_CBC_SHA, »cipher_aes_256, mac_sha, kea_dhe_rsa}, 393 {TLS_DHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dhe_rsa},
419 {TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, hmac_sha256, kea_dhe_r sa}, 394 {TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, hmac_sha256, kea_dhe_r sa},
420 #if 0 395 #if 0
421 {TLS_DH_DSS_WITH_AES_128_CBC_SHA, »cipher_aes_128, mac_sha, kea_dh_dss}, 396 {TLS_DH_DSS_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dh_dss},
422 {TLS_DH_RSA_WITH_AES_128_CBC_SHA, »cipher_aes_128, mac_sha, kea_dh_rsa}, 397 {TLS_DH_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dh_rsa},
423 {TLS_DH_anon_WITH_AES_128_CBC_SHA, »cipher_aes_128, mac_sha, kea_dh_anon}, 398 {TLS_DH_anon_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dh_anon},
424 {TLS_DH_DSS_WITH_AES_256_CBC_SHA, »cipher_aes_256, mac_sha, kea_dh_dss}, 399 {TLS_DH_DSS_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dh_dss},
425 {TLS_DH_RSA_WITH_AES_256_CBC_SHA, »cipher_aes_256, mac_sha, kea_dh_rsa}, 400 {TLS_DH_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dh_rsa},
426 {TLS_DH_anon_WITH_AES_256_CBC_SHA, »cipher_aes_256, mac_sha, kea_dh_anon}, 401 {TLS_DH_anon_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dh_anon},
427 #endif 402 #endif
428 403
429 {TLS_RSA_WITH_SEED_CBC_SHA,» cipher_seed, mac_sha, kea_rsa}, 404 {TLS_RSA_WITH_SEED_CBC_SHA, cipher_seed, mac_sha, kea_rsa},
430 405
431 {TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, cipher_camellia_128, mac_sha, kea_rsa}, 406 {TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, cipher_camellia_128, mac_sha, kea_rsa},
432 {TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA, 407 {TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,
433 cipher_camellia_128, mac_sha, kea_dhe_dss}, 408 cipher_camellia_128, mac_sha, kea_dhe_dss},
434 {TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, 409 {TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,
435 cipher_camellia_128, mac_sha, kea_dhe_rsa}, 410 cipher_camellia_128, mac_sha, kea_dhe_rsa},
436 {TLS_RSA_WITH_CAMELLIA_256_CBC_SHA,»cipher_camellia_256, mac_sha, kea_rsa}, 411 {TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, cipher_camellia_256, mac_sha, kea_rsa},
437 {TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA, 412 {TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,
438 cipher_camellia_256, mac_sha, kea_dhe_dss}, 413 cipher_camellia_256, mac_sha, kea_dhe_dss},
439 {TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, 414 {TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,
440 cipher_camellia_256, mac_sha, kea_dhe_rsa}, 415 cipher_camellia_256, mac_sha, kea_dhe_rsa},
441 416
442 {TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA, 417 {TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA,
443 cipher_des, mac_sha,kea_rsa_export_1024}, 418 cipher_des, mac_sha,kea_rsa_export_1024},
444 {TLS_RSA_EXPORT1024_WITH_RC4_56_SHA, 419 {TLS_RSA_EXPORT1024_WITH_RC4_56_SHA,
445 cipher_rc4_56, mac_sha,kea_rsa_export_1024}, 420 cipher_rc4_56, mac_sha,kea_rsa_export_1024},
446 421
447 {SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_rsa_fips}, 422 {SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_rsa_fips},
448 {SSL_RSA_FIPS_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_rsa_fips}, 423 {SSL_RSA_FIPS_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_rsa_fips},
449 424
450 {TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_dhe_ rsa}, 425 {TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_dhe_ rsa},
451 {TLS_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_rsa}, 426 {TLS_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_rsa},
452 {TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_ec dhe_rsa}, 427 {TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_ec dhe_rsa},
453 {TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_ ecdhe_ecdsa}, 428 {TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_ ecdhe_ecdsa},
454 {TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, cipher_chacha20, mac_aead, kea_ecdhe_ rsa},
455 {TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, cipher_chacha20, mac_aead, kea_ecdh e_ecdsa},
456 429
457 {TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_dhe_ dss}, 430 {TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_dhe_ dss},
458 {TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_dhe_d ss}, 431 {TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_dhe_d ss},
459 {TLS_DHE_DSS_WITH_AES_256_CBC_SHA256, cipher_aes_256, hmac_sha256, kea_dhe_d ss}, 432 {TLS_DHE_DSS_WITH_AES_256_CBC_SHA256, cipher_aes_256, hmac_sha256, kea_dhe_d ss},
460 433
434 {TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256, cipher_chacha20, mac_aead, kea_d he_rsa},
435 {TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, cipher_chacha20, mac_aead, kea _ecdhe_rsa},
436 {TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, cipher_chacha20, mac_aead, k ea_ecdhe_ecdsa},
437
461 #ifndef NSS_DISABLE_ECC 438 #ifndef NSS_DISABLE_ECC
462 {TLS_ECDH_ECDSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdh_ecdsa}, 439 {TLS_ECDH_ECDSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdh_ecdsa},
463 {TLS_ECDH_ECDSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdh_ecdsa}, 440 {TLS_ECDH_ECDSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdh_ecdsa},
464 {TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_ecdsa} , 441 {TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_ecdsa} ,
465 {TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_ecds a}, 442 {TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_ecds a},
466 {TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_ecds a}, 443 {TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_ecds a},
467 444
468 {TLS_ECDHE_ECDSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdhe_ecdsa }, 445 {TLS_ECDHE_ECDSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdhe_ecdsa },
469 {TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdhe_ecdsa }, 446 {TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdhe_ecdsa },
470 {TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdhe_ecds a}, 447 {TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdhe_ecds a},
(...skipping 16 matching lines...) Expand all
487 464
488 #if 0 465 #if 0
489 {TLS_ECDH_anon_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdh_anon }, 466 {TLS_ECDH_anon_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdh_anon },
490 {TLS_ECDH_anon_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdh_anon }, 467 {TLS_ECDH_anon_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdh_anon },
491 {TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_anon }, 468 {TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_anon },
492 {TLS_ECDH_anon_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_anon }, 469 {TLS_ECDH_anon_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_anon },
493 {TLS_ECDH_anon_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_anon }, 470 {TLS_ECDH_anon_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_anon },
494 #endif 471 #endif
495 #endif /* NSS_DISABLE_ECC */ 472 #endif /* NSS_DISABLE_ECC */
496 }; 473 };
474 /* clang-format on */
497 475
498 static const CK_MECHANISM_TYPE kea_alg_defs[] = { 476 static const CK_MECHANISM_TYPE kea_alg_defs[] = {
499 0x80000000L, 477 0x80000000L,
500 CKM_RSA_PKCS, 478 CKM_RSA_PKCS,
501 CKM_DH_PKCS_DERIVE, 479 CKM_DH_PKCS_DERIVE,
502 CKM_KEA_KEY_DERIVE, 480 CKM_KEA_KEY_DERIVE,
503 CKM_ECDH1_DERIVE 481 CKM_ECDH1_DERIVE
504 }; 482 };
505 483
506 typedef struct SSLCipher2MechStr { 484 typedef struct SSLCipher2MechStr {
507 SSLCipherAlgorithm calg; 485 SSLCipherAlgorithm calg;
508 CK_MECHANISM_TYPE cmech; 486 CK_MECHANISM_TYPE cmech;
509 } SSLCipher2Mech; 487 } SSLCipher2Mech;
510 488
511 /* indexed by type SSLCipherAlgorithm */ 489 /* indexed by type SSLCipherAlgorithm */
512 static const SSLCipher2Mech alg2Mech[] = { 490 static const SSLCipher2Mech alg2Mech[] = {
513 /* calg, cmech */ 491 /* calg, cmech */
514 { calg_null , (CK_MECHANISM_TYPE)0x80000000L» }, 492 { calg_null, (CK_MECHANISM_TYPE)0x80000000L },
515 { calg_rc4 , CKM_RC4» » » » }, 493 { calg_rc4, CKM_RC4 },
516 { calg_rc2 , CKM_RC2_CBC» » » }, 494 { calg_rc2, CKM_RC2_CBC },
517 { calg_des , CKM_DES_CBC» » » }, 495 { calg_des, CKM_DES_CBC },
518 { calg_3des , CKM_DES3_CBC» » » }, 496 { calg_3des, CKM_DES3_CBC },
519 { calg_idea , CKM_IDEA_CBC» » » }, 497 { calg_idea, CKM_IDEA_CBC },
520 { calg_fortezza , CKM_SKIPJACK_CBC64 }, 498 { calg_fortezza, CKM_SKIPJACK_CBC64 },
521 { calg_aes , CKM_AES_CBC» » » }, 499 { calg_aes, CKM_AES_CBC },
522 { calg_camellia , CKM_CAMELLIA_CBC» » » }, 500 { calg_camellia, CKM_CAMELLIA_CBC },
523 { calg_seed , CKM_SEED_CBC» » » }, 501 { calg_seed, CKM_SEED_CBC },
524 { calg_aes_gcm , CKM_AES_GCM» » » }, 502 { calg_aes_gcm, CKM_AES_GCM },
525 { calg_chacha20 , CKM_NSS_CHACHA20_POLY1305»» }, 503 { calg_chacha20, CKM_NSS_CHACHA20_POLY1305 },
526 /* { calg_init , (CK_MECHANISM_TYPE)0x7fffffffL } */ 504 /* { calg_init , (CK_MECHANISM_TYPE)0x7fffffffL } */
527 }; 505 };
528 506
529 #define mmech_invalid (CK_MECHANISM_TYPE)0x80000000L 507 #define mmech_invalid (CK_MECHANISM_TYPE)0x80000000L
530 #define mmech_md5 CKM_SSL3_MD5_MAC 508 #define mmech_md5 CKM_SSL3_MD5_MAC
531 #define mmech_sha CKM_SSL3_SHA1_MAC 509 #define mmech_sha CKM_SSL3_SHA1_MAC
532 #define mmech_md5_hmac CKM_MD5_HMAC 510 #define mmech_md5_hmac CKM_MD5_HMAC
533 #define mmech_sha_hmac CKM_SHA_1_HMAC 511 #define mmech_sha_hmac CKM_SHA_1_HMAC
534 #define mmech_sha256_hmac CKM_SHA256_HMAC 512 #define mmech_sha256_hmac CKM_SHA256_HMAC
535 513
514 /* clang-format off */
536 static const ssl3MACDef mac_defs[] = { /* indexed by SSL3MACAlgorithm */ 515 static const ssl3MACDef mac_defs[] = { /* indexed by SSL3MACAlgorithm */
537 /* pad_size is only used for SSL 3.0 MAC. See RFC 6101 Sec. 5.2.3.1. */ 516 /* pad_size is only used for SSL 3.0 MAC. See RFC 6101 Sec. 5.2.3.1. */
538 /* mac mmech pad_size mac_size */ 517 /* mac mmech pad_size mac_size */
539 { mac_null, mmech_invalid, 0, 0 }, 518 { mac_null, mmech_invalid, 0, 0 , 0},
540 { mac_md5, mmech_md5, 48, MD5_LENGTH }, 519 { mac_md5, mmech_md5, 48, MD5_LENGTH, SEC_OID_HMAC_MD5 },
541 { mac_sha, mmech_sha, 40, SHA1_LENGTH}, 520 { mac_sha, mmech_sha, 40, SHA1_LENGTH, SEC_OID_HMAC_SHA1},
542 {hmac_md5, mmech_md5_hmac, 0, MD5_LENGTH }, 521 {hmac_md5, mmech_md5_hmac, 0, MD5_LENGTH, SEC_OID_HMAC_MD5},
543 {hmac_sha, mmech_sha_hmac, 0, SHA1_LENGTH}, 522 {hmac_sha, mmech_sha_hmac, 0, SHA1_LENGTH, SEC_OID_HMAC_SHA1},
544 {hmac_sha256, mmech_sha256_hmac, 0, SHA256_LENGTH}, 523 {hmac_sha256, mmech_sha256_hmac, 0, SHA256_LENGTH, SEC_OID_HMAC_SHA256},
545 { mac_aead, mmech_invalid, 0, 0 }, 524 { mac_aead, mmech_invalid, 0, 0, 0 },
546 }; 525 };
526 /* clang-format on */
547 527
548 /* indexed by SSL3BulkCipher */ 528 /* indexed by SSL3BulkCipher */
549 const char * const ssl3_cipherName[] = { 529 const char *const ssl3_cipherName[] = {
550 "NULL", 530 "NULL",
551 "RC4", 531 "RC4",
552 "RC4-40", 532 "RC4-40",
553 "RC4-56", 533 "RC4-56",
554 "RC2-CBC", 534 "RC2-CBC",
555 "RC2-CBC-40", 535 "RC2-CBC-40",
556 "DES-CBC", 536 "DES-CBC",
557 "3DES-EDE-CBC", 537 "3DES-EDE-CBC",
558 "DES-CBC-40", 538 "DES-CBC-40",
559 "IDEA-CBC", 539 "IDEA-CBC",
560 "AES-128", 540 "AES-128",
561 "AES-256", 541 "AES-256",
562 "Camellia-128", 542 "Camellia-128",
563 "Camellia-256", 543 "Camellia-256",
564 "SEED-CBC", 544 "SEED-CBC",
565 "AES-128-GCM", 545 "AES-128-GCM",
566 "missing" 546 "missing"
567 }; 547 };
568 548
549 const PRUint8 tls13_downgrade_random[] = { 0x44, 0x4F, 0x57, 0x4E,
550 0x47, 0x52, 0x44, 0x01 };
551 const PRUint8 tls12_downgrade_random[] = { 0x44, 0x4F, 0x57, 0x4E,
552 0x47, 0x52, 0x44, 0x00 };
553
569 #ifndef NSS_DISABLE_ECC 554 #ifndef NSS_DISABLE_ECC
570 /* The ECCWrappedKeyInfo structure defines how various pieces of 555 /* The ECCWrappedKeyInfo structure defines how various pieces of
571 * information are laid out within wrappedSymmetricWrappingkey 556 * information are laid out within wrappedSymmetricWrappingkey
572 * for ECDH key exchange. Since wrappedSymmetricWrappingkey is 557 * for ECDH key exchange. Since wrappedSymmetricWrappingkey is
573 * a 512-byte buffer (see sslimpl.h), the variable length field 558 * a 512-byte buffer (see sslimpl.h), the variable length field
574 * in ECCWrappedKeyInfo can be at most (512 - 8) = 504 bytes. 559 * in ECCWrappedKeyInfo can be at most (512 - 8) = 504 bytes.
575 * 560 *
576 * XXX For now, NSS only supports named elliptic curves of size 571 bits 561 * XXX For now, NSS only supports named elliptic curves of size 571 bits
577 * or smaller. The public value will fit within 145 bytes and EC params 562 * or smaller. The public value will fit within 145 bytes and EC params
578 * will fit within 12 bytes. We'll need to revisit this when NSS 563 * will fit within 12 bytes. We'll need to revisit this when NSS
579 * supports arbitrary curves. 564 * supports arbitrary curves.
580 */ 565 */
581 #define MAX_EC_WRAPPED_KEY_BUFLEN 504 566 #define MAX_EC_WRAPPED_KEY_BUFLEN 504
582 567
583 typedef struct ECCWrappedKeyInfoStr { 568 typedef struct ECCWrappedKeyInfoStr {
584 PRUint16 size; /* EC public key size in bits */ 569 PRUint16 size; /* EC public key size in bits */
585 PRUint16 encodedParamLen; /* length (in bytes) of DER encoded EC params */ 570 PRUint16 encodedParamLen; /* length (in bytes) of DER encoded EC params */
586 PRUint16 pubValueLen; /* length (in bytes) of EC public value */ 571 PRUint16 pubValueLen; /* length (in bytes) of EC public va lue */
587 PRUint16 wrappedKeyLen; /* length (in bytes) of the wrapped key */ 572 PRUint16 wrappedKeyLen; /* length (in bytes) of the wrapped key */
588 PRUint8 var[MAX_EC_WRAPPED_KEY_BUFLEN]; /* this buffer contains the */ 573 PRUint8 var[MAX_EC_WRAPPED_KEY_BUFLEN]; /* this buffer contains the */
589 /* EC public-key params, the EC public value and the wrapped key */ 574 /* EC public-key params, the EC public value and the wrapped key */
590 } ECCWrappedKeyInfo; 575 } ECCWrappedKeyInfo;
591 #endif /* NSS_DISABLE_ECC */ 576 #endif /* NSS_DISABLE_ECC */
592 577
578 CK_MECHANISM_TYPE
579 ssl3_Alg2Mech(SSLCipherAlgorithm calg)
580 {
581 PORT_Assert(alg2Mech[calg].calg == calg);
582 return alg2Mech[calg].cmech;
583 }
584
593 #if defined(TRACE) 585 #if defined(TRACE)
594 586
595 static char * 587 static char *
596 ssl3_DecodeHandshakeType(int msgType) 588 ssl3_DecodeHandshakeType(int msgType)
597 { 589 {
598 char * rv; 590 char *rv;
599 static char line[40]; 591 static char line[40];
600 592
601 switch(msgType) { 593 switch (msgType) {
602 case hello_request:» rv = "hello_request (0)"; break; 594 case hello_request:
603 case client_hello:» rv = "client_hello (1)"; break; 595 rv = "hello_request (0)";
604 case server_hello:» rv = "server_hello (2)"; break; 596 break;
605 case hello_verify_request: rv = "hello_verify_request (3)"; break; 597 case client_hello:
606 case certificate:» rv = "certificate (11)"; break; 598 rv = "client_hello (1)";
607 case server_key_exchange:» rv = "server_key_exchange (12)"; break; 599 break;
608 case certificate_request:» rv = "certificate_request (13)"; break; 600 case server_hello:
609 case server_hello_done:» rv = "server_hello_done (14)"; break; 601 rv = "server_hello (2)";
610 case certificate_verify:» rv = "certificate_verify (15)"; break; 602 break;
611 case client_key_exchange:» rv = "client_key_exchange (16)"; break; 603 case hello_verify_request:
612 case finished:» rv = "finished (20)"; break; 604 rv = "hello_verify_request (3)";
613 default: 605 break;
614 sprintf(line, "*UNKNOWN* handshake type! (%d)", msgType); 606 case encrypted_extensions:
615 » rv = line; 607 rv = "encrypted_extensions (8)";
608 break;
609 case certificate:
610 rv = "certificate (11)";
611 break;
612 case server_key_exchange:
613 rv = "server_key_exchange (12)";
614 break;
615 case certificate_request:
616 rv = "certificate_request (13)";
617 break;
618 case server_hello_done:
619 rv = "server_hello_done (14)";
620 break;
621 case certificate_verify:
622 rv = "certificate_verify (15)";
623 break;
624 case client_key_exchange:
625 rv = "client_key_exchange (16)";
626 break;
627 case finished:
628 rv = "finished (20)";
629 break;
630 default:
631 sprintf(line, "*UNKNOWN* handshake type! (%d)", msgType);
632 rv = line;
616 } 633 }
617 return rv; 634 return rv;
618 } 635 }
619 636
620 static char * 637 static char *
621 ssl3_DecodeContentType(int msgType) 638 ssl3_DecodeContentType(int msgType)
622 { 639 {
623 char * rv; 640 char *rv;
624 static char line[40]; 641 static char line[40];
625 642
626 switch(msgType) { 643 switch (msgType) {
627 case content_change_cipher_spec: 644 case content_change_cipher_spec:
628 rv = "change_cipher_spec (20)"; break; 645 rv = "change_cipher_spec (20)";
629 case content_alert:» rv = "alert (21)"; break; 646 break;
630 case content_handshake:» rv = "handshake (22)"; break; 647 case content_alert:
631 case content_application_data: 648 rv = "alert (21)";
632 rv = "application_data (23)"; break; 649 break;
633 default: 650 case content_handshake:
634 sprintf(line, "*UNKNOWN* record type! (%d)", msgType); 651 rv = "handshake (22)";
635 » rv = line; 652 break;
653 case content_application_data:
654 rv = "application_data (23)";
655 break;
656 default:
657 sprintf(line, "*UNKNOWN* record type! (%d)", msgType);
658 rv = line;
636 } 659 }
637 return rv; 660 return rv;
638 } 661 }
639 662
640 #endif 663 #endif
641 664
642 SSL3Statistics * 665 SSL3Statistics *
643 SSL_GetStatistics(void) 666 SSL_GetStatistics(void)
644 { 667 {
645 return &ssl3stats; 668 return &ssl3stats;
646 } 669 }
647 670
648 typedef struct tooLongStr { 671 typedef struct tooLongStr {
649 #if defined(IS_LITTLE_ENDIAN) 672 #if defined(IS_LITTLE_ENDIAN)
650 PRInt32 low; 673 PRInt32 low;
651 PRInt32 high; 674 PRInt32 high;
652 #else 675 #else
653 PRInt32 high; 676 PRInt32 high;
654 PRInt32 low; 677 PRInt32 low;
655 #endif 678 #endif
656 } tooLong; 679 } tooLong;
657 680
658 void SSL_AtomicIncrementLong(long * x) 681 void
682 SSL_AtomicIncrementLong(long *x)
659 { 683 {
660 if ((sizeof *x) == sizeof(PRInt32)) { 684 if ((sizeof *x) == sizeof(PRInt32)) {
661 PR_ATOMIC_INCREMENT((PRInt32 *)x); 685 PR_ATOMIC_INCREMENT((PRInt32 *)x);
662 } else { 686 } else {
663 » tooLong * tl = (tooLong *)x; 687 tooLong *tl = (tooLong *)x;
664 » if (PR_ATOMIC_INCREMENT(&tl->low) == 0) 688 if (PR_ATOMIC_INCREMENT(&tl->low) == 0)
665 » PR_ATOMIC_INCREMENT(&tl->high); 689 PR_ATOMIC_INCREMENT(&tl->high);
666 } 690 }
667 } 691 }
668 692
669 static PRBool 693 static PRBool
670 ssl3_CipherSuiteAllowedForVersionRange( 694 ssl3_CipherSuiteAllowedForVersionRange(
671 ssl3CipherSuite cipherSuite, 695 ssl3CipherSuite cipherSuite,
672 const SSLVersionRange *vrange) 696 const SSLVersionRange *vrange)
673 { 697 {
674 switch (cipherSuite) { 698 switch (cipherSuite) {
675 /* See RFC 4346 A.5. Export cipher suites must not be used in TLS 1.1 or 699 /* See RFC 4346 A.5. Export cipher suites must not be used in TLS 1.1 or
676 * later. This set of cipher suites is similar to, but different from, the 700 * later. This set of cipher suites is similar to, but different from, t he
677 * set of cipher suites considered exportable by SSL_IsExportCipherSuite. 701 * set of cipher suites considered exportable by SSL_IsExportCipherSuite .
678 */ 702 */
679 case TLS_RSA_EXPORT_WITH_RC4_40_MD5: 703 case TLS_RSA_EXPORT_WITH_RC4_40_MD5:
680 case TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5: 704 case TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5:
681 /* TLS_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented 705 /* TLS_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented
682 * TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA: never implemented 706 * TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA: never implemented
683 * TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented 707 * TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented
684 * TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA: never implemented 708 * TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA: never implemented
685 * TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented 709 * TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented
686 * TLS_DH_anon_EXPORT_WITH_RC4_40_MD5: never implemented 710 * TLS_DH_anon_EXPORT_WITH_RC4_40_MD5: never implemented
687 * TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA: never implemented 711 * TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA: never implemented
688 */ 712 */
689 » return vrange->min <= SSL_LIBRARY_VERSION_TLS_1_0; 713 return vrange->min <= SSL_LIBRARY_VERSION_TLS_1_0;
690 714
691 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256: 715 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
692 case TLS_RSA_WITH_AES_256_CBC_SHA256: 716 case TLS_RSA_WITH_AES_256_CBC_SHA256:
693 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256: 717 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
694 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256: 718 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
695 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256: 719 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
696 case TLS_RSA_WITH_AES_128_CBC_SHA256: 720 case TLS_RSA_WITH_AES_128_CBC_SHA256:
697 case TLS_RSA_WITH_AES_128_GCM_SHA256: 721 case TLS_RSA_WITH_AES_128_GCM_SHA256:
698 case TLS_DHE_DSS_WITH_AES_128_CBC_SHA256: 722 case TLS_DHE_DSS_WITH_AES_128_CBC_SHA256:
699 case TLS_DHE_DSS_WITH_AES_256_CBC_SHA256: 723 case TLS_DHE_DSS_WITH_AES_256_CBC_SHA256:
700 case TLS_RSA_WITH_NULL_SHA256: 724 case TLS_RSA_WITH_NULL_SHA256:
701 return vrange->max == SSL_LIBRARY_VERSION_TLS_1_2; 725 case TLS_DHE_DSS_WITH_AES_128_GCM_SHA256:
726 return vrange->max == SSL_LIBRARY_VERSION_TLS_1_2;
702 727
703 case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305: 728 case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
704 case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305: 729 case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
705 case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: 730 case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
706 case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: 731 return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_2;
707 case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
708 case TLS_DHE_DSS_WITH_AES_128_GCM_SHA256:
709 » return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_2;
710 732
711 /* RFC 4492: ECC cipher suites need TLS extensions to negotiate curves and 733 /* RFC 4492: ECC cipher suites need TLS extensions to negotiate curves a nd
712 * point formats.*/ 734 * point formats.*/
713 case TLS_ECDH_ECDSA_WITH_NULL_SHA: 735 case TLS_ECDH_ECDSA_WITH_NULL_SHA:
714 case TLS_ECDH_ECDSA_WITH_RC4_128_SHA: 736 case TLS_ECDH_ECDSA_WITH_RC4_128_SHA:
715 case TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA: 737 case TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA:
716 case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA: 738 case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA:
717 case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA: 739 case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA:
718 case TLS_ECDHE_ECDSA_WITH_NULL_SHA: 740 case TLS_ECDHE_ECDSA_WITH_NULL_SHA:
719 case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA: 741 case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA:
720 case TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA: 742 case TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA:
721 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA: 743 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
722 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA: 744 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
723 case TLS_ECDH_RSA_WITH_NULL_SHA: 745 case TLS_ECDH_RSA_WITH_NULL_SHA:
724 case TLS_ECDH_RSA_WITH_RC4_128_SHA: 746 case TLS_ECDH_RSA_WITH_RC4_128_SHA:
725 case TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA: 747 case TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA:
726 case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA: 748 case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA:
727 case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA: 749 case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA:
728 case TLS_ECDHE_RSA_WITH_NULL_SHA: 750 case TLS_ECDHE_RSA_WITH_NULL_SHA:
729 case TLS_ECDHE_RSA_WITH_RC4_128_SHA: 751 case TLS_ECDHE_RSA_WITH_RC4_128_SHA:
730 case TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA: 752 case TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA:
731 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: 753 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
732 case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA: 754 case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
733 return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_0 && 755 return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_0 &&
734 vrange->min < SSL_LIBRARY_VERSION_TLS_1_3; 756 vrange->min < SSL_LIBRARY_VERSION_TLS_1_3;
735 757
736 default: 758 default:
737 return vrange->min < SSL_LIBRARY_VERSION_TLS_1_3; 759 return vrange->min < SSL_LIBRARY_VERSION_TLS_1_3;
738 } 760 }
739 } 761 }
740 762
741 /* return pointer to ssl3CipherSuiteDef for suite, or NULL */ 763 /* return pointer to ssl3CipherSuiteDef for suite, or NULL */
742 /* XXX This does a linear search. A binary search would be better. */ 764 /* XXX This does a linear search. A binary search would be better. */
743 static const ssl3CipherSuiteDef * 765 static const ssl3CipherSuiteDef *
744 ssl_LookupCipherSuiteDef(ssl3CipherSuite suite) 766 ssl_LookupCipherSuiteDef(ssl3CipherSuite suite)
745 { 767 {
746 int cipher_suite_def_len = 768 int cipher_suite_def_len =
747 » sizeof(cipher_suite_defs) / sizeof(cipher_suite_defs[0]); 769 sizeof(cipher_suite_defs) / sizeof(cipher_suite_defs[0]);
748 int i; 770 int i;
749 771
750 for (i = 0; i < cipher_suite_def_len; i++) { 772 for (i = 0; i < cipher_suite_def_len; i++) {
751 » if (cipher_suite_defs[i].cipher_suite == suite) 773 if (cipher_suite_defs[i].cipher_suite == suite)
752 » return &cipher_suite_defs[i]; 774 return &cipher_suite_defs[i];
753 } 775 }
754 PORT_Assert(PR_FALSE); /* We should never get here. */ 776 PORT_Assert(PR_FALSE); /* We should never get here. */
755 PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE); 777 PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
756 return NULL; 778 return NULL;
757 } 779 }
758 780
759 /* Find the cipher configuration struct associate with suite */ 781 /* Find the cipher configuration struct associate with suite */
760 /* XXX This does a linear search. A binary search would be better. */ 782 /* XXX This does a linear search. A binary search would be better. */
761 static ssl3CipherSuiteCfg * 783 static ssl3CipherSuiteCfg *
762 ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite, ssl3CipherSuiteCfg *suites) 784 ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite, ssl3CipherSuiteCfg *suites)
763 { 785 {
764 int i; 786 int i;
765 787
766 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { 788 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
767 » if (suites[i].cipher_suite == suite) 789 if (suites[i].cipher_suite == suite)
768 » return &suites[i]; 790 return &suites[i];
769 } 791 }
770 /* return NULL and let the caller handle it. */ 792 /* return NULL and let the caller handle it. */
771 PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE); 793 PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
772 return NULL; 794 return NULL;
773 } 795 }
774 796
775
776 /* Initialize the suite->isPresent value for config_match 797 /* Initialize the suite->isPresent value for config_match
777 * Returns count of enabled ciphers supported by extant tokens, 798 * Returns count of enabled ciphers supported by extant tokens,
778 * regardless of policy or user preference. 799 * regardless of policy or user preference.
779 * If this returns zero, the user cannot do SSL v3. 800 * If this returns zero, the user cannot do SSL v3.
780 */ 801 */
781 int 802 int
782 ssl3_config_match_init(sslSocket *ss) 803 ssl3_config_match_init(sslSocket *ss)
783 { 804 {
784 ssl3CipherSuiteCfg * suite; 805 ssl3CipherSuiteCfg *suite;
785 const ssl3CipherSuiteDef *cipher_def; 806 const ssl3CipherSuiteDef *cipher_def;
786 SSLCipherAlgorithm cipher_alg; 807 SSLCipherAlgorithm cipher_alg;
787 CK_MECHANISM_TYPE cipher_mech; 808 CK_MECHANISM_TYPE cipher_mech;
788 SSL3KEAType exchKeyType; 809 SSL3KEAType exchKeyType;
789 int i; 810 int i;
790 int numPresent» » = 0; 811 int numPresent = 0;
791 int numEnabled» » = 0; 812 int numEnabled = 0;
792 PRBool isServer; 813 PRBool isServer;
793 sslServerCerts *svrAuth; 814 sslServerCerts *svrAuth;
794 815
795 PORT_Assert(ss); 816 PORT_Assert(ss);
796 if (!ss) { 817 if (!ss) {
797 » PORT_SetError(SEC_ERROR_INVALID_ARGS); 818 PORT_SetError(SEC_ERROR_INVALID_ARGS);
798 » return 0; 819 return 0;
799 } 820 }
800 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { 821 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
801 » return 0; 822 return 0;
802 } 823 }
803 isServer = (PRBool)(ss->sec.isServer != 0); 824 isServer = (PRBool)(ss->sec.isServer != 0);
804 825
805 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { 826 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
806 » suite = &ss->cipherSuites[i]; 827 suite = &ss->cipherSuites[i];
807 » if (suite->enabled) { 828 if (suite->enabled) {
808 » ++numEnabled; 829 ++numEnabled;
809 » /* We need the cipher defs to see if we have a token that can handle 830 /* We need the cipher defs to see if we have a token that can handle
810 » * this cipher. It isn't part of the static definition. 831 * this cipher. It isn't part of the static definition.
811 » */ 832 */
812 » cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite); 833 cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite);
813 » if (!cipher_def) { 834 if (!cipher_def) {
814 » » suite->isPresent = PR_FALSE; 835 suite->isPresent = PR_FALSE;
815 » » continue; 836 continue;
816 » } 837 }
817 » cipher_alg = bulk_cipher_defs[cipher_def->bulk_cipher_alg].calg; 838 cipher_alg = bulk_cipher_defs[cipher_def->bulk_cipher_alg].calg;
818 » PORT_Assert( alg2Mech[cipher_alg].calg == cipher_alg); 839 cipher_mech = ssl3_Alg2Mech(cipher_alg);
819 » cipher_mech = alg2Mech[cipher_alg].cmech; 840 exchKeyType =
820 » exchKeyType = 841 kea_defs[cipher_def->key_exchange_alg].exchKeyType;
821 » » kea_defs[cipher_def->key_exchange_alg].exchKeyType;
822 #ifdef NSS_DISABLE_ECC 842 #ifdef NSS_DISABLE_ECC
823 » svrAuth = ss->serverCerts + exchKeyType; 843 svrAuth = ss->serverCerts + exchKeyType;
824 #else 844 #else
825 » /* XXX SSLKEAType isn't really a good choice for 845 /* XXX SSLKEAType isn't really a good choice for
826 » * indexing certificates. It doesn't work for 846 * indexing certificates. It doesn't work for
827 » * (EC)DHE-* ciphers. Here we use a hack to ensure 847 * (EC)DHE-* ciphers. Here we use a hack to ensure
828 » * that the server uses an RSA cert for (EC)DHE-RSA. 848 * that the server uses an RSA cert for (EC)DHE-RSA.
829 » */ 849 */
830 » switch (cipher_def->key_exchange_alg) { 850 switch (cipher_def->key_exchange_alg) {
831 » case kea_dhe_dss: 851 case kea_dhe_dss:
832 » » svrAuth = ss->serverCerts + ssl_kea_dh; 852 svrAuth = ss->serverCerts + ssl_kea_dh;
833 » » break; 853 break;
834 » case kea_ecdhe_rsa: 854 case kea_ecdhe_rsa:
835 » case kea_dhe_rsa: 855 case kea_dhe_rsa:
836 » » svrAuth = ss->serverCerts + kt_rsa; 856 svrAuth = ss->serverCerts + kt_rsa;
837 » » break; 857 break;
838 » case kea_ecdh_ecdsa: 858 case kea_ecdh_ecdsa:
839 » case kea_ecdh_rsa: 859 case kea_ecdh_rsa:
840 » /* 860 /*
841 » » * XXX We ought to have different indices for 861 * XXX We ought to have different indices for
842 » » * ECDSA- and RSA-signed EC certificates so 862 * ECDSA- and RSA-signed EC certificates so
843 » » * we could support both key exchange mechanisms 863 * we could support both key exchange mechanisms
844 » » * simultaneously. For now, both of them use 864 * simultaneously. For now, both of them use
845 » » * whatever is in the certificate slot for kt_ecdh 865 * whatever is in the certificate slot for kt_ecdh
846 » » */ 866 */
847 » case kea_dhe_dss_export: 867 case kea_dhe_dss_export:
848 » case kea_dhe_rsa_export: 868 case kea_dhe_rsa_export:
849 » default: 869 default:
850 » » svrAuth = ss->serverCerts + exchKeyType; 870 svrAuth = ss->serverCerts + exchKeyType;
851 » » break; 871 break;
852 » } 872 }
853 #endif /* NSS_DISABLE_ECC */ 873 #endif /* NSS_DISABLE_ECC */
854 874
855 » /* Mark the suites that are backed by real tokens, certs and keys */ 875 /* Mark the suites that are backed by real tokens, certs and keys */
856 » suite->isPresent = (PRBool) 876 suite->isPresent = (PRBool)(((exchKeyType == kt_null) ||
857 » » (((exchKeyType == kt_null) || 877 ((!isServer ||
858 » » ((!isServer || (svrAuth->serverKeyPair && 878 (svrAuth->serverKeyPair && svrAuth->S ERVERKEY &&
859 » » svrAuth->SERVERKEY && 879 svrAuth->serverCertChain)) &&
860 » » » » svrAuth->serverCertChain)) && 880 PK11_TokenExists(kea_alg_defs[exchKeyT ype]))) &&
861 » » PK11_TokenExists(kea_alg_defs[exchKeyType]))) && 881 ((cipher_alg == calg_null) || PK11_Token Exists(cipher_mech)));
862 » » ((cipher_alg == calg_null) || PK11_TokenExists(cipher_mech))); 882 if (suite->isPresent)
863 » if (suite->isPresent) 883 ++numPresent;
864 » » ++numPresent; 884 }
865 » }
866 } 885 }
867 PORT_Assert(numPresent > 0 || numEnabled == 0); 886 PORT_Assert(numPresent > 0 || numEnabled == 0);
868 if (numPresent <= 0) { 887 if (numPresent <= 0) {
869 » PORT_SetError(SSL_ERROR_NO_CIPHERS_SUPPORTED); 888 PORT_SetError(SSL_ERROR_NO_CIPHERS_SUPPORTED);
870 } 889 }
871 return numPresent; 890 return numPresent;
872 } 891 }
873 892
874
875 /* return PR_TRUE if suite matches policy, enabled state and is applicable to 893 /* return PR_TRUE if suite matches policy, enabled state and is applicable to
876 * the given version range. */ 894 * the given version range. */
877 /* It would be a REALLY BAD THING (tm) if we ever permitted the use 895 /* It would be a REALLY BAD THING (tm) if we ever permitted the use
878 ** of a cipher that was NOT_ALLOWED. So, if this is ever called with 896 ** of a cipher that was NOT_ALLOWED. So, if this is ever called with
879 ** policy == SSL_NOT_ALLOWED, report no match. 897 ** policy == SSL_NOT_ALLOWED, report no match.
880 */ 898 */
881 /* adjust suite enabled to the availability of a token that can do the 899 /* adjust suite enabled to the availability of a token that can do the
882 * cipher suite. */ 900 * cipher suite. */
883 static PRBool 901 static PRBool
884 config_match(ssl3CipherSuiteCfg *suite, int policy, PRBool enabled, 902 config_match(ssl3CipherSuiteCfg *suite, int policy, PRBool enabled,
885 » const SSLVersionRange *vrange, const sslSocket *ss) 903 const SSLVersionRange *vrange, const sslSocket *ss)
886 { 904 {
887 const ssl3CipherSuiteDef *cipher_def; 905 const ssl3CipherSuiteDef *cipher_def;
888 906
889 PORT_Assert(policy != SSL_NOT_ALLOWED && enabled != PR_FALSE); 907 PORT_Assert(policy != SSL_NOT_ALLOWED && enabled != PR_FALSE);
890 if (policy == SSL_NOT_ALLOWED || !enabled) 908 if (policy == SSL_NOT_ALLOWED || !enabled)
891 » return PR_FALSE; 909 return PR_FALSE;
892 910
893 cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite); 911 cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite);
894 PORT_Assert(cipher_def != NULL); 912 PORT_Assert(cipher_def != NULL);
895 913
896 PORT_Assert(ss != NULL); 914 PORT_Assert(ss != NULL);
897 if (ss->sec.isServer && !ss->opt.enableServerDhe && 915 if (ss->sec.isServer && !ss->opt.enableServerDhe &&
898 kea_defs[cipher_def->key_exchange_alg].exchKeyType == ssl_kea_dh) 916 kea_defs[cipher_def->key_exchange_alg].exchKeyType == ssl_kea_dh)
899 » return PR_FALSE; 917 return PR_FALSE;
900 918
901 return (PRBool)(suite->enabled && 919 return (PRBool)(suite->enabled &&
902 suite->isPresent && 920 suite->isPresent &&
903 » suite->policy != SSL_NOT_ALLOWED && 921 suite->policy != SSL_NOT_ALLOWED &&
904 » » suite->policy <= policy && 922 suite->policy <= policy &&
905 » » ssl3_CipherSuiteAllowedForVersionRange( 923 ssl3_CipherSuiteAllowedForVersionRange(
906 suite->cipher_suite, vrange)); 924 suite->cipher_suite, vrange));
907 } 925 }
908 926
909 /* return number of cipher suites that match policy, enabled state and are 927 /* return number of cipher suites that match policy, enabled state and are
910 * applicable for the configured protocol version range. */ 928 * applicable for the configured protocol version range. */
911 /* called from ssl3_SendClientHello and ssl3_ConstructV2CipherSpecsHack */ 929 /* called from ssl3_SendClientHello and ssl3_ConstructV2CipherSpecsHack */
912 static int 930 static int
913 count_cipher_suites(sslSocket *ss, int policy, PRBool enabled) 931 count_cipher_suites(sslSocket *ss, int policy, PRBool enabled)
914 { 932 {
915 int i, count = 0; 933 int i, count = 0;
916 934
917 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { 935 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
918 » return 0; 936 return 0;
919 } 937 }
920 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { 938 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
921 » if (config_match(&ss->cipherSuites[i], policy, enabled, &ss->vrange, ss) ) 939 if (config_match(&ss->cipherSuites[i], policy, enabled, &ss->vrange, ss) )
922 » count++; 940 count++;
923 } 941 }
924 if (count <= 0) { 942 if (count <= 0) {
925 » PORT_SetError(SSL_ERROR_SSL_DISABLED); 943 PORT_SetError(SSL_ERROR_SSL_DISABLED);
926 } 944 }
927 return count; 945 return count;
928 } 946 }
929 947
930 /* 948 /*
931 * Null compression, mac and encryption functions 949 * Null compression, mac and encryption functions
932 */ 950 */
933 951
934 static SECStatus 952 static SECStatus
935 Null_Cipher(void *ctx, unsigned char *output, int *outputLen, int maxOutputLen, 953 Null_Cipher(void *ctx, unsigned char *output, int *outputLen, int maxOutputLen,
936 » const unsigned char *input, int inputLen) 954 const unsigned char *input, int inputLen)
937 { 955 {
938 if (inputLen > maxOutputLen) { 956 if (inputLen > maxOutputLen) {
939 *outputLen = 0; /* Match PK11_CipherOp in setting outputLen */ 957 *outputLen = 0; /* Match PK11_CipherOp in setting outputLen */
940 PORT_SetError(SEC_ERROR_OUTPUT_LEN); 958 PORT_SetError(SEC_ERROR_OUTPUT_LEN);
941 return SECFailure; 959 return SECFailure;
942 } 960 }
943 *outputLen = inputLen; 961 *outputLen = inputLen;
944 if (input != output) 962 if (input != output)
945 » PORT_Memcpy(output, input, inputLen); 963 PORT_Memcpy(output, input, inputLen);
946 return SECSuccess; 964 return SECSuccess;
947 } 965 }
948 966
949 /* 967 /*
950 * SSL3 Utility functions 968 * SSL3 Utility functions
951 */ 969 */
952 970
953 /* allowLargerPeerVersion controls whether the function will select the 971 /* allowLargerPeerVersion controls whether the function will select the
954 * highest enabled SSL version or fail when peerVersion is greater than the 972 * highest enabled SSL version or fail when peerVersion is greater than the
955 * highest enabled version. 973 * highest enabled version.
956 * 974 *
957 * If allowLargerPeerVersion is true, peerVersion is the peer's highest 975 * If allowLargerPeerVersion is true, peerVersion is the peer's highest
958 * enabled version rather than the peer's selected version. 976 * enabled version rather than the peer's selected version.
959 */ 977 */
960 SECStatus 978 SECStatus
961 ssl3_NegotiateVersion(sslSocket *ss, SSL3ProtocolVersion peerVersion, 979 ssl3_NegotiateVersion(sslSocket *ss, SSL3ProtocolVersion peerVersion,
962 » » PRBool allowLargerPeerVersion) 980 PRBool allowLargerPeerVersion)
963 { 981 {
964 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { 982 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
965 » PORT_SetError(SSL_ERROR_SSL_DISABLED); 983 PORT_SetError(SSL_ERROR_SSL_DISABLED);
966 » return SECFailure; 984 return SECFailure;
967 } 985 }
968 986
969 if (peerVersion < ss->vrange.min || 987 if (peerVersion < ss->vrange.min ||
970 » (peerVersion > ss->vrange.max && !allowLargerPeerVersion)) { 988 (peerVersion > ss->vrange.max && !allowLargerPeerVersion)) {
971 » PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION); 989 PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION);
972 » return SECFailure; 990 return SECFailure;
973 } 991 }
974 992
975 ss->version = PR_MIN(peerVersion, ss->vrange.max); 993 ss->version = PR_MIN(peerVersion, ss->vrange.max);
976 PORT_Assert(ssl3_VersionIsSupported(ss->protocolVariant, ss->version)); 994 PORT_Assert(ssl3_VersionIsSupported(ss->protocolVariant, ss->version));
977 995
978 return SECSuccess; 996 return SECSuccess;
979 } 997 }
980 998
981 static SECStatus 999 static SECStatus
982 ssl3_GetNewRandom(SSL3Random *random) 1000 ssl3_GetNewRandom(SSL3Random *random)
983 { 1001 {
984 SECStatus rv; 1002 SECStatus rv;
985 1003
986 /* first 4 bytes are reserverd for time */
987 rv = PK11_GenerateRandom(random->rand, SSL3_RANDOM_LENGTH); 1004 rv = PK11_GenerateRandom(random->rand, SSL3_RANDOM_LENGTH);
988 if (rv != SECSuccess) { 1005 if (rv != SECSuccess) {
989 » ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE); 1006 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
990 } 1007 }
991 return rv; 1008 return rv;
992 } 1009 }
993 1010
994 /* Called by ssl3_SendServerKeyExchange and ssl3_SendCertificateVerify */ 1011 /* Called by ssl3_SendServerKeyExchange and ssl3_SendCertificateVerify */
995 SECStatus 1012 SECStatus
996 ssl3_SignHashes(SSL3Hashes *hash, SECKEYPrivateKey *key, SECItem *buf, 1013 ssl3_SignHashes(SSL3Hashes *hash, SECKEYPrivateKey *key, SECItem *buf,
997 PRBool isTLS) 1014 PRBool isTLS)
998 { 1015 {
999 SECStatus rv» » = SECFailure; 1016 SECStatus rv = SECFailure;
1000 PRBool doDerEncode = PR_FALSE; 1017 PRBool doDerEncode = PR_FALSE;
1001 int signatureLen; 1018 int signatureLen;
1002 SECItem hashItem; 1019 SECItem hashItem;
1003 1020
1004 buf->data = NULL; 1021 buf->data = NULL;
1005 1022
1006 switch (key->keyType) { 1023 switch (key->keyType) {
1007 case rsaKey: 1024 case rsaKey:
1008 » hashItem.data = hash->u.raw; 1025 hashItem.data = hash->u.raw;
1009 » hashItem.len = hash->len; 1026 hashItem.len = hash->len;
1010 » break; 1027 break;
1011 case dsaKey: 1028 case dsaKey:
1012 » doDerEncode = isTLS; 1029 doDerEncode = isTLS;
1013 » /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash. 1030 /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
1014 » * In that case, we use just the SHA1 part. */ 1031 * In that case, we use just the SHA1 part. */
1015 » if (hash->hashAlg == ssl_hash_none) { 1032 if (hash->hashAlg == ssl_hash_none) {
1016 » hashItem.data = hash->u.s.sha; 1033 hashItem.data = hash->u.s.sha;
1017 » hashItem.len = sizeof(hash->u.s.sha); 1034 hashItem.len = sizeof(hash->u.s.sha);
1018 » } else { 1035 } else {
1019 » hashItem.data = hash->u.raw; 1036 hashItem.data = hash->u.raw;
1020 » hashItem.len = hash->len; 1037 hashItem.len = hash->len;
1021 » } 1038 }
1022 » break; 1039 break;
1023 #ifndef NSS_DISABLE_ECC 1040 #ifndef NSS_DISABLE_ECC
1024 case ecKey: 1041 case ecKey:
1025 » doDerEncode = PR_TRUE; 1042 doDerEncode = PR_TRUE;
1026 » /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash. 1043 /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
1027 » * In that case, we use just the SHA1 part. */ 1044 * In that case, we use just the SHA1 part. */
1028 » if (hash->hashAlg == ssl_hash_none) { 1045 if (hash->hashAlg == ssl_hash_none) {
1029 » hashItem.data = hash->u.s.sha; 1046 hashItem.data = hash->u.s.sha;
1030 » hashItem.len = sizeof(hash->u.s.sha); 1047 hashItem.len = sizeof(hash->u.s.sha);
1031 » } else { 1048 } else {
1032 » hashItem.data = hash->u.raw; 1049 hashItem.data = hash->u.raw;
1033 » hashItem.len = hash->len; 1050 hashItem.len = hash->len;
1034 » } 1051 }
1035 » break; 1052 break;
1036 #endif /* NSS_DISABLE_ECC */ 1053 #endif /* NSS_DISABLE_ECC */
1037 default: 1054 default:
1038 » PORT_SetError(SEC_ERROR_INVALID_KEY); 1055 PORT_SetError(SEC_ERROR_INVALID_KEY);
1039 » goto done; 1056 goto done;
1040 } 1057 }
1041 PRINT_BUF(60, (NULL, "hash(es) to be signed", hashItem.data, hashItem.len)); 1058 PRINT_BUF(60, (NULL, "hash(es) to be signed", hashItem.data, hashItem.len));
1042 1059
1043 if (hash->hashAlg == ssl_hash_none) { 1060 if (hash->hashAlg == ssl_hash_none) {
1044 » signatureLen = PK11_SignatureLen(key); 1061 signatureLen = PK11_SignatureLen(key);
1045 » if (signatureLen <= 0) { 1062 if (signatureLen <= 0) {
1046 » PORT_SetError(SEC_ERROR_INVALID_KEY); 1063 PORT_SetError(SEC_ERROR_INVALID_KEY);
1047 » goto done; 1064 goto done;
1048 » } 1065 }
1049 1066
1050 » buf->len = (unsigned)signatureLen; 1067 buf->len = (unsigned)signatureLen;
1051 » buf->data = (unsigned char *)PORT_Alloc(signatureLen); 1068 buf->data = (unsigned char *)PORT_Alloc(signatureLen);
1052 » if (!buf->data) 1069 if (!buf->data)
1053 » goto done; /* error code was set. */ 1070 goto done; /* error code was set. */
1054 1071
1055 » rv = PK11_Sign(key, buf, &hashItem); 1072 rv = PK11_Sign(key, buf, &hashItem);
1056 } else { 1073 } else {
1057 SECOidTag hashOID = ssl3_TLSHashAlgorithmToOID(hash->hashAlg); 1074 SECOidTag hashOID = ssl3_TLSHashAlgorithmToOID(hash->hashAlg);
1058 rv = SGN_Digest(key, hashOID, buf, &hashItem); 1075 rv = SGN_Digest(key, hashOID, buf, &hashItem);
1059 } 1076 }
1060 if (rv != SECSuccess) { 1077 if (rv != SECSuccess) {
1061 » ssl_MapLowLevelError(SSL_ERROR_SIGN_HASHES_FAILURE); 1078 ssl_MapLowLevelError(SSL_ERROR_SIGN_HASHES_FAILURE);
1062 } else if (doDerEncode) { 1079 } else if (doDerEncode) {
1063 » SECItem derSig» = {siBuffer, NULL, 0}; 1080 SECItem derSig = { siBuffer, NULL, 0 };
1064 1081
1065 » /* This also works for an ECDSA signature */ 1082 /* This also works for an ECDSA signature */
1066 » rv = DSAU_EncodeDerSigWithLen(&derSig, buf, buf->len); 1083 rv = DSAU_EncodeDerSigWithLen(&derSig, buf, buf->len);
1067 » if (rv == SECSuccess) { 1084 if (rv == SECSuccess) {
1068 » PORT_Free(buf->data);» /* discard unencoded signature. */ 1085 PORT_Free(buf->data); /* discard unencoded signature. */
1069 » *buf = derSig;» » /* give caller encoded signature. */ 1086 *buf = derSig; /* give caller encoded signature. */
1070 » } else if (derSig.data) { 1087 } else if (derSig.data) {
1071 » PORT_Free(derSig.data); 1088 PORT_Free(derSig.data);
1072 » } 1089 }
1073 } 1090 }
1074 1091
1075 PRINT_BUF(60, (NULL, "signed hashes", (unsigned char*)buf->data, buf->len)); 1092 PRINT_BUF(60, (NULL, "signed hashes", (unsigned char *)buf->data, buf->len)) ;
1076 done: 1093 done:
1077 if (rv != SECSuccess && buf->data) { 1094 if (rv != SECSuccess && buf->data) {
1078 » PORT_Free(buf->data); 1095 PORT_Free(buf->data);
1079 » buf->data = NULL; 1096 buf->data = NULL;
1080 } 1097 }
1081 return rv; 1098 return rv;
1082 } 1099 }
1083 1100
1084 /* Called from ssl3_HandleServerKeyExchange, ssl3_HandleCertificateVerify */ 1101 /* Called from ssl3_HandleServerKeyExchange, ssl3_HandleCertificateVerify */
1085 SECStatus 1102 SECStatus
1086 ssl3_VerifySignedHashes(SSL3Hashes *hash, CERTCertificate *cert, 1103 ssl3_VerifySignedHashes(SSL3Hashes *hash, CERTCertificate *cert,
1087 SECItem *buf, PRBool isTLS, void *pwArg) 1104 SECItem *buf, PRBool isTLS, void *pwArg)
1088 { 1105 {
1089 SECKEYPublicKey * key; 1106 SECKEYPublicKey *key;
1090 SECItem * signature»= NULL; 1107 SECItem *signature = NULL;
1091 SECStatus rv; 1108 SECStatus rv;
1092 SECItem hashItem; 1109 SECItem hashItem;
1093 SECOidTag encAlg; 1110 SECOidTag encAlg;
1094 SECOidTag hashAlg; 1111 SECOidTag hashAlg;
1095
1096 1112
1097 PRINT_BUF(60, (NULL, "check signed hashes", 1113 PRINT_BUF(60, (NULL, "check signed hashes",
1098 buf->data, buf->len)); 1114 buf->data, buf->len));
1099 1115
1100 key = CERT_ExtractPublicKey(cert); 1116 key = CERT_ExtractPublicKey(cert);
1101 if (key == NULL) { 1117 if (key == NULL) {
1102 » ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); 1118 ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
1103 » return SECFailure; 1119 return SECFailure;
1104 } 1120 }
1105 1121
1106 hashAlg = ssl3_TLSHashAlgorithmToOID(hash->hashAlg); 1122 hashAlg = ssl3_TLSHashAlgorithmToOID(hash->hashAlg);
1107 switch (key->keyType) { 1123 switch (key->keyType) {
1108 case rsaKey: 1124 case rsaKey:
1109 » encAlg = SEC_OID_PKCS1_RSA_ENCRYPTION; 1125 encAlg = SEC_OID_PKCS1_RSA_ENCRYPTION;
1110 » hashItem.data = hash->u.raw; 1126 hashItem.data = hash->u.raw;
1111 » hashItem.len = hash->len; 1127 hashItem.len = hash->len;
1112 » break; 1128 break;
1113 case dsaKey: 1129 case dsaKey:
1114 » encAlg = SEC_OID_ANSIX9_DSA_SIGNATURE; 1130 encAlg = SEC_OID_ANSIX9_DSA_SIGNATURE;
1115 » /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash. 1131 /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
1116 » * In that case, we use just the SHA1 part. */ 1132 * In that case, we use just the SHA1 part. */
1117 » if (hash->hashAlg == ssl_hash_none) { 1133 if (hash->hashAlg == ssl_hash_none) {
1118 » hashItem.data = hash->u.s.sha; 1134 hashItem.data = hash->u.s.sha;
1119 » hashItem.len = sizeof(hash->u.s.sha); 1135 hashItem.len = sizeof(hash->u.s.sha);
1120 » } else { 1136 } else {
1121 » hashItem.data = hash->u.raw; 1137 hashItem.data = hash->u.raw;
1122 » hashItem.len = hash->len; 1138 hashItem.len = hash->len;
1123 » } 1139 }
1124 » /* Allow DER encoded DSA signatures in SSL 3.0 */ 1140 /* Allow DER encoded DSA signatures in SSL 3.0 */
1125 » if (isTLS || buf->len != SECKEY_SignatureLen(key)) { 1141 if (isTLS || buf->len != SECKEY_SignatureLen(key)) {
1126 » signature = DSAU_DecodeDerSigToLen(buf, SECKEY_SignatureLen(key)); 1142 signature = DSAU_DecodeDerSigToLen(buf, SECKEY_SignatureLen(key) );
1127 » if (!signature) { 1143 if (!signature) {
1128 » » PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); 1144 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
1129 » » return SECFailure; 1145 return SECFailure;
1130 » } 1146 }
1131 » buf = signature; 1147 buf = signature;
1132 » } 1148 }
1133 » break; 1149 break;
1134 1150
1135 #ifndef NSS_DISABLE_ECC 1151 #ifndef NSS_DISABLE_ECC
1136 case ecKey: 1152 case ecKey:
1137 » encAlg = SEC_OID_ANSIX962_EC_PUBLIC_KEY; 1153 encAlg = SEC_OID_ANSIX962_EC_PUBLIC_KEY;
1138 » /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash. 1154 /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
1139 » * In that case, we use just the SHA1 part. 1155 * In that case, we use just the SHA1 part.
1140 » * ECDSA signatures always encode the integers r and s using ASN.1 1156 * ECDSA signatures always encode the integers r and s using ASN.1
1141 » * (unlike DSA where ASN.1 encoding is used with TLS but not with 1157 * (unlike DSA where ASN.1 encoding is used with TLS but not with
1142 » * SSL3). So we can use VFY_VerifyDigestDirect for ECDSA. 1158 * SSL3). So we can use VFY_VerifyDigestDirect for ECDSA.
1143 » */ 1159 */
1144 » if (hash->hashAlg == ssl_hash_none) { 1160 if (hash->hashAlg == ssl_hash_none) {
1145 » hashAlg = SEC_OID_SHA1; 1161 hashAlg = SEC_OID_SHA1;
1146 » hashItem.data = hash->u.s.sha; 1162 hashItem.data = hash->u.s.sha;
1147 » hashItem.len = sizeof(hash->u.s.sha); 1163 hashItem.len = sizeof(hash->u.s.sha);
1148 » } else { 1164 } else {
1149 » hashItem.data = hash->u.raw; 1165 hashItem.data = hash->u.raw;
1150 » hashItem.len = hash->len; 1166 hashItem.len = hash->len;
1151 » } 1167 }
1152 » break; 1168 break;
1153 #endif /* NSS_DISABLE_ECC */ 1169 #endif /* NSS_DISABLE_ECC */
1154 1170
1155 default: 1171 default:
1156 » SECKEY_DestroyPublicKey(key); 1172 SECKEY_DestroyPublicKey(key);
1157 » PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); 1173 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
1158 » return SECFailure; 1174 return SECFailure;
1159 } 1175 }
1160 1176
1161 PRINT_BUF(60, (NULL, "hash(es) to be verified", 1177 PRINT_BUF(60, (NULL, "hash(es) to be verified",
1162 hashItem.data, hashItem.len)); 1178 hashItem.data, hashItem.len));
1163 1179
1164 if (hashAlg == SEC_OID_UNKNOWN || key->keyType == dsaKey) { 1180 if (hashAlg == SEC_OID_UNKNOWN || key->keyType == dsaKey) {
1165 » /* VFY_VerifyDigestDirect requires DSA signatures to be DER-encoded. 1181 /* VFY_VerifyDigestDirect requires DSA signatures to be DER-encoded.
1166 » * DSA signatures are DER-encoded in TLS but not in SSL3 and the code 1182 * DSA signatures are DER-encoded in TLS but not in SSL3 and the code
1167 » * above always removes the DER encoding of DSA signatures when 1183 * above always removes the DER encoding of DSA signatures when
1168 » * present. Thus DSA signatures are always verified with PK11_Verify. 1184 * present. Thus DSA signatures are always verified with PK11_Verify.
1169 » */ 1185 */
1170 » rv = PK11_Verify(key, buf, &hashItem, pwArg); 1186 rv = PK11_Verify(key, buf, &hashItem, pwArg);
1171 } else { 1187 } else {
1172 rv = VFY_VerifyDigestDirect(&hashItem, key, buf, encAlg, hashAlg, 1188 rv = VFY_VerifyDigestDirect(&hashItem, key, buf, encAlg, hashAlg,
1173 pwArg); 1189 pwArg);
1174 } 1190 }
1175 SECKEY_DestroyPublicKey(key); 1191 SECKEY_DestroyPublicKey(key);
1176 if (signature) { 1192 if (signature) {
1177 » SECITEM_FreeItem(signature, PR_TRUE); 1193 SECITEM_FreeItem(signature, PR_TRUE);
1178 } 1194 }
1179 if (rv != SECSuccess) { 1195 if (rv != SECSuccess) {
1180 » ssl_MapLowLevelError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); 1196 ssl_MapLowLevelError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
1181 } 1197 }
1182 return rv; 1198 return rv;
1183 } 1199 }
1184 1200
1185
1186 /* Caller must set hiLevel error code. */ 1201 /* Caller must set hiLevel error code. */
1187 /* Called from ssl3_ComputeExportRSAKeyHash 1202 /* Called from ssl3_ComputeExportRSAKeyHash
1188 * ssl3_ComputeDHKeyHash 1203 * ssl3_ComputeDHKeyHash
1189 * which are called from ssl3_HandleServerKeyExchange. 1204 * which are called from ssl3_HandleServerKeyExchange.
1190 * 1205 *
1191 * hashAlg: ssl_hash_none indicates the pre-1.2, MD5/SHA1 combination hash. 1206 * hashAlg: ssl_hash_none indicates the pre-1.2, MD5/SHA1 combination hash.
1192 */ 1207 */
1193 SECStatus 1208 SECStatus
1194 ssl3_ComputeCommonKeyHash(SSLHashType hashAlg, 1209 ssl3_ComputeCommonKeyHash(SSLHashType hashAlg,
1195 PRUint8 * hashBuf, unsigned int bufLen, 1210 PRUint8 *hashBuf, unsigned int bufLen,
1196 SSL3Hashes *hashes, PRBool bypassPKCS11) 1211 SSL3Hashes *hashes, PRBool bypassPKCS11)
1197 { 1212 {
1198 SECStatus rv; 1213 SECStatus rv;
1199 SECOidTag hashOID; 1214 SECOidTag hashOID;
1200 1215
1201 #ifndef NO_PKCS11_BYPASS 1216 #ifndef NO_PKCS11_BYPASS
1202 if (bypassPKCS11) { 1217 if (bypassPKCS11) {
1203 if (hashAlg == ssl_hash_none) { 1218 if (hashAlg == ssl_hash_none) {
1204 MD5_HashBuf (hashes->u.s.md5, hashBuf, bufLen); 1219 MD5_HashBuf(hashes->u.s.md5, hashBuf, bufLen);
1205 SHA1_HashBuf(hashes->u.s.sha, hashBuf, bufLen); 1220 SHA1_HashBuf(hashes->u.s.sha, hashBuf, bufLen);
1206 hashes->len = MD5_LENGTH + SHA1_LENGTH; 1221 hashes->len = MD5_LENGTH + SHA1_LENGTH;
1207 } else if (hashAlg == ssl_hash_sha1) { 1222 } else if (hashAlg == ssl_hash_sha1) {
1208 SHA1_HashBuf(hashes->u.raw, hashBuf, bufLen); 1223 SHA1_HashBuf(hashes->u.raw, hashBuf, bufLen);
1209 hashes->len = SHA1_LENGTH; 1224 hashes->len = SHA1_LENGTH;
1210 } else if (hashAlg == ssl_hash_sha256) { 1225 } else if (hashAlg == ssl_hash_sha256) {
1211 SHA256_HashBuf(hashes->u.raw, hashBuf, bufLen); 1226 SHA256_HashBuf(hashes->u.raw, hashBuf, bufLen);
1212 hashes->len = SHA256_LENGTH; 1227 hashes->len = SHA256_LENGTH;
1213 } else if (hashAlg == ssl_hash_sha384) { 1228 } else if (hashAlg == ssl_hash_sha384) {
1214 SHA384_HashBuf(hashes->u.raw, hashBuf, bufLen); 1229 SHA384_HashBuf(hashes->u.raw, hashBuf, bufLen);
(...skipping 31 matching lines...) Expand 10 before | Expand all | Expand 10 after
1246 if (rv != SECSuccess) { 1261 if (rv != SECSuccess) {
1247 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); 1262 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
1248 return rv; 1263 return rv;
1249 } 1264 }
1250 } 1265 }
1251 } 1266 }
1252 hashes->hashAlg = hashAlg; 1267 hashes->hashAlg = hashAlg;
1253 return SECSuccess; 1268 return SECSuccess;
1254 } 1269 }
1255 1270
1256 /* Caller must set hiLevel error code. 1271 /* Caller must set hiLevel error code.
1257 ** Called from ssl3_SendServerKeyExchange and 1272 ** Called from ssl3_SendServerKeyExchange and
1258 ** ssl3_HandleServerKeyExchange. 1273 ** ssl3_HandleServerKeyExchange.
1259 */ 1274 */
1260 static SECStatus 1275 static SECStatus
1261 ssl3_ComputeExportRSAKeyHash(SSLHashType hashAlg, 1276 ssl3_ComputeExportRSAKeyHash(SSLHashType hashAlg,
1262 SECItem modulus, SECItem publicExponent, 1277 SECItem modulus, SECItem publicExponent,
1263 SSL3Random *client_rand, SSL3Random *server_rand, 1278 SSL3Random *client_rand, SSL3Random *server_rand,
1264 SSL3Hashes *hashes, PRBool bypassPKCS11) 1279 SSL3Hashes *hashes, PRBool bypassPKCS11)
1265 { 1280 {
1266 PRUint8 * hashBuf; 1281 PRUint8 *hashBuf;
1267 PRUint8 * pBuf; 1282 PRUint8 *pBuf;
1268 SECStatus rv » » = SECSuccess; 1283 SECStatus rv = SECSuccess;
1269 unsigned int bufLen; 1284 unsigned int bufLen;
1270 PRUint8 buf[2*SSL3_RANDOM_LENGTH + 2 + 4096/8 + 2 + 4096/8]; 1285 PRUint8 buf[2 * SSL3_RANDOM_LENGTH + 2 + 4096 / 8 + 2 + 4096 / 8];
1271 1286
1272 bufLen = 2*SSL3_RANDOM_LENGTH + 2 + modulus.len + 2 + publicExponent.len; 1287 bufLen = 2 * SSL3_RANDOM_LENGTH + 2 + modulus.len + 2 + publicExponent.len;
1273 if (bufLen <= sizeof buf) { 1288 if (bufLen <= sizeof buf) {
1274 » hashBuf = buf; 1289 hashBuf = buf;
1275 } else { 1290 } else {
1276 » hashBuf = PORT_Alloc(bufLen); 1291 hashBuf = PORT_Alloc(bufLen);
1277 » if (!hashBuf) { 1292 if (!hashBuf) {
1278 » return SECFailure; 1293 return SECFailure;
1279 » } 1294 }
1280 } 1295 }
1281 1296
1282 memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH); 1297 memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH);
1283 » pBuf = hashBuf + SSL3_RANDOM_LENGTH; 1298 pBuf = hashBuf + SSL3_RANDOM_LENGTH;
1284 memcpy(pBuf, server_rand, SSL3_RANDOM_LENGTH); 1299 memcpy(pBuf, server_rand, SSL3_RANDOM_LENGTH);
1285 » pBuf += SSL3_RANDOM_LENGTH; 1300 pBuf += SSL3_RANDOM_LENGTH;
1286 pBuf[0] = (PRUint8)(modulus.len >> 8); 1301 pBuf[0] = (PRUint8)(modulus.len >> 8);
1287 pBuf[1] = (PRUint8)(modulus.len); 1302 pBuf[1] = (PRUint8)(modulus.len);
1288 » pBuf += 2; 1303 pBuf += 2;
1289 memcpy(pBuf, modulus.data, modulus.len); 1304 memcpy(pBuf, modulus.data, modulus.len);
1290 » pBuf += modulus.len; 1305 pBuf += modulus.len;
1291 pBuf[0] = (PRUint8)(publicExponent.len >> 8); 1306 pBuf[0] = (PRUint8)(publicExponent.len >> 8);
1292 pBuf[1] = (PRUint8)(publicExponent.len); 1307 pBuf[1] = (PRUint8)(publicExponent.len);
1293 » pBuf += 2; 1308 pBuf += 2;
1294 memcpy(pBuf, publicExponent.data, publicExponent.len); 1309 memcpy(pBuf, publicExponent.data, publicExponent.len);
1295 » pBuf += publicExponent.len; 1310 pBuf += publicExponent.len;
1296 PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen); 1311 PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen);
1297 1312
1298 rv = ssl3_ComputeCommonKeyHash(hashAlg, hashBuf, bufLen, hashes, 1313 rv = ssl3_ComputeCommonKeyHash(hashAlg, hashBuf, bufLen, hashes,
1299 » » » » bypassPKCS11); 1314 bypassPKCS11);
1300 1315
1301 PRINT_BUF(95, (NULL, "RSAkey hash: ", hashBuf, bufLen)); 1316 PRINT_BUF(95, (NULL, "RSAkey hash: ", hashBuf, bufLen));
1302 if (hashAlg == ssl_hash_none) { 1317 if (hashAlg == ssl_hash_none) {
1303 » PRINT_BUF(95, (NULL, "RSAkey hash: MD5 result", 1318 PRINT_BUF(95, (NULL, "RSAkey hash: MD5 result",
1304 » » hashes->u.s.md5, MD5_LENGTH)); 1319 hashes->u.s.md5, MD5_LENGTH));
1305 » PRINT_BUF(95, (NULL, "RSAkey hash: SHA1 result", 1320 PRINT_BUF(95, (NULL, "RSAkey hash: SHA1 result",
1306 » » hashes->u.s.sha, SHA1_LENGTH)); 1321 hashes->u.s.sha, SHA1_LENGTH));
1307 } else { 1322 } else {
1308 » PRINT_BUF(95, (NULL, "RSAkey hash: result", 1323 PRINT_BUF(95, (NULL, "RSAkey hash: result",
1309 » » hashes->u.raw, hashes->len)); 1324 hashes->u.raw, hashes->len));
1310 } 1325 }
1311 1326
1312 if (hashBuf != buf && hashBuf != NULL) 1327 if (hashBuf != buf && hashBuf != NULL)
1313 » PORT_Free(hashBuf); 1328 PORT_Free(hashBuf);
1314 return rv; 1329 return rv;
1315 } 1330 }
1316 1331
1317 /* Caller must set hiLevel error code. */ 1332 /* Caller must set hiLevel error code. */
1318 /* Called from ssl3_HandleServerKeyExchange. */ 1333 /* Called from ssl3_HandleServerKeyExchange. */
1319 static SECStatus 1334 static SECStatus
1320 ssl3_ComputeDHKeyHash(SSLHashType hashAlg, 1335 ssl3_ComputeDHKeyHash(SSLHashType hashAlg,
1321 SECItem dh_p, SECItem dh_g, SECItem dh_Ys, 1336 SECItem dh_p, SECItem dh_g, SECItem dh_Ys,
1322 SSL3Random *client_rand, SSL3Random *server_rand, 1337 SSL3Random *client_rand, SSL3Random *server_rand,
1323 SSL3Hashes *hashes, PRBool bypassPKCS11) 1338 SSL3Hashes *hashes, PRBool bypassPKCS11)
1324 { 1339 {
1325 PRUint8 * hashBuf; 1340 PRUint8 *hashBuf;
1326 PRUint8 * pBuf; 1341 PRUint8 *pBuf;
1327 SECStatus rv » » = SECSuccess; 1342 SECStatus rv = SECSuccess;
1328 unsigned int bufLen; 1343 unsigned int bufLen;
1329 PRUint8 buf[2*SSL3_RANDOM_LENGTH + 2 + 4096/8 + 2 + 4096/8]; 1344 PRUint8 buf[2 * SSL3_RANDOM_LENGTH + 2 + 4096 / 8 + 2 + 4096 / 8];
1330 1345
1331 bufLen = 2*SSL3_RANDOM_LENGTH + 2 + dh_p.len + 2 + dh_g.len + 2 + dh_Ys.len; 1346 bufLen = 2 * SSL3_RANDOM_LENGTH + 2 + dh_p.len + 2 + dh_g.len + 2 + dh_Ys.le n;
1332 if (bufLen <= sizeof buf) { 1347 if (bufLen <= sizeof buf) {
1333 » hashBuf = buf; 1348 hashBuf = buf;
1334 } else { 1349 } else {
1335 » hashBuf = PORT_Alloc(bufLen); 1350 hashBuf = PORT_Alloc(bufLen);
1336 » if (!hashBuf) { 1351 if (!hashBuf) {
1337 » return SECFailure; 1352 return SECFailure;
1338 » } 1353 }
1339 } 1354 }
1340 1355
1341 memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH); 1356 memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH);
1342 » pBuf = hashBuf + SSL3_RANDOM_LENGTH; 1357 pBuf = hashBuf + SSL3_RANDOM_LENGTH;
1343 memcpy(pBuf, server_rand, SSL3_RANDOM_LENGTH); 1358 memcpy(pBuf, server_rand, SSL3_RANDOM_LENGTH);
1344 » pBuf += SSL3_RANDOM_LENGTH; 1359 pBuf += SSL3_RANDOM_LENGTH;
1345 pBuf[0] = (PRUint8)(dh_p.len >> 8); 1360 pBuf[0] = (PRUint8)(dh_p.len >> 8);
1346 pBuf[1] = (PRUint8)(dh_p.len); 1361 pBuf[1] = (PRUint8)(dh_p.len);
1347 » pBuf += 2; 1362 pBuf += 2;
1348 memcpy(pBuf, dh_p.data, dh_p.len); 1363 memcpy(pBuf, dh_p.data, dh_p.len);
1349 » pBuf += dh_p.len; 1364 pBuf += dh_p.len;
1350 pBuf[0] = (PRUint8)(dh_g.len >> 8); 1365 pBuf[0] = (PRUint8)(dh_g.len >> 8);
1351 pBuf[1] = (PRUint8)(dh_g.len); 1366 pBuf[1] = (PRUint8)(dh_g.len);
1352 » pBuf += 2; 1367 pBuf += 2;
1353 memcpy(pBuf, dh_g.data, dh_g.len); 1368 memcpy(pBuf, dh_g.data, dh_g.len);
1354 » pBuf += dh_g.len; 1369 pBuf += dh_g.len;
1355 pBuf[0] = (PRUint8)(dh_Ys.len >> 8); 1370 pBuf[0] = (PRUint8)(dh_Ys.len >> 8);
1356 pBuf[1] = (PRUint8)(dh_Ys.len); 1371 pBuf[1] = (PRUint8)(dh_Ys.len);
1357 » pBuf += 2; 1372 pBuf += 2;
1358 memcpy(pBuf, dh_Ys.data, dh_Ys.len); 1373 memcpy(pBuf, dh_Ys.data, dh_Ys.len);
1359 » pBuf += dh_Ys.len; 1374 pBuf += dh_Ys.len;
1360 PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen); 1375 PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen);
1361 1376
1362 rv = ssl3_ComputeCommonKeyHash(hashAlg, hashBuf, bufLen, hashes, 1377 rv = ssl3_ComputeCommonKeyHash(hashAlg, hashBuf, bufLen, hashes,
1363 » » » » bypassPKCS11); 1378 bypassPKCS11);
1364 1379
1365 PRINT_BUF(95, (NULL, "DHkey hash: ", hashBuf, bufLen)); 1380 PRINT_BUF(95, (NULL, "DHkey hash: ", hashBuf, bufLen));
1366 if (hashAlg == ssl_hash_none) { 1381 if (hashAlg == ssl_hash_none) {
1367 » PRINT_BUF(95, (NULL, "DHkey hash: MD5 result", 1382 PRINT_BUF(95, (NULL, "DHkey hash: MD5 result",
1368 » » hashes->u.s.md5, MD5_LENGTH)); 1383 hashes->u.s.md5, MD5_LENGTH));
1369 » PRINT_BUF(95, (NULL, "DHkey hash: SHA1 result", 1384 PRINT_BUF(95, (NULL, "DHkey hash: SHA1 result",
1370 » » hashes->u.s.sha, SHA1_LENGTH)); 1385 hashes->u.s.sha, SHA1_LENGTH));
1371 } else { 1386 } else {
1372 » PRINT_BUF(95, (NULL, "DHkey hash: result", 1387 PRINT_BUF(95, (NULL, "DHkey hash: result",
1373 » » hashes->u.raw, hashes->len)); 1388 hashes->u.raw, hashes->len));
1374 } 1389 }
1375 1390
1376 if (hashBuf != buf && hashBuf != NULL) 1391 if (hashBuf != buf && hashBuf != NULL)
1377 » PORT_Free(hashBuf); 1392 PORT_Free(hashBuf);
1378 return rv; 1393 return rv;
1379 } 1394 }
1380 1395
1381 static void 1396 void
1382 ssl3_BumpSequenceNumber(SSL3SequenceNumber *num) 1397 ssl3_BumpSequenceNumber(SSL3SequenceNumber *num)
1383 { 1398 {
1384 num->low++; 1399 num->low++;
1385 if (num->low == 0) 1400 if (num->low == 0)
1386 » num->high++; 1401 num->high++;
1387 } 1402 }
1388 1403
1389 /* Called twice, only from ssl3_DestroyCipherSpec (immediately below). */ 1404 /* Called twice, only from ssl3_DestroyCipherSpec (immediately below). */
1390 static void 1405 static void
1391 ssl3_CleanupKeyMaterial(ssl3KeyMaterial *mat) 1406 ssl3_CleanupKeyMaterial(ssl3KeyMaterial *mat)
1392 { 1407 {
1393 if (mat->write_key != NULL) { 1408 if (mat->write_key != NULL) {
1394 » PK11_FreeSymKey(mat->write_key); 1409 PK11_FreeSymKey(mat->write_key);
1395 » mat->write_key = NULL; 1410 mat->write_key = NULL;
1396 } 1411 }
1397 if (mat->write_mac_key != NULL) { 1412 if (mat->write_mac_key != NULL) {
1398 » PK11_FreeSymKey(mat->write_mac_key); 1413 PK11_FreeSymKey(mat->write_mac_key);
1399 » mat->write_mac_key = NULL; 1414 mat->write_mac_key = NULL;
1400 } 1415 }
1401 if (mat->write_mac_context != NULL) { 1416 if (mat->write_mac_context != NULL) {
1402 » PK11_DestroyContext(mat->write_mac_context, PR_TRUE); 1417 PK11_DestroyContext(mat->write_mac_context, PR_TRUE);
1403 » mat->write_mac_context = NULL; 1418 mat->write_mac_context = NULL;
1404 } 1419 }
1405 } 1420 }
1406 1421
1407 /* Called from ssl3_SendChangeCipherSpecs() and 1422 /* Called from ssl3_SendChangeCipherSpecs() and
1408 **» ssl3_HandleChangeCipherSpecs() 1423 ** ssl3_HandleChangeCipherSpecs()
1409 ** ssl3_DestroySSL3Info 1424 ** ssl3_DestroySSL3Info
1410 ** Caller must hold SpecWriteLock. 1425 ** Caller must hold SpecWriteLock.
1411 */ 1426 */
1412 void 1427 void
1413 ssl3_DestroyCipherSpec(ssl3CipherSpec *spec, PRBool freeSrvName) 1428 ssl3_DestroyCipherSpec(ssl3CipherSpec *spec, PRBool freeSrvName)
1414 { 1429 {
1415 PRBool freeit = (PRBool)(!spec->bypassCiphers); 1430 PRBool freeit = (PRBool)(!spec->bypassCiphers);
1416 /* PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); Don't have ss! * / 1431 /* PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); Don't have s s! */
1417 if (spec->destroy) { 1432 if (spec->destroy) {
1418 » spec->destroy(spec->encodeContext, freeit); 1433 spec->destroy(spec->encodeContext, freeit);
1419 » spec->destroy(spec->decodeContext, freeit); 1434 spec->destroy(spec->decodeContext, freeit);
1420 » spec->encodeContext = NULL; /* paranoia */ 1435 spec->encodeContext = NULL; /* paranoia */
1421 » spec->decodeContext = NULL; 1436 spec->decodeContext = NULL;
1422 } 1437 }
1423 if (spec->destroyCompressContext && spec->compressContext) { 1438 if (spec->destroyCompressContext && spec->compressContext) {
1424 » spec->destroyCompressContext(spec->compressContext, 1); 1439 spec->destroyCompressContext(spec->compressContext, 1);
1425 » spec->compressContext = NULL; 1440 spec->compressContext = NULL;
1426 } 1441 }
1427 if (spec->destroyDecompressContext && spec->decompressContext) { 1442 if (spec->destroyDecompressContext && spec->decompressContext) {
1428 » spec->destroyDecompressContext(spec->decompressContext, 1); 1443 spec->destroyDecompressContext(spec->decompressContext, 1);
1429 » spec->decompressContext = NULL; 1444 spec->decompressContext = NULL;
1430 } 1445 }
1431 if (freeSrvName && spec->srvVirtName.data) { 1446 if (freeSrvName && spec->srvVirtName.data) {
1432 SECITEM_FreeItem(&spec->srvVirtName, PR_FALSE); 1447 SECITEM_FreeItem(&spec->srvVirtName, PR_FALSE);
1433 } 1448 }
1434 if (spec->master_secret != NULL) { 1449 if (spec->master_secret != NULL) {
1435 » PK11_FreeSymKey(spec->master_secret); 1450 PK11_FreeSymKey(spec->master_secret);
1436 » spec->master_secret = NULL; 1451 spec->master_secret = NULL;
1437 } 1452 }
1438 spec->msItem.data = NULL; 1453 spec->msItem.data = NULL;
1439 spec->msItem.len = 0; 1454 spec->msItem.len = 0;
1440 ssl3_CleanupKeyMaterial(&spec->client); 1455 ssl3_CleanupKeyMaterial(&spec->client);
1441 ssl3_CleanupKeyMaterial(&spec->server); 1456 ssl3_CleanupKeyMaterial(&spec->server);
1442 spec->bypassCiphers = PR_FALSE; 1457 spec->bypassCiphers = PR_FALSE;
1443 spec->destroy=NULL; 1458 spec->destroy = NULL;
1444 spec->destroyCompressContext = NULL; 1459 spec->destroyCompressContext = NULL;
1445 spec->destroyDecompressContext = NULL; 1460 spec->destroyDecompressContext = NULL;
1446 } 1461 }
1447 1462
1448 /* Fill in the pending cipher spec with info from the selected ciphersuite. 1463 /* Fill in the pending cipher spec with info from the selected ciphersuite.
1449 ** This is as much initialization as we can do without having key material. 1464 ** This is as much initialization as we can do without having key material.
1450 ** Called from ssl3_HandleServerHello(), ssl3_SendServerHello() 1465 ** Called from ssl3_HandleServerHello(), ssl3_SendServerHello()
1451 ** Caller must hold the ssl3 handshake lock. 1466 ** Caller must hold the ssl3 handshake lock.
1452 ** Acquires & releases SpecWriteLock. 1467 ** Acquires & releases SpecWriteLock.
1453 */ 1468 */
1454 static SECStatus 1469 SECStatus
1455 ssl3_SetupPendingCipherSpec(sslSocket *ss) 1470 ssl3_SetupPendingCipherSpec(sslSocket *ss)
1456 { 1471 {
1457 ssl3CipherSpec * pwSpec; 1472 ssl3CipherSpec *pwSpec;
1458 ssl3CipherSpec * cwSpec; 1473 ssl3CipherSpec *cwSpec;
1459 ssl3CipherSuite suite = ss->ssl3.hs.cipher_suite; 1474 ssl3CipherSuite suite = ss->ssl3.hs.cipher_suite;
1460 SSL3MACAlgorithm mac; 1475 SSL3MACAlgorithm mac;
1461 SSL3BulkCipher cipher; 1476 SSL3BulkCipher cipher;
1462 SSL3KeyExchangeAlgorithm kea; 1477 SSL3KeyExchangeAlgorithm kea;
1463 const ssl3CipherSuiteDef *suite_def; 1478 const ssl3CipherSuiteDef *suite_def;
1464 PRBool isTLS; 1479 PRBool isTLS;
1465 1480
1466 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 1481 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1467 1482
1468 ssl_GetSpecWriteLock(ss); /*******************************/ 1483 ssl_GetSpecWriteLock(ss); /*******************************/
1469 1484
1470 pwSpec = ss->ssl3.pwSpec; 1485 pwSpec = ss->ssl3.pwSpec;
1471 PORT_Assert(pwSpec == ss->ssl3.prSpec); 1486 PORT_Assert(pwSpec == ss->ssl3.prSpec);
1472 1487
1473 /* This hack provides maximal interoperability with SSL 3 servers. */ 1488 /* This hack provides maximal interoperability with SSL 3 servers. */
1474 cwSpec = ss->ssl3.cwSpec; 1489 cwSpec = ss->ssl3.cwSpec;
1475 if (cwSpec->mac_def->mac == mac_null) { 1490 if (cwSpec->mac_def->mac == mac_null) {
1476 » /* SSL records are not being MACed. */ 1491 /* SSL records are not being MACed. */
1477 » cwSpec->version = ss->version; 1492 cwSpec->version = ss->version;
1478 } 1493 }
1479 1494
1480 pwSpec->version = ss->version; 1495 pwSpec->version = ss->version;
1481 isTLS = (PRBool)(pwSpec->version > SSL_LIBRARY_VERSION_3_0); 1496 isTLS = (PRBool)(pwSpec->version > SSL_LIBRARY_VERSION_3_0);
1482 1497
1483 SSL_TRC(3, ("%d: SSL3[%d]: Set XXX Pending Cipher Suite to 0x%04x", 1498 SSL_TRC(3, ("%d: SSL3[%d]: Set XXX Pending Cipher Suite to 0x%04x",
1484 » » SSL_GETPID(), ss->fd, suite)); 1499 SSL_GETPID(), ss->fd, suite));
1485 1500
1486 suite_def = ssl_LookupCipherSuiteDef(suite); 1501 suite_def = ssl_LookupCipherSuiteDef(suite);
1487 if (suite_def == NULL) { 1502 if (suite_def == NULL) {
1488 » ssl_ReleaseSpecWriteLock(ss); 1503 ssl_ReleaseSpecWriteLock(ss);
1489 » return SECFailure;» /* error code set by ssl_LookupCipherSuiteDef */ 1504 return SECFailure; /* error code set by ssl_LookupCipherSuiteDef */
1490 } 1505 }
1491 1506
1492 if (IS_DTLS(ss)) { 1507 if (IS_DTLS(ss)) {
1493 » /* Double-check that we did not pick an RC4 suite */ 1508 /* Double-check that we did not pick an RC4 suite */
1494 » PORT_Assert((suite_def->bulk_cipher_alg != cipher_rc4) && 1509 PORT_Assert((suite_def->bulk_cipher_alg != cipher_rc4) &&
1495 » » (suite_def->bulk_cipher_alg != cipher_rc4_40) && 1510 (suite_def->bulk_cipher_alg != cipher_rc4_40) &&
1496 » » (suite_def->bulk_cipher_alg != cipher_rc4_56)); 1511 (suite_def->bulk_cipher_alg != cipher_rc4_56));
1497 } 1512 }
1498 1513
1499 cipher = suite_def->bulk_cipher_alg; 1514 cipher = suite_def->bulk_cipher_alg;
1500 kea = suite_def->key_exchange_alg; 1515 kea = suite_def->key_exchange_alg;
1501 mac = suite_def->mac_alg; 1516 mac = suite_def->mac_alg;
1502 if (mac <= ssl_mac_sha && mac != ssl_mac_null && isTLS) 1517 if (mac <= ssl_mac_sha && mac != ssl_mac_null && isTLS)
1503 » mac += 2; 1518 mac += 2;
1504 1519
1505 ss->ssl3.hs.suite_def = suite_def; 1520 ss->ssl3.hs.suite_def = suite_def;
1506 ss->ssl3.hs.kea_def = &kea_defs[kea]; 1521 ss->ssl3.hs.kea_def = &kea_defs[kea];
1507 PORT_Assert(ss->ssl3.hs.kea_def->kea == kea); 1522 PORT_Assert(ss->ssl3.hs.kea_def->kea == kea);
1508 1523
1509 pwSpec->cipher_def = &bulk_cipher_defs[cipher]; 1524 pwSpec->cipher_def = &bulk_cipher_defs[cipher];
1510 PORT_Assert(pwSpec->cipher_def->cipher == cipher); 1525 PORT_Assert(pwSpec->cipher_def->cipher == cipher);
1511 1526
1512 pwSpec->mac_def = &mac_defs[mac]; 1527 pwSpec->mac_def = &mac_defs[mac];
1513 PORT_Assert(pwSpec->mac_def->mac == mac); 1528 PORT_Assert(pwSpec->mac_def->mac == mac);
1514 1529
1515 ss->sec.keyBits = pwSpec->cipher_def->key_size * BPB; 1530 ss->sec.keyBits = pwSpec->cipher_def->key_size * BPB;
1516 ss->sec.secretKeyBits = pwSpec->cipher_def->secret_key_size * BPB; 1531 ss->sec.secretKeyBits = pwSpec->cipher_def->secret_key_size * BPB;
1517 ss->sec.cipherType = cipher; 1532 ss->sec.cipherType = cipher;
1518 1533
1519 pwSpec->encodeContext = NULL; 1534 pwSpec->encodeContext = NULL;
1520 pwSpec->decodeContext = NULL; 1535 pwSpec->decodeContext = NULL;
1521 1536
1522 pwSpec->mac_size = pwSpec->mac_def->mac_size; 1537 pwSpec->mac_size = pwSpec->mac_def->mac_size;
1523 1538
1524 pwSpec->compression_method = ss->ssl3.hs.compression; 1539 pwSpec->compression_method = ss->ssl3.hs.compression;
1525 pwSpec->compressContext = NULL; 1540 pwSpec->compressContext = NULL;
1526 pwSpec->decompressContext = NULL; 1541 pwSpec->decompressContext = NULL;
1527 1542
1528 ssl_ReleaseSpecWriteLock(ss); /*******************************/ 1543 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
1544 PORT_Assert(ss->ssl3.hs.kea_def->ephemeral);
1545 PORT_Assert(pwSpec->cipher_def->type == type_aead);
1546 }
1547 ssl_ReleaseSpecWriteLock(ss); /*******************************/
1529 return SECSuccess; 1548 return SECSuccess;
1530 } 1549 }
1531 1550
1532 #ifdef NSS_ENABLE_ZLIB 1551 #ifdef NSS_SSL_ENABLE_ZLIB
1533 #define SSL3_DEFLATE_CONTEXT_SIZE sizeof(z_stream) 1552 #define SSL3_DEFLATE_CONTEXT_SIZE sizeof(z_stream)
1534 1553
1535 static SECStatus 1554 static SECStatus
1536 ssl3_MapZlibError(int zlib_error) 1555 ssl3_MapZlibError(int zlib_error)
1537 { 1556 {
1538 switch (zlib_error) { 1557 switch (zlib_error) {
1539 case Z_OK: 1558 case Z_OK:
1540 return SECSuccess; 1559 return SECSuccess;
1541 default: 1560 default:
1542 return SECFailure; 1561 return SECFailure;
1543 } 1562 }
1544 } 1563 }
1545 1564
1546 static SECStatus 1565 static SECStatus
1547 ssl3_DeflateInit(void *void_context) 1566 ssl3_DeflateInit(void *void_context)
1548 { 1567 {
1549 z_stream *context = void_context; 1568 z_stream *context = void_context;
1550 context->zalloc = NULL; 1569 context->zalloc = NULL;
1551 context->zfree = NULL; 1570 context->zfree = NULL;
1552 context->opaque = NULL; 1571 context->opaque = NULL;
(...skipping 18 matching lines...) Expand all
1571 ssl3_DeflateCompress(void *void_context, unsigned char *out, int *out_len, 1590 ssl3_DeflateCompress(void *void_context, unsigned char *out, int *out_len,
1572 int maxout, const unsigned char *in, int inlen) 1591 int maxout, const unsigned char *in, int inlen)
1573 { 1592 {
1574 z_stream *context = void_context; 1593 z_stream *context = void_context;
1575 1594
1576 if (!inlen) { 1595 if (!inlen) {
1577 *out_len = 0; 1596 *out_len = 0;
1578 return SECSuccess; 1597 return SECSuccess;
1579 } 1598 }
1580 1599
1581 context->next_in = (unsigned char*) in; 1600 context->next_in = (unsigned char *)in;
1582 context->avail_in = inlen; 1601 context->avail_in = inlen;
1583 context->next_out = out; 1602 context->next_out = out;
1584 context->avail_out = maxout; 1603 context->avail_out = maxout;
1585 if (deflate(context, Z_SYNC_FLUSH) != Z_OK) { 1604 if (deflate(context, Z_SYNC_FLUSH) != Z_OK) {
1586 return SECFailure; 1605 return SECFailure;
1587 } 1606 }
1588 if (context->avail_out == 0) { 1607 if (context->avail_out == 0) {
1589 /* We ran out of space! */ 1608 /* We ran out of space! */
1590 SSL_TRC(3, ("%d: SSL3[%d] Ran out of buffer while compressing", 1609 SSL_TRC(3, ("%d: SSL3[%d] Ran out of buffer while compressing",
1591 SSL_GETPID())); 1610 SSL_GETPID()));
1592 return SECFailure; 1611 return SECFailure;
1593 } 1612 }
1594 1613
1595 *out_len = maxout - context->avail_out; 1614 *out_len = maxout - context->avail_out;
1596 return SECSuccess; 1615 return SECSuccess;
1597 } 1616 }
1598 1617
1599 static SECStatus 1618 static SECStatus
1600 ssl3_DeflateDecompress(void *void_context, unsigned char *out, int *out_len, 1619 ssl3_DeflateDecompress(void *void_context, unsigned char *out, int *out_len,
1601 int maxout, const unsigned char *in, int inlen) 1620 int maxout, const unsigned char *in, int inlen)
1602 { 1621 {
1603 z_stream *context = void_context; 1622 z_stream *context = void_context;
1604 1623
1605 if (!inlen) { 1624 if (!inlen) {
1606 *out_len = 0; 1625 *out_len = 0;
1607 return SECSuccess; 1626 return SECSuccess;
1608 } 1627 }
1609 1628
1610 context->next_in = (unsigned char*) in; 1629 context->next_in = (unsigned char *)in;
1611 context->avail_in = inlen; 1630 context->avail_in = inlen;
1612 context->next_out = out; 1631 context->next_out = out;
1613 context->avail_out = maxout; 1632 context->avail_out = maxout;
1614 if (inflate(context, Z_SYNC_FLUSH) != Z_OK) { 1633 if (inflate(context, Z_SYNC_FLUSH) != Z_OK) {
1615 PORT_SetError(SSL_ERROR_DECOMPRESSION_FAILURE); 1634 PORT_SetError(SSL_ERROR_DECOMPRESSION_FAILURE);
1616 return SECFailure; 1635 return SECFailure;
1617 } 1636 }
1618 1637
1619 *out_len = maxout - context->avail_out; 1638 *out_len = maxout - context->avail_out;
1620 return SECSuccess; 1639 return SECSuccess;
1621 } 1640 }
1622 1641
1623 static SECStatus 1642 static SECStatus
1624 ssl3_DestroyCompressContext(void *void_context, PRBool unused) 1643 ssl3_DestroyCompressContext(void *void_context, PRBool unused)
1625 { 1644 {
1626 deflateEnd(void_context); 1645 deflateEnd(void_context);
1627 PORT_Free(void_context); 1646 PORT_Free(void_context);
1628 return SECSuccess; 1647 return SECSuccess;
1629 } 1648 }
1630 1649
1631 static SECStatus 1650 static SECStatus
1632 ssl3_DestroyDecompressContext(void *void_context, PRBool unused) 1651 ssl3_DestroyDecompressContext(void *void_context, PRBool unused)
1633 { 1652 {
1634 inflateEnd(void_context); 1653 inflateEnd(void_context);
1635 PORT_Free(void_context); 1654 PORT_Free(void_context);
1636 return SECSuccess; 1655 return SECSuccess;
1637 } 1656 }
1638 1657
1639 #endif /* NSS_ENABLE_ZLIB */ 1658 #endif /* NSS_SSL_ENABLE_ZLIB */
1640 1659
1641 /* Initialize the compression functions and contexts for the given 1660 /* Initialize the compression functions and contexts for the given
1642 * CipherSpec. */ 1661 * CipherSpec. */
1643 static SECStatus 1662 static SECStatus
1644 ssl3_InitCompressionContext(ssl3CipherSpec *pwSpec) 1663 ssl3_InitCompressionContext(ssl3CipherSpec *pwSpec)
1645 { 1664 {
1646 /* Setup the compression functions */ 1665 /* Setup the compression functions */
1647 switch (pwSpec->compression_method) { 1666 switch (pwSpec->compression_method) {
1648 case ssl_compression_null: 1667 case ssl_compression_null:
1649 » pwSpec->compressor = NULL; 1668 pwSpec->compressor = NULL;
1650 » pwSpec->decompressor = NULL; 1669 pwSpec->decompressor = NULL;
1651 » pwSpec->compressContext = NULL; 1670 pwSpec->compressContext = NULL;
1652 » pwSpec->decompressContext = NULL; 1671 pwSpec->decompressContext = NULL;
1653 » pwSpec->destroyCompressContext = NULL; 1672 pwSpec->destroyCompressContext = NULL;
1654 » pwSpec->destroyDecompressContext = NULL; 1673 pwSpec->destroyDecompressContext = NULL;
1655 » break; 1674 break;
1656 #ifdef NSS_ENABLE_ZLIB 1675 #ifdef NSS_SSL_ENABLE_ZLIB
1657 case ssl_compression_deflate: 1676 case ssl_compression_deflate:
1658 » pwSpec->compressor = ssl3_DeflateCompress; 1677 pwSpec->compressor = ssl3_DeflateCompress;
1659 » pwSpec->decompressor = ssl3_DeflateDecompress; 1678 pwSpec->decompressor = ssl3_DeflateDecompress;
1660 » pwSpec->compressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE); 1679 pwSpec->compressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE);
1661 » pwSpec->decompressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE); 1680 pwSpec->decompressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE);
1662 » pwSpec->destroyCompressContext = ssl3_DestroyCompressContext; 1681 pwSpec->destroyCompressContext = ssl3_DestroyCompressContext;
1663 » pwSpec->destroyDecompressContext = ssl3_DestroyDecompressContext; 1682 pwSpec->destroyDecompressContext = ssl3_DestroyDecompressContext;
1664 » ssl3_DeflateInit(pwSpec->compressContext); 1683 ssl3_DeflateInit(pwSpec->compressContext);
1665 » ssl3_InflateInit(pwSpec->decompressContext); 1684 ssl3_InflateInit(pwSpec->decompressContext);
1666 » break; 1685 break;
1667 #endif /* NSS_ENABLE_ZLIB */ 1686 #endif /* NSS_SSL_ENABLE_ZLIB */
1668 default: 1687 default:
1669 » PORT_Assert(0); 1688 PORT_Assert(0);
1670 » PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 1689 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1671 » return SECFailure; 1690 return SECFailure;
1672 } 1691 }
1673 1692
1674 return SECSuccess; 1693 return SECSuccess;
1675 } 1694 }
1676 1695
1677 #ifndef NO_PKCS11_BYPASS 1696 #ifndef NO_PKCS11_BYPASS
1678 /* Initialize encryption contexts for pending spec. 1697 /* Initialize encryption contexts for pending spec.
1679 * MAC contexts are set up when computing the mac, not here. 1698 * MAC contexts are set up when computing the mac, not here.
1680 * Master Secret already is derived in spec->msItem 1699 * Master Secret already is derived in spec->msItem
1681 * Caller holds Spec write lock. 1700 * Caller holds Spec write lock.
1682 */ 1701 */
1683 static SECStatus 1702 static SECStatus
1684 ssl3_InitPendingContextsBypass(sslSocket *ss) 1703 ssl3_InitPendingContextsBypass(sslSocket *ss)
1685 { 1704 {
1686 ssl3CipherSpec * pwSpec; 1705 ssl3CipherSpec *pwSpec;
1687 const ssl3BulkCipherDef *cipher_def; 1706 const ssl3BulkCipherDef *cipher_def;
1688 void * serverContext = NULL; 1707 void *serverContext = NULL;
1689 void * clientContext = NULL; 1708 void *clientContext = NULL;
1690 BLapiInitContextFunc initFn = (BLapiInitContextFunc)NULL; 1709 BLapiInitContextFunc initFn = (BLapiInitContextFunc)NULL;
1691 int mode = 0; 1710 int mode = 0;
1692 unsigned int optArg1 = 0; 1711 unsigned int optArg1 = 0;
1693 unsigned int optArg2 = 0; 1712 unsigned int optArg2 = 0;
1694 PRBool server_encrypts = ss->sec.isServer; 1713 PRBool server_encrypts = ss->sec.isServer;
1695 SSLCipherAlgorithm calg; 1714 SSLCipherAlgorithm calg;
1696 SECStatus rv; 1715 SECStatus rv;
1697 1716
1698 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 1717 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1699 PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); 1718 PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
1700 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); 1719 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
1701 1720
1702 pwSpec = ss->ssl3.pwSpec; 1721 pwSpec = ss->ssl3.pwSpec;
1703 cipher_def = pwSpec->cipher_def; 1722 cipher_def = pwSpec->cipher_def;
1704 1723
1705 calg = cipher_def->calg; 1724 calg = cipher_def->calg;
1706 1725
1707 if (calg == ssl_calg_aes_gcm) { 1726 if (calg == ssl_calg_aes_gcm) {
1708 » pwSpec->encode = NULL; 1727 pwSpec->encode = NULL;
1709 » pwSpec->decode = NULL; 1728 pwSpec->decode = NULL;
1710 » pwSpec->destroy = NULL; 1729 pwSpec->destroy = NULL;
1711 » pwSpec->encodeContext = NULL; 1730 pwSpec->encodeContext = NULL;
1712 » pwSpec->decodeContext = NULL; 1731 pwSpec->decodeContext = NULL;
1713 » pwSpec->aead = ssl3_AESGCMBypass; 1732 pwSpec->aead = ssl3_AESGCMBypass;
1714 » ssl3_InitCompressionContext(pwSpec); 1733 ssl3_InitCompressionContext(pwSpec);
1715 » return SECSuccess; 1734 return SECSuccess;
1716 } 1735 }
1717 1736
1718 serverContext = pwSpec->server.cipher_context; 1737 serverContext = pwSpec->server.cipher_context;
1719 clientContext = pwSpec->client.cipher_context; 1738 clientContext = pwSpec->client.cipher_context;
1720 1739
1721 switch (calg) { 1740 switch (calg) {
1722 case ssl_calg_null: 1741 case ssl_calg_null:
1723 » pwSpec->encode = Null_Cipher; 1742 pwSpec->encode = Null_Cipher;
1724 » pwSpec->decode = Null_Cipher; 1743 pwSpec->decode = Null_Cipher;
1725 pwSpec->destroy = NULL; 1744 pwSpec->destroy = NULL;
1726 » goto success; 1745 goto success;
1727 1746
1728 case ssl_calg_rc4: 1747 case ssl_calg_rc4:
1729 » initFn = (BLapiInitContextFunc)RC4_InitContext; 1748 initFn = (BLapiInitContextFunc)RC4_InitContext;
1730 » pwSpec->encode = (SSLCipher) RC4_Encrypt; 1749 pwSpec->encode = (SSLCipher)RC4_Encrypt;
1731 » pwSpec->decode = (SSLCipher) RC4_Decrypt; 1750 pwSpec->decode = (SSLCipher)RC4_Decrypt;
1732 » pwSpec->destroy = (SSLDestroy) RC4_DestroyContext; 1751 pwSpec->destroy = (SSLDestroy)RC4_DestroyContext;
1733 » break; 1752 break;
1734 case ssl_calg_rc2: 1753 case ssl_calg_rc2:
1735 » initFn = (BLapiInitContextFunc)RC2_InitContext; 1754 initFn = (BLapiInitContextFunc)RC2_InitContext;
1736 » mode = NSS_RC2_CBC; 1755 mode = NSS_RC2_CBC;
1737 » optArg1 = cipher_def->key_size; 1756 optArg1 = cipher_def->key_size;
1738 » pwSpec->encode = (SSLCipher) RC2_Encrypt; 1757 pwSpec->encode = (SSLCipher)RC2_Encrypt;
1739 » pwSpec->decode = (SSLCipher) RC2_Decrypt; 1758 pwSpec->decode = (SSLCipher)RC2_Decrypt;
1740 » pwSpec->destroy = (SSLDestroy) RC2_DestroyContext; 1759 pwSpec->destroy = (SSLDestroy)RC2_DestroyContext;
1741 » break; 1760 break;
1742 case ssl_calg_des: 1761 case ssl_calg_des:
1743 » initFn = (BLapiInitContextFunc)DES_InitContext; 1762 initFn = (BLapiInitContextFunc)DES_InitContext;
1744 » mode = NSS_DES_CBC; 1763 mode = NSS_DES_CBC;
1745 » optArg1 = server_encrypts; 1764 optArg1 = server_encrypts;
1746 » pwSpec->encode = (SSLCipher) DES_Encrypt; 1765 pwSpec->encode = (SSLCipher)DES_Encrypt;
1747 » pwSpec->decode = (SSLCipher) DES_Decrypt; 1766 pwSpec->decode = (SSLCipher)DES_Decrypt;
1748 » pwSpec->destroy = (SSLDestroy) DES_DestroyContext; 1767 pwSpec->destroy = (SSLDestroy)DES_DestroyContext;
1749 » break; 1768 break;
1750 case ssl_calg_3des: 1769 case ssl_calg_3des:
1751 » initFn = (BLapiInitContextFunc)DES_InitContext; 1770 initFn = (BLapiInitContextFunc)DES_InitContext;
1752 » mode = NSS_DES_EDE3_CBC; 1771 mode = NSS_DES_EDE3_CBC;
1753 » optArg1 = server_encrypts; 1772 optArg1 = server_encrypts;
1754 » pwSpec->encode = (SSLCipher) DES_Encrypt; 1773 pwSpec->encode = (SSLCipher)DES_Encrypt;
1755 » pwSpec->decode = (SSLCipher) DES_Decrypt; 1774 pwSpec->decode = (SSLCipher)DES_Decrypt;
1756 » pwSpec->destroy = (SSLDestroy) DES_DestroyContext; 1775 pwSpec->destroy = (SSLDestroy)DES_DestroyContext;
1757 » break; 1776 break;
1758 case ssl_calg_aes: 1777 case ssl_calg_aes:
1759 » initFn = (BLapiInitContextFunc)AES_InitContext; 1778 initFn = (BLapiInitContextFunc)AES_InitContext;
1760 » mode = NSS_AES_CBC; 1779 mode = NSS_AES_CBC;
1761 » optArg1 = server_encrypts; 1780 optArg1 = server_encrypts;
1762 » optArg2 = AES_BLOCK_SIZE; 1781 optArg2 = AES_BLOCK_SIZE;
1763 » pwSpec->encode = (SSLCipher) AES_Encrypt; 1782 pwSpec->encode = (SSLCipher)AES_Encrypt;
1764 » pwSpec->decode = (SSLCipher) AES_Decrypt; 1783 pwSpec->decode = (SSLCipher)AES_Decrypt;
1765 » pwSpec->destroy = (SSLDestroy) AES_DestroyContext; 1784 pwSpec->destroy = (SSLDestroy)AES_DestroyContext;
1766 » break; 1785 break;
1767 1786
1768 case ssl_calg_camellia: 1787 case ssl_calg_camellia:
1769 » initFn = (BLapiInitContextFunc)Camellia_InitContext; 1788 initFn = (BLapiInitContextFunc)Camellia_InitContext;
1770 » mode = NSS_CAMELLIA_CBC; 1789 mode = NSS_CAMELLIA_CBC;
1771 » optArg1 = server_encrypts; 1790 optArg1 = server_encrypts;
1772 » optArg2 = CAMELLIA_BLOCK_SIZE; 1791 optArg2 = CAMELLIA_BLOCK_SIZE;
1773 » pwSpec->encode = (SSLCipher) Camellia_Encrypt; 1792 pwSpec->encode = (SSLCipher)Camellia_Encrypt;
1774 » pwSpec->decode = (SSLCipher) Camellia_Decrypt; 1793 pwSpec->decode = (SSLCipher)Camellia_Decrypt;
1775 » pwSpec->destroy = (SSLDestroy) Camellia_DestroyContext; 1794 pwSpec->destroy = (SSLDestroy)Camellia_DestroyContext;
1776 » break; 1795 break;
1777 1796
1778 case ssl_calg_seed: 1797 case ssl_calg_seed:
1779 » initFn = (BLapiInitContextFunc)SEED_InitContext; 1798 initFn = (BLapiInitContextFunc)SEED_InitContext;
1780 » mode = NSS_SEED_CBC; 1799 mode = NSS_SEED_CBC;
1781 » optArg1 = server_encrypts; 1800 optArg1 = server_encrypts;
1782 » optArg2 = SEED_BLOCK_SIZE; 1801 optArg2 = SEED_BLOCK_SIZE;
1783 » pwSpec->encode = (SSLCipher) SEED_Encrypt; 1802 pwSpec->encode = (SSLCipher)SEED_Encrypt;
1784 » pwSpec->decode = (SSLCipher) SEED_Decrypt; 1803 pwSpec->decode = (SSLCipher)SEED_Decrypt;
1785 » pwSpec->destroy = (SSLDestroy) SEED_DestroyContext; 1804 pwSpec->destroy = (SSLDestroy)SEED_DestroyContext;
1786 » break; 1805 break;
1787 1806
1788 case ssl_calg_idea: 1807 case ssl_calg_idea:
1789 case ssl_calg_fortezza : 1808 case ssl_calg_fortezza:
1790 default: 1809 default:
1791 » PORT_Assert(0); 1810 PORT_Assert(0);
1792 » PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 1811 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1793 » goto bail_out; 1812 goto bail_out;
1794 } 1813 }
1795 rv = (*initFn)(serverContext, 1814 rv = (*initFn)(serverContext,
1796 » » pwSpec->server.write_key_item.data, 1815 pwSpec->server.write_key_item.data,
1797 » » pwSpec->server.write_key_item.len, 1816 pwSpec->server.write_key_item.len,
1798 » » pwSpec->server.write_iv_item.data, 1817 pwSpec->server.write_iv_item.data,
1799 » » mode, optArg1, optArg2); 1818 mode, optArg1, optArg2);
1800 if (rv != SECSuccess) { 1819 if (rv != SECSuccess) {
1801 » PORT_Assert(0); 1820 PORT_Assert(0);
1802 » PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 1821 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1803 » goto bail_out; 1822 goto bail_out;
1804 } 1823 }
1805 1824
1806 switch (calg) { 1825 switch (calg) {
1807 case ssl_calg_des: 1826 case ssl_calg_des:
1808 case ssl_calg_3des: 1827 case ssl_calg_3des:
1809 case ssl_calg_aes: 1828 case ssl_calg_aes:
1810 case ssl_calg_camellia: 1829 case ssl_calg_camellia:
1811 case ssl_calg_seed: 1830 case ssl_calg_seed:
1812 » /* For block ciphers, if the server is encrypting, then the client 1831 /* For block ciphers, if the server is encrypting, then the client
1813 » * is decrypting, and vice versa. 1832 * is decrypting, and vice versa.
1814 » */ 1833 */
1815 optArg1 = !optArg1; 1834 optArg1 = !optArg1;
1816 break; 1835 break;
1817 /* kill warnings. */ 1836 /* kill warnings. */
1818 case ssl_calg_null: 1837 case ssl_calg_null:
1819 case ssl_calg_rc4: 1838 case ssl_calg_rc4:
1820 case ssl_calg_rc2: 1839 case ssl_calg_rc2:
1821 case ssl_calg_idea: 1840 case ssl_calg_idea:
1822 case ssl_calg_fortezza: 1841 case ssl_calg_fortezza:
1823 case ssl_calg_aes_gcm: 1842 case ssl_calg_aes_gcm:
1824 break; 1843 case ssl_calg_chacha20:
1844 break;
1825 } 1845 }
1826 1846
1827 rv = (*initFn)(clientContext, 1847 rv = (*initFn)(clientContext,
1828 » » pwSpec->client.write_key_item.data, 1848 pwSpec->client.write_key_item.data,
1829 » » pwSpec->client.write_key_item.len, 1849 pwSpec->client.write_key_item.len,
1830 » » pwSpec->client.write_iv_item.data, 1850 pwSpec->client.write_iv_item.data,
1831 » » mode, optArg1, optArg2); 1851 mode, optArg1, optArg2);
1832 if (rv != SECSuccess) { 1852 if (rv != SECSuccess) {
1833 » PORT_Assert(0); 1853 PORT_Assert(0);
1834 » PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 1854 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1835 » goto bail_out; 1855 goto bail_out;
1836 } 1856 }
1837 1857
1838 pwSpec->encodeContext = (ss->sec.isServer) ? serverContext : clientContext; 1858 pwSpec->encodeContext = (ss->sec.isServer) ? serverContext : clientContext;
1839 pwSpec->decodeContext = (ss->sec.isServer) ? clientContext : serverContext; 1859 pwSpec->decodeContext = (ss->sec.isServer) ? clientContext : serverContext;
1840 1860
1841 ssl3_InitCompressionContext(pwSpec); 1861 ssl3_InitCompressionContext(pwSpec);
1842 1862
1843 success: 1863 success:
1844 return SECSuccess; 1864 return SECSuccess;
1845 1865
1846 bail_out: 1866 bail_out:
1847 return SECFailure; 1867 return SECFailure;
1848 } 1868 }
1849 #endif 1869 #endif
1850 1870
1851 /* This function should probably be moved to pk11wrap and be named 1871 /* This function should probably be moved to pk11wrap and be named
1852 * PK11_ParamFromIVAndEffectiveKeyBits 1872 * PK11_ParamFromIVAndEffectiveKeyBits
1853 */ 1873 */
1854 static SECItem * 1874 static SECItem *
1855 ssl3_ParamFromIV(CK_MECHANISM_TYPE mtype, SECItem *iv, CK_ULONG ulEffectiveBits) 1875 ssl3_ParamFromIV(CK_MECHANISM_TYPE mtype, SECItem *iv, CK_ULONG ulEffectiveBits)
1856 { 1876 {
1857 SECItem * param = PK11_ParamFromIV(mtype, iv); 1877 SECItem *param = PK11_ParamFromIV(mtype, iv);
1858 if (param && param->data && param->len >= sizeof(CK_RC2_PARAMS)) { 1878 if (param && param->data && param->len >= sizeof(CK_RC2_PARAMS)) {
1859 » switch (mtype) { 1879 switch (mtype) {
1860 » case CKM_RC2_KEY_GEN: 1880 case CKM_RC2_KEY_GEN:
1861 » case CKM_RC2_ECB: 1881 case CKM_RC2_ECB:
1862 » case CKM_RC2_CBC: 1882 case CKM_RC2_CBC:
1863 » case CKM_RC2_MAC: 1883 case CKM_RC2_MAC:
1864 » case CKM_RC2_MAC_GENERAL: 1884 case CKM_RC2_MAC_GENERAL:
1865 » case CKM_RC2_CBC_PAD: 1885 case CKM_RC2_CBC_PAD:
1866 » *(CK_RC2_PARAMS *)param->data = ulEffectiveBits; 1886 *(CK_RC2_PARAMS *)param->data = ulEffectiveBits;
1867 » default: break; 1887 default:
1868 » } 1888 break;
1889 }
1869 } 1890 }
1870 return param; 1891 return param;
1871 } 1892 }
1872 1893
1873 /* ssl3_BuildRecordPseudoHeader writes the SSL/TLS pseudo-header (the data 1894 /* ssl3_BuildRecordPseudoHeader writes the SSL/TLS pseudo-header (the data
1874 * which is included in the MAC or AEAD additional data) to |out| and returns 1895 * which is included in the MAC or AEAD additional data) to |out| and returns
1875 * its length. See https://tools.ietf.org/html/rfc5246#section-6.2.3.3 for the 1896 * its length. See https://tools.ietf.org/html/rfc5246#section-6.2.3.3 for the
1876 * definition of the AEAD additional data. 1897 * definition of the AEAD additional data.
1877 * 1898 *
1878 * TLS pseudo-header includes the record's version field, SSL's doesn't. Which 1899 * TLS pseudo-header includes the record's version field, SSL's doesn't. Which
1879 * pseudo-header defintiion to use should be decided based on the version of 1900 * pseudo-header defintiion to use should be decided based on the version of
1880 * the protocol that was negotiated when the cipher spec became current, NOT 1901 * the protocol that was negotiated when the cipher spec became current, NOT
1881 * based on the version value in the record itself, and the decision is passed 1902 * based on the version value in the record itself, and the decision is passed
1882 * to this function as the |includesVersion| argument. But, the |version| 1903 * to this function as the |includesVersion| argument. But, the |version|
1883 * argument should be the record's version value. 1904 * argument should be the record's version value.
1884 */ 1905 */
1885 static unsigned int 1906 static unsigned int
1886 ssl3_BuildRecordPseudoHeader(unsigned char *out, 1907 ssl3_BuildRecordPseudoHeader(unsigned char *out,
1887 » » » SSL3SequenceNumber seq_num, 1908 SSL3SequenceNumber seq_num,
1888 » » » SSL3ContentType type, 1909 SSL3ContentType type,
1889 » » » PRBool includesVersion, 1910 PRBool includesVersion,
1890 » » » SSL3ProtocolVersion version, 1911 SSL3ProtocolVersion version,
1891 » » » PRBool isDTLS, 1912 PRBool isDTLS,
1892 » » » int length) 1913 int length)
1893 { 1914 {
1894 out[0] = (unsigned char)(seq_num.high >> 24); 1915 out[0] = (unsigned char)(seq_num.high >> 24);
1895 out[1] = (unsigned char)(seq_num.high >> 16); 1916 out[1] = (unsigned char)(seq_num.high >> 16);
1896 out[2] = (unsigned char)(seq_num.high >> 8); 1917 out[2] = (unsigned char)(seq_num.high >> 8);
1897 out[3] = (unsigned char)(seq_num.high >> 0); 1918 out[3] = (unsigned char)(seq_num.high >> 0);
1898 out[4] = (unsigned char)(seq_num.low >> 24); 1919 out[4] = (unsigned char)(seq_num.low >> 24);
1899 out[5] = (unsigned char)(seq_num.low >> 16); 1920 out[5] = (unsigned char)(seq_num.low >> 16);
1900 out[6] = (unsigned char)(seq_num.low >> 8); 1921 out[6] = (unsigned char)(seq_num.low >> 8);
1901 out[7] = (unsigned char)(seq_num.low >> 0); 1922 out[7] = (unsigned char)(seq_num.low >> 0);
1902 out[8] = type; 1923 out[8] = type;
1903 1924
1904 /* SSL3 MAC doesn't include the record's version field. */ 1925 /* SSL3 MAC doesn't include the record's version field. */
1905 if (!includesVersion) { 1926 if (!includesVersion) {
1906 » out[9] = MSB(length); 1927 out[9] = MSB(length);
1907 » out[10] = LSB(length); 1928 out[10] = LSB(length);
1908 » return 11; 1929 return 11;
1909 } 1930 }
1910 1931
1911 /* TLS MAC and AEAD additional data include version. */ 1932 /* TLS MAC and AEAD additional data include version. */
1912 if (isDTLS) { 1933 if (isDTLS) {
1913 » SSL3ProtocolVersion dtls_version; 1934 SSL3ProtocolVersion dtls_version;
1914 1935
1915 » dtls_version = dtls_TLSVersionToDTLSVersion(version); 1936 dtls_version = dtls_TLSVersionToDTLSVersion(version);
1916 » out[9] = MSB(dtls_version); 1937 out[9] = MSB(dtls_version);
1917 » out[10] = LSB(dtls_version); 1938 out[10] = LSB(dtls_version);
1918 } else { 1939 } else {
1919 » out[9] = MSB(version); 1940 out[9] = MSB(version);
1920 » out[10] = LSB(version); 1941 out[10] = LSB(version);
1921 } 1942 }
1922 out[11] = MSB(length); 1943 out[11] = MSB(length);
1923 out[12] = LSB(length); 1944 out[12] = LSB(length);
1924 return 13; 1945 return 13;
1925 } 1946 }
1926 1947
1927 typedef SECStatus (*PK11CryptFcn)(
1928 PK11SymKey *symKey, CK_MECHANISM_TYPE mechanism, SECItem *param,
1929 unsigned char *out, unsigned int *outLen, unsigned int maxLen,
1930 const unsigned char *in, unsigned int inLen);
1931
1932 static PK11CryptFcn pk11_encrypt = NULL;
1933 static PK11CryptFcn pk11_decrypt = NULL;
1934
1935 static PRCallOnceType resolvePK11CryptOnce;
1936
1937 static PRStatus
1938 ssl3_ResolvePK11CryptFunctions(void)
1939 {
1940 #ifdef LINUX
1941 /* On Linux we use the system NSS libraries. Look up the PK11_Encrypt and
1942 * PK11_Decrypt functions at run time. */
1943 pk11_encrypt = (PK11CryptFcn)dlsym(RTLD_DEFAULT, "PK11_Encrypt");
1944 pk11_decrypt = (PK11CryptFcn)dlsym(RTLD_DEFAULT, "PK11_Decrypt");
1945 return PR_SUCCESS;
1946 #else
1947 /* On other platforms we use our own copy of NSS. PK11_Encrypt and
1948 * PK11_Decrypt are known to be available. */
1949 pk11_encrypt = PK11_Encrypt;
1950 pk11_decrypt = PK11_Decrypt;
1951 return PR_SUCCESS;
1952 #endif
1953 }
1954
1955 /*
1956 * In NSS 3.15, PK11_Encrypt and PK11_Decrypt were added to provide access
1957 * to the AES GCM implementation in the NSS softoken. So the presence of
1958 * these two functions implies the NSS version supports AES GCM.
1959 */
1960 static PRBool
1961 ssl3_HasGCMSupport(void)
1962 {
1963 (void)PR_CallOnce(&resolvePK11CryptOnce, ssl3_ResolvePK11CryptFunctions);
1964 return pk11_encrypt != NULL;
1965 }
1966
1967 /* On this socket, disable the GCM cipher suites */
1968 SECStatus
1969 ssl3_DisableGCMSuites(sslSocket * ss)
1970 {
1971 unsigned int i;
1972
1973 for (i = 0; i < PR_ARRAY_SIZE(cipher_suite_defs); i++) {
1974 const ssl3CipherSuiteDef *cipher_def = &cipher_suite_defs[i];
1975 if (cipher_def->bulk_cipher_alg == cipher_aes_128_gcm) {
1976 SECStatus rv = ssl3_CipherPrefSet(ss, cipher_def->cipher_suite,
1977 PR_FALSE);
1978 PORT_Assert(rv == SECSuccess); /* else is coding error */
1979 }
1980 }
1981 return SECSuccess;
1982 }
1983
1984 static SECStatus 1948 static SECStatus
1985 ssl3_AESGCM(ssl3KeyMaterial *keys, 1949 ssl3_AESGCM(ssl3KeyMaterial *keys,
1986 » PRBool doDecrypt, 1950 PRBool doDecrypt,
1987 » unsigned char *out, 1951 unsigned char *out,
1988 » int *outlen, 1952 int *outlen,
1989 » int maxout, 1953 int maxout,
1990 » const unsigned char *in, 1954 const unsigned char *in,
1991 » int inlen, 1955 int inlen,
1992 » const unsigned char *additionalData, 1956 const unsigned char *additionalData,
1993 » int additionalDataLen) 1957 int additionalDataLen)
1994 { 1958 {
1995 SECItem param; 1959 SECItem param;
1996 SECStatus rv = SECFailure; 1960 SECStatus rv = SECFailure;
1997 unsigned char nonce[12]; 1961 unsigned char nonce[12];
1998 unsigned int uOutLen; 1962 unsigned int uOutLen;
1999 CK_GCM_PARAMS gcmParams; 1963 CK_GCM_PARAMS gcmParams;
2000 1964
2001 static const int tagSize = 16; 1965 const int tagSize = bulk_cipher_defs[cipher_aes_128_gcm].tag_size;
2002 static const int explicitNonceLen = 8; 1966 const int explicitNonceLen =
1967 bulk_cipher_defs[cipher_aes_128_gcm].explicit_nonce_size;
2003 1968
2004 /* See https://tools.ietf.org/html/rfc5288#section-3 for details of how the 1969 /* See https://tools.ietf.org/html/rfc5288#section-3 for details of how the
2005 * nonce is formed. */ 1970 * nonce is formed. */
2006 memcpy(nonce, keys->write_iv, 4); 1971 memcpy(nonce, keys->write_iv, 4);
2007 if (doDecrypt) { 1972 if (doDecrypt) {
2008 » memcpy(nonce + 4, in, explicitNonceLen); 1973 memcpy(nonce + 4, in, explicitNonceLen);
2009 » in += explicitNonceLen; 1974 in += explicitNonceLen;
2010 » inlen -= explicitNonceLen; 1975 inlen -= explicitNonceLen;
2011 » *outlen = 0; 1976 *outlen = 0;
2012 } else { 1977 } else {
2013 » if (maxout < explicitNonceLen) { 1978 if (maxout < explicitNonceLen) {
2014 » PORT_SetError(SEC_ERROR_INPUT_LEN); 1979 PORT_SetError(SEC_ERROR_INPUT_LEN);
2015 » return SECFailure; 1980 return SECFailure;
2016 } 1981 }
2017 » /* Use the 64-bit sequence number as the explicit nonce. */ 1982 /* Use the 64-bit sequence number as the explicit nonce. */
2018 » memcpy(nonce + 4, additionalData, explicitNonceLen); 1983 memcpy(nonce + 4, additionalData, explicitNonceLen);
2019 » memcpy(out, additionalData, explicitNonceLen); 1984 memcpy(out, additionalData, explicitNonceLen);
2020 » out += explicitNonceLen; 1985 out += explicitNonceLen;
2021 » maxout -= explicitNonceLen; 1986 maxout -= explicitNonceLen;
2022 » *outlen = explicitNonceLen; 1987 *outlen = explicitNonceLen;
2023 } 1988 }
2024 1989
2025 param.type = siBuffer; 1990 param.type = siBuffer;
2026 param.data = (unsigned char *) &gcmParams; 1991 param.data = (unsigned char *)&gcmParams;
2027 param.len = sizeof(gcmParams); 1992 param.len = sizeof(gcmParams);
2028 gcmParams.pIv = nonce; 1993 gcmParams.pIv = nonce;
2029 gcmParams.ulIvLen = sizeof(nonce); 1994 gcmParams.ulIvLen = sizeof(nonce);
2030 gcmParams.pAAD = (unsigned char *)additionalData; /* const cast */ 1995 gcmParams.pAAD = (unsigned char *)additionalData; /* const cast */
2031 gcmParams.ulAADLen = additionalDataLen; 1996 gcmParams.ulAADLen = additionalDataLen;
2032 gcmParams.ulTagBits = tagSize * 8; 1997 gcmParams.ulTagBits = tagSize * 8;
2033 1998
2034 if (doDecrypt) { 1999 if (doDecrypt) {
2035 » rv = pk11_decrypt(keys->write_key, CKM_AES_GCM, &param, out, &uOutLen, 2000 rv = PK11_Decrypt(keys->write_key, CKM_AES_GCM, &param, out, &uOutLen,
2036 » » » maxout, in, inlen); 2001 maxout, in, inlen);
2037 } else { 2002 } else {
2038 » rv = pk11_encrypt(keys->write_key, CKM_AES_GCM, &param, out, &uOutLen, 2003 rv = PK11_Encrypt(keys->write_key, CKM_AES_GCM, &param, out, &uOutLen,
2039 » » » maxout, in, inlen); 2004 maxout, in, inlen);
2040 } 2005 }
2041 *outlen += (int) uOutLen; 2006 *outlen += (int)uOutLen;
2042 2007
2043 return rv; 2008 return rv;
2044 } 2009 }
2045 2010
2046 #ifndef NO_PKCS11_BYPASS 2011 #ifndef NO_PKCS11_BYPASS
2047 static SECStatus 2012 static SECStatus
2048 ssl3_AESGCMBypass(ssl3KeyMaterial *keys, 2013 ssl3_AESGCMBypass(ssl3KeyMaterial *keys,
2049 » » PRBool doDecrypt, 2014 PRBool doDecrypt,
2050 » » unsigned char *out, 2015 unsigned char *out,
2051 » » int *outlen, 2016 int *outlen,
2052 » » int maxout, 2017 int maxout,
2053 » » const unsigned char *in, 2018 const unsigned char *in,
2054 » » int inlen, 2019 int inlen,
2055 » » const unsigned char *additionalData, 2020 const unsigned char *additionalData,
2056 » » int additionalDataLen) 2021 int additionalDataLen)
2057 { 2022 {
2058 SECStatus rv = SECFailure; 2023 SECStatus rv = SECFailure;
2059 unsigned char nonce[12]; 2024 unsigned char nonce[12];
2060 unsigned int uOutLen; 2025 unsigned int uOutLen;
2061 AESContext *cx; 2026 AESContext *cx;
2062 CK_GCM_PARAMS gcmParams; 2027 CK_GCM_PARAMS gcmParams;
2063 2028
2064 static const int tagSize = 16; 2029 const int tagSize = bulk_cipher_defs[cipher_aes_128_gcm].tag_size;
2065 static const int explicitNonceLen = 8; 2030 const int explicitNonceLen =
2031 bulk_cipher_defs[cipher_aes_128_gcm].explicit_nonce_size;
2066 2032
2067 /* See https://tools.ietf.org/html/rfc5288#section-3 for details of how the 2033 /* See https://tools.ietf.org/html/rfc5288#section-3 for details of how the
2068 * nonce is formed. */ 2034 * nonce is formed. */
2069 PORT_Assert(keys->write_iv_item.len == 4); 2035 PORT_Assert(keys->write_iv_item.len == 4);
2070 if (keys->write_iv_item.len != 4) { 2036 if (keys->write_iv_item.len != 4) {
2071 » PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 2037 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2072 » return SECFailure; 2038 return SECFailure;
2073 } 2039 }
2074 memcpy(nonce, keys->write_iv_item.data, 4); 2040 memcpy(nonce, keys->write_iv_item.data, 4);
2075 if (doDecrypt) { 2041 if (doDecrypt) {
2076 » memcpy(nonce + 4, in, explicitNonceLen); 2042 memcpy(nonce + 4, in, explicitNonceLen);
2077 » in += explicitNonceLen; 2043 in += explicitNonceLen;
2078 » inlen -= explicitNonceLen; 2044 inlen -= explicitNonceLen;
2079 » *outlen = 0; 2045 *outlen = 0;
2080 } else { 2046 } else {
2081 » if (maxout < explicitNonceLen) { 2047 if (maxout < explicitNonceLen) {
2082 » PORT_SetError(SEC_ERROR_INPUT_LEN); 2048 PORT_SetError(SEC_ERROR_INPUT_LEN);
2083 » return SECFailure; 2049 return SECFailure;
2084 } 2050 }
2085 » /* Use the 64-bit sequence number as the explicit nonce. */ 2051 /* Use the 64-bit sequence number as the explicit nonce. */
2086 » memcpy(nonce + 4, additionalData, explicitNonceLen); 2052 memcpy(nonce + 4, additionalData, explicitNonceLen);
2087 » memcpy(out, additionalData, explicitNonceLen); 2053 memcpy(out, additionalData, explicitNonceLen);
2088 » out += explicitNonceLen; 2054 out += explicitNonceLen;
2089 » maxout -= explicitNonceLen; 2055 maxout -= explicitNonceLen;
2090 » *outlen = explicitNonceLen; 2056 *outlen = explicitNonceLen;
2091 } 2057 }
2092 2058
2093 gcmParams.pIv = nonce; 2059 gcmParams.pIv = nonce;
2094 gcmParams.ulIvLen = sizeof(nonce); 2060 gcmParams.ulIvLen = sizeof(nonce);
2095 gcmParams.pAAD = (unsigned char *)additionalData; /* const cast */ 2061 gcmParams.pAAD = (unsigned char *)additionalData; /* const cast */
2096 gcmParams.ulAADLen = additionalDataLen; 2062 gcmParams.ulAADLen = additionalDataLen;
2097 gcmParams.ulTagBits = tagSize * 8; 2063 gcmParams.ulTagBits = tagSize * 8;
2098 2064
2099 cx = (AESContext *)keys->cipher_context; 2065 cx = (AESContext *)keys->cipher_context;
2100 rv = AES_InitContext(cx, keys->write_key_item.data, 2066 rv = AES_InitContext(cx, keys->write_key_item.data,
2101 » » » keys->write_key_item.len, 2067 keys->write_key_item.len,
2102 » » » (unsigned char *)&gcmParams, NSS_AES_GCM, !doDecrypt, 2068 (unsigned char *)&gcmParams, NSS_AES_GCM, !doDecrypt,
2103 » » » AES_BLOCK_SIZE); 2069 AES_BLOCK_SIZE);
2104 if (rv != SECSuccess) { 2070 if (rv != SECSuccess) {
2105 » return rv; 2071 return rv;
2106 } 2072 }
2107 if (doDecrypt) { 2073 if (doDecrypt) {
2108 » rv = AES_Decrypt(cx, out, &uOutLen, maxout, in, inlen); 2074 rv = AES_Decrypt(cx, out, &uOutLen, maxout, in, inlen);
2109 } else { 2075 } else {
2110 » rv = AES_Encrypt(cx, out, &uOutLen, maxout, in, inlen); 2076 rv = AES_Encrypt(cx, out, &uOutLen, maxout, in, inlen);
2111 } 2077 }
2112 AES_DestroyContext(cx, PR_FALSE); 2078 AES_DestroyContext(cx, PR_FALSE);
2113 *outlen += (int) uOutLen; 2079 *outlen += (int)uOutLen;
2114 2080
2115 return rv; 2081 return rv;
2116 } 2082 }
2117 #endif 2083 #endif
2118 2084
2119 static SECStatus 2085 static SECStatus
2120 ssl3_ChaCha20Poly1305( 2086 ssl3_ChaCha20Poly1305(ssl3KeyMaterial *keys, PRBool doDecrypt,
2121 » ssl3KeyMaterial *keys, 2087 unsigned char *out, int *outlen, int maxout,
2122 » PRBool doDecrypt, 2088 const unsigned char *in, int inlen,
2123 » unsigned char *out, 2089 const unsigned char *additionalData,
2124 » int *outlen, 2090 int additionalDataLen)
2125 » int maxout,
2126 » const unsigned char *in,
2127 » int inlen,
2128 » const unsigned char *additionalData,
2129 » int additionalDataLen)
2130 { 2091 {
2131 SECItem param; 2092 size_t i;
2132 SECStatus rv = SECFailure; 2093 SECItem param;
2133 unsigned int uOutLen; 2094 SECStatus rv = SECFailure;
2095 unsigned int uOutLen;
2096 unsigned char nonce[12];
2134 CK_NSS_AEAD_PARAMS aeadParams; 2097 CK_NSS_AEAD_PARAMS aeadParams;
2135 static const int tagSize = 16; 2098
2099 const int tagSize = bulk_cipher_defs[cipher_chacha20].tag_size;
2100
2101 /* See
2102 * https://tools.ietf.org/html/draft-ietf-tls-chacha20-poly1305-04#section-2
2103 * for details of how the nonce is formed. */
2104 PORT_Memcpy(nonce, keys->write_iv, 12);
2105
2106 /* XOR the last 8 bytes of the IV with the sequence number. */
2107 PORT_Assert(additionalDataLen >= 8);
2108 for (i = 0; i < 8; ++i) {
2109 nonce[4 + i] ^= additionalData[i];
2110 }
2136 2111
2137 param.type = siBuffer; 2112 param.type = siBuffer;
2138 param.len = sizeof(aeadParams); 2113 param.len = sizeof(aeadParams);
2139 param.data = (unsigned char *) &aeadParams; 2114 param.data = (unsigned char *)&aeadParams;
2140 memset(&aeadParams, 0, sizeof(aeadParams)); 2115 memset(&aeadParams, 0, sizeof(aeadParams));
2141 aeadParams.pIv = (unsigned char *) additionalData; 2116 aeadParams.pNonce = nonce;
2142 aeadParams.ulIvLen = 8; 2117 aeadParams.ulNonceLen = sizeof(nonce);
2143 aeadParams.pAAD = (unsigned char *) additionalData; 2118 aeadParams.pAAD = (unsigned char *)additionalData;
2144 aeadParams.ulAADLen = additionalDataLen; 2119 aeadParams.ulAADLen = additionalDataLen;
2145 aeadParams.ulTagLen = tagSize; 2120 aeadParams.ulTagLen = tagSize;
2146 2121
2147 if (doDecrypt) { 2122 if (doDecrypt) {
2148 » rv = pk11_decrypt(keys->write_key, CKM_NSS_CHACHA20_POLY1305, &param, 2123 rv = PK11_Decrypt(keys->write_key, CKM_NSS_CHACHA20_POLY1305, &param,
2149 » » » out, &uOutLen, maxout, in, inlen); 2124 out, &uOutLen, maxout, in, inlen);
2150 } else { 2125 } else {
2151 » rv = pk11_encrypt(keys->write_key, CKM_NSS_CHACHA20_POLY1305, &param, 2126 rv = PK11_Encrypt(keys->write_key, CKM_NSS_CHACHA20_POLY1305, &param,
2152 » » » out, &uOutLen, maxout, in, inlen); 2127 out, &uOutLen, maxout, in, inlen);
2153 } 2128 }
2154 *outlen = (int) uOutLen; 2129 *outlen = (int)uOutLen;
2155 2130
2156 return rv; 2131 return rv;
2157 } 2132 }
2158 2133
2159 /* Initialize encryption and MAC contexts for pending spec. 2134 /* Initialize encryption and MAC contexts for pending spec.
2160 * Master Secret already is derived. 2135 * Master Secret already is derived.
2161 * Caller holds Spec write lock. 2136 * Caller holds Spec write lock.
2162 */ 2137 */
2163 static SECStatus 2138 static SECStatus
2164 ssl3_InitPendingContextsPKCS11(sslSocket *ss) 2139 ssl3_InitPendingContextsPKCS11(sslSocket *ss)
2165 { 2140 {
2166 ssl3CipherSpec * pwSpec; 2141 ssl3CipherSpec *pwSpec;
2167 const ssl3BulkCipherDef *cipher_def; 2142 const ssl3BulkCipherDef *cipher_def;
2168 PK11Context * serverContext = NULL; 2143 PK11Context *serverContext = NULL;
2169 PK11Context * clientContext = NULL; 2144 PK11Context *clientContext = NULL;
2170 SECItem * param; 2145 SECItem *param;
2171 CK_MECHANISM_TYPE mechanism; 2146 CK_MECHANISM_TYPE mechanism;
2172 CK_MECHANISM_TYPE mac_mech; 2147 CK_MECHANISM_TYPE mac_mech;
2173 CK_ULONG macLength; 2148 CK_ULONG macLength;
2174 CK_ULONG effKeyBits; 2149 CK_ULONG effKeyBits;
2175 SECItem iv; 2150 SECItem iv;
2176 SECItem mac_param; 2151 SECItem mac_param;
2177 SSLCipherAlgorithm calg; 2152 SSLCipherAlgorithm calg;
2178 2153
2179 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 2154 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
2180 PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); 2155 PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
2181 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); 2156 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
2182 2157
2183 pwSpec = ss->ssl3.pwSpec; 2158 pwSpec = ss->ssl3.pwSpec;
2184 cipher_def = pwSpec->cipher_def; 2159 cipher_def = pwSpec->cipher_def;
2185 macLength = pwSpec->mac_size; 2160 macLength = pwSpec->mac_size;
2186 calg = cipher_def->calg; 2161 calg = cipher_def->calg;
2187 PORT_Assert(alg2Mech[calg].calg == calg); 2162 PORT_Assert(alg2Mech[calg].calg == calg);
2188 2163
2189 pwSpec->client.write_mac_context = NULL; 2164 pwSpec->client.write_mac_context = NULL;
2190 pwSpec->server.write_mac_context = NULL; 2165 pwSpec->server.write_mac_context = NULL;
2191 2166
2192 if (calg == calg_aes_gcm || calg == calg_chacha20) { 2167 if (cipher_def->type == type_aead) {
2193 » pwSpec->encode = NULL; 2168 pwSpec->encode = NULL;
2194 » pwSpec->decode = NULL; 2169 pwSpec->decode = NULL;
2195 » pwSpec->destroy = NULL; 2170 pwSpec->destroy = NULL;
2196 » pwSpec->encodeContext = NULL; 2171 pwSpec->encodeContext = NULL;
2197 » pwSpec->decodeContext = NULL; 2172 pwSpec->decodeContext = NULL;
2198 » if (calg == calg_aes_gcm) { 2173 switch (calg) {
2199 » pwSpec->aead = ssl3_AESGCM; 2174 case calg_aes_gcm:
2200 » } else { 2175 pwSpec->aead = ssl3_AESGCM;
2201 » pwSpec->aead = ssl3_ChaCha20Poly1305; 2176 break;
2202 » } 2177 case calg_chacha20:
2203 » return SECSuccess; 2178 pwSpec->aead = ssl3_ChaCha20Poly1305;
2179 break;
2180 default:
2181 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2182 return SECFailure;
2183 }
2184 return SECSuccess;
2204 } 2185 }
2205 2186
2206 /* 2187 /*
2207 ** Now setup the MAC contexts, 2188 ** Now setup the MAC contexts,
2208 ** crypto contexts are setup below. 2189 ** crypto contexts are setup below.
2209 */ 2190 */
2210 2191
2211 mac_mech = pwSpec->mac_def->mmech; 2192 mac_mech = pwSpec->mac_def->mmech;
2212 mac_param.data = (unsigned char *)&macLength; 2193 mac_param.data = (unsigned char *)&macLength;
2213 mac_param.len = sizeof(macLength); 2194 mac_param.len = sizeof(macLength);
2214 mac_param.type = 0; 2195 mac_param.type = 0;
2215 2196
2216 pwSpec->client.write_mac_context = PK11_CreateContextBySymKey( 2197 pwSpec->client.write_mac_context = PK11_CreateContextBySymKey(
2217 » mac_mech, CKA_SIGN, pwSpec->client.write_mac_key, &mac_param); 2198 mac_mech, CKA_SIGN, pwSpec->client.write_mac_key, &mac_param);
2218 if (pwSpec->client.write_mac_context == NULL) { 2199 if (pwSpec->client.write_mac_context == NULL) {
2219 » ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); 2200 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
2220 » goto fail; 2201 goto fail;
2221 } 2202 }
2222 pwSpec->server.write_mac_context = PK11_CreateContextBySymKey( 2203 pwSpec->server.write_mac_context = PK11_CreateContextBySymKey(
2223 » mac_mech, CKA_SIGN, pwSpec->server.write_mac_key, &mac_param); 2204 mac_mech, CKA_SIGN, pwSpec->server.write_mac_key, &mac_param);
2224 if (pwSpec->server.write_mac_context == NULL) { 2205 if (pwSpec->server.write_mac_context == NULL) {
2225 » ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); 2206 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
2226 » goto fail; 2207 goto fail;
2227 } 2208 }
2228 2209
2229 /* 2210 /*
2230 ** Now setup the crypto contexts. 2211 ** Now setup the crypto contexts.
2231 */ 2212 */
2232 2213
2233 if (calg == calg_null) { 2214 if (calg == calg_null) {
2234 » pwSpec->encode = Null_Cipher; 2215 pwSpec->encode = Null_Cipher;
2235 » pwSpec->decode = Null_Cipher; 2216 pwSpec->decode = Null_Cipher;
2236 » pwSpec->destroy = NULL; 2217 pwSpec->destroy = NULL;
2237 » return SECSuccess; 2218 return SECSuccess;
2238 } 2219 }
2239 mechanism = alg2Mech[calg].cmech; 2220 mechanism = ssl3_Alg2Mech(calg);
2240 effKeyBits = cipher_def->key_size * BPB; 2221 effKeyBits = cipher_def->key_size * BPB;
2241 2222
2242 /* 2223 /*
2243 * build the server context 2224 * build the server context
2244 */ 2225 */
2245 iv.data = pwSpec->server.write_iv; 2226 iv.data = pwSpec->server.write_iv;
2246 iv.len = cipher_def->iv_size; 2227 iv.len = cipher_def->iv_size;
2247 param = ssl3_ParamFromIV(mechanism, &iv, effKeyBits); 2228 param = ssl3_ParamFromIV(mechanism, &iv, effKeyBits);
2248 if (param == NULL) { 2229 if (param == NULL) {
2249 » ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE); 2230 ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE);
2250 » goto fail; 2231 goto fail;
2251 } 2232 }
2252 serverContext = PK11_CreateContextBySymKey(mechanism, 2233 serverContext = PK11_CreateContextBySymKey(mechanism,
2253 » » » » (ss->sec.isServer ? CKA_ENCRYPT : CKA_DECRYPT), 2234 (ss->sec.isServer ? CKA_ENCRYPT
2254 » » » » pwSpec->server.write_key, param); 2235 : CKA_DECRYPT),
2236 pwSpec->server.write_key, param);
2255 iv.data = PK11_IVFromParam(mechanism, param, (int *)&iv.len); 2237 iv.data = PK11_IVFromParam(mechanism, param, (int *)&iv.len);
2256 if (iv.data) 2238 if (iv.data)
2257 » PORT_Memcpy(pwSpec->server.write_iv, iv.data, iv.len); 2239 PORT_Memcpy(pwSpec->server.write_iv, iv.data, iv.len);
2258 SECITEM_FreeItem(param, PR_TRUE); 2240 SECITEM_FreeItem(param, PR_TRUE);
2259 if (serverContext == NULL) { 2241 if (serverContext == NULL) {
2260 » ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); 2242 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
2261 » goto fail; 2243 goto fail;
2262 } 2244 }
2263 2245
2264 /* 2246 /*
2265 * build the client context 2247 * build the client context
2266 */ 2248 */
2267 iv.data = pwSpec->client.write_iv; 2249 iv.data = pwSpec->client.write_iv;
2268 iv.len = cipher_def->iv_size; 2250 iv.len = cipher_def->iv_size;
2269 2251
2270 param = ssl3_ParamFromIV(mechanism, &iv, effKeyBits); 2252 param = ssl3_ParamFromIV(mechanism, &iv, effKeyBits);
2271 if (param == NULL) { 2253 if (param == NULL) {
2272 » ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE); 2254 ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE);
2273 » goto fail; 2255 goto fail;
2274 } 2256 }
2275 clientContext = PK11_CreateContextBySymKey(mechanism, 2257 clientContext = PK11_CreateContextBySymKey(mechanism,
2276 » » » » (ss->sec.isServer ? CKA_DECRYPT : CKA_ENCRYPT), 2258 (ss->sec.isServer ? CKA_DECRYPT
2277 » » » » pwSpec->client.write_key, param); 2259 : CKA_ENCRYPT),
2260 pwSpec->client.write_key, param);
2278 iv.data = PK11_IVFromParam(mechanism, param, (int *)&iv.len); 2261 iv.data = PK11_IVFromParam(mechanism, param, (int *)&iv.len);
2279 if (iv.data) 2262 if (iv.data)
2280 » PORT_Memcpy(pwSpec->client.write_iv, iv.data, iv.len); 2263 PORT_Memcpy(pwSpec->client.write_iv, iv.data, iv.len);
2281 SECITEM_FreeItem(param,PR_TRUE); 2264 SECITEM_FreeItem(param, PR_TRUE);
2282 if (clientContext == NULL) { 2265 if (clientContext == NULL) {
2283 » ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); 2266 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
2284 » goto fail; 2267 goto fail;
2285 } 2268 }
2286 pwSpec->encode = (SSLCipher) PK11_CipherOp; 2269 pwSpec->encode = (SSLCipher)PK11_CipherOp;
2287 pwSpec->decode = (SSLCipher) PK11_CipherOp; 2270 pwSpec->decode = (SSLCipher)PK11_CipherOp;
2288 pwSpec->destroy = (SSLDestroy) PK11_DestroyContext; 2271 pwSpec->destroy = (SSLDestroy)PK11_DestroyContext;
2289 2272
2290 pwSpec->encodeContext = (ss->sec.isServer) ? serverContext : clientContext; 2273 pwSpec->encodeContext = (ss->sec.isServer) ? serverContext : clientContext;
2291 pwSpec->decodeContext = (ss->sec.isServer) ? clientContext : serverContext; 2274 pwSpec->decodeContext = (ss->sec.isServer) ? clientContext : serverContext;
2292 2275
2293 serverContext = NULL; 2276 serverContext = NULL;
2294 clientContext = NULL; 2277 clientContext = NULL;
2295 2278
2296 ssl3_InitCompressionContext(pwSpec); 2279 ssl3_InitCompressionContext(pwSpec);
2297 2280
2298 return SECSuccess; 2281 return SECSuccess;
2299 2282
2300 fail: 2283 fail:
2301 if (serverContext != NULL) PK11_DestroyContext(serverContext, PR_TRUE); 2284 if (serverContext != NULL)
2302 if (clientContext != NULL) PK11_DestroyContext(clientContext, PR_TRUE); 2285 PK11_DestroyContext(serverContext, PR_TRUE);
2286 if (clientContext != NULL)
2287 PK11_DestroyContext(clientContext, PR_TRUE);
2303 if (pwSpec->client.write_mac_context != NULL) { 2288 if (pwSpec->client.write_mac_context != NULL) {
2304 » PK11_DestroyContext(pwSpec->client.write_mac_context,PR_TRUE); 2289 PK11_DestroyContext(pwSpec->client.write_mac_context, PR_TRUE);
2305 » pwSpec->client.write_mac_context = NULL; 2290 pwSpec->client.write_mac_context = NULL;
2306 } 2291 }
2307 if (pwSpec->server.write_mac_context != NULL) { 2292 if (pwSpec->server.write_mac_context != NULL) {
2308 » PK11_DestroyContext(pwSpec->server.write_mac_context,PR_TRUE); 2293 PK11_DestroyContext(pwSpec->server.write_mac_context, PR_TRUE);
2309 » pwSpec->server.write_mac_context = NULL; 2294 pwSpec->server.write_mac_context = NULL;
2310 } 2295 }
2311 2296
2312 return SECFailure; 2297 return SECFailure;
2313 } 2298 }
2314 2299
2300 #ifndef NO_PKCS11_BYPASS
2301 /* Returns whether we can bypass PKCS#11 for a given cipher algorithm.
2302 *
2303 * We do not support PKCS#11 bypass for ChaCha20/Poly1305.
2304 */
2305 static PRBool
2306 ssl3_CanBypassCipher(SSLCipherAlgorithm calg)
2307 {
2308 switch (calg) {
2309 case calg_chacha20:
2310 return PR_FALSE;
2311 default:
2312 return PR_TRUE;
2313 }
2314 }
2315 #endif
2316
2315 /* Complete the initialization of all keys, ciphers, MACs and their contexts 2317 /* Complete the initialization of all keys, ciphers, MACs and their contexts
2316 * for the pending Cipher Spec. 2318 * for the pending Cipher Spec.
2317 * Called from: ssl3_SendClientKeyExchange » (for Full handshake) 2319 * Called from: ssl3_SendClientKeyExchange (for Full handshake)
2318 * ssl3_HandleRSAClientKeyExchange»(for Full handshake) 2320 * ssl3_HandleRSAClientKeyExchange (for Full handshake)
2319 * ssl3_HandleServerHello» » (for session restart) 2321 * ssl3_HandleServerHello (for session restart)
2320 * ssl3_HandleClientHello» » (for session restart) 2322 * ssl3_HandleClientHello (for session restart)
2321 * Sets error code, but caller probably should override to disambiguate. 2323 * Sets error code, but caller probably should override to disambiguate.
2322 * NULL pms means re-use old master_secret. 2324 * NULL pms means re-use old master_secret.
2323 * 2325 *
2324 * This code is common to the bypass and PKCS11 execution paths. For 2326 * This code is common to the bypass and PKCS11 execution paths. For
2325 * the bypass case, pms is NULL. If the old master secret is reused, 2327 * the bypass case, pms is NULL. If the old master secret is reused,
2326 * pms is NULL and the master secret is already in either 2328 * pms is NULL and the master secret is already in either
2327 * pwSpec->msItem.len (the bypass case) or pwSpec->master_secret. 2329 * pwSpec->msItem.len (the bypass case) or pwSpec->master_secret.
2328 * 2330 *
2329 * For the bypass case, pms is NULL. 2331 * For the bypass case, pms is NULL.
2330 */ 2332 */
2331 SECStatus 2333 SECStatus
2332 ssl3_InitPendingCipherSpec(sslSocket *ss, PK11SymKey *pms) 2334 ssl3_InitPendingCipherSpec(sslSocket *ss, PK11SymKey *pms)
2333 { 2335 {
2334 ssl3CipherSpec * pwSpec; 2336 ssl3CipherSpec *pwSpec;
2335 ssl3CipherSpec * cwSpec; 2337 ssl3CipherSpec *cwSpec;
2336 SECStatus rv; 2338 SECStatus rv;
2337 2339
2338 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 2340 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
2339 2341
2340 ssl_GetSpecWriteLock(ss);» /**************************************/ 2342 ssl_GetSpecWriteLock(ss); /**************************************/
2341 2343
2342 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); 2344 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
2343 2345
2344 pwSpec = ss->ssl3.pwSpec; 2346 pwSpec = ss->ssl3.pwSpec;
2345 cwSpec = ss->ssl3.cwSpec; 2347 cwSpec = ss->ssl3.cwSpec;
2346 2348
2347 if (pms || (!pwSpec->msItem.len && !pwSpec->master_secret)) { 2349 if (pms || (!pwSpec->msItem.len && !pwSpec->master_secret)) {
2348 » rv = ssl3_DeriveMasterSecret(ss, pms); 2350 rv = ssl3_DeriveMasterSecret(ss, pms);
2349 » if (rv != SECSuccess) { 2351 if (rv != SECSuccess) {
2350 » goto done; /* err code set by ssl3_DeriveMasterSecret */ 2352 goto done; /* err code set by ssl3_DeriveMasterSecret */
2351 » } 2353 }
2352 } 2354 }
2353 #ifndef NO_PKCS11_BYPASS 2355 #ifndef NO_PKCS11_BYPASS
2354 if (ss->opt.bypassPKCS11 && pwSpec->msItem.len && pwSpec->msItem.data) { 2356 if (ss->opt.bypassPKCS11 && pwSpec->msItem.len && pwSpec->msItem.data &&
2355 » /* Double Bypass succeeded in extracting the master_secret */ 2357 ssl3_CanBypassCipher(ss->ssl3.pwSpec->cipher_def->calg)) {
2356 » const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def; 2358 /* Double Bypass succeeded in extracting the master_secret */
2357 » PRBool isTLS = (PRBool)(kea_def->tls_keygen || 2359 const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def;
2360 PRBool isTLS = (PRBool)(kea_def->tls_keygen ||
2358 (pwSpec->version > SSL_LIBRARY_VERSION_3_0)); 2361 (pwSpec->version > SSL_LIBRARY_VERSION_3_0));
2359 » pwSpec->bypassCiphers = PR_TRUE; 2362 pwSpec->bypassCiphers = PR_TRUE;
2360 » rv = ssl3_KeyAndMacDeriveBypass( pwSpec, 2363 rv = ssl3_KeyAndMacDeriveBypass(pwSpec,
2361 » » » (const unsigned char *)&ss->ssl3.hs.client_random, 2364 (const unsigned char *)&ss->ssl3.hs.clie nt_random,
2362 » » » (const unsigned char *)&ss->ssl3.hs.server_random, 2365 (const unsigned char *)&ss->ssl3.hs.serv er_random,
2363 » » » isTLS, 2366 isTLS,
2364 » » » (PRBool)(kea_def->is_limited)); 2367 (PRBool)(kea_def->is_limited));
2365 » if (rv == SECSuccess) { 2368 if (rv == SECSuccess) {
2366 » rv = ssl3_InitPendingContextsBypass(ss); 2369 rv = ssl3_InitPendingContextsBypass(ss);
2367 » } 2370 }
2368 } else 2371 } else
2369 #endif 2372 #endif
2370 if (pwSpec->master_secret) { 2373 if (pwSpec->master_secret) {
2371 » rv = ssl3_DeriveConnectionKeysPKCS11(ss); 2374 rv = ssl3_DeriveConnectionKeysPKCS11(ss);
2372 » if (rv == SECSuccess) { 2375 if (rv == SECSuccess) {
2373 » rv = ssl3_InitPendingContextsPKCS11(ss); 2376 rv = ssl3_InitPendingContextsPKCS11(ss);
2374 » } 2377 }
2375 } else { 2378 } else {
2376 » PORT_Assert(pwSpec->master_secret); 2379 PORT_Assert(pwSpec->master_secret);
2377 » PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 2380 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2378 » rv = SECFailure; 2381 rv = SECFailure;
2379 } 2382 }
2380 if (rv != SECSuccess) { 2383 if (rv != SECSuccess) {
2381 » goto done; 2384 goto done;
2382 } 2385 }
2383 2386
2384 /* Generic behaviors -- common to all crypto methods */ 2387 /* Generic behaviors -- common to all crypto methods */
2385 if (!IS_DTLS(ss)) { 2388 if (!IS_DTLS(ss)) {
2386 » pwSpec->read_seq_num.high = pwSpec->write_seq_num.high = 0; 2389 pwSpec->read_seq_num.high = pwSpec->write_seq_num.high = 0;
2387 } else { 2390 } else {
2388 » if (cwSpec->epoch == PR_UINT16_MAX) { 2391 if (cwSpec->epoch == PR_UINT16_MAX) {
2389 » /* The problem here is that we have rehandshaked too many 2392 /* The problem here is that we have rehandshaked too many
2390 » * times (you are not allowed to wrap the epoch). The 2393 * times (you are not allowed to wrap the epoch). The
2391 » * spec says you should be discarding the connection 2394 * spec says you should be discarding the connection
2392 » * and start over, so not much we can do here. */ 2395 * and start over, so not much we can do here. */
2393 » PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 2396 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2394 » rv = SECFailure; 2397 rv = SECFailure;
2395 » goto done; 2398 goto done;
2396 » } 2399 }
2397 » /* The sequence number has the high 16 bits as the epoch. */ 2400 /* The sequence number has the high 16 bits as the epoch. */
2398 » pwSpec->epoch = cwSpec->epoch + 1; 2401 pwSpec->epoch = cwSpec->epoch + 1;
2399 » pwSpec->read_seq_num.high = pwSpec->write_seq_num.high = 2402 pwSpec->read_seq_num.high = pwSpec->write_seq_num.high =
2400 » pwSpec->epoch << 16; 2403 pwSpec->epoch << 16;
2401 2404
2402 » dtls_InitRecvdRecords(&pwSpec->recvdRecords); 2405 dtls_InitRecvdRecords(&pwSpec->recvdRecords);
2403 } 2406 }
2404 pwSpec->read_seq_num.low = pwSpec->write_seq_num.low = 0; 2407 pwSpec->read_seq_num.low = pwSpec->write_seq_num.low = 0;
2405 2408
2406 done: 2409 done:
2407 ssl_ReleaseSpecWriteLock(ss);» /******************************/ 2410 ssl_ReleaseSpecWriteLock(ss); /******************************/
2408 if (rv != SECSuccess) 2411 if (rv != SECSuccess)
2409 » ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); 2412 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
2410 return rv; 2413 return rv;
2411 } 2414 }
2412 2415
2413 /* 2416 /*
2414 * 60 bytes is 3 times the maximum length MAC size that is supported. 2417 * 60 bytes is 3 times the maximum length MAC size that is supported.
2415 */ 2418 */
2416 static const unsigned char mac_pad_1 [60] = { 2419 static const unsigned char mac_pad_1[60] = {
2417 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 2420 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2418 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 2421 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2419 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 2422 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2420 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 2423 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2421 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 2424 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2422 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 2425 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2423 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 2426 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
2424 0x36, 0x36, 0x36, 0x36 2427 0x36, 0x36, 0x36, 0x36
2425 }; 2428 };
2426 static const unsigned char mac_pad_2 [60] = { 2429 static const unsigned char mac_pad_2[60] = {
2427 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 2430 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2428 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 2431 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2429 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 2432 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2430 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 2433 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2431 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 2434 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2432 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 2435 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2433 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 2436 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
2434 0x5c, 0x5c, 0x5c, 0x5c 2437 0x5c, 0x5c, 0x5c, 0x5c
2435 }; 2438 };
2436 2439
2437 /* Called from: ssl3_SendRecord() 2440 /* Called from: ssl3_SendRecord()
2438 ** Caller must already hold the SpecReadLock. (wish we could assert that!) 2441 ** Caller must already hold the SpecReadLock. (wish we could assert that!)
2439 */ 2442 */
2440 static SECStatus 2443 static SECStatus
2441 ssl3_ComputeRecordMAC( 2444 ssl3_ComputeRecordMAC(
2442 ssl3CipherSpec * spec, 2445 ssl3CipherSpec *spec,
2443 PRBool useServerMacKey, 2446 PRBool useServerMacKey,
2444 const unsigned char *header, 2447 const unsigned char *header,
2445 unsigned int headerLen, 2448 unsigned int headerLen,
2446 const SSL3Opaque * input, 2449 const SSL3Opaque *input,
2447 int inputLength, 2450 int inputLength,
2448 unsigned char * outbuf, 2451 unsigned char *outbuf,
2449 unsigned int * outLength) 2452 unsigned int *outLength)
2450 { 2453 {
2451 const ssl3MACDef * mac_def; 2454 const ssl3MACDef *mac_def;
2452 SECStatus rv; 2455 SECStatus rv;
2453 2456
2454 PRINT_BUF(95, (NULL, "frag hash1: header", header, headerLen)); 2457 PRINT_BUF(95, (NULL, "frag hash1: header", header, headerLen));
2455 PRINT_BUF(95, (NULL, "frag hash1: input", input, inputLength)); 2458 PRINT_BUF(95, (NULL, "frag hash1: input", input, inputLength));
2456 2459
2457 mac_def = spec->mac_def; 2460 mac_def = spec->mac_def;
2458 if (mac_def->mac == mac_null) { 2461 if (mac_def->mac == mac_null) {
2459 » *outLength = 0; 2462 *outLength = 0;
2460 » return SECSuccess; 2463 return SECSuccess;
2461 } 2464 }
2462 #ifndef NO_PKCS11_BYPASS 2465 #ifndef NO_PKCS11_BYPASS
2463 if (spec->bypassCiphers) { 2466 if (spec->bypassCiphers) {
2464 » /* bypass version */ 2467 /* bypass version */
2465 » const SECHashObject *hashObj = NULL; 2468 const SECHashObject *hashObj = NULL;
2466 » unsigned int pad_bytes = 0; 2469 unsigned int pad_bytes = 0;
2467 » PRUint64 write_mac_context[MAX_MAC_CONTEXT_LLONGS]; 2470 PRUint64 write_mac_context[MAX_MAC_CONTEXT_LLONGS];
2468 2471
2469 » switch (mac_def->mac) { 2472 switch (mac_def->mac) {
2470 » case ssl_mac_null: 2473 case ssl_mac_null:
2471 » *outLength = 0; 2474 *outLength = 0;
2472 » return SECSuccess; 2475 return SECSuccess;
2473 » case ssl_mac_md5: 2476 case ssl_mac_md5:
2474 » pad_bytes = 48; 2477 pad_bytes = 48;
2475 » hashObj = HASH_GetRawHashObject(HASH_AlgMD5); 2478 hashObj = HASH_GetRawHashObject(HASH_AlgMD5);
2476 » break; 2479 break;
2477 » case ssl_mac_sha: 2480 case ssl_mac_sha:
2478 » pad_bytes = 40; 2481 pad_bytes = 40;
2479 » hashObj = HASH_GetRawHashObject(HASH_AlgSHA1); 2482 hashObj = HASH_GetRawHashObject(HASH_AlgSHA1);
2480 » break; 2483 break;
2481 » case ssl_hmac_md5: /* used with TLS */ 2484 case ssl_hmac_md5: /* used with TLS */
2482 » hashObj = HASH_GetRawHashObject(HASH_AlgMD5); 2485 hashObj = HASH_GetRawHashObject(HASH_AlgMD5);
2483 » break; 2486 break;
2484 » case ssl_hmac_sha: /* used with TLS */ 2487 case ssl_hmac_sha: /* used with TLS */
2485 » hashObj = HASH_GetRawHashObject(HASH_AlgSHA1); 2488 hashObj = HASH_GetRawHashObject(HASH_AlgSHA1);
2486 » break; 2489 break;
2487 » case ssl_hmac_sha256: /* used with TLS */ 2490 case ssl_hmac_sha256: /* used with TLS */
2488 » hashObj = HASH_GetRawHashObject(HASH_AlgSHA256); 2491 hashObj = HASH_GetRawHashObject(HASH_AlgSHA256);
2489 » break; 2492 break;
2490 » default: 2493 default:
2491 » break; 2494 break;
2492 » } 2495 }
2493 » if (!hashObj) { 2496 if (!hashObj) {
2494 » PORT_Assert(0); 2497 PORT_Assert(0);
2495 » PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 2498 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2496 » return SECFailure; 2499 return SECFailure;
2497 » } 2500 }
2498 2501
2499 » if (spec->version <= SSL_LIBRARY_VERSION_3_0) { 2502 if (spec->version <= SSL_LIBRARY_VERSION_3_0) {
2500 » unsigned int tempLen; 2503 unsigned int tempLen;
2501 » unsigned char temp[MAX_MAC_LENGTH]; 2504 unsigned char temp[MAX_MAC_LENGTH];
2502 2505
2503 » /* compute "inner" part of SSL3 MAC */ 2506 /* compute "inner" part of SSL3 MAC */
2504 » hashObj->begin(write_mac_context); 2507 hashObj->begin(write_mac_context);
2505 » if (useServerMacKey) 2508 if (useServerMacKey)
2506 » » hashObj->update(write_mac_context, 2509 hashObj->update(write_mac_context,
2507 » » » » spec->server.write_mac_key_item.data, 2510 spec->server.write_mac_key_item.data,
2508 » » » » spec->server.write_mac_key_item.len); 2511 spec->server.write_mac_key_item.len);
2509 » else 2512 else
2510 » » hashObj->update(write_mac_context, 2513 hashObj->update(write_mac_context,
2511 » » » » spec->client.write_mac_key_item.data, 2514 spec->client.write_mac_key_item.data,
2512 » » » » spec->client.write_mac_key_item.len); 2515 spec->client.write_mac_key_item.len);
2513 » hashObj->update(write_mac_context, mac_pad_1, pad_bytes); 2516 hashObj->update(write_mac_context, mac_pad_1, pad_bytes);
2514 » hashObj->update(write_mac_context, header, headerLen); 2517 hashObj->update(write_mac_context, header, headerLen);
2515 » hashObj->update(write_mac_context, input, inputLength); 2518 hashObj->update(write_mac_context, input, inputLength);
2516 » hashObj->end(write_mac_context, temp, &tempLen, sizeof temp); 2519 hashObj->end(write_mac_context, temp, &tempLen, sizeof temp);
2517 2520
2518 » /* compute "outer" part of SSL3 MAC */ 2521 /* compute "outer" part of SSL3 MAC */
2519 » hashObj->begin(write_mac_context); 2522 hashObj->begin(write_mac_context);
2520 » if (useServerMacKey) 2523 if (useServerMacKey)
2521 » » hashObj->update(write_mac_context, 2524 hashObj->update(write_mac_context,
2522 » » » » spec->server.write_mac_key_item.data, 2525 spec->server.write_mac_key_item.data,
2523 » » » » spec->server.write_mac_key_item.len); 2526 spec->server.write_mac_key_item.len);
2524 » else 2527 else
2525 » » hashObj->update(write_mac_context, 2528 hashObj->update(write_mac_context,
2526 » » » » spec->client.write_mac_key_item.data, 2529 spec->client.write_mac_key_item.data,
2527 » » » » spec->client.write_mac_key_item.len); 2530 spec->client.write_mac_key_item.len);
2528 » hashObj->update(write_mac_context, mac_pad_2, pad_bytes); 2531 hashObj->update(write_mac_context, mac_pad_2, pad_bytes);
2529 » hashObj->update(write_mac_context, temp, tempLen); 2532 hashObj->update(write_mac_context, temp, tempLen);
2530 » hashObj->end(write_mac_context, outbuf, outLength, spec->mac_size); 2533 hashObj->end(write_mac_context, outbuf, outLength, spec->mac_size);
2531 » rv = SECSuccess; 2534 rv = SECSuccess;
2532 » } else { /* is TLS */ 2535 } else { /* is TLS */
2533 #define cx ((HMACContext *)write_mac_context) 2536 #define cx ((HMACContext *)write_mac_context)
2534 » if (useServerMacKey) { 2537 if (useServerMacKey) {
2535 » » rv = HMAC_Init(cx, hashObj, 2538 rv = HMAC_Init(cx, hashObj,
2536 » » » spec->server.write_mac_key_item.data, 2539 spec->server.write_mac_key_item.data,
2537 » » » spec->server.write_mac_key_item.len, PR_FALSE); 2540 spec->server.write_mac_key_item.len, PR_FALSE);
2538 » } else { 2541 } else {
2539 » » rv = HMAC_Init(cx, hashObj, 2542 rv = HMAC_Init(cx, hashObj,
2540 » » » spec->client.write_mac_key_item.data, 2543 spec->client.write_mac_key_item.data,
2541 » » » spec->client.write_mac_key_item.len, PR_FALSE); 2544 spec->client.write_mac_key_item.len, PR_FALSE);
2542 » } 2545 }
2543 » if (rv == SECSuccess) { 2546 if (rv == SECSuccess) {
2544 » » HMAC_Begin(cx); 2547 HMAC_Begin(cx);
2545 » » HMAC_Update(cx, header, headerLen); 2548 HMAC_Update(cx, header, headerLen);
2546 » » HMAC_Update(cx, input, inputLength); 2549 HMAC_Update(cx, input, inputLength);
2547 » » rv = HMAC_Finish(cx, outbuf, outLength, spec->mac_size); 2550 rv = HMAC_Finish(cx, outbuf, outLength, spec->mac_size);
2548 » » HMAC_Destroy(cx, PR_FALSE); 2551 HMAC_Destroy(cx, PR_FALSE);
2549 » } 2552 }
2550 #undef cx 2553 #undef cx
2551 » } 2554 }
2552 } else 2555 } else
2553 #endif 2556 #endif
2554 { 2557 {
2555 » PK11Context *mac_context = 2558 PK11Context *mac_context =
2556 » (useServerMacKey ? spec->server.write_mac_context 2559 (useServerMacKey ? spec->server.write_mac_context
2557 » : spec->client.write_mac_context); 2560 : spec->client.write_mac_context);
2558 » rv = PK11_DigestBegin(mac_context); 2561 rv = PK11_DigestBegin(mac_context);
2559 » rv |= PK11_DigestOp(mac_context, header, headerLen); 2562 rv |= PK11_DigestOp(mac_context, header, headerLen);
2560 » rv |= PK11_DigestOp(mac_context, input, inputLength); 2563 rv |= PK11_DigestOp(mac_context, input, inputLength);
2561 » rv |= PK11_DigestFinal(mac_context, outbuf, outLength, spec->mac_size); 2564 rv |= PK11_DigestFinal(mac_context, outbuf, outLength, spec->mac_size);
2562 } 2565 }
2563 2566
2564 PORT_Assert(rv != SECSuccess || *outLength == (unsigned)spec->mac_size); 2567 PORT_Assert(rv != SECSuccess || *outLength == (unsigned)spec->mac_size);
2565 2568
2566 PRINT_BUF(95, (NULL, "frag hash2: result", outbuf, *outLength)); 2569 PRINT_BUF(95, (NULL, "frag hash2: result", outbuf, *outLength));
2567 2570
2568 if (rv != SECSuccess) { 2571 if (rv != SECSuccess) {
2569 » rv = SECFailure; 2572 rv = SECFailure;
2570 » ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE); 2573 ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
2571 } 2574 }
2572 return rv; 2575 return rv;
2573 } 2576 }
2574 2577
2575 /* Called from: ssl3_HandleRecord() 2578 /* Called from: ssl3_HandleRecord()
2576 * Caller must already hold the SpecReadLock. (wish we could assert that!) 2579 * Caller must already hold the SpecReadLock. (wish we could assert that!)
2577 * 2580 *
2578 * On entry: 2581 * On entry:
2579 * originalLen >= inputLen >= MAC size 2582 * originalLen >= inputLen >= MAC size
2580 */ 2583 */
2581 static SECStatus 2584 static SECStatus
2582 ssl3_ComputeRecordMACConstantTime( 2585 ssl3_ComputeRecordMACConstantTime(
2583 ssl3CipherSpec * spec, 2586 ssl3CipherSpec *spec,
2584 PRBool useServerMacKey, 2587 PRBool useServerMacKey,
2585 const unsigned char *header, 2588 const unsigned char *header,
2586 unsigned int headerLen, 2589 unsigned int headerLen,
2587 const SSL3Opaque * input, 2590 const SSL3Opaque *input,
2588 int inputLen, 2591 int inputLen,
2589 int originalLen, 2592 int originalLen,
2590 unsigned char * outbuf, 2593 unsigned char *outbuf,
2591 unsigned int * outLen) 2594 unsigned int *outLen)
2592 { 2595 {
2593 CK_MECHANISM_TYPE macType; 2596 CK_MECHANISM_TYPE macType;
2594 CK_NSS_MAC_CONSTANT_TIME_PARAMS params; 2597 CK_NSS_MAC_CONSTANT_TIME_PARAMS params;
2595 SECItem param, inputItem, outputItem; 2598 SECItem param, inputItem, outputItem;
2596 SECStatus rv; 2599 SECStatus rv;
2597 PK11SymKey * key; 2600 PK11SymKey *key;
2598 2601
2599 PORT_Assert(inputLen >= spec->mac_size); 2602 PORT_Assert(inputLen >= spec->mac_size);
2600 PORT_Assert(originalLen >= inputLen); 2603 PORT_Assert(originalLen >= inputLen);
2601 2604
2602 if (spec->bypassCiphers) { 2605 if (spec->bypassCiphers) {
2603 » /* This function doesn't support PKCS#11 bypass. We fallback on the 2606 /* This function doesn't support PKCS#11 bypass. We fallback on the
2604 » * non-constant time version. */ 2607 * non-constant time version. */
2605 » goto fallback; 2608 goto fallback;
2606 } 2609 }
2607 2610
2608 if (spec->mac_def->mac == mac_null) { 2611 if (spec->mac_def->mac == mac_null) {
2609 » *outLen = 0; 2612 *outLen = 0;
2610 » return SECSuccess; 2613 return SECSuccess;
2611 } 2614 }
2612 2615
2613 macType = CKM_NSS_HMAC_CONSTANT_TIME; 2616 macType = CKM_NSS_HMAC_CONSTANT_TIME;
2614 if (spec->version <= SSL_LIBRARY_VERSION_3_0) { 2617 if (spec->version <= SSL_LIBRARY_VERSION_3_0) {
2615 » macType = CKM_NSS_SSL3_MAC_CONSTANT_TIME; 2618 macType = CKM_NSS_SSL3_MAC_CONSTANT_TIME;
2616 } 2619 }
2617 2620
2618 params.macAlg = spec->mac_def->mmech; 2621 params.macAlg = spec->mac_def->mmech;
2619 params.ulBodyTotalLen = originalLen; 2622 params.ulBodyTotalLen = originalLen;
2620 params.pHeader = (unsigned char *) header; /* const cast */ 2623 params.pHeader = (unsigned char *)header; /* const cast */
2621 params.ulHeaderLen = headerLen; 2624 params.ulHeaderLen = headerLen;
2622 2625
2623 param.data = (unsigned char*) &params; 2626 param.data = (unsigned char *)&params;
2624 param.len = sizeof(params); 2627 param.len = sizeof(params);
2625 param.type = 0; 2628 param.type = 0;
2626 2629
2627 inputItem.data = (unsigned char *) input; 2630 inputItem.data = (unsigned char *)input;
2628 inputItem.len = inputLen; 2631 inputItem.len = inputLen;
2629 inputItem.type = 0; 2632 inputItem.type = 0;
2630 2633
2631 outputItem.data = outbuf; 2634 outputItem.data = outbuf;
2632 outputItem.len = *outLen; 2635 outputItem.len = *outLen;
2633 outputItem.type = 0; 2636 outputItem.type = 0;
2634 2637
2635 key = spec->server.write_mac_key; 2638 key = spec->server.write_mac_key;
2636 if (!useServerMacKey) { 2639 if (!useServerMacKey) {
2637 » key = spec->client.write_mac_key; 2640 key = spec->client.write_mac_key;
2638 } 2641 }
2639 2642
2640 rv = PK11_SignWithSymKey(key, macType, &param, &outputItem, &inputItem); 2643 rv = PK11_SignWithSymKey(key, macType, &param, &outputItem, &inputItem);
2641 if (rv != SECSuccess) { 2644 if (rv != SECSuccess) {
2642 » if (PORT_GetError() == SEC_ERROR_INVALID_ALGORITHM) { 2645 if (PORT_GetError() == SEC_ERROR_INVALID_ALGORITHM) {
2643 » goto fallback; 2646 goto fallback;
2644 » } 2647 }
2645 2648
2646 » *outLen = 0; 2649 *outLen = 0;
2647 » rv = SECFailure; 2650 rv = SECFailure;
2648 » ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE); 2651 ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
2649 » return rv; 2652 return rv;
2650 } 2653 }
2651 2654
2652 PORT_Assert(outputItem.len == (unsigned)spec->mac_size); 2655 PORT_Assert(outputItem.len == (unsigned)spec->mac_size);
2653 *outLen = outputItem.len; 2656 *outLen = outputItem.len;
2654 2657
2655 return rv; 2658 return rv;
2656 2659
2657 fallback: 2660 fallback:
2658 /* ssl3_ComputeRecordMAC expects the MAC to have been removed from the 2661 /* ssl3_ComputeRecordMAC expects the MAC to have been removed from the
2659 * length already. */ 2662 * length already. */
2660 inputLen -= spec->mac_size; 2663 inputLen -= spec->mac_size;
2661 return ssl3_ComputeRecordMAC(spec, useServerMacKey, header, headerLen, 2664 return ssl3_ComputeRecordMAC(spec, useServerMacKey, header, headerLen,
2662 » » » » input, inputLen, outbuf, outLen); 2665 input, inputLen, outbuf, outLen);
2663 } 2666 }
2664 2667
2665 static PRBool 2668 static PRBool
2666 ssl3_ClientAuthTokenPresent(sslSessionID *sid) { 2669 ssl3_ClientAuthTokenPresent(sslSessionID *sid)
2670 {
2667 PK11SlotInfo *slot = NULL; 2671 PK11SlotInfo *slot = NULL;
2668 PRBool isPresent = PR_TRUE; 2672 PRBool isPresent = PR_TRUE;
2669 2673
2670 /* we only care if we are doing client auth */ 2674 /* we only care if we are doing client auth */
2671 /* If NSS_PLATFORM_CLIENT_AUTH is defined and a platformClientKey is being
2672 * used, u.ssl3.clAuthValid will be false and this function will always
2673 * return PR_TRUE. */
2674 if (!sid || !sid->u.ssl3.clAuthValid) { 2675 if (!sid || !sid->u.ssl3.clAuthValid) {
2675 » return PR_TRUE; 2676 return PR_TRUE;
2676 } 2677 }
2677 2678
2678 /* get the slot */ 2679 /* get the slot */
2679 slot = SECMOD_LookupSlot(sid->u.ssl3.clAuthModuleID, 2680 slot = SECMOD_LookupSlot(sid->u.ssl3.clAuthModuleID,
2680 » sid->u.ssl3.clAuthSlotID); 2681 sid->u.ssl3.clAuthSlotID);
2681 if (slot == NULL || 2682 if (slot == NULL ||
2682 » !PK11_IsPresent(slot) || 2683 !PK11_IsPresent(slot) ||
2683 » sid->u.ssl3.clAuthSeries != PK11_GetSlotSeries(slot) || 2684 sid->u.ssl3.clAuthSeries != PK11_GetSlotSeries(slot) ||
2684 » sid->u.ssl3.clAuthSlotID != PK11_GetSlotID(slot) || 2685 sid->u.ssl3.clAuthSlotID != PK11_GetSlotID(slot) ||
2685 » sid->u.ssl3.clAuthModuleID != PK11_GetModuleID(slot) || 2686 sid->u.ssl3.clAuthModuleID != PK11_GetModuleID(slot) ||
2686 » (PK11_NeedLogin(slot) && !PK11_IsLoggedIn(slot, NULL))) { 2687 (PK11_NeedLogin(slot) && !PK11_IsLoggedIn(slot, NULL))) {
2687 » isPresent = PR_FALSE; 2688 isPresent = PR_FALSE;
2688 } 2689 }
2689 if (slot) { 2690 if (slot) {
2690 » PK11_FreeSlot(slot); 2691 PK11_FreeSlot(slot);
2691 } 2692 }
2692 return isPresent; 2693 return isPresent;
2693 } 2694 }
2694 2695
2695 /* Caller must hold the spec read lock. */ 2696 /* Caller must hold the spec read lock. */
2696 SECStatus 2697 SECStatus
2697 ssl3_CompressMACEncryptRecord(ssl3CipherSpec * cwSpec, 2698 ssl3_CompressMACEncryptRecord(ssl3CipherSpec *cwSpec,
2698 » » PRBool isServer, 2699 PRBool isServer,
2699 » » » PRBool isDTLS, 2700 PRBool isDTLS,
2700 » » » PRBool capRecordVersion, 2701 PRBool capRecordVersion,
2701 SSL3ContentType type, 2702 SSL3ContentType type,
2702 » » const SSL3Opaque * pIn, 2703 const SSL3Opaque *pIn,
2703 » » PRUint32 contentLen, 2704 PRUint32 contentLen,
2704 » » sslBuffer * wrBuf) 2705 sslBuffer *wrBuf)
2705 { 2706 {
2706 const ssl3BulkCipherDef * cipher_def; 2707 const ssl3BulkCipherDef *cipher_def;
2707 SECStatus rv; 2708 SECStatus rv;
2708 PRUint32 macLen = 0; 2709 PRUint32 macLen = 0;
2709 PRUint32 fragLen; 2710 PRUint32 fragLen;
2710 PRUint32 p1Len, p2Len, oddLen = 0; 2711 PRUint32 p1Len, p2Len, oddLen = 0;
2711 PRUint16 headerLen; 2712 PRUint16 headerLen;
2712 unsigned int ivLen = 0; 2713 unsigned int ivLen = 0;
2713 int cipherBytes = 0; 2714 int cipherBytes = 0;
2714 unsigned char pseudoHeader[13]; 2715 unsigned char pseudoHeader[13];
2715 unsigned int pseudoHeaderLen; 2716 unsigned int pseudoHeaderLen;
2716 2717
2717 cipher_def = cwSpec->cipher_def; 2718 cipher_def = cwSpec->cipher_def;
2718 headerLen = isDTLS ? DTLS_RECORD_HEADER_LENGTH : SSL3_RECORD_HEADER_LENGTH; 2719 headerLen = isDTLS ? DTLS_RECORD_HEADER_LENGTH : SSL3_RECORD_HEADER_LENGTH;
2719 2720
2720 if (cipher_def->type == type_block && 2721 if (cipher_def->type == type_block &&
2721 » cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) { 2722 cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
2722 » /* Prepend the per-record explicit IV using technique 2b from 2723 /* Prepend the per-record explicit IV using technique 2b from
2723 » * RFC 4346 section 6.2.3.2: The IV is a cryptographically 2724 * RFC 4346 section 6.2.3.2: The IV is a cryptographically
2724 » * strong random number XORed with the CBC residue from the previous 2725 * strong random number XORed with the CBC residue from the previous
2725 » * record. 2726 * record.
2726 » */ 2727 */
2727 » ivLen = cipher_def->iv_size; 2728 ivLen = cipher_def->iv_size;
2728 » if (ivLen > wrBuf->space - headerLen) { 2729 if (ivLen > wrBuf->space - headerLen) {
2729 » PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 2730 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2730 » return SECFailure; 2731 return SECFailure;
2731 » } 2732 }
2732 » rv = PK11_GenerateRandom(wrBuf->buf + headerLen, ivLen); 2733 rv = PK11_GenerateRandom(wrBuf->buf + headerLen, ivLen);
2733 » if (rv != SECSuccess) { 2734 if (rv != SECSuccess) {
2734 » ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE); 2735 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
2735 » return rv; 2736 return rv;
2736 » } 2737 }
2737 » rv = cwSpec->encode( cwSpec->encodeContext, 2738 rv = cwSpec->encode(cwSpec->encodeContext,
2738 » wrBuf->buf + headerLen, 2739 wrBuf->buf + headerLen,
2739 » &cipherBytes, /* output and actual outLen */ 2740 &cipherBytes, /* output and actual outLen */
2740 » ivLen, /* max outlen */ 2741 ivLen, /* max outlen */
2741 » wrBuf->buf + headerLen, 2742 wrBuf->buf + headerLen,
2742 » ivLen); /* input and inputLen*/ 2743 ivLen); /* input and inputLen*/
2743 » if (rv != SECSuccess || cipherBytes != ivLen) { 2744 if (rv != SECSuccess || cipherBytes != ivLen) {
2744 » PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); 2745 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2745 » return SECFailure; 2746 return SECFailure;
2746 » } 2747 }
2747 } 2748 }
2748 2749
2749 if (cwSpec->compressor) { 2750 if (cwSpec->compressor) {
2750 » int outlen; 2751 int outlen;
2751 » rv = cwSpec->compressor( 2752 rv = cwSpec->compressor(
2752 » cwSpec->compressContext, 2753 cwSpec->compressContext,
2753 » wrBuf->buf + headerLen + ivLen, &outlen, 2754 wrBuf->buf + headerLen + ivLen, &outlen,
2754 » wrBuf->space - headerLen - ivLen, pIn, contentLen); 2755 wrBuf->space - headerLen - ivLen, pIn, contentLen);
2755 » if (rv != SECSuccess) 2756 if (rv != SECSuccess)
2756 » return rv; 2757 return rv;
2757 » pIn = wrBuf->buf + headerLen + ivLen; 2758 pIn = wrBuf->buf + headerLen + ivLen;
2758 » contentLen = outlen; 2759 contentLen = outlen;
2759 } 2760 }
2760 2761
2761 pseudoHeaderLen = ssl3_BuildRecordPseudoHeader( 2762 pseudoHeaderLen = ssl3_BuildRecordPseudoHeader(
2762 » pseudoHeader, cwSpec->write_seq_num, type, 2763 pseudoHeader, cwSpec->write_seq_num, type,
2763 » cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_0, cwSpec->version, 2764 cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_0, cwSpec->version,
2764 » isDTLS, contentLen); 2765 isDTLS, contentLen);
2765 PORT_Assert(pseudoHeaderLen <= sizeof(pseudoHeader)); 2766 PORT_Assert(pseudoHeaderLen <= sizeof(pseudoHeader));
2766 if (cipher_def->type == type_aead) { 2767 if (cipher_def->type == type_aead) {
2767 » const int nonceLen = cipher_def->explicit_nonce_size; 2768 const int nonceLen = cipher_def->explicit_nonce_size;
2768 » const int tagLen = cipher_def->tag_size; 2769 const int tagLen = cipher_def->tag_size;
2769 2770
2770 » if (headerLen + nonceLen + contentLen + tagLen > wrBuf->space) { 2771 if (headerLen + nonceLen + contentLen + tagLen > wrBuf->space) {
2771 » PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 2772 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2772 » return SECFailure; 2773 return SECFailure;
2773 » } 2774 }
2774 2775
2775 » cipherBytes = contentLen; 2776 cipherBytes = contentLen;
2776 » rv = cwSpec->aead( 2777 rv = cwSpec->aead(
2777 » » isServer ? &cwSpec->server : &cwSpec->client, 2778 isServer ? &cwSpec->server : &cwSpec->client,
2778 » » PR_FALSE, /* do encrypt */ 2779 PR_FALSE, /* do encrypt */
2779 » » wrBuf->buf + headerLen, /* output */ 2780 wrBuf->buf + headerLen, /* output */
2780 » » &cipherBytes, /* out len */ 2781 &cipherBytes, /* out len */
2781 » » wrBuf->space - headerLen, /* max out */ 2782 wrBuf->space - headerLen, /* max out */
2782 » » pIn, contentLen, /* input */ 2783 pIn, contentLen, /* input */
2783 » » pseudoHeader, pseudoHeaderLen); 2784 pseudoHeader, pseudoHeaderLen);
2784 » if (rv != SECSuccess) { 2785 if (rv != SECSuccess) {
2785 » PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); 2786 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2786 » return SECFailure; 2787 return SECFailure;
2787 » } 2788 }
2788 } else { 2789 } else {
2789 » /* 2790 /*
2790 » * Add the MAC 2791 * Add the MAC
2791 » */ 2792 */
2792 » rv = ssl3_ComputeRecordMAC(cwSpec, isServer, 2793 rv = ssl3_ComputeRecordMAC(cwSpec, isServer,
2793 » pseudoHeader, pseudoHeaderLen, pIn, contentLen, 2794 pseudoHeader, pseudoHeaderLen, pIn, contentLe n,
2794 » wrBuf->buf + headerLen + ivLen + contentLen, &macLen); 2795 wrBuf->buf + headerLen + ivLen + contentLen,
2795 » if (rv != SECSuccess) { 2796 &macLen);
2796 » ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE); 2797 if (rv != SECSuccess) {
2797 » return SECFailure; 2798 ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
2798 » } 2799 return SECFailure;
2799 » p1Len = contentLen; 2800 }
2800 » p2Len = macLen; 2801 p1Len = contentLen;
2801 » fragLen = contentLen + macLen;» /* needs to be encrypted */ 2802 p2Len = macLen;
2802 » PORT_Assert(fragLen <= MAX_FRAGMENT_LENGTH + 1024); 2803 fragLen = contentLen + macLen; /* needs to be encrypted */
2803 2804 PORT_Assert(fragLen <= MAX_FRAGMENT_LENGTH + 1024);
2804 » /* 2805
2805 » * Pad the text (if we're doing a block cipher) 2806 /*
2806 » * then Encrypt it 2807 * Pad the text (if we're doing a block cipher)
2807 » */ 2808 * then Encrypt it
2808 » if (cipher_def->type == type_block) { 2809 */
2809 » unsigned char * pBuf; 2810 if (cipher_def->type == type_block) {
2810 » int padding_length; 2811 unsigned char *pBuf;
2811 » int i; 2812 int padding_length;
2812 2813 int i;
2813 » oddLen = contentLen % cipher_def->block_size; 2814
2814 » /* Assume blockSize is a power of two */ 2815 oddLen = contentLen % cipher_def->block_size;
2815 » padding_length = cipher_def->block_size - 1 - 2816 /* Assume blockSize is a power of two */
2816 » » » ((fragLen) & (cipher_def->block_size - 1)); 2817 padding_length = cipher_def->block_size - 1 - ((fragLen) & (cipher_d ef->block_size - 1));
2817 » fragLen += padding_length + 1; 2818 fragLen += padding_length + 1;
2818 » PORT_Assert((fragLen % cipher_def->block_size) == 0); 2819 PORT_Assert((fragLen % cipher_def->block_size) == 0);
2819 2820
2820 » /* Pad according to TLS rules (also acceptable to SSL3). */ 2821 /* Pad according to TLS rules (also acceptable to SSL3). */
2821 » pBuf = &wrBuf->buf[headerLen + ivLen + fragLen - 1]; 2822 pBuf = &wrBuf->buf[headerLen + ivLen + fragLen - 1];
2822 » for (i = padding_length + 1; i > 0; --i) { 2823 for (i = padding_length + 1; i > 0; --i) {
2823 » » *pBuf-- = padding_length; 2824 *pBuf-- = padding_length;
2824 » } 2825 }
2825 » /* now, if contentLen is not a multiple of block size, fix it */ 2826 /* now, if contentLen is not a multiple of block size, fix it */
2826 » p2Len = fragLen - p1Len; 2827 p2Len = fragLen - p1Len;
2827 » } 2828 }
2828 » if (p1Len < 256) { 2829 if (p1Len < 256) {
2829 » oddLen = p1Len; 2830 oddLen = p1Len;
2830 » p1Len = 0; 2831 p1Len = 0;
2831 » } else { 2832 } else {
2832 » p1Len -= oddLen; 2833 p1Len -= oddLen;
2833 » } 2834 }
2834 » if (oddLen) { 2835 if (oddLen) {
2835 » p2Len += oddLen; 2836 p2Len += oddLen;
2836 » PORT_Assert( (cipher_def->block_size < 2) || \ 2837 PORT_Assert((cipher_def->block_size < 2) ||
2837 » » » (p2Len % cipher_def->block_size) == 0); 2838 (p2Len % cipher_def->block_size) == 0);
2838 » memmove(wrBuf->buf + headerLen + ivLen + p1Len, pIn + p1Len, 2839 memmove(wrBuf->buf + headerLen + ivLen + p1Len, pIn + p1Len,
2839 » » oddLen); 2840 oddLen);
2840 » } 2841 }
2841 » if (p1Len > 0) { 2842 if (p1Len > 0) {
2842 » int cipherBytesPart1 = -1; 2843 int cipherBytesPart1 = -1;
2843 » rv = cwSpec->encode( cwSpec->encodeContext, 2844 rv = cwSpec->encode(cwSpec->encodeContext,
2844 » » wrBuf->buf + headerLen + ivLen, /* output */ 2845 wrBuf->buf + headerLen + ivLen, /* output */
2845 » » &cipherBytesPart1, /* actual outlen */ 2846 &cipherBytesPart1, /* actual outlen */
2846 » » p1Len, /* max outlen */ 2847 p1Len, /* max outlen */
2847 » » pIn, p1Len); /* input, and inputlen */ 2848 pIn,
2848 » PORT_Assert(rv == SECSuccess && cipherBytesPart1 == (int) p1Len); 2849 p1Len); /* input, and inputlen */
2849 » if (rv != SECSuccess || cipherBytesPart1 != (int) p1Len) { 2850 PORT_Assert(rv == SECSuccess && cipherBytesPart1 == (int)p1Len);
2850 » » PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); 2851 if (rv != SECSuccess || cipherBytesPart1 != (int)p1Len) {
2851 » » return SECFailure; 2852 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2852 » } 2853 return SECFailure;
2853 » cipherBytes += cipherBytesPart1; 2854 }
2854 » } 2855 cipherBytes += cipherBytesPart1;
2855 » if (p2Len > 0) { 2856 }
2856 » int cipherBytesPart2 = -1; 2857 if (p2Len > 0) {
2857 » rv = cwSpec->encode( cwSpec->encodeContext, 2858 int cipherBytesPart2 = -1;
2858 » » wrBuf->buf + headerLen + ivLen + p1Len, 2859 rv = cwSpec->encode(cwSpec->encodeContext,
2859 » » &cipherBytesPart2, /* output and actual outLen */ 2860 wrBuf->buf + headerLen + ivLen + p1Len,
2860 » » p2Len, /* max outlen */ 2861 &cipherBytesPart2, /* output and actual outLen * /
2861 » » wrBuf->buf + headerLen + ivLen + p1Len, 2862 p2Len, /* max outlen */
2862 » » p2Len); /* input and inputLen*/ 2863 wrBuf->buf + headerLen + ivLen + p1Len,
2863 » PORT_Assert(rv == SECSuccess && cipherBytesPart2 == (int) p2Len); 2864 p2Len); /* input and inputLen*/
2864 » if (rv != SECSuccess || cipherBytesPart2 != (int) p2Len) { 2865 PORT_Assert(rv == SECSuccess && cipherBytesPart2 == (int)p2Len);
2865 » » PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); 2866 if (rv != SECSuccess || cipherBytesPart2 != (int)p2Len) {
2866 » » return SECFailure; 2867 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
2867 » } 2868 return SECFailure;
2868 » cipherBytes += cipherBytesPart2; 2869 }
2869 » } 2870 cipherBytes += cipherBytesPart2;
2871 }
2870 } 2872 }
2871 2873
2872 PORT_Assert(cipherBytes <= MAX_FRAGMENT_LENGTH + 1024); 2874 PORT_Assert(cipherBytes <= MAX_FRAGMENT_LENGTH + 1024);
2873 2875
2874 wrBuf->len = cipherBytes + headerLen; 2876 wrBuf->len = cipherBytes + headerLen;
2875 wrBuf->buf[0] = type; 2877 wrBuf->buf[0] = type;
2876 if (isDTLS) { 2878 if (isDTLS) {
2877 » SSL3ProtocolVersion version; 2879 SSL3ProtocolVersion version;
2878 2880
2879 » version = dtls_TLSVersionToDTLSVersion(cwSpec->version); 2881 version = dtls_TLSVersionToDTLSVersion(cwSpec->version);
2880 » wrBuf->buf[1] = MSB(version); 2882 wrBuf->buf[1] = MSB(version);
2881 » wrBuf->buf[2] = LSB(version); 2883 wrBuf->buf[2] = LSB(version);
2882 » wrBuf->buf[3] = (unsigned char)(cwSpec->write_seq_num.high >> 24); 2884 wrBuf->buf[3] = (unsigned char)(cwSpec->write_seq_num.high >> 24);
2883 » wrBuf->buf[4] = (unsigned char)(cwSpec->write_seq_num.high >> 16); 2885 wrBuf->buf[4] = (unsigned char)(cwSpec->write_seq_num.high >> 16);
2884 » wrBuf->buf[5] = (unsigned char)(cwSpec->write_seq_num.high >> 8); 2886 wrBuf->buf[5] = (unsigned char)(cwSpec->write_seq_num.high >> 8);
2885 » wrBuf->buf[6] = (unsigned char)(cwSpec->write_seq_num.high >> 0); 2887 wrBuf->buf[6] = (unsigned char)(cwSpec->write_seq_num.high >> 0);
2886 » wrBuf->buf[7] = (unsigned char)(cwSpec->write_seq_num.low >> 24); 2888 wrBuf->buf[7] = (unsigned char)(cwSpec->write_seq_num.low >> 24);
2887 » wrBuf->buf[8] = (unsigned char)(cwSpec->write_seq_num.low >> 16); 2889 wrBuf->buf[8] = (unsigned char)(cwSpec->write_seq_num.low >> 16);
2888 » wrBuf->buf[9] = (unsigned char)(cwSpec->write_seq_num.low >> 8); 2890 wrBuf->buf[9] = (unsigned char)(cwSpec->write_seq_num.low >> 8);
2889 » wrBuf->buf[10] = (unsigned char)(cwSpec->write_seq_num.low >> 0); 2891 wrBuf->buf[10] = (unsigned char)(cwSpec->write_seq_num.low >> 0);
2890 » wrBuf->buf[11] = MSB(cipherBytes); 2892 wrBuf->buf[11] = MSB(cipherBytes);
2891 » wrBuf->buf[12] = LSB(cipherBytes); 2893 wrBuf->buf[12] = LSB(cipherBytes);
2892 } else { 2894 } else {
2893 » SSL3ProtocolVersion version = cwSpec->version; 2895 SSL3ProtocolVersion version = cwSpec->version;
2894 2896
2895 » if (capRecordVersion) { 2897 if (capRecordVersion || version >= SSL_LIBRARY_VERSION_TLS_1_3) {
2896 » version = PR_MIN(SSL_LIBRARY_VERSION_TLS_1_0, version); 2898 version = PR_MIN(SSL_LIBRARY_VERSION_TLS_1_0, version);
2897 » } 2899 }
2898 » wrBuf->buf[1] = MSB(version); 2900
2899 » wrBuf->buf[2] = LSB(version); 2901 wrBuf->buf[1] = MSB(version);
2900 » wrBuf->buf[3] = MSB(cipherBytes); 2902 wrBuf->buf[2] = LSB(version);
2901 » wrBuf->buf[4] = LSB(cipherBytes); 2903 wrBuf->buf[3] = MSB(cipherBytes);
2904 wrBuf->buf[4] = LSB(cipherBytes);
2902 } 2905 }
2903 2906
2904 ssl3_BumpSequenceNumber(&cwSpec->write_seq_num); 2907 ssl3_BumpSequenceNumber(&cwSpec->write_seq_num);
2905 2908
2906 return SECSuccess; 2909 return SECSuccess;
2907 } 2910 }
2908 2911
2909 /* Process the plain text before sending it. 2912 /* Process the plain text before sending it.
2910 * Returns the number of bytes of plaintext that were successfully sent 2913 * Returns the number of bytes of plaintext that were successfully sent
2911 * » plus the number of bytes of plaintext that were copied into the 2914 * plus the number of bytes of plaintext that were copied into the
2912 *» output (write) buffer. 2915 * output (write) buffer.
2913 * Returns SECFailure on a hard IO error, memory error, or crypto error. 2916 * Returns SECFailure on a hard IO error, memory error, or crypto error.
2914 * Does NOT return SECWouldBlock. 2917 * Does NOT return SECWouldBlock.
2915 * 2918 *
2916 * Notes on the use of the private ssl flags: 2919 * Notes on the use of the private ssl flags:
2917 * (no private SSL flags) 2920 * (no private SSL flags)
2918 * Attempt to make and send SSL records for all plaintext 2921 * Attempt to make and send SSL records for all plaintext
2919 * If non-blocking and a send gets WOULD_BLOCK, 2922 * If non-blocking and a send gets WOULD_BLOCK,
2920 * or if the pending (ciphertext) buffer is not empty, 2923 * or if the pending (ciphertext) buffer is not empty,
2921 * then buffer remaining bytes of ciphertext into pending buf, 2924 * then buffer remaining bytes of ciphertext into pending buf,
2922 * and continue to do that for all succssive records until all 2925 * and continue to do that for all succssive records until all
2923 * bytes are used. 2926 * bytes are used.
2924 * ssl_SEND_FLAG_FORCE_INTO_BUFFER 2927 * ssl_SEND_FLAG_FORCE_INTO_BUFFER
2925 * As above, except this suppresses all write attempts, and forces 2928 * As above, except this suppresses all write attempts, and forces
2926 * all ciphertext into the pending ciphertext buffer. 2929 * all ciphertext into the pending ciphertext buffer.
2927 * ssl_SEND_FLAG_USE_EPOCH (for DTLS) 2930 * ssl_SEND_FLAG_USE_EPOCH (for DTLS)
2928 * Forces the use of the provided epoch 2931 * Forces the use of the provided epoch
2929 * ssl_SEND_FLAG_CAP_RECORD_VERSION 2932 * ssl_SEND_FLAG_CAP_RECORD_VERSION
2930 * Caps the record layer version number of TLS ClientHello to { 3, 1 } 2933 * Caps the record layer version number of TLS ClientHello to { 3, 1 }
2931 * (TLS 1.0). Some TLS 1.0 servers (which seem to use F5 BIG-IP) ignore 2934 * (TLS 1.0). Some TLS 1.0 servers (which seem to use F5 BIG-IP) ignore
2932 * ClientHello.client_version and use the record layer version number 2935 * ClientHello.client_version and use the record layer version number
2933 * (TLSPlaintext.version) instead when negotiating protocol versions. In 2936 * (TLSPlaintext.version) instead when negotiating protocol versions. In
2934 * addition, if the record layer version number of ClientHello is { 3, 2 } 2937 * addition, if the record layer version number of ClientHello is { 3, 2 }
2935 * (TLS 1.1) or higher, these servers reset the TCP connections. Lastly, 2938 * (TLS 1.1) or higher, these servers reset the TCP connections. Lastly,
2936 * some F5 BIG-IP servers hang if a record containing a ClientHello has a 2939 * some F5 BIG-IP servers hang if a record containing a ClientHello has a
2937 * version greater than { 3, 1 } and a length greater than 255. Set this 2940 * version greater than { 3, 1 } and a length greater than 255. Set this
2938 * flag to work around such servers. 2941 * flag to work around such servers.
2939 */ 2942 */
2940 PRInt32 2943 PRInt32
2941 ssl3_SendRecord( sslSocket * ss, 2944 ssl3_SendRecord(sslSocket *ss,
2942 DTLSEpoch epoch, /* DTLS only */ 2945 DTLSEpoch epoch, /* DTLS only */
2943 SSL3ContentType type, 2946 SSL3ContentType type,
2944 » » const SSL3Opaque * pIn, /* input buffer */ 2947 const SSL3Opaque *pIn, /* input buffer */
2945 » » PRInt32 nIn, /* bytes of input */ 2948 PRInt32 nIn, /* bytes of input */
2946 » » PRInt32 flags) 2949 PRInt32 flags)
2947 { 2950 {
2948 sslBuffer * wrBuf » = &ss->sec.writeBuf; 2951 sslBuffer *wrBuf = &ss->sec.writeBuf;
2949 SECStatus rv; 2952 SECStatus rv;
2950 PRInt32 totalSent = 0; 2953 PRInt32 totalSent = 0;
2951 PRBool capRecordVersion; 2954 PRBool capRecordVersion;
2952 2955
2953 SSL_TRC(3, ("%d: SSL3[%d] SendRecord type: %s nIn=%d", 2956 SSL_TRC(3, ("%d: SSL3[%d] SendRecord type: %s nIn=%d",
2954 » » SSL_GETPID(), ss->fd, ssl3_DecodeContentType(type), 2957 SSL_GETPID(), ss->fd, ssl3_DecodeContentType(type),
2955 » » nIn)); 2958 nIn));
2956 PRINT_BUF(50, (ss, "Send record (plain text)", pIn, nIn)); 2959 PRINT_BUF(50, (ss, "Send record (plain text)", pIn, nIn));
2957 2960
2958 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); 2961 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
2959 2962
2960 if (ss->ssl3.fatalAlertSent) { 2963 if (ss->ssl3.fatalAlertSent) {
2961 SSL_TRC(3, ("%d: SSL3[%d] Suppress write, fatal alert already sent", 2964 SSL_TRC(3, ("%d: SSL3[%d] Suppress write, fatal alert already sent",
2962 SSL_GETPID(), ss->fd)); 2965 SSL_GETPID(), ss->fd));
2963 return SECFailure; 2966 return SECFailure;
2964 } 2967 }
2965 2968
2966 capRecordVersion = ((flags & ssl_SEND_FLAG_CAP_RECORD_VERSION) != 0); 2969 capRecordVersion = ((flags & ssl_SEND_FLAG_CAP_RECORD_VERSION) != 0);
2967 2970
2968 if (capRecordVersion) { 2971 if (capRecordVersion) {
2969 » /* ssl_SEND_FLAG_CAP_RECORD_VERSION can only be used with the 2972 /* ssl_SEND_FLAG_CAP_RECORD_VERSION can only be used with the
2970 » * TLS initial ClientHello. */ 2973 * TLS initial ClientHello. */
2971 » PORT_Assert(!IS_DTLS(ss)); 2974 PORT_Assert(!IS_DTLS(ss));
2972 » PORT_Assert(!ss->firstHsDone); 2975 PORT_Assert(!ss->firstHsDone);
2973 » PORT_Assert(type == content_handshake); 2976 PORT_Assert(type == content_handshake);
2974 » PORT_Assert(ss->ssl3.hs.ws == wait_server_hello); 2977 PORT_Assert(ss->ssl3.hs.ws == wait_server_hello);
2975 } 2978 }
2976 2979
2977 if (ss->ssl3.initialized == PR_FALSE) { 2980 if (ss->ssl3.initialized == PR_FALSE) {
2978 » /* This can happen on a server if the very first incoming record 2981 /* This can happen on a server if the very first incoming record
2979 » ** looks like a defective ssl3 record (e.g. too long), and we're 2982 ** looks like a defective ssl3 record (e.g. too long), and we're
2980 » ** trying to send an alert. 2983 ** trying to send an alert.
2981 » */ 2984 */
2982 » PR_ASSERT(type == content_alert); 2985 PR_ASSERT(type == content_alert);
2983 » rv = ssl3_InitState(ss); 2986 rv = ssl3_InitState(ss);
2984 » if (rv != SECSuccess) { 2987 if (rv != SECSuccess) {
2985 » return SECFailure;» /* ssl3_InitState has set the error code. */ 2988 return SECFailure; /* ssl3_InitState has set the error code. */
2986 » } 2989 }
2987 } 2990 }
2988 2991
2989 /* check for Token Presence */ 2992 /* check for Token Presence */
2990 if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) { 2993 if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
2991 » PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); 2994 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
2992 » return SECFailure; 2995 return SECFailure;
2993 } 2996 }
2994 2997
2995 while (nIn > 0) { 2998 while (nIn > 0) {
2996 » PRUint32 contentLen = PR_MIN(nIn, MAX_FRAGMENT_LENGTH); 2999 PRUint32 contentLen = PR_MIN(nIn, MAX_FRAGMENT_LENGTH);
2997 » unsigned int spaceNeeded; 3000 unsigned int spaceNeeded;
2998 » unsigned int numRecords; 3001 unsigned int numRecords;
2999 3002
3000 » ssl_GetSpecReadLock(ss); /********************************/ 3003 ssl_GetSpecReadLock(ss); /********************************/
3001 3004
3002 » if (nIn > 1 && ss->opt.cbcRandomIV && 3005 if (nIn > 1 && ss->opt.cbcRandomIV &&
3003 » ss->ssl3.cwSpec->version < SSL_LIBRARY_VERSION_TLS_1_1 && 3006 ss->ssl3.cwSpec->version < SSL_LIBRARY_VERSION_TLS_1_1 &&
3004 » type == content_application_data && 3007 type == content_application_data &&
3005 » ss->ssl3.cwSpec->cipher_def->type == type_block /* CBC mode */) { 3008 ss->ssl3.cwSpec->cipher_def->type == type_block /* CBC mode */) {
3006 » /* We will split the first byte of the record into its own record, 3009 /* We will split the first byte of the record into its own record,
3007 » * as explained in the documentation for SSL_CBC_RANDOM_IV in ssl.h 3010 * as explained in the documentation for SSL_CBC_RANDOM_IV in ssl.h
3008 » */ 3011 */
3009 » numRecords = 2; 3012 numRecords = 2;
3010 » } else { 3013 } else {
3011 » numRecords = 1; 3014 numRecords = 1;
3012 » } 3015 }
3013 3016
3014 » spaceNeeded = contentLen + (numRecords * SSL3_BUFFER_FUDGE); 3017 spaceNeeded = contentLen + (numRecords * SSL3_BUFFER_FUDGE);
3015 » if (ss->ssl3.cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1 && 3018 if (ss->ssl3.cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1 &&
3016 » ss->ssl3.cwSpec->cipher_def->type == type_block) { 3019 ss->ssl3.cwSpec->cipher_def->type == type_block) {
3017 » spaceNeeded += ss->ssl3.cwSpec->cipher_def->iv_size; 3020 spaceNeeded += ss->ssl3.cwSpec->cipher_def->iv_size;
3018 » } 3021 }
3019 » if (spaceNeeded > wrBuf->space) { 3022 if (spaceNeeded > wrBuf->space) {
3020 » rv = sslBuffer_Grow(wrBuf, spaceNeeded); 3023 rv = sslBuffer_Grow(wrBuf, spaceNeeded);
3021 » if (rv != SECSuccess) { 3024 if (rv != SECSuccess) {
3022 » » SSL_DBG(("%d: SSL3[%d]: SendRecord, tried to get %d bytes", 3025 SSL_DBG(("%d: SSL3[%d]: SendRecord, tried to get %d bytes",
3023 » » » SSL_GETPID(), ss->fd, spaceNeeded)); 3026 SSL_GETPID(), ss->fd, spaceNeeded));
3024 » » goto spec_locked_loser; /* sslBuffer_Grow set error code. */ 3027 goto spec_locked_loser; /* sslBuffer_Grow set error code. */
3025 » } 3028 }
3026 » } 3029 }
3027 3030
3028 » if (numRecords == 2) { 3031 if (numRecords == 2) {
3029 » sslBuffer secondRecord; 3032 sslBuffer secondRecord;
3033 rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec,
3034 ss->sec.isServer, IS_DTLS(ss),
3035 capRecordVersion, type, pIn,
3036 1, wrBuf);
3037 if (rv != SECSuccess)
3038 goto spec_locked_loser;
3030 3039
3031 » rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec, 3040 PRINT_BUF(50, (ss, "send (encrypted) record data [1/2]:",
3032 » » » » » ss->sec.isServer, IS_DTLS(ss), 3041 wrBuf->buf, wrBuf->len));
3033 » » » » » capRecordVersion, type, pIn,
3034 » » » » » 1, wrBuf);
3035 » if (rv != SECSuccess)
3036 » goto spec_locked_loser;
3037 3042
3038 » PRINT_BUF(50, (ss, "send (encrypted) record data [1/2]:", 3043 secondRecord.buf = wrBuf->buf + wrBuf->len;
3039 » wrBuf->buf, wrBuf->len)); 3044 secondRecord.len = 0;
3045 secondRecord.space = wrBuf->space - wrBuf->len;
3040 3046
3041 » secondRecord.buf = wrBuf->buf + wrBuf->len; 3047 rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec,
3042 » secondRecord.len = 0; 3048 ss->sec.isServer, IS_DTLS(ss),
3043 » secondRecord.space = wrBuf->space - wrBuf->len; 3049 capRecordVersion, type,
3050 pIn + 1,
3051 contentLen - 1,
3052 &secondRecord);
3053 if (rv == SECSuccess) {
3054 PRINT_BUF(50, (ss, "send (encrypted) record data [2/2]:",
3055 secondRecord.buf, secondRecord.len));
3056 wrBuf->len += secondRecord.len;
3057 }
3058 } else {
3059 if (!IS_DTLS(ss)) {
3060 if (ss->ssl3.cwSpec->version < SSL_LIBRARY_VERSION_TLS_1_3) {
3061 rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec,
3062 ss->sec.isServer,
3063 PR_FALSE,
3064 capRecordVersion,
3065 type, pIn,
3066 contentLen, wrBuf);
3067 } else {
3068 rv = tls13_ProtectRecord(ss, type, pIn,
3069 contentLen, wrBuf);
3070 }
3071 } else {
3072 /* TLS <= 1.2 and TLS 1.3 cases are both handled in
3073 * dtls_CompressMACEncryptRecord. */
3074 rv = dtls_CompressMACEncryptRecord(ss, epoch,
3075 !!(flags & ssl_SEND_FLAG_USE_ EPOCH),
3076 type, pIn,
3077 contentLen, wrBuf);
3078 }
3044 3079
3045 » rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec, 3080 if (rv == SECSuccess) {
3046 » ss->sec.isServer, IS_DTLS(ss), 3081 PRINT_BUF(50, (ss, "send (encrypted) record data:",
3047 » » » » » capRecordVersion, type, 3082 wrBuf->buf, wrBuf->len));
3048 » » » » » pIn + 1, contentLen - 1, 3083 }
3049 » &secondRecord); 3084 }
3050 » if (rv == SECSuccess) {
3051 » PRINT_BUF(50, (ss, "send (encrypted) record data [2/2]:",
3052 » secondRecord.buf, secondRecord.len));
3053 » wrBuf->len += secondRecord.len;
3054 » }
3055 » } else {
3056 » if (!IS_DTLS(ss)) {
3057 » » rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec,
3058 » » » » » » ss->sec.isServer,
3059 » » » » » » IS_DTLS(ss),
3060 » » » » » » capRecordVersion,
3061 » » » » » » type, pIn,
3062 » » » » » » contentLen, wrBuf);
3063 » } else {
3064 » » rv = dtls_CompressMACEncryptRecord(ss, epoch,
3065 » » » » » » !!(flags & ssl_SEND_FLAG_USE_ EPOCH),
3066 » » » » » » type, pIn,
3067 » » » » » » contentLen, wrBuf);
3068 » }
3069 3085
3070 » if (rv == SECSuccess) { 3086 spec_locked_loser:
3071 » PRINT_BUF(50, (ss, "send (encrypted) record data:", 3087 ssl_ReleaseSpecReadLock(ss); /************************************/
3072 » wrBuf->buf, wrBuf->len));
3073 » }
3074 » }
3075 3088
3076 spec_locked_loser: 3089 if (rv != SECSuccess)
3077 » ssl_ReleaseSpecReadLock(ss); /************************************/ 3090 return SECFailure;
3078 3091
3079 » if (rv != SECSuccess) 3092 pIn += contentLen;
3080 » return SECFailure; 3093 nIn -= contentLen;
3094 PORT_Assert(nIn >= 0);
3081 3095
3082 » pIn += contentLen; 3096 /* If there's still some previously saved ciphertext,
3083 » nIn -= contentLen; 3097 * or the caller doesn't want us to send the data yet,
3084 » PORT_Assert( nIn >= 0 ); 3098 * then add all our new ciphertext to the amount previously saved.
3099 */
3100 if ((ss->pendingBuf.len > 0) ||
3101 (flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) {
3085 3102
3086 » /* If there's still some previously saved ciphertext, 3103 rv = ssl_SaveWriteData(ss, wrBuf->buf, wrBuf->len);
3087 » * or the caller doesn't want us to send the data yet, 3104 if (rv != SECSuccess) {
3088 » * then add all our new ciphertext to the amount previously saved. 3105 /* presumably a memory error, SEC_ERROR_NO_MEMORY */
3089 » */ 3106 return SECFailure;
3090 » if ((ss->pendingBuf.len > 0) || 3107 }
3091 » (flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) { 3108 wrBuf->len = 0; /* All cipher text is saved away. */
3092 3109
3093 » rv = ssl_SaveWriteData(ss, wrBuf->buf, wrBuf->len); 3110 if (!(flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) {
3094 » if (rv != SECSuccess) { 3111 PRInt32 sent;
3095 » » /* presumably a memory error, SEC_ERROR_NO_MEMORY */ 3112 ss->handshakeBegun = 1;
3096 » » return SECFailure; 3113 sent = ssl_SendSavedWriteData(ss);
3097 » } 3114 if (sent < 0 && PR_GetError() != PR_WOULD_BLOCK_ERROR) {
3098 » wrBuf->len = 0;» /* All cipher text is saved away. */ 3115 ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
3099 3116 return SECFailure;
3100 » if (!(flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) { 3117 }
3101 » » PRInt32 sent; 3118 if (ss->pendingBuf.len) {
3102 » » ss->handshakeBegun = 1; 3119 flags |= ssl_SEND_FLAG_FORCE_INTO_BUFFER;
3103 » » sent = ssl_SendSavedWriteData(ss); 3120 }
3104 » » if (sent < 0 && PR_GetError() != PR_WOULD_BLOCK_ERROR) { 3121 }
3105 » » ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE); 3122 } else if (wrBuf->len > 0) {
3106 » » return SECFailure; 3123 PRInt32 sent;
3107 » » } 3124 ss->handshakeBegun = 1;
3108 » » if (ss->pendingBuf.len) { 3125 sent = ssl_DefSend(ss, wrBuf->buf, wrBuf->len,
3109 » » flags |= ssl_SEND_FLAG_FORCE_INTO_BUFFER; 3126 flags & ~ssl_SEND_FLAG_MASK);
3110 » » } 3127 if (sent < 0) {
3111 » } 3128 if (PR_GetError() != PR_WOULD_BLOCK_ERROR) {
3112 » } else if (wrBuf->len > 0) { 3129 ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
3113 » PRInt32 sent; 3130 return SECFailure;
3114 » ss->handshakeBegun = 1; 3131 }
3115 » sent = ssl_DefSend(ss, wrBuf->buf, wrBuf->len, 3132 /* we got PR_WOULD_BLOCK_ERROR, which means none was sent. */
3116 » » » flags & ~ssl_SEND_FLAG_MASK); 3133 sent = 0;
3117 » if (sent < 0) { 3134 }
3118 » » if (PR_GetError() != PR_WOULD_BLOCK_ERROR) { 3135 wrBuf->len -= sent;
3119 » » ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE); 3136 if (wrBuf->len) {
3120 » » return SECFailure; 3137 if (IS_DTLS(ss)) {
3121 » » } 3138 /* DTLS just says no in this case. No buffering */
3122 » » /* we got PR_WOULD_BLOCK_ERROR, which means none was sent. */ 3139 PR_SetError(PR_WOULD_BLOCK_ERROR, 0);
3123 » » sent = 0; 3140 return SECFailure;
3124 » } 3141 }
3125 » wrBuf->len -= sent; 3142 /* now take all the remaining unsent new ciphertext and
3126 » if (wrBuf->len) { 3143 * append it to the buffer of previously unsent ciphertext.
3127 » » if (IS_DTLS(ss)) { 3144 */
3128 » » /* DTLS just says no in this case. No buffering */ 3145 rv = ssl_SaveWriteData(ss, wrBuf->buf + sent, wrBuf->len);
3129 » » PR_SetError(PR_WOULD_BLOCK_ERROR, 0); 3146 if (rv != SECSuccess) {
3130 » » return SECFailure; 3147 /* presumably a memory error, SEC_ERROR_NO_MEMORY */
3131 » » } 3148 return SECFailure;
3132 » » /* now take all the remaining unsent new ciphertext and 3149 }
3133 » » * append it to the buffer of previously unsent ciphertext. 3150 }
3134 » » */ 3151 }
3135 » » rv = ssl_SaveWriteData(ss, wrBuf->buf + sent, wrBuf->len); 3152 totalSent += contentLen;
3136 » » if (rv != SECSuccess) {
3137 » » /* presumably a memory error, SEC_ERROR_NO_MEMORY */
3138 » » return SECFailure;
3139 » » }
3140 » }
3141 » }
3142 » totalSent += contentLen;
3143 } 3153 }
3144 return totalSent; 3154 return totalSent;
3145 } 3155 }
3146 3156
3147 #define SSL3_PENDING_HIGH_WATER 1024 3157 #define SSL3_PENDING_HIGH_WATER 1024
3148 3158
3149 /* Attempt to send the content of "in" in an SSL application_data record. 3159 /* Attempt to send the content of "in" in an SSL application_data record.
3150 * Returns "len" or SECFailure, never SECWouldBlock, nor SECSuccess. 3160 * Returns "len" or SECFailure, never SECWouldBlock, nor SECSuccess.
3151 */ 3161 */
3152 int 3162 int
3153 ssl3_SendApplicationData(sslSocket *ss, const unsigned char *in, 3163 ssl3_SendApplicationData(sslSocket *ss, const unsigned char *in,
3154 » » » PRInt32 len, PRInt32 flags) 3164 PRInt32 len, PRInt32 flags)
3155 { 3165 {
3156 PRInt32 totalSent»= 0; 3166 PRInt32 totalSent = 0;
3157 PRInt32 discarded = 0; 3167 PRInt32 discarded = 0;
3158 3168
3159 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); 3169 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
3160 /* These flags for internal use only */ 3170 /* These flags for internal use only */
3161 PORT_Assert(!(flags & (ssl_SEND_FLAG_USE_EPOCH | 3171 PORT_Assert(!(flags & (ssl_SEND_FLAG_USE_EPOCH |
3162 » » » ssl_SEND_FLAG_NO_RETRANSMIT))); 3172 ssl_SEND_FLAG_NO_RETRANSMIT)));
3163 if (len < 0 || !in) { 3173 if (len < 0 || !in) {
3164 » PORT_SetError(PR_INVALID_ARGUMENT_ERROR); 3174 PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
3165 » return SECFailure; 3175 return SECFailure;
3166 } 3176 }
3167 3177
3168 if (ss->pendingBuf.len > SSL3_PENDING_HIGH_WATER && 3178 if (ss->pendingBuf.len > SSL3_PENDING_HIGH_WATER &&
3169 !ssl_SocketIsBlocking(ss)) { 3179 !ssl_SocketIsBlocking(ss)) {
3170 » PORT_Assert(!ssl_SocketIsBlocking(ss)); 3180 PORT_Assert(!ssl_SocketIsBlocking(ss));
3171 » PORT_SetError(PR_WOULD_BLOCK_ERROR); 3181 PORT_SetError(PR_WOULD_BLOCK_ERROR);
3172 » return SECFailure; 3182 return SECFailure;
3173 } 3183 }
3174 3184
3175 if (ss->appDataBuffered && len) { 3185 if (ss->appDataBuffered && len) {
3176 » PORT_Assert (in[0] == (unsigned char)(ss->appDataBuffered)); 3186 PORT_Assert(in[0] == (unsigned char)(ss->appDataBuffered));
3177 » if (in[0] != (unsigned char)(ss->appDataBuffered)) { 3187 if (in[0] != (unsigned char)(ss->appDataBuffered)) {
3178 » PORT_SetError(PR_INVALID_ARGUMENT_ERROR); 3188 PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
3179 » return SECFailure; 3189 return SECFailure;
3180 » } 3190 }
3181 » in++; 3191 in++;
3182 » len--; 3192 len--;
3183 » discarded = 1; 3193 discarded = 1;
3184 } 3194 }
3185 while (len > totalSent) { 3195 while (len > totalSent) {
3186 » PRInt32 sent, toSend; 3196 PRInt32 sent, toSend;
3187 3197
3188 » if (totalSent > 0) { 3198 if (totalSent > 0) {
3189 » /* 3199 /*
3190 » * The thread yield is intended to give the reader thread a 3200 * The thread yield is intended to give the reader thread a
3191 » * chance to get some cycles while the writer thread is in 3201 * chance to get some cycles while the writer thread is in
3192 » * the middle of a large application data write. (See 3202 * the middle of a large application data write. (See
3193 » * Bugzilla bug 127740, comment #1.) 3203 * Bugzilla bug 127740, comment #1.)
3194 » */ 3204 */
3195 » ssl_ReleaseXmitBufLock(ss); 3205 ssl_ReleaseXmitBufLock(ss);
3196 » PR_Sleep(PR_INTERVAL_NO_WAIT);» /* PR_Yield(); */ 3206 PR_Sleep(PR_INTERVAL_NO_WAIT); /* PR_Yield(); */
3197 » ssl_GetXmitBufLock(ss); 3207 ssl_GetXmitBufLock(ss);
3198 » } 3208 }
3199 » toSend = PR_MIN(len - totalSent, MAX_FRAGMENT_LENGTH); 3209 toSend = PR_MIN(len - totalSent, MAX_FRAGMENT_LENGTH);
3200 » /* 3210 /*
3201 » * Note that the 0 epoch is OK because flags will never require 3211 * Note that the 0 epoch is OK because flags will never require
3202 » * its use, as guaranteed by the PORT_Assert above. 3212 * its use, as guaranteed by the PORT_Assert above.
3203 » */ 3213 */
3204 » sent = ssl3_SendRecord(ss, 0, content_application_data, 3214 sent = ssl3_SendRecord(ss, 0, content_application_data,
3205 » in + totalSent, toSend, flags); 3215 in + totalSent, toSend, flags);
3206 » if (sent < 0) { 3216 if (sent < 0) {
3207 » if (totalSent > 0 && PR_GetError() == PR_WOULD_BLOCK_ERROR) { 3217 if (totalSent > 0 && PR_GetError() == PR_WOULD_BLOCK_ERROR) {
3208 » » PORT_Assert(ss->lastWriteBlocked); 3218 PORT_Assert(ss->lastWriteBlocked);
3209 » » break; 3219 break;
3210 » } 3220 }
3211 » return SECFailure; /* error code set by ssl3_SendRecord */ 3221 return SECFailure; /* error code set by ssl3_SendRecord */
3212 » } 3222 }
3213 » totalSent += sent; 3223 totalSent += sent;
3214 » if (ss->pendingBuf.len) { 3224 if (ss->pendingBuf.len) {
3215 » /* must be a non-blocking socket */ 3225 /* must be a non-blocking socket */
3216 » PORT_Assert(!ssl_SocketIsBlocking(ss)); 3226 PORT_Assert(!ssl_SocketIsBlocking(ss));
3217 » PORT_Assert(ss->lastWriteBlocked); 3227 PORT_Assert(ss->lastWriteBlocked);
3218 » break;» 3228 break;
3219 » } 3229 }
3220 } 3230 }
3221 if (ss->pendingBuf.len) { 3231 if (ss->pendingBuf.len) {
3222 » /* Must be non-blocking. */ 3232 /* Must be non-blocking. */
3223 » PORT_Assert(!ssl_SocketIsBlocking(ss)); 3233 PORT_Assert(!ssl_SocketIsBlocking(ss));
3224 » if (totalSent > 0) { 3234 if (totalSent > 0) {
3225 » ss->appDataBuffered = 0x100 | in[totalSent - 1]; 3235 ss->appDataBuffered = 0x100 | in[totalSent - 1];
3226 » } 3236 }
3227 3237
3228 » totalSent = totalSent + discarded - 1; 3238 totalSent = totalSent + discarded - 1;
3229 » if (totalSent <= 0) { 3239 if (totalSent <= 0) {
3230 » PORT_SetError(PR_WOULD_BLOCK_ERROR); 3240 PORT_SetError(PR_WOULD_BLOCK_ERROR);
3231 » totalSent = SECFailure; 3241 totalSent = SECFailure;
3232 » } 3242 }
3233 » return totalSent; 3243 return totalSent;
3234 } 3244 }
3235 ss->appDataBuffered = 0; 3245 ss->appDataBuffered = 0;
3236 return totalSent + discarded; 3246 return totalSent + discarded;
3237 } 3247 }
3238 3248
3239 /* Attempt to send buffered handshake messages. 3249 /* Attempt to send buffered handshake messages.
3240 * This function returns SECSuccess or SECFailure, never SECWouldBlock. 3250 * This function returns SECSuccess or SECFailure, never SECWouldBlock.
3241 * Always set sendBuf.len to 0, even when returning SECFailure. 3251 * Always set sendBuf.len to 0, even when returning SECFailure.
3242 * 3252 *
3243 * Depending on whether we are doing DTLS or not, this either calls 3253 * Depending on whether we are doing DTLS or not, this either calls
3244 * 3254 *
3245 * - ssl3_FlushHandshakeMessages if non-DTLS 3255 * - ssl3_FlushHandshakeMessages if non-DTLS
3246 * - dtls_FlushHandshakeMessages if DTLS 3256 * - dtls_FlushHandshakeMessages if DTLS
3247 * 3257 *
3248 * Called from SSL3_SendAlert(), ssl3_SendChangeCipherSpecs(), 3258 * Called from SSL3_SendAlert(), ssl3_SendChangeCipherSpecs(),
3249 * ssl3_AppendHandshake(), ssl3_SendClientHello(), 3259 * ssl3_AppendHandshake(), ssl3_SendClientHello(),
3250 * ssl3_SendHelloRequest(), ssl3_SendServerHelloDone(), 3260 * ssl3_SendHelloRequest(), ssl3_SendServerHelloDone(),
3251 * ssl3_SendFinished(), 3261 * ssl3_SendFinished(),
3252 */ 3262 */
3253 static SECStatus 3263 SECStatus
3254 ssl3_FlushHandshake(sslSocket *ss, PRInt32 flags) 3264 ssl3_FlushHandshake(sslSocket *ss, PRInt32 flags)
3255 { 3265 {
3256 if (IS_DTLS(ss)) { 3266 if (IS_DTLS(ss)) {
3257 return dtls_FlushHandshakeMessages(ss, flags); 3267 return dtls_FlushHandshakeMessages(ss, flags);
3258 } else { 3268 } else {
3259 return ssl3_FlushHandshakeMessages(ss, flags); 3269 return ssl3_FlushHandshakeMessages(ss, flags);
3260 } 3270 }
3261 } 3271 }
3262 3272
3263 /* Attempt to send the content of sendBuf buffer in an SSL handshake record. 3273 /* Attempt to send the content of sendBuf buffer in an SSL handshake record.
3264 * This function returns SECSuccess or SECFailure, never SECWouldBlock. 3274 * This function returns SECSuccess or SECFailure, never SECWouldBlock.
3265 * Always set sendBuf.len to 0, even when returning SECFailure. 3275 * Always set sendBuf.len to 0, even when returning SECFailure.
3266 * 3276 *
3267 * Called from ssl3_FlushHandshake 3277 * Called from ssl3_FlushHandshake
3268 */ 3278 */
3269 static SECStatus 3279 static SECStatus
3270 ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags) 3280 ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags)
3271 { 3281 {
3272 static const PRInt32 allowedFlags = ssl_SEND_FLAG_FORCE_INTO_BUFFER | 3282 static const PRInt32 allowedFlags = ssl_SEND_FLAG_FORCE_INTO_BUFFER |
3273 ssl_SEND_FLAG_CAP_RECORD_VERSION; 3283 ssl_SEND_FLAG_CAP_RECORD_VERSION;
3274 PRInt32 count = -1; 3284 PRInt32 count = -1;
3275 SECStatus rv = SECSuccess; 3285 SECStatus rv = SECSuccess;
3276 3286
3277 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 3287 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3278 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); 3288 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
3279 3289
3280 if (!ss->sec.ci.sendBuf.buf || !ss->sec.ci.sendBuf.len) 3290 if (!ss->sec.ci.sendBuf.buf || !ss->sec.ci.sendBuf.len)
3281 » return rv; 3291 return rv;
3282 3292
3283 /* only these flags are allowed */ 3293 /* only these flags are allowed */
3284 PORT_Assert(!(flags & ~allowedFlags)); 3294 PORT_Assert(!(flags & ~allowedFlags));
3285 if ((flags & ~allowedFlags) != 0) { 3295 if ((flags & ~allowedFlags) != 0) {
3286 » PORT_SetError(SEC_ERROR_INVALID_ARGS); 3296 PORT_SetError(SEC_ERROR_INVALID_ARGS);
3287 » rv = SECFailure; 3297 rv = SECFailure;
3288 } else { 3298 } else {
3289 » count = ssl3_SendRecord(ss, 0, content_handshake, ss->sec.ci.sendBuf.buf , 3299 count = ssl3_SendRecord(ss, 0, content_handshake, ss->sec.ci.sendBuf.buf ,
3290 » » » ss->sec.ci.sendBuf.len, flags); 3300 ss->sec.ci.sendBuf.len, flags);
3291 } 3301 }
3292 if (count < 0) { 3302 if (count < 0) {
3293 » int err = PORT_GetError(); 3303 int err = PORT_GetError();
3294 » PORT_Assert(err != PR_WOULD_BLOCK_ERROR); 3304 PORT_Assert(err != PR_WOULD_BLOCK_ERROR);
3295 » if (err == PR_WOULD_BLOCK_ERROR) { 3305 if (err == PR_WOULD_BLOCK_ERROR) {
3296 » PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 3306 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
3297 » } 3307 }
3298 rv = SECFailure; 3308 rv = SECFailure;
3299 } else if ((unsigned int)count < ss->sec.ci.sendBuf.len) { 3309 } else if ((unsigned int)count < ss->sec.ci.sendBuf.len) {
3300 » /* short write should never happen */ 3310 /* short write should never happen */
3301 » PORT_Assert((unsigned int)count >= ss->sec.ci.sendBuf.len); 3311 PORT_Assert((unsigned int)count >= ss->sec.ci.sendBuf.len);
3302 » PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 3312 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
3303 » rv = SECFailure; 3313 rv = SECFailure;
3304 } else { 3314 } else {
3305 » rv = SECSuccess; 3315 rv = SECSuccess;
3306 } 3316 }
3307 3317
3308 /* Whether we succeeded or failed, toss the old handshake data. */ 3318 /* Whether we succeeded or failed, toss the old handshake data. */
3309 ss->sec.ci.sendBuf.len = 0; 3319 ss->sec.ci.sendBuf.len = 0;
3310 return rv; 3320 return rv;
3311 } 3321 }
3312 3322
3313 /* 3323 /*
3314 * Called from ssl3_HandleAlert and from ssl3_HandleCertificate when 3324 * Called from ssl3_HandleAlert and from ssl3_HandleCertificate when
3315 * the remote client sends a negative response to our certificate request. 3325 * the remote client sends a negative response to our certificate request.
3316 * Returns SECFailure if the application has required client auth. 3326 * Returns SECFailure if the application has required client auth.
3317 * SECSuccess otherwise. 3327 * SECSuccess otherwise.
3318 */ 3328 */
3319 static SECStatus 3329 static SECStatus
3320 ssl3_HandleNoCertificate(sslSocket *ss) 3330 ssl3_HandleNoCertificate(sslSocket *ss)
3321 { 3331 {
3322 if (ss->sec.peerCert != NULL) { 3332 if (ss->sec.peerCert != NULL) {
3323 » if (ss->sec.peerKey != NULL) { 3333 if (ss->sec.peerKey != NULL) {
3324 » SECKEY_DestroyPublicKey(ss->sec.peerKey); 3334 SECKEY_DestroyPublicKey(ss->sec.peerKey);
3325 » ss->sec.peerKey = NULL; 3335 ss->sec.peerKey = NULL;
3326 » } 3336 }
3327 » CERT_DestroyCertificate(ss->sec.peerCert); 3337 CERT_DestroyCertificate(ss->sec.peerCert);
3328 » ss->sec.peerCert = NULL; 3338 ss->sec.peerCert = NULL;
3329 } 3339 }
3330 ssl3_CleanupPeerCerts(ss); 3340 ssl3_CleanupPeerCerts(ss);
3331 3341
3332 /* If the server has required client-auth blindly but doesn't 3342 /* If the server has required client-auth blindly but doesn't
3333 * actually look at the certificate it won't know that no 3343 * actually look at the certificate it won't know that no
3334 * certificate was presented so we shutdown the socket to ensure 3344 * certificate was presented so we shutdown the socket to ensure
3335 * an error. We only do this if we haven't already completed the 3345 * an error. We only do this if we haven't already completed the
3336 * first handshake because if we're redoing the handshake we 3346 * first handshake because if we're redoing the handshake we
3337 * know the server is paying attention to the certificate. 3347 * know the server is paying attention to the certificate.
3338 */ 3348 */
3339 if ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) || 3349 if ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) ||
3340 » (!ss->firstHsDone && 3350 (!ss->firstHsDone &&
3341 » (ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE))) { 3351 (ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE))) {
3342 » PRFileDesc * lower; 3352 PRFileDesc *lower;
3343 3353
3344 » if (ss->sec.uncache) 3354 if (ss->sec.uncache)
3345 ss->sec.uncache(ss->sec.ci.sid); 3355 ss->sec.uncache(ss->sec.ci.sid);
3346 » SSL3_SendAlert(ss, alert_fatal, bad_certificate); 3356 SSL3_SendAlert(ss, alert_fatal, bad_certificate);
3347 3357
3348 » lower = ss->fd->lower; 3358 lower = ss->fd->lower;
3349 #ifdef _WIN32 3359 #ifdef _WIN32
3350 » lower->methods->shutdown(lower, PR_SHUTDOWN_SEND); 3360 lower->methods->shutdown(lower, PR_SHUTDOWN_SEND);
3351 #else 3361 #else
3352 » lower->methods->shutdown(lower, PR_SHUTDOWN_BOTH); 3362 lower->methods->shutdown(lower, PR_SHUTDOWN_BOTH);
3353 #endif 3363 #endif
3354 » PORT_SetError(SSL_ERROR_NO_CERTIFICATE); 3364 PORT_SetError(SSL_ERROR_NO_CERTIFICATE);
3355 » return SECFailure; 3365 return SECFailure;
3356 } 3366 }
3357 return SECSuccess; 3367 return SECSuccess;
3358 } 3368 }
3359 3369
3360 /************************************************************************ 3370 /************************************************************************
3361 * Alerts 3371 * Alerts
3362 */ 3372 */
3363 3373
3364 /* 3374 /*
3365 ** Acquires both handshake and XmitBuf locks. 3375 ** Acquires both handshake and XmitBuf locks.
3366 ** Called from: ssl3_IllegalParameter» <- 3376 ** Called from: ssl3_IllegalParameter <-
3367 ** ssl3_HandshakeFailure» <- 3377 ** ssl3_HandshakeFailure <-
3368 ** ssl3_HandleAlert» <- ssl3_HandleRecord. 3378 ** ssl3_HandleAlert <- ssl3_HandleRecord.
3369 ** ssl3_HandleChangeCipherSpecs <- ssl3_HandleRecord 3379 ** ssl3_HandleChangeCipherSpecs <- ssl3_HandleRecord
3370 ** ssl3_ConsumeHandshakeVariable <- 3380 ** ssl3_ConsumeHandshakeVariable <-
3371 ** ssl3_HandleHelloRequest»<- 3381 ** ssl3_HandleHelloRequest <-
3372 ** ssl3_HandleServerHello» <- 3382 ** ssl3_HandleServerHello <-
3373 ** ssl3_HandleServerKeyExchange <- 3383 ** ssl3_HandleServerKeyExchange <-
3374 ** ssl3_HandleCertificateRequest <- 3384 ** ssl3_HandleCertificateRequest <-
3375 ** ssl3_HandleServerHelloDone <- 3385 ** ssl3_HandleServerHelloDone <-
3376 ** ssl3_HandleClientHello» <- 3386 ** ssl3_HandleClientHello <-
3377 ** ssl3_HandleV2ClientHello <- 3387 ** ssl3_HandleV2ClientHello <-
3378 ** ssl3_HandleCertificateVerify <- 3388 ** ssl3_HandleCertificateVerify <-
3379 ** ssl3_HandleClientKeyExchange <- 3389 ** ssl3_HandleClientKeyExchange <-
3380 ** ssl3_HandleCertificate» <- 3390 ** ssl3_HandleCertificate <-
3381 ** ssl3_HandleFinished» <- 3391 ** ssl3_HandleFinished <-
3382 ** ssl3_HandleHandshakeMessage <- 3392 ** ssl3_HandleHandshakeMessage <-
3383 ** ssl3_HandleRecord» <- 3393 ** ssl3_HandlePostHelloHandshakeMessage <-
3394 ** ssl3_HandleRecord <-
3384 ** 3395 **
3385 */ 3396 */
3386 SECStatus 3397 SECStatus
3387 SSL3_SendAlert(sslSocket *ss, SSL3AlertLevel level, SSL3AlertDescription desc) 3398 SSL3_SendAlert(sslSocket *ss, SSL3AlertLevel level, SSL3AlertDescription desc)
3388 { 3399 {
3389 PRUint8 » bytes[2]; 3400 PRUint8 bytes[2];
3390 SECStatus» rv; 3401 SECStatus rv;
3391 3402
3392 SSL_TRC(3, ("%d: SSL3[%d]: send alert record, level=%d desc=%d", 3403 SSL_TRC(3, ("%d: SSL3[%d]: send alert record, level=%d desc=%d",
3393 » » SSL_GETPID(), ss->fd, level, desc)); 3404 SSL_GETPID(), ss->fd, level, desc));
3394 3405
3395 bytes[0] = level; 3406 bytes[0] = level;
3396 bytes[1] = desc; 3407 bytes[1] = desc;
3397 3408
3398 ssl_GetSSL3HandshakeLock(ss); 3409 ssl_GetSSL3HandshakeLock(ss);
3399 if (level == alert_fatal) { 3410 if (level == alert_fatal) {
3400 » if (!ss->opt.noCache && ss->sec.ci.sid && ss->sec.uncache) { 3411 if (!ss->opt.noCache && ss->sec.ci.sid && ss->sec.uncache) {
3401 » ss->sec.uncache(ss->sec.ci.sid); 3412 ss->sec.uncache(ss->sec.ci.sid);
3402 » } 3413 }
3403 } 3414 }
3404 ssl_GetXmitBufLock(ss); 3415 ssl_GetXmitBufLock(ss);
3405 rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER); 3416 rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
3406 if (rv == SECSuccess) { 3417 if (rv == SECSuccess) {
3407 » PRInt32 sent; 3418 PRInt32 sent;
3408 » sent = ssl3_SendRecord(ss, 0, content_alert, bytes, 2, 3419 sent = ssl3_SendRecord(ss, 0, content_alert, bytes, 2,
3409 » » » desc == no_certificate 3420 desc == no_certificate ? ssl_SEND_FLAG_FORCE_INTO _BUFFER : 0);
3410 » » » ? ssl_SEND_FLAG_FORCE_INTO_BUFFER : 0); 3421 rv = (sent >= 0) ? SECSuccess : (SECStatus)sent;
3411 » rv = (sent >= 0) ? SECSuccess : (SECStatus)sent;
3412 } 3422 }
3413 if (level == alert_fatal) { 3423 if (level == alert_fatal) {
3414 ss->ssl3.fatalAlertSent = PR_TRUE; 3424 ss->ssl3.fatalAlertSent = PR_TRUE;
3415 } 3425 }
3416 ssl_ReleaseXmitBufLock(ss); 3426 ssl_ReleaseXmitBufLock(ss);
3417 ssl_ReleaseSSL3HandshakeLock(ss); 3427 ssl_ReleaseSSL3HandshakeLock(ss);
3418 return rv;» /* error set by ssl3_FlushHandshake or ssl3_SendRecord */ 3428 return rv; /* error set by ssl3_FlushHandshake or ssl3_SendRecord */
3419 } 3429 }
3420 3430
3421 /* 3431 /*
3422 * Send illegal_parameter alert. Set generic error number. 3432 * Send illegal_parameter alert. Set generic error number.
3423 */ 3433 */
3424 static SECStatus 3434 static SECStatus
3425 ssl3_IllegalParameter(sslSocket *ss) 3435 ssl3_IllegalParameter(sslSocket *ss)
3426 { 3436 {
3427 (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter); 3437 (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
3428 PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT 3438 PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
3429 : SSL_ERROR_BAD_SERVER ); 3439 : SSL_ERROR_BAD_SERVER);
3430 return SECFailure; 3440 return SECFailure;
3431 } 3441 }
3432 3442
3433 /* 3443 /*
3434 * Send handshake_Failure alert. Set generic error number. 3444 * Send handshake_Failure alert. Set generic error number.
3435 */ 3445 */
3436 static SECStatus 3446 static SECStatus
3437 ssl3_HandshakeFailure(sslSocket *ss) 3447 ssl3_HandshakeFailure(sslSocket *ss)
3438 { 3448 {
3439 (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure); 3449 (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
3440 PORT_SetError( ss->sec.isServer ? SSL_ERROR_BAD_CLIENT 3450 PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
3441 : SSL_ERROR_BAD_SERVER ); 3451 : SSL_ERROR_BAD_SERVER);
3442 return SECFailure; 3452 return SECFailure;
3443 } 3453 }
3444 3454
3445 static void 3455 static void
3446 ssl3_SendAlertForCertError(sslSocket * ss, PRErrorCode errCode) 3456 ssl3_SendAlertForCertError(sslSocket *ss, PRErrorCode errCode)
3447 { 3457 {
3448 SSL3AlertDescription desc» = bad_certificate; 3458 SSL3AlertDescription desc = bad_certificate;
3449 PRBool isTLS = ss->version >= SSL_LIBRARY_VERSION_3_1_TLS; 3459 PRBool isTLS = ss->version >= SSL_LIBRARY_VERSION_3_1_TLS;
3450 3460
3451 switch (errCode) { 3461 switch (errCode) {
3452 case SEC_ERROR_LIBRARY_FAILURE: desc = unsupported_certificate; break; 3462 case SEC_ERROR_LIBRARY_FAILURE:
3453 case SEC_ERROR_EXPIRED_CERTIFICATE: desc = certificate_expired; break; 3463 desc = unsupported_certificate;
3454 case SEC_ERROR_REVOKED_CERTIFICATE: desc = certificate_revoked; break; 3464 break;
3455 case SEC_ERROR_INADEQUATE_KEY_USAGE: 3465 case SEC_ERROR_EXPIRED_CERTIFICATE:
3456 case SEC_ERROR_INADEQUATE_CERT_TYPE: 3466 desc = certificate_expired;
3457 » » desc = certificate_unknown; break; 3467 break;
3458 case SEC_ERROR_UNTRUSTED_CERT: 3468 case SEC_ERROR_REVOKED_CERTIFICATE:
3459 » » desc = isTLS ? access_denied : certificate_unknown; break; 3469 desc = certificate_revoked;
3460 case SEC_ERROR_UNKNOWN_ISSUER: 3470 break;
3461 case SEC_ERROR_UNTRUSTED_ISSUER: 3471 case SEC_ERROR_INADEQUATE_KEY_USAGE:
3462 » » desc = isTLS ? unknown_ca : certificate_unknown; break; 3472 case SEC_ERROR_INADEQUATE_CERT_TYPE:
3463 case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE: 3473 desc = certificate_unknown;
3464 » » desc = isTLS ? unknown_ca : certificate_expired; break; 3474 break;
3475 case SEC_ERROR_UNTRUSTED_CERT:
3476 desc = isTLS ? access_denied : certificate_unknown;
3477 break;
3478 case SEC_ERROR_UNKNOWN_ISSUER:
3479 case SEC_ERROR_UNTRUSTED_ISSUER:
3480 desc = isTLS ? unknown_ca : certificate_unknown;
3481 break;
3482 case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE:
3483 desc = isTLS ? unknown_ca : certificate_expired;
3484 break;
3465 3485
3466 case SEC_ERROR_CERT_NOT_IN_NAME_SPACE: 3486 case SEC_ERROR_CERT_NOT_IN_NAME_SPACE:
3467 case SEC_ERROR_PATH_LEN_CONSTRAINT_INVALID: 3487 case SEC_ERROR_PATH_LEN_CONSTRAINT_INVALID:
3468 case SEC_ERROR_CA_CERT_INVALID: 3488 case SEC_ERROR_CA_CERT_INVALID:
3469 case SEC_ERROR_BAD_SIGNATURE: 3489 case SEC_ERROR_BAD_SIGNATURE:
3470 default: desc = bad_certificate; break; 3490 default:
3491 desc = bad_certificate;
3492 break;
3471 } 3493 }
3472 SSL_DBG(("%d: SSL3[%d]: peer certificate is no good: error=%d", 3494 SSL_DBG(("%d: SSL3[%d]: peer certificate is no good: error=%d",
3473 » SSL_GETPID(), ss->fd, errCode)); 3495 SSL_GETPID(), ss->fd, errCode));
3474 3496
3475 (void) SSL3_SendAlert(ss, alert_fatal, desc); 3497 (void)SSL3_SendAlert(ss, alert_fatal, desc);
3476 } 3498 }
3477 3499
3478
3479 /* 3500 /*
3480 * Send decode_error alert. Set generic error number. 3501 * Send decode_error alert. Set generic error number.
3481 */ 3502 */
3482 SECStatus 3503 SECStatus
3483 ssl3_DecodeError(sslSocket *ss) 3504 ssl3_DecodeError(sslSocket *ss)
3484 { 3505 {
3485 (void)SSL3_SendAlert(ss, alert_fatal, 3506 (void)SSL3_SendAlert(ss, alert_fatal,
3486 » » ss->version > SSL_LIBRARY_VERSION_3_0 ? decode_error 3507 ss->version > SSL_LIBRARY_VERSION_3_0 ? decode_error
3487 » » » » » » » : illegal_parameter); 3508 : illegal_paramet er);
3488 PORT_SetError( ss->sec.isServer ? SSL_ERROR_BAD_CLIENT 3509 PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
3489 : SSL_ERROR_BAD_SERVER ); 3510 : SSL_ERROR_BAD_SERVER);
3490 return SECFailure; 3511 return SECFailure;
3491 } 3512 }
3492 3513
3493 /* Called from ssl3_HandleRecord. 3514 /* Called from ssl3_HandleRecord.
3494 ** Caller must hold both RecvBuf and Handshake locks. 3515 ** Caller must hold both RecvBuf and Handshake locks.
3495 */ 3516 */
3496 static SECStatus 3517 static SECStatus
3497 ssl3_HandleAlert(sslSocket *ss, sslBuffer *buf) 3518 ssl3_HandleAlert(sslSocket *ss, sslBuffer *buf)
3498 { 3519 {
3499 SSL3AlertLevel level; 3520 SSL3AlertLevel level;
3500 SSL3AlertDescription desc; 3521 SSL3AlertDescription desc;
3501 int error; 3522 int error;
3502 3523
3503 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 3524 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
3504 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 3525 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3505 3526
3506 SSL_TRC(3, ("%d: SSL3[%d]: handle alert record", SSL_GETPID(), ss->fd)); 3527 SSL_TRC(3, ("%d: SSL3[%d]: handle alert record", SSL_GETPID(), ss->fd));
3507 3528
3508 if (buf->len != 2) { 3529 if (buf->len != 2) {
3509 » (void)ssl3_DecodeError(ss); 3530 (void)ssl3_DecodeError(ss);
3510 » PORT_SetError(SSL_ERROR_RX_MALFORMED_ALERT); 3531 PORT_SetError(SSL_ERROR_RX_MALFORMED_ALERT);
3511 » return SECFailure; 3532 return SECFailure;
3512 } 3533 }
3513 level = (SSL3AlertLevel)buf->buf[0]; 3534 level = (SSL3AlertLevel)buf->buf[0];
3514 desc = (SSL3AlertDescription)buf->buf[1]; 3535 desc = (SSL3AlertDescription)buf->buf[1];
3515 buf->len = 0; 3536 buf->len = 0;
3516 SSL_TRC(5, ("%d: SSL3[%d] received alert, level = %d, description = %d", 3537 SSL_TRC(5, ("%d: SSL3[%d] received alert, level = %d, description = %d",
3517 SSL_GETPID(), ss->fd, level, desc)); 3538 SSL_GETPID(), ss->fd, level, desc));
3518 3539
3519 switch (desc) { 3540 switch (desc) {
3520 case close_notify:» » ss->recvdCloseNotify = 1; 3541 case close_notify:
3521 » » » error = SSL_ERROR_CLOSE_NOTIFY_ALERT; break; 3542 ss->recvdCloseNotify = 1;
3522 case unexpected_message: » error = SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT; 3543 error = SSL_ERROR_CLOSE_NOTIFY_ALERT;
3523 » » » » » » » » » break; 3544 break;
3524 case bad_record_mac: » error = SSL_ERROR_BAD_MAC_ALERT; » break; 3545 case unexpected_message:
3525 case decryption_failed_RESERVED: 3546 error = SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT;
3526 error = SSL_ERROR_DECRYPTION_FAILED_ALERT; 3547 break;
3527 » » » » » » » » » break; 3548 case bad_record_mac:
3528 case record_overflow: » error = SSL_ERROR_RECORD_OVERFLOW_ALERT; break; 3549 error = SSL_ERROR_BAD_MAC_ALERT;
3529 case decompression_failure: error = SSL_ERROR_DECOMPRESSION_FAILURE_ALERT; 3550 break;
3530 » » » » » » » » » break; 3551 case decryption_failed_RESERVED:
3531 case handshake_failure: » error = SSL_ERROR_HANDSHAKE_FAILURE_ALERT; 3552 error = SSL_ERROR_DECRYPTION_FAILED_ALERT;
3532 » » » » » » » » break; 3553 break;
3533 case no_certificate: » error = SSL_ERROR_NO_CERTIFICATE;» break; 3554 case record_overflow:
3534 case bad_certificate: » error = SSL_ERROR_BAD_CERT_ALERT; » break; 3555 error = SSL_ERROR_RECORD_OVERFLOW_ALERT;
3535 case unsupported_certificate:error = SSL_ERROR_UNSUPPORTED_CERT_ALERT;break; 3556 break;
3536 case certificate_revoked: » error = SSL_ERROR_REVOKED_CERT_ALERT; » break; 3557 case decompression_failure:
3537 case certificate_expired: » error = SSL_ERROR_EXPIRED_CERT_ALERT; » break; 3558 error = SSL_ERROR_DECOMPRESSION_FAILURE_ALERT;
3538 case certificate_unknown: » error = SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT; 3559 break;
3539 » » » » » » » » break; 3560 case handshake_failure:
3540 case illegal_parameter: » error = SSL_ERROR_ILLEGAL_PARAMETER_ALERT;break; 3561 error = SSL_ERROR_HANDSHAKE_FAILURE_ALERT;
3541 case inappropriate_fallback: 3562 break;
3542 error = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT; 3563 case no_certificate:
3543 break; 3564 error = SSL_ERROR_NO_CERTIFICATE;
3565 break;
3566 case bad_certificate:
3567 error = SSL_ERROR_BAD_CERT_ALERT;
3568 break;
3569 case unsupported_certificate:
3570 error = SSL_ERROR_UNSUPPORTED_CERT_ALERT;
3571 break;
3572 case certificate_revoked:
3573 error = SSL_ERROR_REVOKED_CERT_ALERT;
3574 break;
3575 case certificate_expired:
3576 error = SSL_ERROR_EXPIRED_CERT_ALERT;
3577 break;
3578 case certificate_unknown:
3579 error = SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT;
3580 break;
3581 case illegal_parameter:
3582 error = SSL_ERROR_ILLEGAL_PARAMETER_ALERT;
3583 break;
3584 case inappropriate_fallback:
3585 error = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT;
3586 break;
3544 3587
3545 /* All alerts below are TLS only. */ 3588 /* All alerts below are TLS only. */
3546 case unknown_ca: » » error = SSL_ERROR_UNKNOWN_CA_ALERT; break; 3589 case unknown_ca:
3547 case access_denied: » error = SSL_ERROR_ACCESS_DENIED_ALERT; break; 3590 error = SSL_ERROR_UNKNOWN_CA_ALERT;
3548 case decode_error: »» error = SSL_ERROR_DECODE_ERROR_ALERT; break; 3591 break;
3549 case decrypt_error: » error = SSL_ERROR_DECRYPT_ERROR_ALERT; break; 3592 case access_denied:
3550 case export_restriction: » error = SSL_ERROR_EXPORT_RESTRICTION_ALERT; 3593 error = SSL_ERROR_ACCESS_DENIED_ALERT;
3551 » » » » » » » » » break; 3594 break;
3552 case protocol_version: » error = SSL_ERROR_PROTOCOL_VERSION_ALERT; break; 3595 case decode_error:
3553 case insufficient_security: error = SSL_ERROR_INSUFFICIENT_SECURITY_ALERT; 3596 error = SSL_ERROR_DECODE_ERROR_ALERT;
3554 » » » » » » » » » break; 3597 break;
3555 case internal_error: » error = SSL_ERROR_INTERNAL_ERROR_ALERT; break; 3598 case decrypt_error:
3556 case user_canceled: » error = SSL_ERROR_USER_CANCELED_ALERT; break; 3599 error = SSL_ERROR_DECRYPT_ERROR_ALERT;
3557 case no_renegotiation: » error = SSL_ERROR_NO_RENEGOTIATION_ALERT; break; 3600 break;
3601 case export_restriction:
3602 error = SSL_ERROR_EXPORT_RESTRICTION_ALERT;
3603 break;
3604 case protocol_version:
3605 error = SSL_ERROR_PROTOCOL_VERSION_ALERT;
3606 break;
3607 case insufficient_security:
3608 error = SSL_ERROR_INSUFFICIENT_SECURITY_ALERT;
3609 break;
3610 case internal_error:
3611 error = SSL_ERROR_INTERNAL_ERROR_ALERT;
3612 break;
3613 case user_canceled:
3614 error = SSL_ERROR_USER_CANCELED_ALERT;
3615 break;
3616 case no_renegotiation:
3617 error = SSL_ERROR_NO_RENEGOTIATION_ALERT;
3618 break;
3558 3619
3559 /* Alerts for TLS client hello extensions */ 3620 /* Alerts for TLS client hello extensions */
3560 case unsupported_extension: 3621 case missing_extension:
3561 » » » error = SSL_ERROR_UNSUPPORTED_EXTENSION_ALERT; break; 3622 error = SSL_ERROR_MISSING_EXTENSION_ALERT;
3562 case certificate_unobtainable: 3623 break;
3563 » » » error = SSL_ERROR_CERTIFICATE_UNOBTAINABLE_ALERT; break; 3624 case unsupported_extension:
3564 case unrecognized_name: 3625 error = SSL_ERROR_UNSUPPORTED_EXTENSION_ALERT;
3565 » » » error = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; break; 3626 break;
3566 case bad_certificate_status_response: 3627 case certificate_unobtainable:
3567 » » » error = SSL_ERROR_BAD_CERT_STATUS_RESPONSE_ALERT; break; 3628 error = SSL_ERROR_CERTIFICATE_UNOBTAINABLE_ALERT;
3568 case bad_certificate_hash_value: 3629 break;
3569 » » » error = SSL_ERROR_BAD_CERT_HASH_VALUE_ALERT; break; 3630 case unrecognized_name:
3570 default: » » error = SSL_ERROR_RX_UNKNOWN_ALERT; break; 3631 error = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
3632 break;
3633 case bad_certificate_status_response:
3634 error = SSL_ERROR_BAD_CERT_STATUS_RESPONSE_ALERT;
3635 break;
3636 case bad_certificate_hash_value:
3637 error = SSL_ERROR_BAD_CERT_HASH_VALUE_ALERT;
3638 break;
3639 default:
3640 error = SSL_ERROR_RX_UNKNOWN_ALERT;
3641 break;
3571 } 3642 }
3572 if (level == alert_fatal) { 3643 if (level == alert_fatal) {
3573 » if (!ss->opt.noCache) { 3644 if (!ss->opt.noCache) {
3574 » if (ss->sec.uncache) 3645 if (ss->sec.uncache)
3575 ss->sec.uncache(ss->sec.ci.sid); 3646 ss->sec.uncache(ss->sec.ci.sid);
3576 » } 3647 }
3577 » if ((ss->ssl3.hs.ws == wait_server_hello) && 3648 if ((ss->ssl3.hs.ws == wait_server_hello) &&
3578 » (desc == handshake_failure)) { 3649 (desc == handshake_failure)) {
3579 » /* XXX This is a hack. We're assuming that any handshake failure 3650 /* XXX This is a hack. We're assuming that any handshake failure
3580 » * XXX on the client hello is a failure to match ciphers. 3651 * XXX on the client hello is a failure to match ciphers.
3581 » */ 3652 */
3582 » error = SSL_ERROR_NO_CYPHER_OVERLAP; 3653 error = SSL_ERROR_NO_CYPHER_OVERLAP;
3583 » } 3654 }
3584 » PORT_SetError(error); 3655 PORT_SetError(error);
3585 » return SECFailure; 3656 return SECFailure;
3586 } 3657 }
3587 if ((desc == no_certificate) && (ss->ssl3.hs.ws == wait_client_cert)) { 3658 if ((desc == no_certificate) && (ss->ssl3.hs.ws == wait_client_cert)) {
3588 » /* I'm a server. I've requested a client cert. He hasn't got one. */ 3659 /* I'm a server. I've requested a client cert. He hasn't got one. */
3589 » SECStatus rv; 3660 SECStatus rv;
3590 3661
3591 » PORT_Assert(ss->sec.isServer); 3662 PORT_Assert(ss->sec.isServer);
3592 » ss->ssl3.hs.ws = wait_client_key; 3663 ss->ssl3.hs.ws = wait_client_key;
3593 » rv = ssl3_HandleNoCertificate(ss); 3664 rv = ssl3_HandleNoCertificate(ss);
3594 » return rv; 3665 return rv;
3595 } 3666 }
3596 return SECSuccess; 3667 return SECSuccess;
3597 } 3668 }
3598 3669
3599 /* 3670 /*
3600 * Change Cipher Specs 3671 * Change Cipher Specs
3601 * Called from ssl3_HandleServerHelloDone, 3672 * Called from ssl3_HandleServerHelloDone,
3602 * ssl3_HandleClientHello, 3673 * ssl3_HandleClientHello,
3603 * and ssl3_HandleFinished 3674 * and ssl3_HandleFinished
3604 * 3675 *
3605 * Acquires and releases spec write lock, to protect switching the current 3676 * Acquires and releases spec write lock, to protect switching the current
3606 * and pending write spec pointers. 3677 * and pending write spec pointers.
3607 */ 3678 */
3608 3679
3609 static SECStatus 3680 static SECStatus
3610 ssl3_SendChangeCipherSpecs(sslSocket *ss) 3681 ssl3_SendChangeCipherSpecs(sslSocket *ss)
3611 { 3682 {
3612 PRUint8 change = change_cipher_spec_choice; 3683 PRUint8 change = change_cipher_spec_choice;
3613 ssl3CipherSpec * pwSpec; 3684 ssl3CipherSpec *pwSpec;
3614 SECStatus rv; 3685 SECStatus rv;
3615 PRInt32 sent; 3686 PRInt32 sent;
3616 3687
3617 SSL_TRC(3, ("%d: SSL3[%d]: send change_cipher_spec record", 3688 SSL_TRC(3, ("%d: SSL3[%d]: send change_cipher_spec record",
3618 » » SSL_GETPID(), ss->fd)); 3689 SSL_GETPID(), ss->fd));
3619 3690
3620 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); 3691 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
3621 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 3692 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3622 3693
3623 rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER); 3694 rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
3624 if (rv != SECSuccess) { 3695 if (rv != SECSuccess) {
3625 » return rv;» /* error code set by ssl3_FlushHandshake */ 3696 return rv; /* error code set by ssl3_FlushHandshake */
3626 } 3697 }
3627 if (!IS_DTLS(ss)) { 3698 if (!IS_DTLS(ss)) {
3628 » sent = ssl3_SendRecord(ss, 0, content_change_cipher_spec, &change, 1, 3699 sent = ssl3_SendRecord(ss, 0, content_change_cipher_spec, &change, 1,
3629 » » » ssl_SEND_FLAG_FORCE_INTO_BUFFER); 3700 ssl_SEND_FLAG_FORCE_INTO_BUFFER);
3630 » if (sent < 0) { 3701 if (sent < 0) {
3631 » return (SECStatus)sent;» /* error code set by ssl3_SendRecord */ 3702 return (SECStatus)sent; /* error code set by ssl3_SendRecord */
3632 » } 3703 }
3633 } else { 3704 } else {
3634 » rv = dtls_QueueMessage(ss, content_change_cipher_spec, &change, 1); 3705 rv = dtls_QueueMessage(ss, content_change_cipher_spec, &change, 1);
3635 » if (rv != SECSuccess) { 3706 if (rv != SECSuccess) {
3636 » return rv; 3707 return rv;
3637 » } 3708 }
3638 } 3709 }
3639 3710
3640 /* swap the pending and current write specs. */ 3711 /* swap the pending and current write specs. */
3641 ssl_GetSpecWriteLock(ss);» /**************************************/ 3712 ssl_GetSpecWriteLock(ss); /**************************************/
3642 pwSpec = ss->ssl3.pwSpec; 3713 pwSpec = ss->ssl3.pwSpec;
3643 3714
3644 ss->ssl3.pwSpec = ss->ssl3.cwSpec; 3715 ss->ssl3.pwSpec = ss->ssl3.cwSpec;
3645 ss->ssl3.cwSpec = pwSpec; 3716 ss->ssl3.cwSpec = pwSpec;
3646 3717
3647 SSL_TRC(3, ("%d: SSL3[%d] Set Current Write Cipher Suite to Pending", 3718 SSL_TRC(3, ("%d: SSL3[%d] Set Current Write Cipher Suite to Pending",
3648 » » SSL_GETPID(), ss->fd )); 3719 SSL_GETPID(), ss->fd));
3649 3720
3650 /* We need to free up the contexts, keys and certs ! */ 3721 /* We need to free up the contexts, keys and certs ! */
3651 /* If we are really through with the old cipher spec 3722 /* If we are really through with the old cipher spec
3652 * (Both the read and write sides have changed) destroy it. 3723 * (Both the read and write sides have changed) destroy it.
3653 */ 3724 */
3654 if (ss->ssl3.prSpec == ss->ssl3.pwSpec) { 3725 if (ss->ssl3.prSpec == ss->ssl3.pwSpec) {
3655 » if (!IS_DTLS(ss)) { 3726 if (!IS_DTLS(ss)) {
3656 » ssl3_DestroyCipherSpec(ss->ssl3.pwSpec, PR_FALSE/*freeSrvName*/); 3727 ssl3_DestroyCipherSpec(ss->ssl3.pwSpec, PR_FALSE /*freeSrvName*/);
3657 » } else { 3728 } else {
3658 » /* With DTLS, we need to set a holddown timer in case the final 3729 /* With DTLS, we need to set a holddown timer in case the final
3659 » * message got lost */ 3730 * message got lost */
3660 » ss->ssl3.hs.rtTimeoutMs = DTLS_FINISHED_TIMER_MS; 3731 ss->ssl3.hs.rtTimeoutMs = DTLS_FINISHED_TIMER_MS;
3661 » dtls_StartTimer(ss, dtls_FinishedTimerCb); 3732 dtls_StartTimer(ss, dtls_FinishedTimerCb);
3662 » } 3733 }
3663 } 3734 }
3664 ssl_ReleaseSpecWriteLock(ss); /**************************************/ 3735 ssl_ReleaseSpecWriteLock(ss); /**************************************/
3665 3736
3666 return SECSuccess; 3737 return SECSuccess;
3667 } 3738 }
3668 3739
3669 /* Called from ssl3_HandleRecord. 3740 /* Called from ssl3_HandleRecord.
3670 ** Caller must hold both RecvBuf and Handshake locks. 3741 ** Caller must hold both RecvBuf and Handshake locks.
3671 * 3742 *
3672 * Acquires and releases spec write lock, to protect switching the current 3743 * Acquires and releases spec write lock, to protect switching the current
3673 * and pending write spec pointers. 3744 * and pending write spec pointers.
3674 */ 3745 */
3675 static SECStatus 3746 static SECStatus
3676 ssl3_HandleChangeCipherSpecs(sslSocket *ss, sslBuffer *buf) 3747 ssl3_HandleChangeCipherSpecs(sslSocket *ss, sslBuffer *buf)
3677 { 3748 {
3678 ssl3CipherSpec * prSpec; 3749 ssl3CipherSpec *prSpec;
3679 SSL3WaitState ws = ss->ssl3.hs.ws; 3750 SSL3WaitState ws = ss->ssl3.hs.ws;
3680 SSL3ChangeCipherSpecChoice change; 3751 SSL3ChangeCipherSpecChoice change;
3681 3752
3682 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 3753 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
3683 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 3754 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3684 3755
3685 SSL_TRC(3, ("%d: SSL3[%d]: handle change_cipher_spec record", 3756 SSL_TRC(3, ("%d: SSL3[%d]: handle change_cipher_spec record",
3686 » » SSL_GETPID(), ss->fd)); 3757 SSL_GETPID(), ss->fd));
3687 3758
3688 if (ws != wait_change_cipher) { 3759 if (ws != wait_change_cipher) {
3689 » if (IS_DTLS(ss)) { 3760 if (IS_DTLS(ss)) {
3690 » /* Ignore this because it's out of order. */ 3761 /* Ignore this because it's out of order. */
3691 » SSL_TRC(3, ("%d: SSL3[%d]: discard out of order " 3762 SSL_TRC(3, ("%d: SSL3[%d]: discard out of order "
3692 » » » "DTLS change_cipher_spec", 3763 "DTLS change_cipher_spec",
3693 » » » SSL_GETPID(), ss->fd)); 3764 SSL_GETPID(), ss->fd));
3694 » buf->len = 0; 3765 buf->len = 0;
3695 » return SECSuccess; 3766 return SECSuccess;
3696 » } 3767 }
3697 » (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 3768 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
3698 » PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER); 3769 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER);
3699 » return SECFailure; 3770 return SECFailure;
3700 } 3771 }
3701 3772
3702 if(buf->len != 1) { 3773 if (buf->len != 1) {
3703 » (void)ssl3_DecodeError(ss); 3774 (void)ssl3_DecodeError(ss);
3704 » PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER); 3775 PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
3705 » return SECFailure; 3776 return SECFailure;
3706 } 3777 }
3707 change = (SSL3ChangeCipherSpecChoice)buf->buf[0]; 3778 change = (SSL3ChangeCipherSpecChoice)buf->buf[0];
3708 if (change != change_cipher_spec_choice) { 3779 if (change != change_cipher_spec_choice) {
3709 » /* illegal_parameter is correct here for both SSL3 and TLS. */ 3780 /* illegal_parameter is correct here for both SSL3 and TLS. */
3710 » (void)ssl3_IllegalParameter(ss); 3781 (void)ssl3_IllegalParameter(ss);
3711 » PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER); 3782 PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
3712 » return SECFailure; 3783 return SECFailure;
3713 } 3784 }
3714 buf->len = 0; 3785 buf->len = 0;
3715 3786
3716 /* Swap the pending and current read specs. */ 3787 /* Swap the pending and current read specs. */
3717 ssl_GetSpecWriteLock(ss); /*************************************/ 3788 ssl_GetSpecWriteLock(ss); /*************************************/
3718 prSpec = ss->ssl3.prSpec; 3789 prSpec = ss->ssl3.prSpec;
3719 3790
3720 ss->ssl3.prSpec = ss->ssl3.crSpec; 3791 ss->ssl3.prSpec = ss->ssl3.crSpec;
3721 ss->ssl3.crSpec = prSpec; 3792 ss->ssl3.crSpec = prSpec;
3722 ss->ssl3.hs.ws = wait_finished; 3793 ss->ssl3.hs.ws = wait_finished;
3723 3794
3724 SSL_TRC(3, ("%d: SSL3[%d] Set Current Read Cipher Suite to Pending", 3795 SSL_TRC(3, ("%d: SSL3[%d] Set Current Read Cipher Suite to Pending",
3725 » » SSL_GETPID(), ss->fd )); 3796 SSL_GETPID(), ss->fd));
3726 3797
3727 /* If we are really through with the old cipher prSpec 3798 /* If we are really through with the old cipher prSpec
3728 * (Both the read and write sides have changed) destroy it. 3799 * (Both the read and write sides have changed) destroy it.
3729 */ 3800 */
3730 if (ss->ssl3.prSpec == ss->ssl3.pwSpec) { 3801 if (ss->ssl3.prSpec == ss->ssl3.pwSpec) {
3731 » ssl3_DestroyCipherSpec(ss->ssl3.prSpec, PR_FALSE/*freeSrvName*/); 3802 ssl3_DestroyCipherSpec(ss->ssl3.prSpec, PR_FALSE /*freeSrvName*/);
3732 } 3803 }
3733 ssl_ReleaseSpecWriteLock(ss); /*************************************/ 3804 ssl_ReleaseSpecWriteLock(ss); /*************************************/
3734 return SECSuccess; 3805 return SECSuccess;
3735 } 3806 }
3736 3807
3737 /* This method completes the derivation of the MS from the PMS. 3808 /* This method completes the derivation of the MS from the PMS.
3738 ** 3809 **
3739 ** 1. Derive the MS, if possible, else return an error. 3810 ** 1. Derive the MS, if possible, else return an error.
3740 ** 3811 **
3741 ** 2. Check the version if |pms_version| is non-zero and if wrong, 3812 ** 2. Check the version if |pms_version| is non-zero and if wrong,
3742 ** return an error. 3813 ** return an error.
3743 ** 3814 **
(...skipping 48 matching lines...) Expand 10 before | Expand all | Expand 10 after
3792 3863
3793 /* Compute the ordinary (pre draft-ietf-tls-session-hash) master 3864 /* Compute the ordinary (pre draft-ietf-tls-session-hash) master
3794 ** secret and return it in |*msp|. 3865 ** secret and return it in |*msp|.
3795 ** 3866 **
3796 ** Called from: ssl3_ComputeMasterSecret 3867 ** Called from: ssl3_ComputeMasterSecret
3797 */ 3868 */
3798 static SECStatus 3869 static SECStatus
3799 ssl3_ComputeMasterSecretInt(sslSocket *ss, PK11SymKey *pms, 3870 ssl3_ComputeMasterSecretInt(sslSocket *ss, PK11SymKey *pms,
3800 PK11SymKey **msp) 3871 PK11SymKey **msp)
3801 { 3872 {
3802 ssl3CipherSpec * pwSpec = ss->ssl3.pwSpec; 3873 ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec;
3803 const ssl3KEADef *kea_def= ss->ssl3.hs.kea_def; 3874 const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def;
3804 unsigned char * cr = (unsigned char *)&ss->ssl3.hs.client_random; 3875 unsigned char *cr = (unsigned char *)&ss->ssl3.hs.client_random;
3805 unsigned char * sr = (unsigned char *)&ss->ssl3.hs.server_random; 3876 unsigned char *sr = (unsigned char *)&ss->ssl3.hs.server_random;
3806 PRBool isTLS = (PRBool)(kea_def->tls_keygen || 3877 PRBool isTLS = (PRBool)(kea_def->tls_keygen ||
3807 (pwSpec->version > SSL_LIBRARY_VERSION_3_0)); 3878 (pwSpec->version > SSL_LIBRARY_VERSION_3_0));
3808 PRBool isTLS12= 3879 PRBool isTLS12 =
3809 » (PRBool)(isTLS && pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); 3880 (PRBool)(isTLS && pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
3810 /* 3881 /*
3811 * Whenever isDH is true, we need to use CKM_TLS_MASTER_KEY_DERIVE_DH 3882 * Whenever isDH is true, we need to use CKM_TLS_MASTER_KEY_DERIVE_DH
3812 * which, unlike CKM_TLS_MASTER_KEY_DERIVE, converts arbitrary size 3883 * which, unlike CKM_TLS_MASTER_KEY_DERIVE, converts arbitrary size
3813 * data into a 48-byte value, and does not expect to return the version. 3884 * data into a 48-byte value, and does not expect to return the version.
3814 */ 3885 */
3815 PRBool isDH = (PRBool) ((ss->ssl3.hs.kea_def->exchKeyType == kt_dh) || 3886 PRBool isDH = (PRBool)((ss->ssl3.hs.kea_def->exchKeyType == kt_dh) ||
3816 » (ss->ssl3.hs.kea_def->exchKeyType == kt_ecdh)); 3887 (ss->ssl3.hs.kea_def->exchKeyType == kt_ecdh));
3817 CK_MECHANISM_TYPE master_derive; 3888 CK_MECHANISM_TYPE master_derive;
3818 CK_MECHANISM_TYPE key_derive; 3889 CK_MECHANISM_TYPE key_derive;
3819 SECItem params; 3890 SECItem params;
3820 CK_FLAGS keyFlags; 3891 CK_FLAGS keyFlags;
3821 CK_VERSION pms_version; 3892 CK_VERSION pms_version;
3822 CK_VERSION *pms_version_ptr = NULL; 3893 CK_VERSION *pms_version_ptr = NULL;
3823 /* master_params may be used as a CK_SSL3_MASTER_KEY_DERIVE_PARAMS */ 3894 /* master_params may be used as a CK_SSL3_MASTER_KEY_DERIVE_PARAMS */
3824 CK_TLS12_MASTER_KEY_DERIVE_PARAMS master_params; 3895 CK_TLS12_MASTER_KEY_DERIVE_PARAMS master_params;
3825 unsigned int master_params_len; 3896 unsigned int master_params_len;
3826 3897
3827 if (isTLS12) { 3898 if (isTLS12) {
3828 » if(isDH) master_derive = CKM_TLS12_MASTER_KEY_DERIVE_DH; 3899 if (isDH)
3829 » else master_derive = CKM_TLS12_MASTER_KEY_DERIVE; 3900 master_derive = CKM_TLS12_MASTER_KEY_DERIVE_DH;
3830 » key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE; 3901 else
3831 » keyFlags = CKF_SIGN | CKF_VERIFY; 3902 master_derive = CKM_TLS12_MASTER_KEY_DERIVE;
3903 key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE;
3904 keyFlags = CKF_SIGN | CKF_VERIFY;
3832 } else if (isTLS) { 3905 } else if (isTLS) {
3833 » if(isDH) master_derive = CKM_TLS_MASTER_KEY_DERIVE_DH; 3906 if (isDH)
3834 » else master_derive = CKM_TLS_MASTER_KEY_DERIVE; 3907 master_derive = CKM_TLS_MASTER_KEY_DERIVE_DH;
3835 » key_derive = CKM_TLS_KEY_AND_MAC_DERIVE; 3908 else
3836 » keyFlags = CKF_SIGN | CKF_VERIFY; 3909 master_derive = CKM_TLS_MASTER_KEY_DERIVE;
3910 key_derive = CKM_TLS_KEY_AND_MAC_DERIVE;
3911 keyFlags = CKF_SIGN | CKF_VERIFY;
3837 } else { 3912 } else {
3838 » if (isDH) master_derive = CKM_SSL3_MASTER_KEY_DERIVE_DH; 3913 if (isDH)
3839 » else master_derive = CKM_SSL3_MASTER_KEY_DERIVE; 3914 master_derive = CKM_SSL3_MASTER_KEY_DERIVE_DH;
3840 » key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE; 3915 else
3841 » keyFlags = 0; 3916 master_derive = CKM_SSL3_MASTER_KEY_DERIVE;
3917 key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE;
3918 keyFlags = 0;
3842 } 3919 }
3843 3920
3844 if (!isDH) { 3921 if (!isDH) {
3845 pms_version_ptr = &pms_version; 3922 pms_version_ptr = &pms_version;
3846 } 3923 }
3847 3924
3848 master_params.pVersion = pms_version_ptr; 3925 master_params.pVersion = pms_version_ptr;
3849 master_params.RandomInfo.pClientRandom = cr; 3926 master_params.RandomInfo.pClientRandom = cr;
3850 master_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH; 3927 master_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH;
3851 master_params.RandomInfo.pServerRandom = sr; 3928 master_params.RandomInfo.pServerRandom = sr;
3852 master_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH; 3929 master_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH;
3853 if (isTLS12) { 3930 if (isTLS12) {
3854 master_params.prfHashMechanism = CKM_SHA256; 3931 master_params.prfHashMechanism = CKM_SHA256;
3855 master_params_len = sizeof(CK_TLS12_MASTER_KEY_DERIVE_PARAMS); 3932 master_params_len = sizeof(CK_TLS12_MASTER_KEY_DERIVE_PARAMS);
3856 } else { 3933 } else {
3857 /* prfHashMechanism is not relevant with this PRF */ 3934 /* prfHashMechanism is not relevant with this PRF */
3858 master_params_len = sizeof(CK_SSL3_MASTER_KEY_DERIVE_PARAMS); 3935 master_params_len = sizeof(CK_SSL3_MASTER_KEY_DERIVE_PARAMS);
3859 } 3936 }
3860 3937
3861 params.data = (unsigned char *) &master_params; 3938 params.data = (unsigned char *)&master_params;
3862 params.len = master_params_len; 3939 params.len = master_params_len;
3863 3940
3864 return ssl3_ComputeMasterSecretFinish(ss, master_derive, key_derive, 3941 return ssl3_ComputeMasterSecretFinish(ss, master_derive, key_derive,
3865 pms_version_ptr, &params, 3942 pms_version_ptr, &params,
3866 keyFlags, pms, msp); 3943 keyFlags, pms, msp);
3867 } 3944 }
3868 3945
3869 /* Compute the draft-ietf-tls-session-hash master 3946 /* Compute the draft-ietf-tls-session-hash master
3870 ** secret and return it in |*msp|. 3947 ** secret and return it in |*msp|.
3871 ** 3948 **
3872 ** Called from: ssl3_ComputeMasterSecret 3949 ** Called from: ssl3_ComputeMasterSecret
3873 */ 3950 */
3874 static SECStatus 3951 static SECStatus
3875 tls_ComputeExtendedMasterSecretInt(sslSocket *ss, PK11SymKey *pms, 3952 tls_ComputeExtendedMasterSecretInt(sslSocket *ss, PK11SymKey *pms,
3876 PK11SymKey **msp) 3953 PK11SymKey **msp)
3877 { 3954 {
3878 ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec; 3955 ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec;
3879 CK_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE_PARAMS extended_master_params; 3956 CK_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE_PARAMS extended_master_params;
3880 SSL3Hashes hashes; 3957 SSL3Hashes hashes;
3881 /* 3958 /*
3882 * Determine whether to use the DH/ECDH or RSA derivation modes. 3959 * Determine whether to use the DH/ECDH or RSA derivation modes.
3883 */ 3960 */
3884 /* 3961 /*
3885 * TODO(ekr@rtfm.com): Verify that the slot can handle this key expansion 3962 * TODO(ekr@rtfm.com): Verify that the slot can handle this key expansion
3886 * mode. Bug 1198298 */ 3963 * mode. Bug 1198298 */
3887 PRBool isDH = (PRBool) ((ss->ssl3.hs.kea_def->exchKeyType == kt_dh) || 3964 PRBool isDH = (PRBool)((ss->ssl3.hs.kea_def->exchKeyType == kt_dh) ||
3888 (ss->ssl3.hs.kea_def->exchKeyType == kt_ecdh)); 3965 (ss->ssl3.hs.kea_def->exchKeyType == kt_ecdh));
3889 CK_MECHANISM_TYPE master_derive; 3966 CK_MECHANISM_TYPE master_derive;
3890 CK_MECHANISM_TYPE key_derive; 3967 CK_MECHANISM_TYPE key_derive;
3891 SECItem params; 3968 SECItem params;
3892 const CK_FLAGS keyFlags = CKF_SIGN | CKF_VERIFY; 3969 const CK_FLAGS keyFlags = CKF_SIGN | CKF_VERIFY;
3893 CK_VERSION pms_version; 3970 CK_VERSION pms_version;
3894 CK_VERSION *pms_version_ptr = NULL; 3971 CK_VERSION *pms_version_ptr = NULL;
3895 SECStatus rv; 3972 SECStatus rv;
3896 3973
3897 rv = ssl3_ComputeHandshakeHashes(ss, pwSpec, &hashes, 0); 3974 rv = ssl3_ComputeHandshakeHashes(ss, pwSpec, &hashes, 0);
3898 if (rv != SECSuccess) { 3975 if (rv != SECSuccess) {
3899 PORT_Assert(0); /* Should never fail */ 3976 PORT_Assert(0); /* Should never fail */
3900 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); 3977 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3901 return SECFailure; 3978 return SECFailure;
3902 } 3979 }
3903 3980
3904 if (isDH) { 3981 if (isDH) {
3905 master_derive = CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE_DH; 3982 master_derive = CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE_DH;
3906 } else { 3983 } else {
3907 master_derive = CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE; 3984 master_derive = CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE;
3908 pms_version_ptr = &pms_version; 3985 pms_version_ptr = &pms_version;
3909 } 3986 }
3910 3987
3911 if (pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { 3988 if (pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
3912 /* TLS 1.2 */ 3989 /* TLS 1.2 */
3913 extended_master_params.prfHashMechanism = CKM_SHA256; 3990 extended_master_params.prfHashMechanism = CKM_SHA256;
3914 key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE; 3991 key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE;
3915 } else { 3992 } else {
3916 /* TLS < 1.2 */ 3993 /* TLS < 1.2 */
3917 extended_master_params.prfHashMechanism = CKM_TLS_PRF; 3994 extended_master_params.prfHashMechanism = CKM_TLS_PRF;
3918 » key_derive = CKM_TLS_KEY_AND_MAC_DERIVE; 3995 key_derive = CKM_TLS_KEY_AND_MAC_DERIVE;
3919 } 3996 }
3920 3997
3921 extended_master_params.pVersion = pms_version_ptr; 3998 extended_master_params.pVersion = pms_version_ptr;
3922 extended_master_params.pSessionHash = hashes.u.raw; 3999 extended_master_params.pSessionHash = hashes.u.raw;
3923 extended_master_params.ulSessionHashLen = hashes.len; 4000 extended_master_params.ulSessionHashLen = hashes.len;
3924 4001
3925 params.data = (unsigned char *) &extended_master_params; 4002 params.data = (unsigned char *)&extended_master_params;
3926 params.len = sizeof extended_master_params; 4003 params.len = sizeof extended_master_params;
3927 4004
3928 return ssl3_ComputeMasterSecretFinish(ss, master_derive, key_derive, 4005 return ssl3_ComputeMasterSecretFinish(ss, master_derive, key_derive,
3929 pms_version_ptr, &params, 4006 pms_version_ptr, &params,
3930 keyFlags, pms, msp); 4007 keyFlags, pms, msp);
3931 } 4008 }
3932 4009
3933
3934 /* Wrapper method to compute the master secret and return it in |*msp|. 4010 /* Wrapper method to compute the master secret and return it in |*msp|.
3935 ** 4011 **
3936 ** Called from ssl3_ComputeMasterSecret 4012 ** Called from ssl3_ComputeMasterSecret
3937 */ 4013 */
3938 static SECStatus 4014 static SECStatus
3939 ssl3_ComputeMasterSecret(sslSocket *ss, PK11SymKey *pms, 4015 ssl3_ComputeMasterSecret(sslSocket *ss, PK11SymKey *pms,
3940 PK11SymKey **msp) 4016 PK11SymKey **msp)
3941 { 4017 {
3942 PORT_Assert(pms != NULL); 4018 PORT_Assert(pms != NULL);
3943 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 4019 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
(...skipping 12 matching lines...) Expand all
3956 ** 4032 **
3957 ** This is used in all cases except the "triple bypass" with RSA key 4033 ** This is used in all cases except the "triple bypass" with RSA key
3958 ** exchange. 4034 ** exchange.
3959 ** 4035 **
3960 ** Called from ssl3_InitPendingCipherSpec. prSpec is pwSpec. 4036 ** Called from ssl3_InitPendingCipherSpec. prSpec is pwSpec.
3961 */ 4037 */
3962 static SECStatus 4038 static SECStatus
3963 ssl3_DeriveMasterSecret(sslSocket *ss, PK11SymKey *pms) 4039 ssl3_DeriveMasterSecret(sslSocket *ss, PK11SymKey *pms)
3964 { 4040 {
3965 SECStatus rv; 4041 SECStatus rv;
3966 PK11SymKey* ms = NULL; 4042 PK11SymKey *ms = NULL;
3967 ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec; 4043 ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec;
3968 4044
3969 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 4045 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
3970 PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); 4046 PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
3971 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); 4047 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
3972 4048
3973 if (pms) { 4049 if (pms) {
3974 rv = ssl3_ComputeMasterSecret(ss, pms, &ms); 4050 rv = ssl3_ComputeMasterSecret(ss, pms, &ms);
3975 pwSpec->master_secret = ms; 4051 pwSpec->master_secret = ms;
3976 if (rv != SECSuccess) 4052 if (rv != SECSuccess)
3977 return rv; 4053 return rv;
3978 } 4054 }
3979 4055
3980 #ifndef NO_PKCS11_BYPASS 4056 #ifndef NO_PKCS11_BYPASS
3981 if (ss->opt.bypassPKCS11) { 4057 if (ss->opt.bypassPKCS11) {
3982 » SECItem * keydata; 4058 SECItem *keydata;
3983 » /* In hope of doing a "double bypass", 4059 /* In hope of doing a "double bypass",
3984 » * need to extract the master secret's value from the key object 4060 * need to extract the master secret's value from the key object
3985 » * and store it raw in the sslSocket struct. 4061 * and store it raw in the sslSocket struct.
3986 » */ 4062 */
3987 » rv = PK11_ExtractKeyValue(pwSpec->master_secret); 4063 rv = PK11_ExtractKeyValue(pwSpec->master_secret);
3988 » if (rv != SECSuccess) { 4064 if (rv != SECSuccess) {
3989 » return rv; 4065 return rv;
3990 } 4066 }
3991 » /* This returns the address of the secItem inside the key struct, 4067 /* This returns the address of the secItem inside the key struct,
3992 » * not a copy or a reference. So, there's no need to free it. 4068 * not a copy or a reference. So, there's no need to free it.
3993 » */ 4069 */
3994 » keydata = PK11_GetKeyData(pwSpec->master_secret); 4070 keydata = PK11_GetKeyData(pwSpec->master_secret);
3995 » if (keydata && keydata->len <= sizeof pwSpec->raw_master_secret) { 4071 if (keydata && keydata->len <= sizeof pwSpec->raw_master_secret) {
3996 » memcpy(pwSpec->raw_master_secret, keydata->data, keydata->len); 4072 memcpy(pwSpec->raw_master_secret, keydata->data, keydata->len);
3997 » pwSpec->msItem.data = pwSpec->raw_master_secret; 4073 pwSpec->msItem.data = pwSpec->raw_master_secret;
3998 » pwSpec->msItem.len = keydata->len; 4074 pwSpec->msItem.len = keydata->len;
3999 » } else { 4075 } else {
4000 » PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 4076 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
4001 » return SECFailure; 4077 return SECFailure;
4002 » } 4078 }
4003 } 4079 }
4004 #endif 4080 #endif
4005 4081
4006 return SECSuccess; 4082 return SECSuccess;
4007 } 4083 }
4008 4084
4009 /* 4085 /*
4010 * Derive encryption and MAC Keys (and IVs) from master secret 4086 * Derive encryption and MAC Keys (and IVs) from master secret
4011 * Sets a useful error code when returning SECFailure. 4087 * Sets a useful error code when returning SECFailure.
4012 * 4088 *
4013 * Called only from ssl3_InitPendingCipherSpec(), 4089 * Called only from ssl3_InitPendingCipherSpec(),
4014 * which in turn is called from 4090 * which in turn is called from
4015 * sendRSAClientKeyExchange (for Full handshake) 4091 * sendRSAClientKeyExchange (for Full handshake)
4016 * sendDHClientKeyExchange (for Full handshake) 4092 * sendDHClientKeyExchange (for Full handshake)
4017 * ssl3_HandleClientKeyExchange (for Full handshake) 4093 * ssl3_HandleClientKeyExchange (for Full handshake)
4018 * ssl3_HandleServerHello (for session restart) 4094 * ssl3_HandleServerHello (for session restart)
4019 * ssl3_HandleClientHello (for session restart) 4095 * ssl3_HandleClientHello (for session restart)
4020 * Caller MUST hold the specWriteLock, and SSL3HandshakeLock. 4096 * Caller MUST hold the specWriteLock, and SSL3HandshakeLock.
4021 * ssl3_InitPendingCipherSpec does that. 4097 * ssl3_InitPendingCipherSpec does that.
4022 * 4098 *
4023 */ 4099 */
4024 static SECStatus 4100 static SECStatus
4025 ssl3_DeriveConnectionKeysPKCS11(sslSocket *ss) 4101 ssl3_DeriveConnectionKeysPKCS11(sslSocket *ss)
4026 { 4102 {
4027 ssl3CipherSpec * pwSpec = ss->ssl3.pwSpec; 4103 ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec;
4028 const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def; 4104 const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def;
4029 unsigned char * cr = (unsigned char *)&ss->ssl3.hs.client_random; 4105 unsigned char *cr = (unsigned char *)&ss->ssl3.hs.client_random;
4030 unsigned char * sr = (unsigned char *)&ss->ssl3.hs.server_random; 4106 unsigned char *sr = (unsigned char *)&ss->ssl3.hs.server_random;
4031 PRBool isTLS = (PRBool)(kea_def->tls_keygen || 4107 PRBool isTLS = (PRBool)(kea_def->tls_keygen ||
4032 (pwSpec->version > SSL_LIBRARY_VERSION_3_0)); 4108 (pwSpec->version > SSL_LIBRARY_VERSION_3_0));
4033 PRBool isTLS12= 4109 PRBool isTLS12 =
4034 » (PRBool)(isTLS && pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); 4110 (PRBool)(isTLS && pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
4035 /* following variables used in PKCS11 path */ 4111 /* following variables used in PKCS11 path */
4036 const ssl3BulkCipherDef *cipher_def = pwSpec->cipher_def; 4112 const ssl3BulkCipherDef *cipher_def = pwSpec->cipher_def;
4037 PK11SlotInfo * slot = NULL; 4113 PK11SlotInfo *slot = NULL;
4038 PK11SymKey * symKey = NULL; 4114 PK11SymKey *symKey = NULL;
4039 void * pwArg = ss->pkcs11PinArg; 4115 void *pwArg = ss->pkcs11PinArg;
4040 int keySize; 4116 int keySize;
4041 CK_TLS12_KEY_MAT_PARAMS key_material_params; /* may be used as a 4117 CK_TLS12_KEY_MAT_PARAMS key_material_params; /* may be used as a
4042 » » » » » » * CK_SSL3_KEY_MAT_PARAMS */ 4118 * CK_SSL3_KEY_MAT_PARAMS */
4043 unsigned int key_material_params_len; 4119 unsigned int key_material_params_len;
4044 CK_SSL3_KEY_MAT_OUT returnedKeys; 4120 CK_SSL3_KEY_MAT_OUT returnedKeys;
4045 CK_MECHANISM_TYPE key_derive; 4121 CK_MECHANISM_TYPE key_derive;
4046 CK_MECHANISM_TYPE bulk_mechanism; 4122 CK_MECHANISM_TYPE bulk_mechanism;
4047 SSLCipherAlgorithm calg; 4123 SSLCipherAlgorithm calg;
4048 SECItem params; 4124 SECItem params;
4049 PRBool skipKeysAndIVs = (PRBool)(cipher_def->calg == calg_null); 4125 PRBool skipKeysAndIVs = (PRBool)(cipher_def->calg == calg_null);
4050 4126
4051 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 4127 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4052 PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); 4128 PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
4053 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); 4129 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
4054 4130
4055 if (!pwSpec->master_secret) { 4131 if (!pwSpec->master_secret) {
4056 » PORT_SetError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); 4132 PORT_SetError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
4057 » return SECFailure; 4133 return SECFailure;
4058 } 4134 }
4059 /* 4135 /*
4060 * generate the key material 4136 * generate the key material
4061 */ 4137 */
4062 key_material_params.ulMacSizeInBits = pwSpec->mac_size * BPB; 4138 key_material_params.ulMacSizeInBits = pwSpec->mac_size * BPB;
4063 key_material_params.ulKeySizeInBits = cipher_def->secret_key_size* BPB; 4139 key_material_params.ulKeySizeInBits = cipher_def->secret_key_size * BPB;
4064 key_material_params.ulIVSizeInBits = cipher_def->iv_size * BPB; 4140 key_material_params.ulIVSizeInBits = cipher_def->iv_size * BPB;
4065 if (cipher_def->type == type_block && 4141 if (cipher_def->type == type_block &&
4066 » pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) { 4142 pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
4067 » /* Block ciphers in >= TLS 1.1 use a per-record, explicit IV. */ 4143 /* Block ciphers in >= TLS 1.1 use a per-record, explicit IV. */
4068 » key_material_params.ulIVSizeInBits = 0; 4144 key_material_params.ulIVSizeInBits = 0;
4069 » memset(pwSpec->client.write_iv, 0, cipher_def->iv_size); 4145 memset(pwSpec->client.write_iv, 0, cipher_def->iv_size);
4070 » memset(pwSpec->server.write_iv, 0, cipher_def->iv_size); 4146 memset(pwSpec->server.write_iv, 0, cipher_def->iv_size);
4071 } 4147 }
4072 4148
4073 key_material_params.bIsExport = (CK_BBOOL)(kea_def->is_limited); 4149 key_material_params.bIsExport = (CK_BBOOL)(kea_def->is_limited);
4074 4150
4075 key_material_params.RandomInfo.pClientRandom = cr; 4151 key_material_params.RandomInfo.pClientRandom = cr;
4076 key_material_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH; 4152 key_material_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH;
4077 key_material_params.RandomInfo.pServerRandom = sr; 4153 key_material_params.RandomInfo.pServerRandom = sr;
4078 key_material_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH; 4154 key_material_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH;
4079 key_material_params.pReturnedKeyMaterial = &returnedKeys; 4155 key_material_params.pReturnedKeyMaterial = &returnedKeys;
4080 4156
4081 returnedKeys.pIVClient = pwSpec->client.write_iv; 4157 returnedKeys.pIVClient = pwSpec->client.write_iv;
4082 returnedKeys.pIVServer = pwSpec->server.write_iv; 4158 returnedKeys.pIVServer = pwSpec->server.write_iv;
4083 keySize = cipher_def->key_size; 4159 keySize = cipher_def->key_size;
4084 4160
4085 if (skipKeysAndIVs) { 4161 if (skipKeysAndIVs) {
4086 » keySize = 0; 4162 keySize = 0;
4087 key_material_params.ulKeySizeInBits = 0; 4163 key_material_params.ulKeySizeInBits = 0;
4088 key_material_params.ulIVSizeInBits = 0; 4164 key_material_params.ulIVSizeInBits = 0;
4089 » returnedKeys.pIVClient = NULL; 4165 returnedKeys.pIVClient = NULL;
4090 » returnedKeys.pIVServer = NULL; 4166 returnedKeys.pIVServer = NULL;
4091 } 4167 }
4092 4168
4093 calg = cipher_def->calg; 4169 calg = cipher_def->calg;
4094 PORT_Assert( alg2Mech[calg].calg == calg); 4170 bulk_mechanism = ssl3_Alg2Mech(calg);
4095 bulk_mechanism = alg2Mech[calg].cmech;
4096 4171
4097 if (isTLS12) { 4172 if (isTLS12) {
4098 » key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE; 4173 key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE;
4099 » key_material_params.prfHashMechanism = CKM_SHA256; 4174 key_material_params.prfHashMechanism = CKM_SHA256;
4100 » key_material_params_len = sizeof(CK_TLS12_KEY_MAT_PARAMS); 4175 key_material_params_len = sizeof(CK_TLS12_KEY_MAT_PARAMS);
4101 } else if (isTLS) { 4176 } else if (isTLS) {
4102 » key_derive = CKM_TLS_KEY_AND_MAC_DERIVE; 4177 key_derive = CKM_TLS_KEY_AND_MAC_DERIVE;
4103 » key_material_params_len = sizeof(CK_SSL3_KEY_MAT_PARAMS); 4178 key_material_params_len = sizeof(CK_SSL3_KEY_MAT_PARAMS);
4104 } else { 4179 } else {
4105 » key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE; 4180 key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE;
4106 » key_material_params_len = sizeof(CK_SSL3_KEY_MAT_PARAMS); 4181 key_material_params_len = sizeof(CK_SSL3_KEY_MAT_PARAMS);
4107 } 4182 }
4108 4183
4109 params.data = (unsigned char *)&key_material_params; 4184 params.data = (unsigned char *)&key_material_params;
4110 params.len = key_material_params_len; 4185 params.len = key_material_params_len;
4111 4186
4112 /* CKM_SSL3_KEY_AND_MAC_DERIVE is defined to set ENCRYPT, DECRYPT, and 4187 /* CKM_SSL3_KEY_AND_MAC_DERIVE is defined to set ENCRYPT, DECRYPT, and
4113 * DERIVE by DEFAULT */ 4188 * DERIVE by DEFAULT */
4114 symKey = PK11_Derive(pwSpec->master_secret, key_derive, &params, 4189 symKey = PK11_Derive(pwSpec->master_secret, key_derive, &params,
4115 bulk_mechanism, CKA_ENCRYPT, keySize); 4190 bulk_mechanism, CKA_ENCRYPT, keySize);
4116 if (!symKey) { 4191 if (!symKey) {
4117 » ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); 4192 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
4118 » return SECFailure; 4193 return SECFailure;
4119 } 4194 }
4120 /* we really should use the actual mac'ing mechanism here, but we 4195 /* we really should use the actual mac'ing mechanism here, but we
4121 * don't because these types are used to map keytype anyway and both 4196 * don't because these types are used to map keytype anyway and both
4122 * mac's map to the same keytype. 4197 * mac's map to the same keytype.
4123 */ 4198 */
4124 slot = PK11_GetSlotFromKey(symKey); 4199 slot = PK11_GetSlotFromKey(symKey);
4125 4200
4126 PK11_FreeSlot(slot); /* slot is held until the key is freed */ 4201 PK11_FreeSlot(slot); /* slot is held until the key is freed */
4127 pwSpec->client.write_mac_key = 4202 pwSpec->client.write_mac_key =
4128 » PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, 4203 PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
4129 » CKM_SSL3_SHA1_MAC, returnedKeys.hClientMacSecret, PR_TRUE, pwArg); 4204 CKM_SSL3_SHA1_MAC, returnedKeys.hClientMacSecret, PR_TRUE, pwArg);
4130 if (pwSpec->client.write_mac_key == NULL ) { 4205 if (pwSpec->client.write_mac_key == NULL) {
4131 » goto loser;» /* loser sets err */ 4206 goto loser; /* loser sets err */
4132 } 4207 }
4133 pwSpec->server.write_mac_key = 4208 pwSpec->server.write_mac_key =
4134 » PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, 4209 PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
4135 » CKM_SSL3_SHA1_MAC, returnedKeys.hServerMacSecret, PR_TRUE, pwArg); 4210 CKM_SSL3_SHA1_MAC, returnedKeys.hServerMacSecret, PR_TRUE, pwArg);
4136 if (pwSpec->server.write_mac_key == NULL ) { 4211 if (pwSpec->server.write_mac_key == NULL) {
4137 » goto loser;» /* loser sets err */ 4212 goto loser; /* loser sets err */
4138 } 4213 }
4139 if (!skipKeysAndIVs) { 4214 if (!skipKeysAndIVs) {
4140 » pwSpec->client.write_key = 4215 pwSpec->client.write_key =
4141 » » PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, 4216 PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
4142 » » bulk_mechanism, returnedKeys.hClientKey, PR_TRUE, pwArg); 4217 bulk_mechanism, returnedKeys.hClientKey, PR_TR UE, pwArg);
4143 » if (pwSpec->client.write_key == NULL ) { 4218 if (pwSpec->client.write_key == NULL) {
4144 » goto loser;»/* loser sets err */ 4219 goto loser; /* loser sets err */
4145 » } 4220 }
4146 » pwSpec->server.write_key = 4221 pwSpec->server.write_key =
4147 » » PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, 4222 PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
4148 » » bulk_mechanism, returnedKeys.hServerKey, PR_TRUE, pwArg); 4223 bulk_mechanism, returnedKeys.hServerKey, PR_TR UE, pwArg);
4149 » if (pwSpec->server.write_key == NULL ) { 4224 if (pwSpec->server.write_key == NULL) {
4150 » goto loser;»/* loser sets err */ 4225 goto loser; /* loser sets err */
4151 » } 4226 }
4152 } 4227 }
4153 PK11_FreeSymKey(symKey); 4228 PK11_FreeSymKey(symKey);
4154 return SECSuccess; 4229 return SECSuccess;
4155 4230
4156
4157 loser: 4231 loser:
4158 if (symKey) PK11_FreeSymKey(symKey); 4232 if (symKey)
4233 PK11_FreeSymKey(symKey);
4159 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); 4234 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
4160 return SECFailure; 4235 return SECFailure;
4161 } 4236 }
4162 4237
4163 /* ssl3_InitHandshakeHashes creates handshake hash contexts and hashes in 4238 /* ssl3_InitHandshakeHashes creates handshake hash contexts and hashes in
4164 * buffered messages in ss->ssl3.hs.messages. */ 4239 * buffered messages in ss->ssl3.hs.messages. */
4165 static SECStatus 4240 static SECStatus
4166 ssl3_InitHandshakeHashes(sslSocket *ss) 4241 ssl3_InitHandshakeHashes(sslSocket *ss)
4167 { 4242 {
4168 SSL_TRC(30,("%d: SSL3[%d]: start handshake hashes", SSL_GETPID(), ss->fd)); 4243 SSL_TRC(30, ("%d: SSL3[%d]: start handshake hashes", SSL_GETPID(), ss->fd));
4169 4244
4170 PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_unknown); 4245 PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_unknown);
4171 #ifndef NO_PKCS11_BYPASS 4246 #ifndef NO_PKCS11_BYPASS
4172 if (ss->opt.bypassPKCS11) { 4247 if (ss->opt.bypassPKCS11) {
4173 » PORT_Assert(!ss->ssl3.hs.sha_obj && !ss->ssl3.hs.sha_clone); 4248 PORT_Assert(!ss->ssl3.hs.sha_obj && !ss->ssl3.hs.sha_clone);
4174 » if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) { 4249 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
4175 » /* If we ever support ciphersuites where the PRF hash isn't SHA-256 4250 /* If we ever support ciphersuites where the PRF hash isn't SHA-256
4176 » * then this will need to be updated. */ 4251 * then this will need to be updated. */
4177 » ss->ssl3.hs.sha_obj = HASH_GetRawHashObject(HASH_AlgSHA256); 4252 ss->ssl3.hs.sha_obj = HASH_GetRawHashObject(HASH_AlgSHA256);
4178 » if (!ss->ssl3.hs.sha_obj) { 4253 if (!ss->ssl3.hs.sha_obj) {
4179 » » ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); 4254 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4180 » » return SECFailure; 4255 return SECFailure;
4181 » } 4256 }
4182 » ss->ssl3.hs.sha_clone = (void (*)(void *, void *))SHA256_Clone; 4257 ss->ssl3.hs.sha_clone = (void (*)(void *, void *))SHA256_Clone;
4183 » ss->ssl3.hs.hashType = handshake_hash_single; 4258 ss->ssl3.hs.hashType = handshake_hash_single;
4184 » ss->ssl3.hs.sha_obj->begin(ss->ssl3.hs.sha_cx); 4259 ss->ssl3.hs.sha_obj->begin(ss->ssl3.hs.sha_cx);
4185 » } else { 4260 } else {
4186 » ss->ssl3.hs.hashType = handshake_hash_combo; 4261 ss->ssl3.hs.hashType = handshake_hash_combo;
4187 » MD5_Begin((MD5Context *)ss->ssl3.hs.md5_cx); 4262 MD5_Begin((MD5Context *)ss->ssl3.hs.md5_cx);
4188 » SHA1_Begin((SHA1Context *)ss->ssl3.hs.sha_cx); 4263 SHA1_Begin((SHA1Context *)ss->ssl3.hs.sha_cx);
4189 » } 4264 }
4190 } else 4265 } else
4191 #endif 4266 #endif
4192 { 4267 {
4193 » PORT_Assert(!ss->ssl3.hs.md5 && !ss->ssl3.hs.sha); 4268 PORT_Assert(!ss->ssl3.hs.md5 && !ss->ssl3.hs.sha);
4194 » /* 4269 /*
4195 » * note: We should probably lookup an SSL3 slot for these 4270 * note: We should probably lookup an SSL3 slot for these
4196 » * handshake hashes in hopes that we wind up with the same slots 4271 * handshake hashes in hopes that we wind up with the same slots
4197 » * that the master secret will wind up in ... 4272 * that the master secret will wind up in ...
4198 » */ 4273 */
4199 » if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) { 4274 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
4200 » /* If we ever support ciphersuites where the PRF hash isn't SHA-256 4275 /* If we ever support ciphersuites where the PRF hash isn't SHA-256
4201 » * then this will need to be updated. */ 4276 * then this will need to be updated. */
4202 » ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA256); 4277 ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA256);
4203 » if (ss->ssl3.hs.sha == NULL) { 4278 if (ss->ssl3.hs.sha == NULL) {
4204 » » ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 4279 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4205 » » return SECFailure; 4280 return SECFailure;
4206 » } 4281 }
4207 » ss->ssl3.hs.hashType = handshake_hash_single; 4282 ss->ssl3.hs.hashType = handshake_hash_single;
4208 4283
4209 » if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) { 4284 if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) {
4210 » » ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); 4285 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4211 » » return SECFailure; 4286 return SECFailure;
4212 » } 4287 }
4213 4288
4214 » /* Create a backup SHA-1 hash for a potential client auth 4289 /* Create a backup SHA-1 hash for a potential client auth
4215 » * signature. 4290 * signature.
4216 » * 4291 *
4217 » * In TLS 1.2, ssl3_ComputeHandshakeHashes always uses the 4292 * In TLS 1.2, ssl3_ComputeHandshakeHashes always uses the
4218 » * handshake hash function (SHA-256). If the server or the client 4293 * handshake hash function (SHA-256). If the server or the client
4219 » * does not support SHA-256 as a signature hash, we can either 4294 * does not support SHA-256 as a signature hash, we can either
4220 » * maintain a backup SHA-1 handshake hash or buffer all handshake 4295 * maintain a backup SHA-1 handshake hash or buffer all handshake
4221 » * messages. 4296 * messages.
4222 » */ 4297 */
4223 » if (!ss->sec.isServer) { 4298 if (!ss->sec.isServer) {
4224 » » ss->ssl3.hs.backupHash = PK11_CreateDigestContext(SEC_OID_SHA1); 4299 ss->ssl3.hs.backupHash = PK11_CreateDigestContext(SEC_OID_SHA1);
4225 » » if (ss->ssl3.hs.backupHash == NULL) { 4300 if (ss->ssl3.hs.backupHash == NULL) {
4226 » » ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 4301 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4227 » » return SECFailure; 4302 return SECFailure;
4228 » » } 4303 }
4229 4304
4230 » » if (PK11_DigestBegin(ss->ssl3.hs.backupHash) != SECSuccess) { 4305 if (PK11_DigestBegin(ss->ssl3.hs.backupHash) != SECSuccess) {
4231 » » ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 4306 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4232 » » return SECFailure; 4307 return SECFailure;
4233 » » } 4308 }
4234 » } 4309 }
4235 » } else { 4310 } else {
4236 » /* Both ss->ssl3.hs.md5 and ss->ssl3.hs.sha should be NULL or 4311 /* Both ss->ssl3.hs.md5 and ss->ssl3.hs.sha should be NULL or
4237 » * created successfully. */ 4312 * created successfully. */
4238 » ss->ssl3.hs.md5 = PK11_CreateDigestContext(SEC_OID_MD5); 4313 ss->ssl3.hs.md5 = PK11_CreateDigestContext(SEC_OID_MD5);
4239 » if (ss->ssl3.hs.md5 == NULL) { 4314 if (ss->ssl3.hs.md5 == NULL) {
4240 » » ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); 4315 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4241 » » return SECFailure; 4316 return SECFailure;
4242 » } 4317 }
4243 » ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA1); 4318 ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA1);
4244 » if (ss->ssl3.hs.sha == NULL) { 4319 if (ss->ssl3.hs.sha == NULL) {
4245 » » PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE); 4320 PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE);
4246 » » ss->ssl3.hs.md5 = NULL; 4321 ss->ssl3.hs.md5 = NULL;
4247 » » ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 4322 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4248 » » return SECFailure; 4323 return SECFailure;
4249 » } 4324 }
4250 » ss->ssl3.hs.hashType = handshake_hash_combo; 4325 ss->ssl3.hs.hashType = handshake_hash_combo;
4251 4326
4252 » if (PK11_DigestBegin(ss->ssl3.hs.md5) != SECSuccess) { 4327 if (PK11_DigestBegin(ss->ssl3.hs.md5) != SECSuccess) {
4253 » » ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); 4328 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4254 » » return SECFailure; 4329 return SECFailure;
4255 » } 4330 }
4256 » if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) { 4331 if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) {
4257 » » ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 4332 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4258 » » return SECFailure; 4333 return SECFailure;
4259 » } 4334 }
4260 » } 4335 }
4261 } 4336 }
4262 4337
4263 if (ss->ssl3.hs.messages.len > 0) { 4338 if (ss->ssl3.hs.messages.len > 0) {
4264 » if (ssl3_UpdateHandshakeHashes(ss, ss->ssl3.hs.messages.buf, 4339 if (ssl3_UpdateHandshakeHashes(ss, ss->ssl3.hs.messages.buf,
4265 » » » » ss->ssl3.hs.messages.len) != 4340 ss->ssl3.hs.messages.len) !=
4266 » SECSuccess) { 4341 SECSuccess) {
4267 » return SECFailure; 4342 return SECFailure;
4268 » } 4343 }
4269 » PORT_Free(ss->ssl3.hs.messages.buf); 4344 PORT_Free(ss->ssl3.hs.messages.buf);
4270 » ss->ssl3.hs.messages.buf = NULL; 4345 ss->ssl3.hs.messages.buf = NULL;
4271 » ss->ssl3.hs.messages.len = 0; 4346 ss->ssl3.hs.messages.len = 0;
4272 » ss->ssl3.hs.messages.space = 0; 4347 ss->ssl3.hs.messages.space = 0;
4273 } 4348 }
4274 4349
4275 return SECSuccess; 4350 return SECSuccess;
4276 } 4351 }
4277 4352
4278 static SECStatus 4353 static SECStatus
4279 ssl3_RestartHandshakeHashes(sslSocket *ss) 4354 ssl3_RestartHandshakeHashes(sslSocket *ss)
4280 { 4355 {
4281 SECStatus rv = SECSuccess; 4356 SECStatus rv = SECSuccess;
4282 4357
4283 SSL_TRC(30,("%d: SSL3[%d]: reset handshake hashes", 4358 SSL_TRC(30, ("%d: SSL3[%d]: reset handshake hashes",
4284 » SSL_GETPID(), ss->fd )); 4359 SSL_GETPID(), ss->fd));
4285 ss->ssl3.hs.hashType = handshake_hash_unknown; 4360 ss->ssl3.hs.hashType = handshake_hash_unknown;
4286 ss->ssl3.hs.messages.len = 0; 4361 ss->ssl3.hs.messages.len = 0;
4287 #ifndef NO_PKCS11_BYPASS 4362 #ifndef NO_PKCS11_BYPASS
4288 ss->ssl3.hs.sha_obj = NULL; 4363 ss->ssl3.hs.sha_obj = NULL;
4289 ss->ssl3.hs.sha_clone = NULL; 4364 ss->ssl3.hs.sha_clone = NULL;
4290 #endif 4365 #endif
4291 if (ss->ssl3.hs.md5) { 4366 if (ss->ssl3.hs.md5) {
4292 » PK11_DestroyContext(ss->ssl3.hs.md5,PR_TRUE); 4367 PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE);
4293 » ss->ssl3.hs.md5 = NULL; 4368 ss->ssl3.hs.md5 = NULL;
4294 } 4369 }
4295 if (ss->ssl3.hs.sha) { 4370 if (ss->ssl3.hs.sha) {
4296 » PK11_DestroyContext(ss->ssl3.hs.sha,PR_TRUE); 4371 PK11_DestroyContext(ss->ssl3.hs.sha, PR_TRUE);
4297 » ss->ssl3.hs.sha = NULL; 4372 ss->ssl3.hs.sha = NULL;
4298 } 4373 }
4299 return rv; 4374 return rv;
4300 } 4375 }
4301 4376
4302 /* 4377 /*
4303 * Handshake messages 4378 * Handshake messages
4304 */ 4379 */
4305 /* Called from» ssl3_InitHandshakeHashes() 4380 /* Called from ssl3_InitHandshakeHashes()
4306 **» » ssl3_AppendHandshake() 4381 ** ssl3_AppendHandshake()
4307 **» » ssl3_StartHandshakeHash() 4382 ** ssl3_StartHandshakeHash()
4308 **» » ssl3_HandleV2ClientHello() 4383 ** ssl3_HandleV2ClientHello()
4309 **» » ssl3_HandleHandshakeMessage() 4384 ** ssl3_HandleHandshakeMessage()
4310 ** Caller must hold the ssl3Handshake lock. 4385 ** Caller must hold the ssl3Handshake lock.
4311 */ 4386 */
4312 static SECStatus 4387 static SECStatus
4313 ssl3_UpdateHandshakeHashes(sslSocket *ss, const unsigned char *b, 4388 ssl3_UpdateHandshakeHashes(sslSocket *ss, const unsigned char *b,
4314 » » » unsigned int l) 4389 unsigned int l)
4315 { 4390 {
4316 SECStatus rv = SECSuccess; 4391 SECStatus rv = SECSuccess;
4317 4392
4318 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 4393 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4319 4394
4320 /* We need to buffer the handshake messages until we have established 4395 /* We need to buffer the handshake messages until we have established
4321 * which handshake hash function to use. */ 4396 * which handshake hash function to use. */
4322 if (ss->ssl3.hs.hashType == handshake_hash_unknown) { 4397 if (ss->ssl3.hs.hashType == handshake_hash_unknown) {
4323 » return sslBuffer_Append(&ss->ssl3.hs.messages, b, l); 4398 return sslBuffer_Append(&ss->ssl3.hs.messages, b, l);
4324 } 4399 }
4325 4400
4326 PRINT_BUF(90, (NULL, "handshake hash input:", b, l)); 4401 PRINT_BUF(90, (NULL, "handshake hash input:", b, l));
4327 4402
4328 #ifndef NO_PKCS11_BYPASS 4403 #ifndef NO_PKCS11_BYPASS
4329 if (ss->opt.bypassPKCS11) { 4404 if (ss->opt.bypassPKCS11) {
4330 » if (ss->ssl3.hs.hashType == handshake_hash_single) { 4405 if (ss->ssl3.hs.hashType == handshake_hash_single) {
4331 » ss->ssl3.hs.sha_obj->update(ss->ssl3.hs.sha_cx, b, l); 4406 ss->ssl3.hs.sha_obj->update(ss->ssl3.hs.sha_cx, b, l);
4332 » } else { 4407 } else {
4333 » MD5_Update((MD5Context *)ss->ssl3.hs.md5_cx, b, l); 4408 MD5_Update((MD5Context *)ss->ssl3.hs.md5_cx, b, l);
4334 » SHA1_Update((SHA1Context *)ss->ssl3.hs.sha_cx, b, l); 4409 SHA1_Update((SHA1Context *)ss->ssl3.hs.sha_cx, b, l);
4335 » } 4410 }
4336 » return rv; 4411 return rv;
4337 } 4412 }
4338 #endif 4413 #endif
4339 if (ss->ssl3.hs.hashType == handshake_hash_single) { 4414 if (ss->ssl3.hs.hashType == handshake_hash_single) {
4340 » rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l); 4415 rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l);
4341 » if (rv != SECSuccess) { 4416 if (rv != SECSuccess) {
4342 » ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); 4417 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4343 » return rv; 4418 return rv;
4344 » } 4419 }
4345 » if (ss->ssl3.hs.backupHash) { 4420 if (ss->ssl3.hs.backupHash) {
4346 » rv = PK11_DigestOp(ss->ssl3.hs.backupHash, b, l); 4421 rv = PK11_DigestOp(ss->ssl3.hs.backupHash, b, l);
4347 » if (rv != SECSuccess) { 4422 if (rv != SECSuccess) {
4348 » » ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 4423 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4349 » » return rv; 4424 return rv;
4350 » } 4425 }
4351 » } 4426 }
4352 } else { 4427 } else {
4353 » rv = PK11_DigestOp(ss->ssl3.hs.md5, b, l); 4428 rv = PK11_DigestOp(ss->ssl3.hs.md5, b, l);
4354 » if (rv != SECSuccess) { 4429 if (rv != SECSuccess) {
4355 » ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); 4430 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4356 » return rv; 4431 return rv;
4357 » } 4432 }
4358 » rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l); 4433 rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l);
4359 » if (rv != SECSuccess) { 4434 if (rv != SECSuccess) {
4360 » ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 4435 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4361 » return rv; 4436 return rv;
4362 » } 4437 }
4363 } 4438 }
4364 return rv; 4439 return rv;
4365 } 4440 }
4366 4441
4367 /************************************************************************** 4442 /**************************************************************************
4368 * Append Handshake functions. 4443 * Append Handshake functions.
4369 * All these functions set appropriate error codes. 4444 * All these functions set appropriate error codes.
4370 * Most rely on ssl3_AppendHandshake to set the error code. 4445 * Most rely on ssl3_AppendHandshake to set the error code.
4371 **************************************************************************/ 4446 **************************************************************************/
4372 SECStatus 4447 SECStatus
4373 ssl3_AppendHandshake(sslSocket *ss, const void *void_src, PRInt32 bytes) 4448 ssl3_AppendHandshake(sslSocket *ss, const void *void_src, PRInt32 bytes)
4374 { 4449 {
4375 unsigned char * src = (unsigned char *)void_src; 4450 unsigned char *src = (unsigned char *)void_src;
4376 int room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len; 4451 int room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len;
4377 SECStatus rv; 4452 SECStatus rv;
4378 4453
4379 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); /* protects sendBuf. */ 4454 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); /* protects s endBuf. */
4380 4455
4381 if (!bytes) 4456 if (!bytes)
4382 » return SECSuccess; 4457 return SECSuccess;
4383 if (ss->sec.ci.sendBuf.space < MAX_SEND_BUF_LENGTH && room < bytes) { 4458 if (ss->sec.ci.sendBuf.space < MAX_SEND_BUF_LENGTH && room < bytes) {
4384 » rv = sslBuffer_Grow(&ss->sec.ci.sendBuf, PR_MAX(MIN_SEND_BUF_LENGTH, 4459 rv = sslBuffer_Grow(&ss->sec.ci.sendBuf, PR_MAX(MIN_SEND_BUF_LENGTH,
4385 » » PR_MIN(MAX_SEND_BUF_LENGTH, ss->sec.ci.sendBuf.len + bytes))); 4460 PR_MIN(MAX_SEND_BUF_LENG TH, ss->sec.ci.sendBuf.len + bytes)));
4386 » if (rv != SECSuccess) 4461 if (rv != SECSuccess)
4387 » return rv;» /* sslBuffer_Grow has set a memory error code. */ 4462 return rv; /* sslBuffer_Grow has set a memory error code. */
4388 » room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len; 4463 room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len;
4389 } 4464 }
4390 4465
4391 PRINT_BUF(60, (ss, "Append to Handshake", (unsigned char*)void_src, bytes)); 4466 PRINT_BUF(60, (ss, "Append to Handshake", (unsigned char *)void_src, bytes)) ;
4392 rv = ssl3_UpdateHandshakeHashes(ss, src, bytes); 4467 rv = ssl3_UpdateHandshakeHashes(ss, src, bytes);
4393 if (rv != SECSuccess) 4468 if (rv != SECSuccess)
4394 » return rv;» /* error code set by ssl3_UpdateHandshakeHashes */ 4469 return rv; /* error code set by ssl3_UpdateHandshakeHashes */
4395 4470
4396 while (bytes > room) { 4471 while (bytes > room) {
4397 » if (room > 0) 4472 if (room > 0)
4398 » PORT_Memcpy(ss->sec.ci.sendBuf.buf + ss->sec.ci.sendBuf.len, src, 4473 PORT_Memcpy(ss->sec.ci.sendBuf.buf + ss->sec.ci.sendBuf.len, src,
4399 » room); 4474 room);
4400 » ss->sec.ci.sendBuf.len += room; 4475 ss->sec.ci.sendBuf.len += room;
4401 » rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER); 4476 rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
4402 » if (rv != SECSuccess) { 4477 if (rv != SECSuccess) {
4403 » return rv;» /* error code set by ssl3_FlushHandshake */ 4478 return rv; /* error code set by ssl3_FlushHandshake */
4404 » } 4479 }
4405 » bytes -= room; 4480 bytes -= room;
4406 » src += room; 4481 src += room;
4407 » room = ss->sec.ci.sendBuf.space; 4482 room = ss->sec.ci.sendBuf.space;
4408 » PORT_Assert(ss->sec.ci.sendBuf.len == 0); 4483 PORT_Assert(ss->sec.ci.sendBuf.len == 0);
4409 } 4484 }
4410 PORT_Memcpy(ss->sec.ci.sendBuf.buf + ss->sec.ci.sendBuf.len, src, bytes); 4485 PORT_Memcpy(ss->sec.ci.sendBuf.buf + ss->sec.ci.sendBuf.len, src, bytes);
4411 ss->sec.ci.sendBuf.len += bytes; 4486 ss->sec.ci.sendBuf.len += bytes;
4412 return SECSuccess; 4487 return SECSuccess;
4413 } 4488 }
4414 4489
4415 SECStatus 4490 SECStatus
4416 ssl3_AppendHandshakeNumber(sslSocket *ss, PRInt32 num, PRInt32 lenSize) 4491 ssl3_AppendHandshakeNumber(sslSocket *ss, PRInt32 num, PRInt32 lenSize)
4417 { 4492 {
4418 SECStatus rv; 4493 SECStatus rv;
4419 PRUint8 b[4]; 4494 PRUint8 b[4];
4420 PRUint8 * p = b; 4495 PRUint8 *p = b;
4421 4496
4422 PORT_Assert(lenSize <= 4 && lenSize > 0); 4497 PORT_Assert(lenSize <= 4 && lenSize > 0);
4423 if (lenSize < 4 && num >= (1L << (lenSize * 8))) { 4498 if (lenSize < 4 && num >= (1L << (lenSize * 8))) {
4424 PORT_SetError(SSL_ERROR_TX_RECORD_TOO_LONG); 4499 PORT_SetError(SSL_ERROR_TX_RECORD_TOO_LONG);
4425 return SECFailure; 4500 return SECFailure;
4426 } 4501 }
4427 4502
4428 switch (lenSize) { 4503 switch (lenSize) {
4429 case 4: 4504 case 4:
4430 » *p++ = (num >> 24) & 0xff; 4505 *p++ = (num >> 24) & 0xff;
4431 case 3: 4506 case 3:
4432 » *p++ = (num >> 16) & 0xff; 4507 *p++ = (num >> 16) & 0xff;
4433 case 2: 4508 case 2:
4434 » *p++ = (num >> 8) & 0xff; 4509 *p++ = (num >> 8) & 0xff;
4435 case 1: 4510 case 1:
4436 » *p = num & 0xff; 4511 *p = num & 0xff;
4437 } 4512 }
4438 SSL_TRC(60, ("%d: number:", SSL_GETPID())); 4513 SSL_TRC(60, ("%d: number:", SSL_GETPID()));
4439 rv = ssl3_AppendHandshake(ss, &b[0], lenSize); 4514 rv = ssl3_AppendHandshake(ss, &b[0], lenSize);
4440 return rv;» /* error code set by AppendHandshake, if applicable. */ 4515 return rv; /* error code set by AppendHandshake, if applicable. */
4441 } 4516 }
4442 4517
4443 SECStatus 4518 SECStatus
4444 ssl3_AppendHandshakeVariable( 4519 ssl3_AppendHandshakeVariable(
4445 sslSocket *ss, const SSL3Opaque *src, PRInt32 bytes, PRInt32 lenSize) 4520 sslSocket *ss, const SSL3Opaque *src, PRInt32 bytes, PRInt32 lenSize)
4446 { 4521 {
4447 SECStatus rv; 4522 SECStatus rv;
4448 4523
4449 PORT_Assert((bytes < (1<<8) && lenSize == 1) || 4524 PORT_Assert((bytes < (1 << 8) && lenSize == 1) ||
4450 » (bytes < (1L<<16) && lenSize == 2) || 4525 (bytes < (1L << 16) && lenSize == 2) ||
4451 » (bytes < (1L<<24) && lenSize == 3)); 4526 (bytes < (1L << 24) && lenSize == 3));
4452 4527
4453 SSL_TRC(60,("%d: append variable:", SSL_GETPID())); 4528 SSL_TRC(60, ("%d: append variable:", SSL_GETPID()));
4454 rv = ssl3_AppendHandshakeNumber(ss, bytes, lenSize); 4529 rv = ssl3_AppendHandshakeNumber(ss, bytes, lenSize);
4455 if (rv != SECSuccess) { 4530 if (rv != SECSuccess) {
4456 » return rv;» /* error code set by AppendHandshake, if applicable. */ 4531 return rv; /* error code set by AppendHandshake, if applicable. */
4457 } 4532 }
4458 SSL_TRC(60, ("data:")); 4533 SSL_TRC(60, ("data:"));
4459 rv = ssl3_AppendHandshake(ss, src, bytes); 4534 rv = ssl3_AppendHandshake(ss, src, bytes);
4460 return rv;» /* error code set by AppendHandshake, if applicable. */ 4535 return rv; /* error code set by AppendHandshake, if applicable. */
4461 } 4536 }
4462 4537
4463 SECStatus 4538 SECStatus
4464 ssl3_AppendHandshakeHeader(sslSocket *ss, SSL3HandshakeType t, PRUint32 length) 4539 ssl3_AppendHandshakeHeader(sslSocket *ss, SSL3HandshakeType t, PRUint32 length)
4465 { 4540 {
4466 SECStatus rv; 4541 SECStatus rv;
4467 4542
4468 /* If we already have a message in place, we need to enqueue it. 4543 /* If we already have a message in place, we need to enqueue it.
4469 * This empties the buffer. This is a convenient place to call 4544 * This empties the buffer. This is a convenient place to call
4470 * dtls_StageHandshakeMessage to mark the message boundary. 4545 * dtls_StageHandshakeMessage to mark the message boundary.
4471 */ 4546 */
4472 if (IS_DTLS(ss)) { 4547 if (IS_DTLS(ss)) {
4473 » rv = dtls_StageHandshakeMessage(ss); 4548 rv = dtls_StageHandshakeMessage(ss);
4474 » if (rv != SECSuccess) { 4549 if (rv != SECSuccess) {
4475 » return rv; 4550 return rv;
4476 » } 4551 }
4477 } 4552 }
4478 4553
4479 SSL_TRC(30,("%d: SSL3[%d]: append handshake header: type %s", 4554 SSL_TRC(30, ("%d: SSL3[%d]: append handshake header: type %s",
4480 » SSL_GETPID(), ss->fd, ssl3_DecodeHandshakeType(t))); 4555 SSL_GETPID(), ss->fd, ssl3_DecodeHandshakeType(t)));
4481 4556
4482 rv = ssl3_AppendHandshakeNumber(ss, t, 1); 4557 rv = ssl3_AppendHandshakeNumber(ss, t, 1);
4483 if (rv != SECSuccess) { 4558 if (rv != SECSuccess) {
4484 » return rv;» /* error code set by AppendHandshake, if applicable. */ 4559 return rv; /* error code set by AppendHandshake, if applicable. */
4485 } 4560 }
4486 rv = ssl3_AppendHandshakeNumber(ss, length, 3); 4561 rv = ssl3_AppendHandshakeNumber(ss, length, 3);
4487 if (rv != SECSuccess) { 4562 if (rv != SECSuccess) {
4488 » return rv;» /* error code set by AppendHandshake, if applicable. */ 4563 return rv; /* error code set by AppendHandshake, if applicable. */
4489 } 4564 }
4490 4565
4491 if (IS_DTLS(ss)) { 4566 if (IS_DTLS(ss)) {
4492 » /* Note that we make an unfragmented message here. We fragment in the 4567 /* Note that we make an unfragmented message here. We fragment in the
4493 » * transmission code, if necessary */ 4568 * transmission code, if necessary */
4494 » rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.sendMessageSeq, 2); 4569 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.sendMessageSeq, 2);
4495 » if (rv != SECSuccess) { 4570 if (rv != SECSuccess) {
4496 » return rv;» /* error code set by AppendHandshake, if applicable. */ 4571 return rv; /* error code set by AppendHandshake, if applicable. */
4497 » } 4572 }
4498 » ss->ssl3.hs.sendMessageSeq++; 4573 ss->ssl3.hs.sendMessageSeq++;
4499 4574
4500 » /* 0 is the fragment offset, because it's not fragmented yet */ 4575 /* 0 is the fragment offset, because it's not fragmented yet */
4501 » rv = ssl3_AppendHandshakeNumber(ss, 0, 3); 4576 rv = ssl3_AppendHandshakeNumber(ss, 0, 3);
4502 » if (rv != SECSuccess) { 4577 if (rv != SECSuccess) {
4503 » return rv;» /* error code set by AppendHandshake, if applicable. */ 4578 return rv; /* error code set by AppendHandshake, if applicable. */
4504 » } 4579 }
4505 4580
4506 » /* Fragment length -- set to the packet length because not fragmented */ 4581 /* Fragment length -- set to the packet length because not fragmented */
4507 » rv = ssl3_AppendHandshakeNumber(ss, length, 3); 4582 rv = ssl3_AppendHandshakeNumber(ss, length, 3);
4508 » if (rv != SECSuccess) { 4583 if (rv != SECSuccess) {
4509 » return rv;» /* error code set by AppendHandshake, if applicable. */ 4584 return rv; /* error code set by AppendHandshake, if applicable. */
4510 » } 4585 }
4511 } 4586 }
4512 4587
4513 return rv;» » /* error code set by AppendHandshake, if applicable. */ 4588 return rv; /* error code set by AppendHandshake, if applicable. */
4514 } 4589 }
4515 4590
4516 /* ssl3_AppendSignatureAndHashAlgorithm appends the serialisation of 4591 /* ssl3_AppendSignatureAndHashAlgorithm appends the serialisation of
4517 * |sigAndHash| to the current handshake message. */ 4592 * |sigAndHash| to the current handshake message. */
4518 SECStatus 4593 SECStatus
4519 ssl3_AppendSignatureAndHashAlgorithm( 4594 ssl3_AppendSignatureAndHashAlgorithm(
4520 sslSocket *ss, const SSLSignatureAndHashAlg* sigAndHash) 4595 sslSocket *ss, const SSLSignatureAndHashAlg *sigAndHash)
4521 { 4596 {
4522 PRUint8 serialized[2]; 4597 PRUint8 serialized[2];
4523 4598
4524 serialized[0] = (PRUint8)sigAndHash->hashAlg; 4599 serialized[0] = (PRUint8)sigAndHash->hashAlg;
4525 serialized[1] = (PRUint8)sigAndHash->sigAlg; 4600 serialized[1] = (PRUint8)sigAndHash->sigAlg;
4526 4601
4527 return ssl3_AppendHandshake(ss, serialized, sizeof(serialized)); 4602 return ssl3_AppendHandshake(ss, serialized, sizeof(serialized));
4528 } 4603 }
4529 4604
4530 /************************************************************************** 4605 /**************************************************************************
4531 * Consume Handshake functions. 4606 * Consume Handshake functions.
4532 * 4607 *
4533 * All data used in these functions is protected by two locks, 4608 * All data used in these functions is protected by two locks,
4534 * the RecvBufLock and the SSL3HandshakeLock 4609 * the RecvBufLock and the SSL3HandshakeLock
4535 **************************************************************************/ 4610 **************************************************************************/
4536 4611
4537 /* Read up the next "bytes" number of bytes from the (decrypted) input 4612 /* Read up the next "bytes" number of bytes from the (decrypted) input
4538 * stream "b" (which is *length bytes long). Copy them into buffer "v". 4613 * stream "b" (which is *length bytes long). Copy them into buffer "v".
4539 * Reduces *length by bytes. Advances *b by bytes. 4614 * Reduces *length by bytes. Advances *b by bytes.
4540 * 4615 *
4541 * If this function returns SECFailure, it has already sent an alert, 4616 * If this function returns SECFailure, it has already sent an alert,
4542 * and has set a generic error code. The caller should probably 4617 * and has set a generic error code. The caller should probably
4543 * override the generic error code by setting another. 4618 * override the generic error code by setting another.
4544 */ 4619 */
4545 SECStatus 4620 SECStatus
4546 ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRInt32 bytes, SSL3Opaque **b, 4621 ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRInt32 bytes, SSL3Opaque **b,
4547 » » PRUint32 *length) 4622 PRUint32 *length)
4548 { 4623 {
4549 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 4624 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
4550 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 4625 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4551 4626
4552 if ((PRUint32)bytes > *length) { 4627 if ((PRUint32)bytes > *length) {
4553 » return ssl3_DecodeError(ss); 4628 return ssl3_DecodeError(ss);
4554 } 4629 }
4555 PORT_Memcpy(v, *b, bytes); 4630 PORT_Memcpy(v, *b, bytes);
4556 PRINT_BUF(60, (ss, "consume bytes:", *b, bytes)); 4631 PRINT_BUF(60, (ss, "consume bytes:", *b, bytes));
4557 *b += bytes; 4632 *b += bytes;
4558 *length -= bytes; 4633 *length -= bytes;
4559 return SECSuccess; 4634 return SECSuccess;
4560 } 4635 }
4561 4636
4562 /* Read up the next "bytes" number of bytes from the (decrypted) input 4637 /* Read up the next "bytes" number of bytes from the (decrypted) input
4563 * stream "b" (which is *length bytes long), and interpret them as an 4638 * stream "b" (which is *length bytes long), and interpret them as an
4564 * integer in network byte order. Returns the received value. 4639 * integer in network byte order. Returns the received value.
4565 * Reduces *length by bytes. Advances *b by bytes. 4640 * Reduces *length by bytes. Advances *b by bytes.
4566 * 4641 *
4567 * Returns SECFailure (-1) on failure. 4642 * Returns SECFailure (-1) on failure.
4568 * This value is indistinguishable from the equivalent received value. 4643 * This value is indistinguishable from the equivalent received value.
4569 * Only positive numbers are to be received this way. 4644 * Only positive numbers are to be received this way.
4570 * Thus, the largest value that may be sent this way is 0x7fffffff. 4645 * Thus, the largest value that may be sent this way is 0x7fffffff.
4571 * On error, an alert has been sent, and a generic error code has been set. 4646 * On error, an alert has been sent, and a generic error code has been set.
4572 */ 4647 */
4573 PRInt32 4648 PRInt32
4574 ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRInt32 bytes, SSL3Opaque **b, 4649 ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRInt32 bytes, SSL3Opaque **b,
4575 » » » PRUint32 *length) 4650 PRUint32 *length)
4576 { 4651 {
4577 PRUint8 *buf = *b; 4652 PRUint8 *buf = *b;
4578 int i; 4653 int i;
4579 PRInt32 num = 0; 4654 PRInt32 num = 0;
4580 4655
4581 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 4656 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
4582 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 4657 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4583 PORT_Assert( bytes <= sizeof num); 4658 PORT_Assert(bytes <= sizeof num);
4584 4659
4585 if ((PRUint32)bytes > *length) { 4660 if ((PRUint32)bytes > *length) {
4586 » return ssl3_DecodeError(ss); 4661 return ssl3_DecodeError(ss);
4587 } 4662 }
4588 PRINT_BUF(60, (ss, "consume bytes:", *b, bytes)); 4663 PRINT_BUF(60, (ss, "consume bytes:", *b, bytes));
4589 4664
4590 for (i = 0; i < bytes; i++) 4665 for (i = 0; i < bytes; i++)
4591 » num = (num << 8) + buf[i]; 4666 num = (num << 8) + buf[i];
4592 *b += bytes; 4667 *b += bytes;
4593 *length -= bytes; 4668 *length -= bytes;
4594 return num; 4669 return num;
4595 } 4670 }
4596 4671
4597 /* Read in two values from the incoming decrypted byte stream "b", which is 4672 /* Read in two values from the incoming decrypted byte stream "b", which is
4598 * *length bytes long. The first value is a number whose size is "bytes" 4673 * *length bytes long. The first value is a number whose size is "bytes"
4599 * bytes long. The second value is a byte-string whose size is the value 4674 * bytes long. The second value is a byte-string whose size is the value
4600 * of the first number received. The latter byte-string, and its length, 4675 * of the first number received. The latter byte-string, and its length,
4601 * is returned in the SECItem i. 4676 * is returned in the SECItem i.
4602 * 4677 *
4603 * Returns SECFailure (-1) on failure. 4678 * Returns SECFailure (-1) on failure.
4604 * On error, an alert has been sent, and a generic error code has been set. 4679 * On error, an alert has been sent, and a generic error code has been set.
4605 * 4680 *
4606 * RADICAL CHANGE for NSS 3.11. All callers of this function make copies 4681 * RADICAL CHANGE for NSS 3.11. All callers of this function make copies
4607 * of the data returned in the SECItem *i, so making a copy of it here 4682 * of the data returned in the SECItem *i, so making a copy of it here
4608 * is simply wasteful. So, This function now just sets SECItem *i to 4683 * is simply wasteful. So, This function now just sets SECItem *i to
4609 * point to the values in the buffer **b. 4684 * point to the values in the buffer **b.
4610 */ 4685 */
4611 SECStatus 4686 SECStatus
4612 ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i, PRInt32 bytes, 4687 ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i, PRInt32 bytes,
4613 » » » SSL3Opaque **b, PRUint32 *length) 4688 SSL3Opaque **b, PRUint32 *length)
4614 { 4689 {
4615 PRInt32 count; 4690 PRInt32 count;
4616 4691
4617 PORT_Assert(bytes <= 3); 4692 PORT_Assert(bytes <= 3);
4618 i->len = 0; 4693 i->len = 0;
4619 i->data = NULL; 4694 i->data = NULL;
4620 i->type = siBuffer; 4695 i->type = siBuffer;
4621 count = ssl3_ConsumeHandshakeNumber(ss, bytes, b, length); 4696 count = ssl3_ConsumeHandshakeNumber(ss, bytes, b, length);
4622 if (count < 0) { » » /* Can't test for SECSuccess here. */ 4697 if (count < 0) { /* Can't test for SECSuccess here. */
4623 » return SECFailure; 4698 return SECFailure;
4624 } 4699 }
4625 if (count > 0) { 4700 if (count > 0) {
4626 » if ((PRUint32)count > *length) { 4701 if ((PRUint32)count > *length) {
4627 » return ssl3_DecodeError(ss); 4702 return ssl3_DecodeError(ss);
4628 » } 4703 }
4629 » i->data = *b; 4704 i->data = *b;
4630 » i->len = count; 4705 i->len = count;
4631 » *b += count; 4706 *b += count;
4632 » *length -= count; 4707 *length -= count;
4633 } 4708 }
4634 return SECSuccess; 4709 return SECSuccess;
4635 } 4710 }
4636 4711
4637 /* tlsHashOIDMap contains the mapping between TLS hash identifiers and the 4712 /* tlsHashOIDMap contains the mapping between TLS hash identifiers and the
4638 * SECOidTag used internally by NSS. */ 4713 * SECOidTag used internally by NSS. */
4639 static const struct { 4714 static const struct {
4640 SSLHashType tlsHash; 4715 SSLHashType tlsHash;
4641 SECOidTag oid; 4716 SECOidTag oid;
4642 } tlsHashOIDMap[] = { 4717 } tlsHashOIDMap[] = {
4643 { ssl_hash_sha1, SEC_OID_SHA1 }, 4718 { ssl_hash_sha1, SEC_OID_SHA1 },
4644 { ssl_hash_sha256, SEC_OID_SHA256 }, 4719 { ssl_hash_sha256, SEC_OID_SHA256 },
4645 { ssl_hash_sha384, SEC_OID_SHA384 }, 4720 { ssl_hash_sha384, SEC_OID_SHA384 },
4646 { ssl_hash_sha512, SEC_OID_SHA512 } 4721 { ssl_hash_sha512, SEC_OID_SHA512 }
4647 }; 4722 };
4648 4723
4649 /* ssl3_TLSHashAlgorithmToOID converts a TLS hash identifier into an OID value. 4724 /* ssl3_TLSHashAlgorithmToOID converts a TLS hash identifier into an OID value.
4650 * If the hash is not recognised, SEC_OID_UNKNOWN is returned. 4725 * If the hash is not recognised, SEC_OID_UNKNOWN is returned.
4651 * 4726 *
4652 * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */ 4727 * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
4653 SECOidTag 4728 SECOidTag
4654 ssl3_TLSHashAlgorithmToOID(SSLHashType hashFunc) 4729 ssl3_TLSHashAlgorithmToOID(SSLHashType hashFunc)
4655 { 4730 {
4656 unsigned int i; 4731 unsigned int i;
4657 4732
4658 for (i = 0; i < PR_ARRAY_SIZE(tlsHashOIDMap); i++) { 4733 for (i = 0; i < PR_ARRAY_SIZE(tlsHashOIDMap); i++) {
4659 » if (hashFunc == tlsHashOIDMap[i].tlsHash) { 4734 if (hashFunc == tlsHashOIDMap[i].tlsHash) {
4660 » return tlsHashOIDMap[i].oid; 4735 return tlsHashOIDMap[i].oid;
4661 » } 4736 }
4662 } 4737 }
4663 return SEC_OID_UNKNOWN; 4738 return SEC_OID_UNKNOWN;
4664 } 4739 }
4665 4740
4666 /* ssl3_TLSSignatureAlgorithmForKeyType returns the TLS 1.2 signature algorithm 4741 /* ssl3_TLSSignatureAlgorithmForKeyType returns the TLS 1.2 signature algorithm
4667 * identifier for a given KeyType. */ 4742 * identifier for a given KeyType. */
4668 static SECStatus 4743 static SECStatus
4669 ssl3_TLSSignatureAlgorithmForKeyType(KeyType keyType, SSLSignType *out) 4744 ssl3_TLSSignatureAlgorithmForKeyType(KeyType keyType, SSLSignType *out)
4670 { 4745 {
4671 switch (keyType) { 4746 switch (keyType) {
4672 case rsaKey: 4747 case rsaKey:
4673 *out = ssl_sign_rsa; 4748 *out = ssl_sign_rsa;
4674 return SECSuccess; 4749 return SECSuccess;
4675 case dsaKey: 4750 case dsaKey:
4676 *out = ssl_sign_dsa; 4751 *out = ssl_sign_dsa;
4677 return SECSuccess; 4752 return SECSuccess;
4678 case ecKey: 4753 case ecKey:
4679 *out = ssl_sign_ecdsa; 4754 *out = ssl_sign_ecdsa;
4680 return SECSuccess; 4755 return SECSuccess;
4681 default: 4756 default:
4682 PORT_SetError(SEC_ERROR_INVALID_KEY); 4757 PORT_SetError(SEC_ERROR_INVALID_KEY);
4683 return SECFailure; 4758 return SECFailure;
4684 } 4759 }
4685 } 4760 }
4686 4761
4687 /* ssl3_TLSSignatureAlgorithmForCertificate returns the TLS 1.2 signature 4762 /* ssl3_TLSSignatureAlgorithmForCertificate returns the TLS 1.2 signature
4688 * algorithm identifier for the given certificate. */ 4763 * algorithm identifier for the given certificate. */
4689 static SECStatus 4764 static SECStatus
4690 ssl3_TLSSignatureAlgorithmForCertificate(CERTCertificate *cert, 4765 ssl3_TLSSignatureAlgorithmForCertificate(CERTCertificate *cert,
4691 SSLSignType *out) 4766 SSLSignType *out)
4692 { 4767 {
4693 SECKEYPublicKey *key; 4768 SECKEYPublicKey *key;
(...skipping 11 matching lines...) Expand all
4705 } 4780 }
4706 4781
4707 /* ssl3_CheckSignatureAndHashAlgorithmConsistency checks that the signature 4782 /* ssl3_CheckSignatureAndHashAlgorithmConsistency checks that the signature
4708 * algorithm identifier in |sigAndHash| is consistent with the public key in 4783 * algorithm identifier in |sigAndHash| is consistent with the public key in
4709 * |cert|. It also checks the hash algorithm against the configured signature 4784 * |cert|. It also checks the hash algorithm against the configured signature
4710 * algorithms. If all the tests pass, SECSuccess is returned. Otherwise, 4785 * algorithms. If all the tests pass, SECSuccess is returned. Otherwise,
4711 * PORT_SetError is called and SECFailure is returned. */ 4786 * PORT_SetError is called and SECFailure is returned. */
4712 SECStatus 4787 SECStatus
4713 ssl3_CheckSignatureAndHashAlgorithmConsistency( 4788 ssl3_CheckSignatureAndHashAlgorithmConsistency(
4714 sslSocket *ss, const SSLSignatureAndHashAlg *sigAndHash, 4789 sslSocket *ss, const SSLSignatureAndHashAlg *sigAndHash,
4715 CERTCertificate* cert) 4790 CERTCertificate *cert)
4716 { 4791 {
4717 SECStatus rv; 4792 SECStatus rv;
4718 SSLSignType sigAlg; 4793 SSLSignType sigAlg;
4719 unsigned int i; 4794 unsigned int i;
4720 4795
4796 /* If we're a client, check that the signature algorithm matches the signing
4797 * key type of the cipher suite. */
4798 if (!ss->sec.isServer &&
4799 ss->ssl3.hs.kea_def->signKeyType != sigAndHash->sigAlg) {
4800 PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM);
4801 return SECFailure;
4802 }
4803
4804 /* Verify that the signature algorithm used for the
4805 * signature matches the signing key. */
4721 rv = ssl3_TLSSignatureAlgorithmForCertificate(cert, &sigAlg); 4806 rv = ssl3_TLSSignatureAlgorithmForCertificate(cert, &sigAlg);
4722 if (rv != SECSuccess) { 4807 if (rv != SECSuccess) {
4723 return rv; 4808 return rv;
4724 } 4809 }
4725 if (sigAlg != sigAndHash->sigAlg) { 4810 if (sigAlg != sigAndHash->sigAlg) {
4726 PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM); 4811 PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM);
4727 return SECFailure; 4812 return SECFailure;
4728 } 4813 }
4729 4814
4730 for (i = 0; i < ss->ssl3.signatureAlgorithmCount; ++i) { 4815 for (i = 0; i < ss->ssl3.signatureAlgorithmCount; ++i) {
(...skipping 78 matching lines...) Expand 10 before | Expand all | Expand 10 after
4809 * end of Consume Handshake functions. 4894 * end of Consume Handshake functions.
4810 **************************************************************************/ 4895 **************************************************************************/
4811 4896
4812 /* Extract the hashes of handshake messages to this point. 4897 /* Extract the hashes of handshake messages to this point.
4813 * Called from ssl3_SendCertificateVerify 4898 * Called from ssl3_SendCertificateVerify
4814 * ssl3_SendFinished 4899 * ssl3_SendFinished
4815 * ssl3_HandleHandshakeMessage 4900 * ssl3_HandleHandshakeMessage
4816 * 4901 *
4817 * Caller must hold the SSL3HandshakeLock. 4902 * Caller must hold the SSL3HandshakeLock.
4818 * Caller must hold a read or write lock on the Spec R/W lock. 4903 * Caller must hold a read or write lock on the Spec R/W lock.
4819 *» (There is presently no way to assert on a Read lock.) 4904 * (There is presently no way to assert on a Read lock.)
4820 */ 4905 */
4821 static SECStatus 4906 SECStatus
4822 ssl3_ComputeHandshakeHashes(sslSocket * ss, 4907 ssl3_ComputeHandshakeHashes(sslSocket *ss,
4823 ssl3CipherSpec *spec, /* uses ->master_secret */ 4908 ssl3CipherSpec *spec, /* uses ->master_secret */
4824 » » » SSL3Hashes * hashes, /* output goes here. */ 4909 SSL3Hashes *hashes, /* output goes here. */
4825 » » » PRUint32 sender) 4910 PRUint32 sender)
4826 { 4911 {
4827 SECStatus rv = SECSuccess; 4912 SECStatus rv = SECSuccess;
4828 PRBool isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0); 4913 PRBool isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0);
4829 unsigned int outLength; 4914 unsigned int outLength;
4830 SSL3Opaque md5_inner[MAX_MAC_LENGTH]; 4915 SSL3Opaque md5_inner[MAX_MAC_LENGTH];
4831 SSL3Opaque sha_inner[MAX_MAC_LENGTH]; 4916 SSL3Opaque sha_inner[MAX_MAC_LENGTH];
4832 4917
4833 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 4918 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
4834 if (ss->ssl3.hs.hashType == handshake_hash_unknown) { 4919 if (ss->ssl3.hs.hashType == handshake_hash_unknown) {
4835 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 4920 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
4836 return SECFailure; 4921 return SECFailure;
4837 } 4922 }
4838 4923
4839 hashes->hashAlg = ssl_hash_none; 4924 hashes->hashAlg = ssl_hash_none;
4840 4925
4841 #ifndef NO_PKCS11_BYPASS 4926 #ifndef NO_PKCS11_BYPASS
4842 if (ss->opt.bypassPKCS11 && 4927 if (ss->opt.bypassPKCS11 &&
4843 » ss->ssl3.hs.hashType == handshake_hash_single) { 4928 ss->ssl3.hs.hashType == handshake_hash_single) {
4844 » /* compute them without PKCS11 */ 4929 /* compute them without PKCS11 */
4845 » PRUint64 sha_cx[MAX_MAC_CONTEXT_LLONGS]; 4930 PRUint64 sha_cx[MAX_MAC_CONTEXT_LLONGS];
4846 4931
4847 » ss->ssl3.hs.sha_clone(sha_cx, ss->ssl3.hs.sha_cx); 4932 ss->ssl3.hs.sha_clone(sha_cx, ss->ssl3.hs.sha_cx);
4848 » ss->ssl3.hs.sha_obj->end(sha_cx, hashes->u.raw, &hashes->len, 4933 ss->ssl3.hs.sha_obj->end(sha_cx, hashes->u.raw, &hashes->len,
4849 » » » » sizeof(hashes->u.raw)); 4934 sizeof(hashes->u.raw));
4850 4935
4851 » PRINT_BUF(60, (NULL, "SHA-256: result", hashes->u.raw, hashes->len)); 4936 PRINT_BUF(60, (NULL, "SHA-256: result", hashes->u.raw, hashes->len));
4852 4937
4853 » /* If we ever support ciphersuites where the PRF hash isn't SHA-256 4938 /* If we ever support ciphersuites where the PRF hash isn't SHA-256
4854 » * then this will need to be updated. */ 4939 * then this will need to be updated. */
4855 » hashes->hashAlg = ssl_hash_sha256; 4940 hashes->hashAlg = ssl_hash_sha256;
4856 » rv = SECSuccess; 4941 rv = SECSuccess;
4857 } else if (ss->opt.bypassPKCS11) { 4942 } else if (ss->opt.bypassPKCS11) {
4858 » /* compute them without PKCS11 */ 4943 /* compute them without PKCS11 */
4859 » PRUint64 md5_cx[MAX_MAC_CONTEXT_LLONGS]; 4944 PRUint64 md5_cx[MAX_MAC_CONTEXT_LLONGS];
4860 » PRUint64 sha_cx[MAX_MAC_CONTEXT_LLONGS]; 4945 PRUint64 sha_cx[MAX_MAC_CONTEXT_LLONGS];
4861 4946
4862 #define md5cx ((MD5Context *)md5_cx) 4947 #define md5cx ((MD5Context *)md5_cx)
4863 #define shacx ((SHA1Context *)sha_cx) 4948 #define shacx ((SHA1Context *)sha_cx)
4864 4949
4865 » MD5_Clone (md5cx, (MD5Context *)ss->ssl3.hs.md5_cx); 4950 MD5_Clone(md5cx, (MD5Context *)ss->ssl3.hs.md5_cx);
4866 » SHA1_Clone(shacx, (SHA1Context *)ss->ssl3.hs.sha_cx); 4951 SHA1_Clone(shacx, (SHA1Context *)ss->ssl3.hs.sha_cx);
4867 4952
4868 » if (!isTLS) { 4953 if (!isTLS) {
4869 » /* compute hashes for SSL3. */ 4954 /* compute hashes for SSL3. */
4870 » unsigned char s[4]; 4955 unsigned char s[4];
4871 4956
4872 if (!spec->msItem.data) { 4957 if (!spec->msItem.data) {
4873 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE); 4958 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
4874 return SECFailure; 4959 return SECFailure;
4875 } 4960 }
4876 4961
4877 » s[0] = (unsigned char)(sender >> 24); 4962 s[0] = (unsigned char)(sender >> 24);
4878 » s[1] = (unsigned char)(sender >> 16); 4963 s[1] = (unsigned char)(sender >> 16);
4879 » s[2] = (unsigned char)(sender >> 8); 4964 s[2] = (unsigned char)(sender >> 8);
4880 » s[3] = (unsigned char)sender; 4965 s[3] = (unsigned char)sender;
4881 4966
4882 » if (sender != 0) { 4967 if (sender != 0) {
4883 » » MD5_Update(md5cx, s, 4); 4968 MD5_Update(md5cx, s, 4);
4884 » » PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4)); 4969 PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4));
4885 » } 4970 }
4886 4971
4887 » PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1, 4972 PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1,
4888 » » » mac_defs[mac_md5].pad_size)); 4973 mac_defs[mac_md5].pad_size));
4889 4974
4890 » MD5_Update(md5cx, spec->msItem.data, spec->msItem.len); 4975 MD5_Update(md5cx, spec->msItem.data, spec->msItem.len);
4891 » MD5_Update(md5cx, mac_pad_1, mac_defs[mac_md5].pad_size); 4976 MD5_Update(md5cx, mac_pad_1, mac_defs[mac_md5].pad_size);
4892 » MD5_End(md5cx, md5_inner, &outLength, MD5_LENGTH); 4977 MD5_End(md5cx, md5_inner, &outLength, MD5_LENGTH);
4893 4978
4894 » PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength)); 4979 PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength));
4895 4980
4896 » if (sender != 0) { 4981 if (sender != 0) {
4897 » » SHA1_Update(shacx, s, 4); 4982 SHA1_Update(shacx, s, 4);
4898 » » PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4)); 4983 PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4));
4899 » } 4984 }
4900 4985
4901 » PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1, 4986 PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1,
4902 » » » mac_defs[mac_sha].pad_size)); 4987 mac_defs[mac_sha].pad_size));
4903 4988
4904 » SHA1_Update(shacx, spec->msItem.data, spec->msItem.len); 4989 SHA1_Update(shacx, spec->msItem.data, spec->msItem.len);
4905 » SHA1_Update(shacx, mac_pad_1, mac_defs[mac_sha].pad_size); 4990 SHA1_Update(shacx, mac_pad_1, mac_defs[mac_sha].pad_size);
4906 » SHA1_End(shacx, sha_inner, &outLength, SHA1_LENGTH); 4991 SHA1_End(shacx, sha_inner, &outLength, SHA1_LENGTH);
4907 4992
4908 » PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength)); 4993 PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength));
4909 » PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2, 4994 PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2,
4910 » » » mac_defs[mac_md5].pad_size)); 4995 mac_defs[mac_md5].pad_size));
4911 » PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH)) ; 4996 PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH)) ;
4912 4997
4913 » MD5_Begin(md5cx); 4998 MD5_Begin(md5cx);
4914 » MD5_Update(md5cx, spec->msItem.data, spec->msItem.len); 4999 MD5_Update(md5cx, spec->msItem.data, spec->msItem.len);
4915 » MD5_Update(md5cx, mac_pad_2, mac_defs[mac_md5].pad_size); 5000 MD5_Update(md5cx, mac_pad_2, mac_defs[mac_md5].pad_size);
4916 » MD5_Update(md5cx, md5_inner, MD5_LENGTH); 5001 MD5_Update(md5cx, md5_inner, MD5_LENGTH);
4917 » } 5002 }
4918 » MD5_End(md5cx, hashes->u.s.md5, &outLength, MD5_LENGTH); 5003 MD5_End(md5cx, hashes->u.s.md5, &outLength, MD5_LENGTH);
4919 5004
4920 » PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH)); 5005 PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH));
4921 5006
4922 » if (!isTLS) { 5007 if (!isTLS) {
4923 » PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2, 5008 PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2,
4924 » » » mac_defs[mac_sha].pad_size)); 5009 mac_defs[mac_sha].pad_size));
4925 » PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH) ); 5010 PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH) );
4926 5011
4927 » SHA1_Begin(shacx); 5012 SHA1_Begin(shacx);
4928 » SHA1_Update(shacx, spec->msItem.data, spec->msItem.len); 5013 SHA1_Update(shacx, spec->msItem.data, spec->msItem.len);
4929 » SHA1_Update(shacx, mac_pad_2, mac_defs[mac_sha].pad_size); 5014 SHA1_Update(shacx, mac_pad_2, mac_defs[mac_sha].pad_size);
4930 » SHA1_Update(shacx, sha_inner, SHA1_LENGTH); 5015 SHA1_Update(shacx, sha_inner, SHA1_LENGTH);
4931 » } 5016 }
4932 » SHA1_End(shacx, hashes->u.s.sha, &outLength, SHA1_LENGTH); 5017 SHA1_End(shacx, hashes->u.s.sha, &outLength, SHA1_LENGTH);
4933 5018
4934 » PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH)) ; 5019 PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH)) ;
4935 5020
4936 » hashes->len = MD5_LENGTH + SHA1_LENGTH; 5021 hashes->len = MD5_LENGTH + SHA1_LENGTH;
4937 » rv = SECSuccess; 5022 rv = SECSuccess;
4938 #undef md5cx 5023 #undef md5cx
4939 #undef shacx 5024 #undef shacx
4940 } else 5025 } else
4941 #endif 5026 #endif
4942 if (ss->ssl3.hs.hashType == handshake_hash_single) { 5027 if (ss->ssl3.hs.hashType == handshake_hash_single) {
4943 » /* compute hashes with PKCS11 */ 5028 /* compute hashes with PKCS11 */
4944 » PK11Context *h; 5029 PK11Context *h;
4945 » unsigned int stateLen; 5030 unsigned int stateLen;
4946 » unsigned char stackBuf[1024]; 5031 unsigned char stackBuf[1024];
4947 » unsigned char *stateBuf = NULL; 5032 unsigned char *stateBuf = NULL;
4948 5033
4949 » h = ss->ssl3.hs.sha; 5034 h = ss->ssl3.hs.sha;
4950 » stateBuf = PK11_SaveContextAlloc(h, stackBuf, 5035 stateBuf = PK11_SaveContextAlloc(h, stackBuf,
4951 » » » » » sizeof(stackBuf), &stateLen); 5036 sizeof(stackBuf), &stateLen);
4952 » if (stateBuf == NULL) { 5037 if (stateBuf == NULL) {
4953 » ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); 5038 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4954 » goto tls12_loser; 5039 goto tls12_loser;
4955 » } 5040 }
4956 » rv |= PK11_DigestFinal(h, hashes->u.raw, &hashes->len, 5041 rv |= PK11_DigestFinal(h, hashes->u.raw, &hashes->len,
4957 » » » sizeof(hashes->u.raw)); 5042 sizeof(hashes->u.raw));
4958 » if (rv != SECSuccess) { 5043 if (rv != SECSuccess) {
4959 » ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); 5044 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4960 » rv = SECFailure; 5045 rv = SECFailure;
4961 » goto tls12_loser; 5046 goto tls12_loser;
4962 » } 5047 }
4963 » /* If we ever support ciphersuites where the PRF hash isn't SHA-256 5048 /* If we ever support ciphersuites where the PRF hash isn't SHA-256
4964 » * then this will need to be updated. */ 5049 * then this will need to be updated. */
4965 » hashes->hashAlg = ssl_hash_sha256; 5050 hashes->hashAlg = ssl_hash_sha256;
4966 » rv = SECSuccess; 5051 rv = SECSuccess;
4967 5052
4968 tls12_loser: 5053 tls12_loser:
4969 » if (stateBuf) { 5054 if (stateBuf) {
4970 » if (PK11_RestoreContext(h, stateBuf, stateLen) != SECSuccess) { 5055 if (PK11_RestoreContext(h, stateBuf, stateLen) != SECSuccess) {
4971 » » ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); 5056 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4972 » » rv = SECFailure; 5057 rv = SECFailure;
4973 » } 5058 }
4974 » if (stateBuf != stackBuf) { 5059 if (stateBuf != stackBuf) {
4975 » » PORT_ZFree(stateBuf, stateLen); 5060 PORT_ZFree(stateBuf, stateLen);
4976 » } 5061 }
4977 » } 5062 }
4978 } else { 5063 } else {
4979 » /* compute hashes with PKCS11 */ 5064 /* compute hashes with PKCS11 */
4980 » PK11Context * md5; 5065 PK11Context *md5;
4981 » PK11Context * sha = NULL; 5066 PK11Context *sha = NULL;
4982 » unsigned char *md5StateBuf = NULL; 5067 unsigned char *md5StateBuf = NULL;
4983 » unsigned char *shaStateBuf = NULL; 5068 unsigned char *shaStateBuf = NULL;
4984 » unsigned int md5StateLen, shaStateLen; 5069 unsigned int md5StateLen, shaStateLen;
4985 » unsigned char md5StackBuf[256]; 5070 unsigned char md5StackBuf[256];
4986 » unsigned char shaStackBuf[512]; 5071 unsigned char shaStackBuf[512];
4987 5072
4988 » md5StateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.md5, md5StackBuf, 5073 md5StateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.md5, md5StackBuf,
4989 » » » » » sizeof md5StackBuf, &md5StateLen); 5074 sizeof md5StackBuf, &md5StateLen);
4990 » if (md5StateBuf == NULL) { 5075 if (md5StateBuf == NULL) {
4991 » ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); 5076 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4992 » goto loser; 5077 goto loser;
4993 » } 5078 }
4994 » md5 = ss->ssl3.hs.md5; 5079 md5 = ss->ssl3.hs.md5;
4995 5080
4996 » shaStateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.sha, shaStackBuf, 5081 shaStateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.sha, shaStackBuf,
4997 » » » » » sizeof shaStackBuf, &shaStateLen); 5082 sizeof shaStackBuf, &shaStateLen);
4998 » if (shaStateBuf == NULL) { 5083 if (shaStateBuf == NULL) {
4999 » ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 5084 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
5000 » goto loser; 5085 goto loser;
5001 » } 5086 }
5002 » sha = ss->ssl3.hs.sha; 5087 sha = ss->ssl3.hs.sha;
5003 5088
5004 » if (!isTLS) { 5089 if (!isTLS) {
5005 » /* compute hashes for SSL3. */ 5090 /* compute hashes for SSL3. */
5006 » unsigned char s[4]; 5091 unsigned char s[4];
5007 5092
5008 if (!spec->master_secret) { 5093 if (!spec->master_secret) {
5009 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE); 5094 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
5010 return SECFailure; 5095 rv = SECFailure;
5011 } 5096 goto loser;
5012 5097 }
5013 » s[0] = (unsigned char)(sender >> 24); 5098
5014 » s[1] = (unsigned char)(sender >> 16); 5099 s[0] = (unsigned char)(sender >> 24);
5015 » s[2] = (unsigned char)(sender >> 8); 5100 s[1] = (unsigned char)(sender >> 16);
5016 » s[3] = (unsigned char)sender; 5101 s[2] = (unsigned char)(sender >> 8);
5017 5102 s[3] = (unsigned char)sender;
5018 » if (sender != 0) { 5103
5019 » » rv |= PK11_DigestOp(md5, s, 4); 5104 if (sender != 0) {
5020 » » PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4)); 5105 rv |= PK11_DigestOp(md5, s, 4);
5021 » } 5106 PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4));
5022 5107 }
5023 » PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1, 5108
5024 » » » mac_defs[mac_md5].pad_size)); 5109 PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1,
5025 5110 mac_defs[mac_md5].pad_size));
5026 » rv |= PK11_DigestKey(md5,spec->master_secret); 5111
5027 » rv |= PK11_DigestOp(md5, mac_pad_1, mac_defs[mac_md5].pad_size); 5112 rv |= PK11_DigestKey(md5, spec->master_secret);
5028 » rv |= PK11_DigestFinal(md5, md5_inner, &outLength, MD5_LENGTH); 5113 rv |= PK11_DigestOp(md5, mac_pad_1, mac_defs[mac_md5].pad_size);
5029 » PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH); 5114 rv |= PK11_DigestFinal(md5, md5_inner, &outLength, MD5_LENGTH);
5030 » if (rv != SECSuccess) { 5115 PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH);
5031 » » ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); 5116 if (rv != SECSuccess) {
5032 » » rv = SECFailure; 5117 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
5033 » » goto loser; 5118 rv = SECFailure;
5034 » } 5119 goto loser;
5035 5120 }
5036 » PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength)); 5121
5037 5122 PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength));
5038 » if (sender != 0) { 5123
5039 » » rv |= PK11_DigestOp(sha, s, 4); 5124 if (sender != 0) {
5040 » » PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4)); 5125 rv |= PK11_DigestOp(sha, s, 4);
5041 » } 5126 PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4));
5042 5127 }
5043 » PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1, 5128
5044 » » » mac_defs[mac_sha].pad_size)); 5129 PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1,
5045 5130 mac_defs[mac_sha].pad_size));
5046 » rv |= PK11_DigestKey(sha, spec->master_secret); 5131
5047 » rv |= PK11_DigestOp(sha, mac_pad_1, mac_defs[mac_sha].pad_size); 5132 rv |= PK11_DigestKey(sha, spec->master_secret);
5048 » rv |= PK11_DigestFinal(sha, sha_inner, &outLength, SHA1_LENGTH); 5133 rv |= PK11_DigestOp(sha, mac_pad_1, mac_defs[mac_sha].pad_size);
5049 » PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH); 5134 rv |= PK11_DigestFinal(sha, sha_inner, &outLength, SHA1_LENGTH);
5050 » if (rv != SECSuccess) { 5135 PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH);
5051 » » ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 5136 if (rv != SECSuccess) {
5052 » » rv = SECFailure; 5137 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
5053 » » goto loser; 5138 rv = SECFailure;
5054 » } 5139 goto loser;
5055 5140 }
5056 » PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength)); 5141
5057 5142 PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength));
5058 » PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2, 5143
5059 » » » mac_defs[mac_md5].pad_size)); 5144 PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2,
5060 » PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH)) ; 5145 mac_defs[mac_md5].pad_size));
5061 5146 PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH)) ;
5062 » rv |= PK11_DigestBegin(md5); 5147
5063 » rv |= PK11_DigestKey(md5, spec->master_secret); 5148 rv |= PK11_DigestBegin(md5);
5064 » rv |= PK11_DigestOp(md5, mac_pad_2, mac_defs[mac_md5].pad_size); 5149 rv |= PK11_DigestKey(md5, spec->master_secret);
5065 » rv |= PK11_DigestOp(md5, md5_inner, MD5_LENGTH); 5150 rv |= PK11_DigestOp(md5, mac_pad_2, mac_defs[mac_md5].pad_size);
5066 » } 5151 rv |= PK11_DigestOp(md5, md5_inner, MD5_LENGTH);
5067 » rv |= PK11_DigestFinal(md5, hashes->u.s.md5, &outLength, MD5_LENGTH); 5152 }
5068 » PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH); 5153 rv |= PK11_DigestFinal(md5, hashes->u.s.md5, &outLength, MD5_LENGTH);
5069 » if (rv != SECSuccess) { 5154 PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH);
5070 » ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); 5155 if (rv != SECSuccess) {
5071 » rv = SECFailure; 5156 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
5072 » goto loser; 5157 rv = SECFailure;
5073 » } 5158 goto loser;
5074 5159 }
5075 » PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH)); 5160
5076 5161 PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH));
5077 » if (!isTLS) { 5162
5078 » PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2, 5163 if (!isTLS) {
5079 » » » mac_defs[mac_sha].pad_size)); 5164 PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2,
5080 » PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH) ); 5165 mac_defs[mac_sha].pad_size));
5081 5166 PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH) );
5082 » rv |= PK11_DigestBegin(sha); 5167
5083 » rv |= PK11_DigestKey(sha,spec->master_secret); 5168 rv |= PK11_DigestBegin(sha);
5084 » rv |= PK11_DigestOp(sha, mac_pad_2, mac_defs[mac_sha].pad_size); 5169 rv |= PK11_DigestKey(sha, spec->master_secret);
5085 » rv |= PK11_DigestOp(sha, sha_inner, SHA1_LENGTH); 5170 rv |= PK11_DigestOp(sha, mac_pad_2, mac_defs[mac_sha].pad_size);
5086 » } 5171 rv |= PK11_DigestOp(sha, sha_inner, SHA1_LENGTH);
5087 » rv |= PK11_DigestFinal(sha, hashes->u.s.sha, &outLength, SHA1_LENGTH); 5172 }
5088 » PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH); 5173 rv |= PK11_DigestFinal(sha, hashes->u.s.sha, &outLength, SHA1_LENGTH);
5089 » if (rv != SECSuccess) { 5174 PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH);
5090 » ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 5175 if (rv != SECSuccess) {
5091 » rv = SECFailure; 5176 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
5092 » goto loser; 5177 rv = SECFailure;
5093 » } 5178 goto loser;
5094 5179 }
5095 » PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH)) ; 5180
5096 5181 PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH)) ;
5097 » hashes->len = MD5_LENGTH + SHA1_LENGTH; 5182
5098 » rv = SECSuccess; 5183 hashes->len = MD5_LENGTH + SHA1_LENGTH;
5184 rv = SECSuccess;
5099 5185
5100 loser: 5186 loser:
5101 » if (md5StateBuf) { 5187 if (md5StateBuf) {
5102 » if (PK11_RestoreContext(ss->ssl3.hs.md5, md5StateBuf, md5StateLen) 5188 if (PK11_RestoreContext(ss->ssl3.hs.md5, md5StateBuf, md5StateLen) ! =
5103 » » != SECSuccess) 5189 SECSuccess) {
5104 » { 5190 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
5105 » » ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); 5191 rv = SECFailure;
5106 » » rv = SECFailure; 5192 }
5107 » } 5193 if (md5StateBuf != md5StackBuf) {
5108 » if (md5StateBuf != md5StackBuf) { 5194 PORT_ZFree(md5StateBuf, md5StateLen);
5109 » » PORT_ZFree(md5StateBuf, md5StateLen); 5195 }
5110 » } 5196 }
5111 » } 5197 if (shaStateBuf) {
5112 » if (shaStateBuf) { 5198 if (PK11_RestoreContext(ss->ssl3.hs.sha, shaStateBuf, shaStateLen) ! =
5113 » if (PK11_RestoreContext(ss->ssl3.hs.sha, shaStateBuf, shaStateLen) 5199 SECSuccess) {
5114 » » != SECSuccess) 5200 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
5115 » { 5201 rv = SECFailure;
5116 » » ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 5202 }
5117 » » rv = SECFailure; 5203 if (shaStateBuf != shaStackBuf) {
5118 » } 5204 PORT_ZFree(shaStateBuf, shaStateLen);
5119 » if (shaStateBuf != shaStackBuf) { 5205 }
5120 » » PORT_ZFree(shaStateBuf, shaStateLen); 5206 }
5121 » }
5122 » }
5123 } 5207 }
5124 return rv; 5208 return rv;
5125 } 5209 }
5126 5210
5127 static SECStatus 5211 static SECStatus
5128 ssl3_ComputeBackupHandshakeHashes(sslSocket * ss, 5212 ssl3_ComputeBackupHandshakeHashes(sslSocket *ss,
5129 » » » » SSL3Hashes * hashes) /* output goes here. */ 5213 SSL3Hashes *hashes) /* output goes here. */
5130 { 5214 {
5131 SECStatus rv = SECSuccess; 5215 SECStatus rv = SECSuccess;
5132 5216
5133 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 5217 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5134 PORT_Assert( !ss->sec.isServer ); 5218 PORT_Assert(!ss->sec.isServer);
5135 PORT_Assert( ss->ssl3.hs.hashType == handshake_hash_single ); 5219 PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_single);
5136 5220
5137 rv = PK11_DigestFinal(ss->ssl3.hs.backupHash, hashes->u.raw, &hashes->len, 5221 rv = PK11_DigestFinal(ss->ssl3.hs.backupHash, hashes->u.raw, &hashes->len,
5138 » » » sizeof(hashes->u.raw)); 5222 sizeof(hashes->u.raw));
5139 if (rv != SECSuccess) { 5223 if (rv != SECSuccess) {
5140 » ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 5224 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
5141 » rv = SECFailure; 5225 rv = SECFailure;
5142 » goto loser; 5226 goto loser;
5143 } 5227 }
5144 hashes->hashAlg = ssl_hash_sha1; 5228 hashes->hashAlg = ssl_hash_sha1;
5145 5229
5146 loser: 5230 loser:
5147 PK11_DestroyContext(ss->ssl3.hs.backupHash, PR_TRUE); 5231 PK11_DestroyContext(ss->ssl3.hs.backupHash, PR_TRUE);
5148 ss->ssl3.hs.backupHash = NULL; 5232 ss->ssl3.hs.backupHash = NULL;
5149 return rv; 5233 return rv;
5150 } 5234 }
5151 5235
5152 /* 5236 /*
5153 * SSL 2 based implementations pass in the initial outbound buffer 5237 * SSL 2 based implementations pass in the initial outbound buffer
5154 * so that the handshake hash can contain the included information. 5238 * so that the handshake hash can contain the included information.
5155 * 5239 *
5156 * Called from ssl2_BeginClientHandshake() in sslcon.c 5240 * Called from ssl2_BeginClientHandshake() in sslcon.c
5157 */ 5241 */
5158 SECStatus 5242 SECStatus
5159 ssl3_StartHandshakeHash(sslSocket *ss, unsigned char * buf, int length) 5243 ssl3_StartHandshakeHash(sslSocket *ss, unsigned char *buf, int length)
5160 { 5244 {
5161 SECStatus rv; 5245 SECStatus rv;
5162 5246
5163 ssl_GetSSL3HandshakeLock(ss); /**************************************/ 5247 ssl_GetSSL3HandshakeLock(ss); /**************************************/
5164 5248
5165 rv = ssl3_InitState(ss); 5249 rv = ssl3_InitState(ss);
5166 if (rv != SECSuccess) { 5250 if (rv != SECSuccess) {
5167 » goto done;» » /* ssl3_InitState has set the error code. */ 5251 goto done; /* ssl3_InitState has set the error code. */
5168 } 5252 }
5169 rv = ssl3_RestartHandshakeHashes(ss); 5253 rv = ssl3_RestartHandshakeHashes(ss);
5170 if (rv != SECSuccess) { 5254 if (rv != SECSuccess) {
5171 » goto done; 5255 goto done;
5172 } 5256 }
5173 5257
5174 PORT_Memset(&ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH); 5258 PORT_Memset(&ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH);
5175 PORT_Memcpy( 5259 PORT_Memcpy(
5176 » &ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - SSL_CHALLENGE_BYTES ], 5260 &ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - SSL_CHALLENGE_BYTES ],
5177 » &ss->sec.ci.clientChallenge, 5261 &ss->sec.ci.clientChallenge,
5178 » SSL_CHALLENGE_BYTES); 5262 SSL_CHALLENGE_BYTES);
5179 5263
5180 rv = ssl3_UpdateHandshakeHashes(ss, buf, length); 5264 rv = ssl3_UpdateHandshakeHashes(ss, buf, length);
5181 /* if it failed, ssl3_UpdateHandshakeHashes has set the error code. */ 5265 /* if it failed, ssl3_UpdateHandshakeHashes has set the error code. */
5182 5266
5183 done: 5267 done:
5184 ssl_ReleaseSSL3HandshakeLock(ss); /**************************************/ 5268 ssl_ReleaseSSL3HandshakeLock(ss); /**************************************/
5185 return rv; 5269 return rv;
5186 } 5270 }
5187 5271
5188 /************************************************************************** 5272 /**************************************************************************
5189 * end of Handshake Hash functions. 5273 * end of Handshake Hash functions.
5190 * Begin Send and Handle functions for handshakes. 5274 * Begin Send and Handle functions for handshakes.
5191 **************************************************************************/ 5275 **************************************************************************/
5192 5276
5193 /* Called from ssl3_HandleHelloRequest(), 5277 /* Called from ssl3_HandleHelloRequest(),
5194 * ssl3_RedoHandshake() 5278 * ssl3_RedoHandshake()
5195 * ssl2_BeginClientHandshake (when resuming ssl3 session) 5279 * ssl2_BeginClientHandshake (when resuming ssl3 session)
5196 * dtls_HandleHelloVerifyRequest(with resending=PR_TRUE) 5280 * dtls_HandleHelloVerifyRequest(with resending=PR_TRUE)
5197 */ 5281 */
5198 SECStatus 5282 SECStatus
5199 ssl3_SendClientHello(sslSocket *ss, PRBool resending) 5283 ssl3_SendClientHello(sslSocket *ss, PRBool resending)
5200 { 5284 {
5201 sslSessionID * sid; 5285 sslSessionID *sid;
5202 ssl3CipherSpec * cwSpec; 5286 ssl3CipherSpec *cwSpec;
5203 SECStatus rv; 5287 SECStatus rv;
5204 int i; 5288 int i;
5205 int length; 5289 int length;
5206 int num_suites; 5290 int num_suites;
5207 int actual_count = 0; 5291 int actual_count = 0;
5208 PRBool isTLS = PR_FALSE; 5292 PRBool isTLS = PR_FALSE;
5209 PRBool requestingResume = PR_FALSE, fallbackSCSV = PR_FALSE; 5293 PRBool requestingResume = PR_FALSE, fallbackSCSV = PR_FALSE;
5210 PRInt32 total_exten_len = 0; 5294 PRInt32 total_exten_len = 0;
5211 unsigned paddingExtensionLen; 5295 unsigned paddingExtensionLen;
5212 unsigned numCompressionMethods; 5296 unsigned numCompressionMethods;
5213 PRInt32 flags; 5297 PRInt32 flags;
5214 5298
5215 SSL_TRC(3, ("%d: SSL3[%d]: send client_hello handshake", SSL_GETPID(), 5299 SSL_TRC(3, ("%d: SSL3[%d]: send client_hello handshake", SSL_GETPID(),
5216 » » ss->fd)); 5300 ss->fd));
5217 5301
5218 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 5302 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5219 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); 5303 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
5220 5304
5221 rv = ssl3_InitState(ss); 5305 rv = ssl3_InitState(ss);
5222 if (rv != SECSuccess) { 5306 if (rv != SECSuccess) {
5223 » return rv;» » /* ssl3_InitState has set the error code. */ 5307 return rv; /* ssl3_InitState has set the error code. */
5224 } 5308 }
5225 /* These must be reset every handshake. */ 5309 /* These must be reset every handshake. */
5226 ss->ssl3.hs.sendingSCSV = PR_FALSE; 5310 ss->ssl3.hs.sendingSCSV = PR_FALSE;
5227 ss->ssl3.hs.preliminaryInfo = 0; 5311 ss->ssl3.hs.preliminaryInfo = 0;
5228 PORT_Assert(IS_DTLS(ss) || !resending); 5312 PORT_Assert(IS_DTLS(ss) || !resending);
5229 5313
5230 SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket, PR_FALSE); 5314 SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket, PR_FALSE);
5231 ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE; 5315 ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE;
5232 5316
5233 /* We might be starting a session renegotiation in which case we should 5317 /* We might be starting a session renegotiation in which case we should
5234 * clear previous state. 5318 * clear previous state.
5235 */ 5319 */
5236 PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData)); 5320 PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
5237 5321
5238 rv = ssl3_RestartHandshakeHashes(ss); 5322 rv = ssl3_RestartHandshakeHashes(ss);
5239 if (rv != SECSuccess) { 5323 if (rv != SECSuccess) {
5240 » return rv; 5324 return rv;
5241 } 5325 }
5242 5326
5243 /* 5327 /*
5244 * During a renegotiation, ss->clientHelloVersion will be used again to 5328 * During a renegotiation, ss->clientHelloVersion will be used again to
5245 * work around a Windows SChannel bug. Ensure that it is still enabled. 5329 * work around a Windows SChannel bug. Ensure that it is still enabled.
5246 */ 5330 */
5247 if (ss->firstHsDone) { 5331 if (ss->firstHsDone) {
5248 » if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { 5332 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
5249 » PORT_SetError(SSL_ERROR_SSL_DISABLED); 5333 PORT_SetError(SSL_ERROR_SSL_DISABLED);
5250 » return SECFailure; 5334 return SECFailure;
5251 » } 5335 }
5252 5336
5253 » if (ss->clientHelloVersion < ss->vrange.min || 5337 if (ss->clientHelloVersion < ss->vrange.min ||
5254 » ss->clientHelloVersion > ss->vrange.max) { 5338 ss->clientHelloVersion > ss->vrange.max) {
5255 » PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); 5339 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
5256 » return SECFailure; 5340 return SECFailure;
5257 » } 5341 }
5258 } 5342 }
5259 5343
5260 /* We ignore ss->sec.ci.sid here, and use ssl_Lookup because Lookup 5344 /* We ignore ss->sec.ci.sid here, and use ssl_Lookup because Lookup
5261 * handles expired entries and other details. 5345 * handles expired entries and other details.
5262 * XXX If we've been called from ssl2_BeginClientHandshake, then 5346 * XXX If we've been called from ssl2_BeginClientHandshake, then
5263 * this lookup is duplicative and wasteful. 5347 * this lookup is duplicative and wasteful.
5264 */ 5348 */
5265 sid = (ss->opt.noCache) ? NULL 5349 sid = (ss->opt.noCache) ? NULL
5266 » : ssl_LookupSID(&ss->sec.ci.peer, ss->sec.ci.port, ss->peerID, ss->u rl); 5350 : ssl_LookupSID(&ss->sec.ci.peer, ss->sec.ci.port, s s->peerID, ss->url);
5267 5351
5268 /* We can't resume based on a different token. If the sid exists, 5352 /* We can't resume based on a different token. If the sid exists,
5269 * make sure the token that holds the master secret still exists ... 5353 * make sure the token that holds the master secret still exists ...
5270 * If we previously did client-auth, make sure that the token that holds 5354 * If we previously did client-auth, make sure that the token that holds
5271 * the private key still exists, is logged in, hasn't been removed, etc. 5355 * the private key still exists, is logged in, hasn't been removed, etc.
5272 */ 5356 */
5273 if (sid) { 5357 if (sid) {
5274 » PRBool sidOK = PR_TRUE; 5358 PRBool sidOK = PR_TRUE;
5275 » if (sid->u.ssl3.keys.msIsWrapped) { 5359 if (sid->u.ssl3.keys.msIsWrapped) {
5276 » /* Session key was wrapped, which means it was using PKCS11, */ 5360 /* Session key was wrapped, which means it was using PKCS11, */
5277 » PK11SlotInfo *slot = NULL; 5361 PK11SlotInfo *slot = NULL;
5278 » if (sid->u.ssl3.masterValid && !ss->opt.bypassPKCS11) { 5362 if (sid->u.ssl3.masterValid && !ss->opt.bypassPKCS11) {
5279 » » slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID, 5363 slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
5280 » » » » » sid->u.ssl3.masterSlotID); 5364 sid->u.ssl3.masterSlotID);
5281 » } 5365 }
5282 » if (slot == NULL) { 5366 if (slot == NULL) {
5283 » sidOK = PR_FALSE; 5367 sidOK = PR_FALSE;
5284 » } else { 5368 } else {
5285 » » PK11SymKey *wrapKey = NULL; 5369 PK11SymKey *wrapKey = NULL;
5286 » » if (!PK11_IsPresent(slot) || 5370 if (!PK11_IsPresent(slot) ||
5287 » » ((wrapKey = PK11_GetWrapKey(slot, 5371 ((wrapKey = PK11_GetWrapKey(slot,
5288 » » » » » » sid->u.ssl3.masterWrapIndex, 5372 sid->u.ssl3.masterWrapIndex,
5289 » » » » » » sid->u.ssl3.masterWrapMech, 5373 sid->u.ssl3.masterWrapMech,
5290 » » » » » » sid->u.ssl3.masterWrapSeries, 5374 sid->u.ssl3.masterWrapSeries,
5291 » » » » » » ss->pkcs11PinArg)) == NULL) ) { 5375 ss->pkcs11PinArg)) == NULL)) {
5292 » » sidOK = PR_FALSE; 5376 sidOK = PR_FALSE;
5293 » » } 5377 }
5294 » » if (wrapKey) PK11_FreeSymKey(wrapKey); 5378 if (wrapKey)
5295 » » PK11_FreeSlot(slot); 5379 PK11_FreeSymKey(wrapKey);
5296 » » slot = NULL; 5380 PK11_FreeSlot(slot);
5297 » } 5381 slot = NULL;
5298 » } 5382 }
5299 » /* If we previously did client-auth, make sure that the token that 5383 }
5300 » ** holds the private key still exists, is logged in, hasn't been 5384 /* If we previously did client-auth, make sure that the token that
5301 » ** removed, etc. 5385 ** holds the private key still exists, is logged in, hasn't been
5302 » */ 5386 ** removed, etc.
5303 » if (sidOK && !ssl3_ClientAuthTokenPresent(sid)) { 5387 */
5304 » sidOK = PR_FALSE; 5388 if (sidOK && !ssl3_ClientAuthTokenPresent(sid)) {
5305 » } 5389 sidOK = PR_FALSE;
5390 }
5306 5391
5307 » if (sidOK) { 5392 if (sidOK) {
5308 /* Set ss->version based on the session cache */ 5393 /* Set ss->version based on the session cache */
5309 » if (ss->firstHsDone) { 5394 if (ss->firstHsDone) {
5310 » » /* 5395 /*
5311 » * Windows SChannel compares the client_version inside the RSA 5396 * Windows SChannel compares the client_version inside the RSA
5312 » * EncryptedPreMasterSecret of a renegotiation with the 5397 * EncryptedPreMasterSecret of a renegotiation with the
5313 » * client_version of the initial ClientHello rather than the 5398 * client_version of the initial ClientHello rather than the
5314 » * ClientHello in the renegotiation. To work around this bug, we 5399 * ClientHello in the renegotiation. To work around this bug, we
5315 » * continue to use the client_version used in the initial 5400 * continue to use the client_version used in the initial
5316 » * ClientHello when renegotiating. 5401 * ClientHello when renegotiating.
5317 » * 5402 *
5318 » » * The client_version of the initial ClientHello is still 5403 * The client_version of the initial ClientHello is still
5319 » » * available in ss->clientHelloVersion. Ensure that 5404 * available in ss->clientHelloVersion. Ensure that
5320 » » * sid->version is bounded within 5405 * sid->version is bounded within
5321 » » * [ss->vrange.min, ss->clientHelloVersion], otherwise we 5406 * [ss->vrange.min, ss->clientHelloVersion], otherwise we
5322 » » * can't use sid. 5407 * can't use sid.
5323 » » */ 5408 */
5324 » » if (sid->version >= ss->vrange.min && 5409 if (sid->version >= ss->vrange.min &&
5325 » » sid->version <= ss->clientHelloVersion) { 5410 sid->version <= ss->clientHelloVersion) {
5326 » » ss->version = ss->clientHelloVersion; 5411 ss->version = ss->clientHelloVersion;
5327 » » } else { 5412 } else {
5328 » » sidOK = PR_FALSE; 5413 sidOK = PR_FALSE;
5329 » » } 5414 }
5330 » } else { 5415 } else {
5331 /* 5416 /*
5332 * Check sid->version is OK first. 5417 * Check sid->version is OK first.
5333 * Previously, we would cap the version based on sid->version, 5418 * Previously, we would cap the version based on sid->version,
5334 * but that prevents negotiation of a higher version if the 5419 * but that prevents negotiation of a higher version if the
5335 * previous session was reduced (e.g., with version fallback) 5420 * previous session was reduced (e.g., with version fallback)
5336 */ 5421 */
5337 » » if (sid->version < ss->vrange.min || 5422 if (sid->version < ss->vrange.min ||
5338 sid->version > ss->vrange.max) { 5423 sid->version > ss->vrange.max) {
5339 » » sidOK = PR_FALSE; 5424 sidOK = PR_FALSE;
5340 » » } else { 5425 } else {
5341 » rv = ssl3_NegotiateVersion(ss, SSL_LIBRARY_VERSION_MAX_SUPPO RTED, 5426 rv = ssl3_NegotiateVersion(ss, SSL_LIBRARY_VERSION_MAX_SUPPO RTED,
5342 PR_TRUE); 5427 PR_TRUE);
5343 » if (rv != SECSuccess) { 5428 if (rv != SECSuccess) {
5344 return rv;» /* error code was set */ 5429 return rv; /* error code was set */
5345 } 5430 }
5346 » } 5431 }
5347 » } 5432 }
5348 » } 5433 }
5349 5434
5350 » if (!sidOK) { 5435 if (!sidOK) {
5351 » SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_not_ok ); 5436 SSL_AtomicIncrementLong(&ssl3stats.sch_sid_cache_not_ok);
5352 » if (ss->sec.uncache) 5437 if (ss->sec.uncache)
5353 (*ss->sec.uncache)(sid); 5438 (*ss->sec.uncache)(sid);
5354 » ssl_FreeSID(sid); 5439 ssl_FreeSID(sid);
5355 » sid = NULL; 5440 sid = NULL;
5356 » } 5441 }
5357 } 5442 }
5358 5443
5359 if (sid) { 5444 if (sid) {
5360 » requestingResume = PR_TRUE; 5445 requestingResume = PR_TRUE;
5361 » SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_hits ); 5446 SSL_AtomicIncrementLong(&ssl3stats.sch_sid_cache_hits);
5362 5447
5363 » PRINT_BUF(4, (ss, "client, found session-id:", sid->u.ssl3.sessionID, 5448 PRINT_BUF(4, (ss, "client, found session-id:", sid->u.ssl3.sessionID,
5364 » » sid->u.ssl3.sessionIDLength)); 5449 sid->u.ssl3.sessionIDLength));
5365 5450
5366 » ss->ssl3.policy = sid->u.ssl3.policy; 5451 ss->ssl3.policy = sid->u.ssl3.policy;
5367 } else { 5452 } else {
5368 » SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_misses ); 5453 SSL_AtomicIncrementLong(&ssl3stats.sch_sid_cache_misses);
5369 5454
5370 » /* 5455 /*
5371 » * Windows SChannel compares the client_version inside the RSA 5456 * Windows SChannel compares the client_version inside the RSA
5372 » * EncryptedPreMasterSecret of a renegotiation with the 5457 * EncryptedPreMasterSecret of a renegotiation with the
5373 » * client_version of the initial ClientHello rather than the 5458 * client_version of the initial ClientHello rather than the
5374 » * ClientHello in the renegotiation. To work around this bug, we 5459 * ClientHello in the renegotiation. To work around this bug, we
5375 » * continue to use the client_version used in the initial 5460 * continue to use the client_version used in the initial
5376 » * ClientHello when renegotiating. 5461 * ClientHello when renegotiating.
5377 » */ 5462 */
5378 » if (ss->firstHsDone) { 5463 if (ss->firstHsDone) {
5379 » ss->version = ss->clientHelloVersion; 5464 ss->version = ss->clientHelloVersion;
5380 » } else { 5465 } else {
5381 » rv = ssl3_NegotiateVersion(ss, SSL_LIBRARY_VERSION_MAX_SUPPORTED, 5466 rv = ssl3_NegotiateVersion(ss, SSL_LIBRARY_VERSION_MAX_SUPPORTED,
5382 » » » » PR_TRUE); 5467 PR_TRUE);
5383 » if (rv != SECSuccess) 5468 if (rv != SECSuccess)
5384 » » return rv;» /* error code was set */ 5469 return rv; /* error code was set */
5385 » } 5470 }
5386 5471
5387 » sid = ssl3_NewSessionID(ss, PR_FALSE); 5472 sid = ssl3_NewSessionID(ss, PR_FALSE);
5388 » if (!sid) { 5473 if (!sid) {
5389 » return SECFailure;» /* memory error is set */ 5474 return SECFailure; /* memory error is set */
5390 } 5475 }
5391 } 5476 }
5392 5477
5478 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
5479 rv = tls13_SetupClientHello(ss);
5480 if (rv != SECSuccess) {
5481 if (sid) {
5482 ssl_FreeSID(sid);
5483 }
5484 return rv;
5485 }
5486 }
5487
5393 isTLS = (ss->version > SSL_LIBRARY_VERSION_3_0); 5488 isTLS = (ss->version > SSL_LIBRARY_VERSION_3_0);
5394 ssl_GetSpecWriteLock(ss); 5489 ssl_GetSpecWriteLock(ss);
5395 cwSpec = ss->ssl3.cwSpec; 5490 cwSpec = ss->ssl3.cwSpec;
5396 if (cwSpec->mac_def->mac == mac_null) { 5491 if (cwSpec->mac_def->mac == mac_null) {
5397 » /* SSL records are not being MACed. */ 5492 /* SSL records are not being MACed. */
5398 » cwSpec->version = ss->version; 5493 cwSpec->version = ss->version;
5399 } 5494 }
5400 ssl_ReleaseSpecWriteLock(ss); 5495 ssl_ReleaseSpecWriteLock(ss);
5401 5496
5402 if (ss->sec.ci.sid != NULL) { 5497 if (ss->sec.ci.sid != NULL) {
5403 » ssl_FreeSID(ss->sec.ci.sid);» /* decrement ref count, free if zero */ 5498 ssl_FreeSID(ss->sec.ci.sid); /* decrement ref count, free if zero */
5404 } 5499 }
5405 ss->sec.ci.sid = sid; 5500 ss->sec.ci.sid = sid;
5406 5501
5407 ss->sec.send = ssl3_SendApplicationData; 5502 ss->sec.send = ssl3_SendApplicationData;
5408 5503
5409 /* shouldn't get here if SSL3 is disabled, but ... */ 5504 /* shouldn't get here if SSL3 is disabled, but ... */
5410 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { 5505 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
5411 » PR_NOT_REACHED("No versions of SSL 3.0 or later are enabled"); 5506 PR_NOT_REACHED("No versions of SSL 3.0 or later are enabled");
5412 » PORT_SetError(SSL_ERROR_SSL_DISABLED); 5507 PORT_SetError(SSL_ERROR_SSL_DISABLED);
5413 » return SECFailure; 5508 return SECFailure;
5414 } 5509 }
5415 5510
5416 /* how many suites does our PKCS11 support (regardless of policy)? */ 5511 /* how many suites does our PKCS11 support (regardless of policy)? */
5417 num_suites = ssl3_config_match_init(ss); 5512 num_suites = ssl3_config_match_init(ss);
5418 if (!num_suites) 5513 if (!num_suites)
5419 » return SECFailure;» /* ssl3_config_match_init has set error code. */ 5514 return SECFailure; /* ssl3_config_match_init has set error code. */
5420 5515
5421 /* HACK for SCSV in SSL 3.0. On initial handshake, prepend SCSV, 5516 /* HACK for SCSV in SSL 3.0. On initial handshake, prepend SCSV,
5422 * only if TLS is disabled. 5517 * only if TLS is disabled.
5423 */ 5518 */
5424 if (!ss->firstHsDone && !isTLS) { 5519 if (!ss->firstHsDone && !isTLS) {
5425 » /* Must set this before calling Hello Extension Senders, 5520 /* Must set this before calling Hello Extension Senders,
5426 » * to suppress sending of empty RI extension. 5521 * to suppress sending of empty RI extension.
5427 » */ 5522 */
5428 » ss->ssl3.hs.sendingSCSV = PR_TRUE; 5523 ss->ssl3.hs.sendingSCSV = PR_TRUE;
5429 } 5524 }
5430 5525
5431 /* When we attempt session resumption (only), we must lock the sid to 5526 /* When we attempt session resumption (only), we must lock the sid to
5432 * prevent races with other resumption connections that receive a 5527 * prevent races with other resumption connections that receive a
5433 * NewSessionTicket that will cause the ticket in the sid to be replaced. 5528 * NewSessionTicket that will cause the ticket in the sid to be replaced.
5434 * Once we've copied the session ticket into our ClientHello message, it 5529 * Once we've copied the session ticket into our ClientHello message, it
5435 * is OK for the ticket to change, so we just need to make sure we hold 5530 * is OK for the ticket to change, so we just need to make sure we hold
5436 * the lock across the calls to ssl3_CallHelloExtensionSenders. 5531 * the lock across the calls to ssl3_CallHelloExtensionSenders.
5437 */ 5532 */
5438 if (sid->u.ssl3.lock) { 5533 if (sid->u.ssl3.lock) {
5439 NSSRWLock_LockRead(sid->u.ssl3.lock); 5534 PR_RWLock_Rlock(sid->u.ssl3.lock);
5440 } 5535 }
5441 5536
5442 if (isTLS || (ss->firstHsDone && ss->peerRequestedProtection)) { 5537 if (isTLS || (ss->firstHsDone && ss->peerRequestedProtection)) {
5443 » PRUint32 maxBytes = 65535; /* 2^16 - 1 */ 5538 PRUint32 maxBytes = 65535; /* 2^16 - 1 */
5444 » PRInt32 extLen; 5539 PRInt32 extLen;
5445 5540
5446 » extLen = ssl3_CallHelloExtensionSenders(ss, PR_FALSE, maxBytes, NULL); 5541 extLen = ssl3_CallHelloExtensionSenders(ss, PR_FALSE, maxBytes, NULL);
5447 » if (extLen < 0) { 5542 if (extLen < 0) {
5448 » if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } 5543 if (sid->u.ssl3.lock) {
5449 » return SECFailure; 5544 PR_RWLock_Unlock(sid->u.ssl3.lock);
5450 » } 5545 }
5451 » total_exten_len += extLen; 5546 return SECFailure;
5547 }
5548 total_exten_len += extLen;
5452 5549
5453 » if (total_exten_len > 0) 5550 if (total_exten_len > 0)
5454 » total_exten_len += 2; 5551 total_exten_len += 2;
5455 } 5552 }
5456 5553
5457 #ifndef NSS_DISABLE_ECC 5554 #ifndef NSS_DISABLE_ECC
5458 if (!total_exten_len || !isTLS) { 5555 if (!total_exten_len || !isTLS) {
5459 » /* not sending the elliptic_curves and ec_point_formats extensions */ 5556 /* not sending the elliptic_curves and ec_point_formats extensions */
5460 » ssl3_DisableECCSuites(ss, NULL); /* disable all ECC suites */ 5557 ssl3_DisableECCSuites(ss, NULL); /* disable all ECC suites */
5461 } 5558 }
5462 #endif /* NSS_DISABLE_ECC */ 5559 #endif /* NSS_DISABLE_ECC */
5463 5560
5464 if (IS_DTLS(ss)) { 5561 if (IS_DTLS(ss)) {
5465 » ssl3_DisableNonDTLSSuites(ss); 5562 ssl3_DisableNonDTLSSuites(ss);
5466 }
5467
5468 if (!ssl3_HasGCMSupport()) {
5469 » ssl3_DisableGCMSuites(ss);
5470 } 5563 }
5471 5564
5472 /* how many suites are permitted by policy and user preference? */ 5565 /* how many suites are permitted by policy and user preference? */
5473 num_suites = count_cipher_suites(ss, ss->ssl3.policy, PR_TRUE); 5566 num_suites = count_cipher_suites(ss, ss->ssl3.policy, PR_TRUE);
5474 if (!num_suites) { 5567 if (!num_suites) {
5475 » if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } 5568 if (sid->u.ssl3.lock) {
5476 » return SECFailure;» /* count_cipher_suites has set error code. */ 5569 PR_RWLock_Unlock(sid->u.ssl3.lock);
5570 }
5571 return SECFailure; /* count_cipher_suites has set error code. */
5477 } 5572 }
5478 5573
5479 fallbackSCSV = ss->opt.enableFallbackSCSV && (!requestingResume || 5574 fallbackSCSV = ss->opt.enableFallbackSCSV && (!requestingResume ||
5480 » » » » » » ss->version < sid->version); 5575 ss->version < sid->version);
5481 /* make room for SCSV */ 5576 /* make room for SCSV */
5482 if (ss->ssl3.hs.sendingSCSV) { 5577 if (ss->ssl3.hs.sendingSCSV) {
5483 » ++num_suites; 5578 ++num_suites;
5484 } 5579 }
5485 if (fallbackSCSV) { 5580 if (fallbackSCSV) {
5486 » ++num_suites; 5581 ++num_suites;
5487 } 5582 }
5488 5583
5489 /* count compression methods */ 5584 /* count compression methods */
5490 numCompressionMethods = 0; 5585 numCompressionMethods = 0;
5491 for (i = 0; i < compressionMethodsCount; i++) { 5586 for (i = 0; i < compressionMethodsCount; i++) {
5492 » if (compressionEnabled(ss, compressions[i])) 5587 if (compressionEnabled(ss, compressions[i]))
5493 » numCompressionMethods++; 5588 numCompressionMethods++;
5494 } 5589 }
5495 5590
5496 length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH + 5591 length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH +
5497 » 1 + ((sid == NULL) ? 0 : sid->u.ssl3.sessionIDLength) + 5592 1 + ((sid == NULL) ? 0 : sid->u.ssl3.sessionIDLength) +
5498 » 2 + num_suites*sizeof(ssl3CipherSuite) + 5593 2 + num_suites * sizeof(ssl3CipherSuite) +
5499 » 1 + numCompressionMethods + total_exten_len; 5594 1 + numCompressionMethods + total_exten_len;
5500 if (IS_DTLS(ss)) { 5595 if (IS_DTLS(ss)) {
5501 » length += 1 + ss->ssl3.hs.cookieLen; 5596 length += 1 + ss->ssl3.hs.cookieLen;
5502 } 5597 }
5503 5598
5504 /* A padding extension may be included to ensure that the record containing 5599 /* A padding extension may be included to ensure that the record containing
5505 * the ClientHello doesn't have a length between 256 and 511 bytes 5600 * the ClientHello doesn't have a length between 256 and 511 bytes
5506 * (inclusive). Initial, ClientHello records with such lengths trigger bugs 5601 * (inclusive). Initial, ClientHello records with such lengths trigger bugs
5507 * in F5 devices. 5602 * in F5 devices.
5508 * 5603 *
5509 * This is not done for DTLS nor for renegotiation. */ 5604 * This is not done for DTLS nor for renegotiation. */
5510 if (!IS_DTLS(ss) && isTLS && !ss->firstHsDone) { 5605 if (!IS_DTLS(ss) && isTLS && !ss->firstHsDone) {
5511 paddingExtensionLen = ssl3_CalculatePaddingExtensionLength(length); 5606 paddingExtensionLen = ssl3_CalculatePaddingExtensionLength(length);
5512 total_exten_len += paddingExtensionLen; 5607 total_exten_len += paddingExtensionLen;
5513 length += paddingExtensionLen; 5608 length += paddingExtensionLen;
5514 } else { 5609 } else {
5515 paddingExtensionLen = 0; 5610 paddingExtensionLen = 0;
5516 } 5611 }
5517 5612
5518 rv = ssl3_AppendHandshakeHeader(ss, client_hello, length); 5613 rv = ssl3_AppendHandshakeHeader(ss, client_hello, length);
5519 if (rv != SECSuccess) { 5614 if (rv != SECSuccess) {
5520 » if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } 5615 if (sid->u.ssl3.lock) {
5521 » return rv;» /* err set by ssl3_AppendHandshake* */ 5616 PR_RWLock_Unlock(sid->u.ssl3.lock);
5617 }
5618 return rv; /* err set by ssl3_AppendHandshake* */
5522 } 5619 }
5523 5620
5524 if (ss->firstHsDone) { 5621 if (ss->firstHsDone) {
5525 » /* The client hello version must stay unchanged to work around 5622 /* The client hello version must stay unchanged to work around
5526 » * the Windows SChannel bug described above. */ 5623 * the Windows SChannel bug described above. */
5527 » PORT_Assert(ss->version == ss->clientHelloVersion); 5624 PORT_Assert(ss->version == ss->clientHelloVersion);
5528 } 5625 }
5529 ss->clientHelloVersion = ss->version; 5626 ss->clientHelloVersion = ss->version;
5530 if (IS_DTLS(ss)) { 5627 if (IS_DTLS(ss)) {
5531 » PRUint16 version; 5628 PRUint16 version;
5532 5629
5533 » version = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion); 5630 version = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion);
5534 » rv = ssl3_AppendHandshakeNumber(ss, version, 2); 5631 rv = ssl3_AppendHandshakeNumber(ss, version, 2);
5535 } else { 5632 } else {
5536 » rv = ssl3_AppendHandshakeNumber(ss, ss->clientHelloVersion, 2); 5633 rv = ssl3_AppendHandshakeNumber(ss, ss->clientHelloVersion, 2);
5537 } 5634 }
5538 if (rv != SECSuccess) { 5635 if (rv != SECSuccess) {
5539 » if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } 5636 if (sid->u.ssl3.lock) {
5540 » return rv;» /* err set by ssl3_AppendHandshake* */ 5637 PR_RWLock_Unlock(sid->u.ssl3.lock);
5638 }
5639 return rv; /* err set by ssl3_AppendHandshake* */
5541 } 5640 }
5542 5641
5543 if (!resending) { /* Don't re-generate if we are in DTLS re-sending mode */ 5642 if (!resending) { /* Don't re-generate if we are in DTLS re-sending mode */
5544 » rv = ssl3_GetNewRandom(&ss->ssl3.hs.client_random); 5643 rv = ssl3_GetNewRandom(&ss->ssl3.hs.client_random);
5545 » if (rv != SECSuccess) { 5644 if (rv != SECSuccess) {
5546 » if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } 5645 if (sid->u.ssl3.lock) {
5547 » return rv;» /* err set by GetNewRandom. */ 5646 PR_RWLock_Unlock(sid->u.ssl3.lock);
5548 » } 5647 }
5648 return rv; /* err set by GetNewRandom. */
5649 }
5549 } 5650 }
5550 rv = ssl3_AppendHandshake(ss, &ss->ssl3.hs.client_random, 5651 rv = ssl3_AppendHandshake(ss, &ss->ssl3.hs.client_random,
5551 SSL3_RANDOM_LENGTH); 5652 SSL3_RANDOM_LENGTH);
5552 if (rv != SECSuccess) { 5653 if (rv != SECSuccess) {
5553 » if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } 5654 if (sid->u.ssl3.lock) {
5554 » return rv;» /* err set by ssl3_AppendHandshake* */ 5655 PR_RWLock_Unlock(sid->u.ssl3.lock);
5656 }
5657 return rv; /* err set by ssl3_AppendHandshake* */
5555 } 5658 }
5556 5659
5557 if (sid) 5660 if (sid)
5558 » rv = ssl3_AppendHandshakeVariable( 5661 rv = ssl3_AppendHandshakeVariable(
5559 » ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1); 5662 ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1);
5560 else 5663 else
5561 » rv = ssl3_AppendHandshakeNumber(ss, 0, 1); 5664 rv = ssl3_AppendHandshakeNumber(ss, 0, 1);
5562 if (rv != SECSuccess) { 5665 if (rv != SECSuccess) {
5563 » if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } 5666 if (sid->u.ssl3.lock) {
5564 » return rv;» /* err set by ssl3_AppendHandshake* */ 5667 PR_RWLock_Unlock(sid->u.ssl3.lock);
5668 }
5669 return rv; /* err set by ssl3_AppendHandshake* */
5565 } 5670 }
5566 5671
5567 if (IS_DTLS(ss)) { 5672 if (IS_DTLS(ss)) {
5568 » rv = ssl3_AppendHandshakeVariable( 5673 rv = ssl3_AppendHandshakeVariable(
5569 » ss, ss->ssl3.hs.cookie, ss->ssl3.hs.cookieLen, 1); 5674 ss, ss->ssl3.hs.cookie, ss->ssl3.hs.cookieLen, 1);
5570 » if (rv != SECSuccess) { 5675 if (rv != SECSuccess) {
5571 » if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } 5676 if (sid->u.ssl3.lock) {
5572 » return rv;» /* err set by ssl3_AppendHandshake* */ 5677 PR_RWLock_Unlock(sid->u.ssl3.lock);
5573 » } 5678 }
5679 return rv; /* err set by ssl3_AppendHandshake* */
5680 }
5574 } 5681 }
5575 5682
5576 rv = ssl3_AppendHandshakeNumber(ss, num_suites*sizeof(ssl3CipherSuite), 2); 5683 rv = ssl3_AppendHandshakeNumber(ss, num_suites * sizeof(ssl3CipherSuite), 2) ;
5577 if (rv != SECSuccess) { 5684 if (rv != SECSuccess) {
5578 » if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } 5685 if (sid->u.ssl3.lock) {
5579 » return rv;» /* err set by ssl3_AppendHandshake* */ 5686 PR_RWLock_Unlock(sid->u.ssl3.lock);
5687 }
5688 return rv; /* err set by ssl3_AppendHandshake* */
5580 } 5689 }
5581 5690
5582 if (ss->ssl3.hs.sendingSCSV) { 5691 if (ss->ssl3.hs.sendingSCSV) {
5583 » /* Add the actual SCSV */ 5692 /* Add the actual SCSV */
5584 » rv = ssl3_AppendHandshakeNumber(ss, TLS_EMPTY_RENEGOTIATION_INFO_SCSV, 5693 rv = ssl3_AppendHandshakeNumber(ss, TLS_EMPTY_RENEGOTIATION_INFO_SCSV,
5585 » » » » » sizeof(ssl3CipherSuite)); 5694 sizeof(ssl3CipherSuite));
5586 » if (rv != SECSuccess) { 5695 if (rv != SECSuccess) {
5587 » if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } 5696 if (sid->u.ssl3.lock) {
5588 » return rv;» /* err set by ssl3_AppendHandshake* */ 5697 PR_RWLock_Unlock(sid->u.ssl3.lock);
5589 » } 5698 }
5590 » actual_count++; 5699 return rv; /* err set by ssl3_AppendHandshake* */
5700 }
5701 actual_count++;
5591 } 5702 }
5592 if (fallbackSCSV) { 5703 if (fallbackSCSV) {
5593 » rv = ssl3_AppendHandshakeNumber(ss, TLS_FALLBACK_SCSV, 5704 rv = ssl3_AppendHandshakeNumber(ss, TLS_FALLBACK_SCSV,
5594 » » » » » sizeof(ssl3CipherSuite)); 5705 sizeof(ssl3CipherSuite));
5595 » if (rv != SECSuccess) { 5706 if (rv != SECSuccess) {
5596 » if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } 5707 if (sid->u.ssl3.lock) {
5597 » return rv;» /* err set by ssl3_AppendHandshake* */ 5708 PR_RWLock_Unlock(sid->u.ssl3.lock);
5598 » } 5709 }
5599 » actual_count++; 5710 return rv; /* err set by ssl3_AppendHandshake* */
5711 }
5712 actual_count++;
5600 } 5713 }
5601 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { 5714 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
5602 » ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i]; 5715 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
5603 » if (config_match(suite, ss->ssl3.policy, PR_TRUE, &ss->vrange, ss)) { 5716 if (config_match(suite, ss->ssl3.policy, PR_TRUE, &ss->vrange, ss)) {
5604 » actual_count++; 5717 actual_count++;
5605 » if (actual_count > num_suites) { 5718 if (actual_count > num_suites) {
5606 » » if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } 5719 if (sid->u.ssl3.lock) {
5607 » » /* set error card removal/insertion error */ 5720 PR_RWLock_Unlock(sid->u.ssl3.lock);
5608 » » PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); 5721 }
5609 » » return SECFailure; 5722 /* set error card removal/insertion error */
5610 » } 5723 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
5611 » rv = ssl3_AppendHandshakeNumber(ss, suite->cipher_suite, 5724 return SECFailure;
5612 » » » » » sizeof(ssl3CipherSuite)); 5725 }
5613 » if (rv != SECSuccess) { 5726 rv = ssl3_AppendHandshakeNumber(ss, suite->cipher_suite,
5614 » » if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } 5727 sizeof(ssl3CipherSuite));
5615 » » return rv;» /* err set by ssl3_AppendHandshake* */ 5728 if (rv != SECSuccess) {
5616 » } 5729 if (sid->u.ssl3.lock) {
5617 » } 5730 PR_RWLock_Unlock(sid->u.ssl3.lock);
5731 }
5732 return rv; /* err set by ssl3_AppendHandshake* */
5733 }
5734 }
5618 } 5735 }
5619 5736
5620 /* if cards were removed or inserted between count_cipher_suites and 5737 /* if cards were removed or inserted between count_cipher_suites and
5621 * generating our list, detect the error here rather than send it off to 5738 * generating our list, detect the error here rather than send it off to
5622 * the server.. */ 5739 * the server.. */
5623 if (actual_count != num_suites) { 5740 if (actual_count != num_suites) {
5624 » /* Card removal/insertion error */ 5741 /* Card removal/insertion error */
5625 » if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } 5742 if (sid->u.ssl3.lock) {
5626 » PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); 5743 PR_RWLock_Unlock(sid->u.ssl3.lock);
5627 » return SECFailure; 5744 }
5745 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
5746 return SECFailure;
5628 } 5747 }
5629 5748
5630 rv = ssl3_AppendHandshakeNumber(ss, numCompressionMethods, 1); 5749 rv = ssl3_AppendHandshakeNumber(ss, numCompressionMethods, 1);
5631 if (rv != SECSuccess) { 5750 if (rv != SECSuccess) {
5632 » if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } 5751 if (sid->u.ssl3.lock) {
5633 » return rv;» /* err set by ssl3_AppendHandshake* */ 5752 PR_RWLock_Unlock(sid->u.ssl3.lock);
5753 }
5754 return rv; /* err set by ssl3_AppendHandshake* */
5634 } 5755 }
5635 for (i = 0; i < compressionMethodsCount; i++) { 5756 for (i = 0; i < compressionMethodsCount; i++) {
5636 » if (!compressionEnabled(ss, compressions[i])) 5757 if (!compressionEnabled(ss, compressions[i]))
5637 » continue; 5758 continue;
5638 » rv = ssl3_AppendHandshakeNumber(ss, compressions[i], 1); 5759 rv = ssl3_AppendHandshakeNumber(ss, compressions[i], 1);
5639 » if (rv != SECSuccess) { 5760 if (rv != SECSuccess) {
5640 » if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } 5761 if (sid->u.ssl3.lock) {
5641 » return rv;» /* err set by ssl3_AppendHandshake* */ 5762 PR_RWLock_Unlock(sid->u.ssl3.lock);
5642 » } 5763 }
5764 return rv; /* err set by ssl3_AppendHandshake* */
5765 }
5643 } 5766 }
5644 5767
5645 if (total_exten_len) { 5768 if (total_exten_len) {
5646 » PRUint32 maxBytes = total_exten_len - 2; 5769 PRUint32 maxBytes = total_exten_len - 2;
5647 » PRInt32 extLen; 5770 PRInt32 extLen;
5648 5771
5649 » rv = ssl3_AppendHandshakeNumber(ss, maxBytes, 2); 5772 rv = ssl3_AppendHandshakeNumber(ss, maxBytes, 2);
5650 » if (rv != SECSuccess) { 5773 if (rv != SECSuccess) {
5651 » if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } 5774 if (sid->u.ssl3.lock) {
5652 » return rv;» /* err set by AppendHandshake. */ 5775 PR_RWLock_Unlock(sid->u.ssl3.lock);
5653 » } 5776 }
5777 return rv; /* err set by AppendHandshake. */
5778 }
5654 5779
5655 » extLen = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, maxBytes, NULL); 5780 extLen = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, maxBytes, NULL);
5656 » if (extLen < 0) { 5781 if (extLen < 0) {
5657 » if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } 5782 if (sid->u.ssl3.lock) {
5658 » return SECFailure; 5783 PR_RWLock_Unlock(sid->u.ssl3.lock);
5659 » } 5784 }
5660 » maxBytes -= extLen; 5785 return SECFailure;
5786 }
5787 maxBytes -= extLen;
5661 5788
5662 » extLen = ssl3_AppendPaddingExtension(ss, paddingExtensionLen, maxBytes); 5789 extLen = ssl3_AppendPaddingExtension(ss, paddingExtensionLen, maxBytes);
5663 » if (extLen < 0) { 5790 if (extLen < 0) {
5664 » if (sid->u.ssl3.lock) { NSSRWLock_UnlockRead(sid->u.ssl3.lock); } 5791 if (sid->u.ssl3.lock) {
5665 » return SECFailure; 5792 PR_RWLock_Unlock(sid->u.ssl3.lock);
5666 » } 5793 }
5667 » maxBytes -= extLen; 5794 return SECFailure;
5795 }
5796 maxBytes -= extLen;
5668 5797
5669 » PORT_Assert(!maxBytes); 5798 PORT_Assert(!maxBytes);
5670 } 5799 }
5671 5800
5672 if (sid->u.ssl3.lock) { 5801 if (sid->u.ssl3.lock) {
5673 NSSRWLock_UnlockRead(sid->u.ssl3.lock); 5802 PR_RWLock_Unlock(sid->u.ssl3.lock);
5674 } 5803 }
5675 5804
5676 if (ss->xtnData.sentSessionTicketInClientHello) { 5805 if (ss->xtnData.sentSessionTicketInClientHello) {
5677 SSL_AtomicIncrementLong(&ssl3stats.sch_sid_stateless_resumes); 5806 SSL_AtomicIncrementLong(&ssl3stats.sch_sid_stateless_resumes);
5678 } 5807 }
5679 5808
5680 if (ss->ssl3.hs.sendingSCSV) { 5809 if (ss->ssl3.hs.sendingSCSV) {
5681 » /* Since we sent the SCSV, pretend we sent empty RI extension. */ 5810 /* Since we sent the SCSV, pretend we sent empty RI extension. */
5682 » TLSExtensionData *xtnData = &ss->xtnData; 5811 TLSExtensionData *xtnData = &ss->xtnData;
5683 » xtnData->advertised[xtnData->numAdvertised++] = 5812 xtnData->advertised[xtnData->numAdvertised++] =
5684 » ssl_renegotiation_info_xtn; 5813 ssl_renegotiation_info_xtn;
5685 } 5814 }
5686 5815
5687 flags = 0; 5816 flags = 0;
5688 if (!ss->firstHsDone && !IS_DTLS(ss)) { 5817 if (!ss->firstHsDone && !IS_DTLS(ss)) {
5689 » flags |= ssl_SEND_FLAG_CAP_RECORD_VERSION; 5818 flags |= ssl_SEND_FLAG_CAP_RECORD_VERSION;
5690 } 5819 }
5691 rv = ssl3_FlushHandshake(ss, flags); 5820 rv = ssl3_FlushHandshake(ss, flags);
5692 if (rv != SECSuccess) { 5821 if (rv != SECSuccess) {
5693 » return rv;» /* error code set by ssl3_FlushHandshake */ 5822 return rv; /* error code set by ssl3_FlushHandshake */
5694 } 5823 }
5695 5824
5696 ss->ssl3.hs.ws = wait_server_hello; 5825 ss->ssl3.hs.ws = wait_server_hello;
5697 return rv; 5826 return rv;
5698 } 5827 }
5699 5828
5700 5829 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered a
5701 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete 5830 * complete ssl3 Hello Request.
5702 * ssl3 Hello Request.
5703 * Caller must hold Handshake and RecvBuf locks. 5831 * Caller must hold Handshake and RecvBuf locks.
5704 */ 5832 */
5705 static SECStatus 5833 static SECStatus
5706 ssl3_HandleHelloRequest(sslSocket *ss) 5834 ssl3_HandleHelloRequest(sslSocket *ss)
5707 { 5835 {
5708 sslSessionID *sid = ss->sec.ci.sid; 5836 sslSessionID *sid = ss->sec.ci.sid;
5709 SECStatus rv; 5837 SECStatus rv;
5710 5838
5711 SSL_TRC(3, ("%d: SSL3[%d]: handle hello_request handshake", 5839 SSL_TRC(3, ("%d: SSL3[%d]: handle hello_request handshake",
5712 » » SSL_GETPID(), ss->fd)); 5840 SSL_GETPID(), ss->fd));
5713 5841
5714 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 5842 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
5715 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 5843 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
5844 PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);
5716 5845
5717 if (ss->ssl3.hs.ws == wait_server_hello) 5846 if (ss->ssl3.hs.ws == wait_server_hello)
5718 » return SECSuccess; 5847 return SECSuccess;
5719 if (ss->ssl3.hs.ws != idle_handshake || ss->sec.isServer) { 5848 if (ss->ssl3.hs.ws != idle_handshake || ss->sec.isServer) {
5720 » (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 5849 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
5721 » PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST); 5850 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST);
5722 » return SECFailure; 5851 return SECFailure;
5723 } 5852 }
5724 if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) { 5853 if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
5725 » (void)SSL3_SendAlert(ss, alert_warning, no_renegotiation); 5854 (void)SSL3_SendAlert(ss, alert_warning, no_renegotiation);
5726 » PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED); 5855 PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
5727 » return SECFailure; 5856 return SECFailure;
5728 } 5857 }
5729 5858
5730 if (sid) { 5859 if (sid) {
5731 » if (ss->sec.uncache) 5860 if (ss->sec.uncache)
5732 ss->sec.uncache(sid); 5861 ss->sec.uncache(sid);
5733 » ssl_FreeSID(sid); 5862 ssl_FreeSID(sid);
5734 » ss->sec.ci.sid = NULL; 5863 ss->sec.ci.sid = NULL;
5735 } 5864 }
5736 5865
5737 if (IS_DTLS(ss)) { 5866 if (IS_DTLS(ss)) {
5738 » dtls_RehandshakeCleanup(ss); 5867 dtls_RehandshakeCleanup(ss);
5739 } 5868 }
5740 5869
5741 ssl_GetXmitBufLock(ss); 5870 ssl_GetXmitBufLock(ss);
5742 rv = ssl3_SendClientHello(ss, PR_FALSE); 5871 rv = ssl3_SendClientHello(ss, PR_FALSE);
5743 ssl_ReleaseXmitBufLock(ss); 5872 ssl_ReleaseXmitBufLock(ss);
5744 5873
5745 return rv; 5874 return rv;
5746 } 5875 }
5747 5876
5748 #define UNKNOWN_WRAP_MECHANISM 0x7fffffff 5877 #define UNKNOWN_WRAP_MECHANISM 0x7fffffff
(...skipping 16 matching lines...) Expand all
5765 CKM_SEED_ECB, 5894 CKM_SEED_ECB,
5766 UNKNOWN_WRAP_MECHANISM 5895 UNKNOWN_WRAP_MECHANISM
5767 }; 5896 };
5768 5897
5769 static int 5898 static int
5770 ssl_FindIndexByWrapMechanism(CK_MECHANISM_TYPE mech) 5899 ssl_FindIndexByWrapMechanism(CK_MECHANISM_TYPE mech)
5771 { 5900 {
5772 const CK_MECHANISM_TYPE *pMech = wrapMechanismList; 5901 const CK_MECHANISM_TYPE *pMech = wrapMechanismList;
5773 5902
5774 while (mech != *pMech && *pMech != UNKNOWN_WRAP_MECHANISM) { 5903 while (mech != *pMech && *pMech != UNKNOWN_WRAP_MECHANISM) {
5775 » ++pMech; 5904 ++pMech;
5776 } 5905 }
5777 return (*pMech == UNKNOWN_WRAP_MECHANISM) ? -1 5906 return (*pMech == UNKNOWN_WRAP_MECHANISM) ? -1
5778 : (pMech - wrapMechanismList); 5907 : (pMech - wrapMechanismList);
5779 } 5908 }
5780 5909
5781 static PK11SymKey * 5910 static PK11SymKey *
5782 ssl_UnwrapSymWrappingKey( 5911 ssl_UnwrapSymWrappingKey(
5783 » SSLWrappedSymWrappingKey *pWswk, 5912 SSLWrappedSymWrappingKey *pWswk,
5784 » SECKEYPrivateKey * svrPrivKey, 5913 SECKEYPrivateKey *svrPrivKey,
5785 » SSL3KEAType exchKeyType, 5914 SSL3KEAType exchKeyType,
5786 » CK_MECHANISM_TYPE masterWrapMech, 5915 CK_MECHANISM_TYPE masterWrapMech,
5787 » void * pwArg) 5916 void *pwArg)
5788 { 5917 {
5789 PK11SymKey * unwrappedWrappingKey = NULL; 5918 PK11SymKey *unwrappedWrappingKey = NULL;
5790 SECItem wrappedKey; 5919 SECItem wrappedKey;
5791 #ifndef NSS_DISABLE_ECC 5920 #ifndef NSS_DISABLE_ECC
5792 PK11SymKey * Ks; 5921 PK11SymKey *Ks;
5793 SECKEYPublicKey pubWrapKey; 5922 SECKEYPublicKey pubWrapKey;
5794 ECCWrappedKeyInfo *ecWrapped; 5923 ECCWrappedKeyInfo *ecWrapped;
5795 #endif /* NSS_DISABLE_ECC */ 5924 #endif /* NSS_DISABLE_ECC */
5796 5925
5797 /* found the wrapping key on disk. */ 5926 /* found the wrapping key on disk. */
5798 PORT_Assert(pWswk->symWrapMechanism == masterWrapMech); 5927 PORT_Assert(pWswk->symWrapMechanism == masterWrapMech);
5799 PORT_Assert(pWswk->exchKeyType == exchKeyType); 5928 PORT_Assert(pWswk->exchKeyType == exchKeyType);
5800 if (pWswk->symWrapMechanism != masterWrapMech || 5929 if (pWswk->symWrapMechanism != masterWrapMech ||
5801 » pWswk->exchKeyType != exchKeyType) { 5930 pWswk->exchKeyType != exchKeyType) {
5802 » goto loser; 5931 goto loser;
5803 } 5932 }
5804 wrappedKey.type = siBuffer; 5933 wrappedKey.type = siBuffer;
5805 wrappedKey.data = pWswk->wrappedSymmetricWrappingkey; 5934 wrappedKey.data = pWswk->wrappedSymmetricWrappingkey;
5806 wrappedKey.len = pWswk->wrappedSymKeyLen; 5935 wrappedKey.len = pWswk->wrappedSymKeyLen;
5807 PORT_Assert(wrappedKey.len <= sizeof pWswk->wrappedSymmetricWrappingkey); 5936 PORT_Assert(wrappedKey.len <= sizeof pWswk->wrappedSymmetricWrappingkey);
5808 5937
5809 switch (exchKeyType) { 5938 switch (exchKeyType) {
5810 5939
5811 case kt_rsa: 5940 case kt_rsa:
5812 » unwrappedWrappingKey = 5941 unwrappedWrappingKey =
5813 » PK11_PubUnwrapSymKey(svrPrivKey, &wrappedKey, 5942 PK11_PubUnwrapSymKey(svrPrivKey, &wrappedKey,
5814 » » » » masterWrapMech, CKA_UNWRAP, 0); 5943 masterWrapMech, CKA_UNWRAP, 0);
5815 » break; 5944 break;
5816 5945
5817 #ifndef NSS_DISABLE_ECC 5946 #ifndef NSS_DISABLE_ECC
5818 case kt_ecdh: 5947 case kt_ecdh:
5819 /* 5948 /*
5820 * For kt_ecdh, we first create an EC public key based on 5949 * For kt_ecdh, we first create an EC public key based on
5821 * data stored with the wrappedSymmetricWrappingkey. Next, 5950 * data stored with the wrappedSymmetricWrappingkey. Next,
5822 * we do an ECDH computation involving this public key and 5951 * we do an ECDH computation involving this public key and
5823 * the SSL server's (long-term) EC private key. The resulting 5952 * the SSL server's (long-term) EC private key. The resulting
5824 * shared secret is treated the same way as Fortezza's Ks, i.e., 5953 * shared secret is treated the same way as Fortezza's Ks, i.e.,
5825 * it is used to recover the symmetric wrapping key. 5954 * it is used to recover the symmetric wrapping key.
5826 * 5955 *
5827 * The data in wrappedSymmetricWrappingkey is laid out as defined 5956 * The data in wrappedSymmetricWrappingkey is laid out as defined
5828 * in the ECCWrappedKeyInfo structure. 5957 * in the ECCWrappedKeyInfo structure.
5829 */ 5958 */
5830 ecWrapped = (ECCWrappedKeyInfo *) pWswk->wrappedSymmetricWrappingkey; 5959 ecWrapped = (ECCWrappedKeyInfo *)pWswk->wrappedSymmetricWrappingkey;
5831 5960
5832 PORT_Assert(ecWrapped->encodedParamLen + ecWrapped->pubValueLen + 5961 PORT_Assert(ecWrapped->encodedParamLen + ecWrapped->pubValueLen +
5833 ecWrapped->wrappedKeyLen <= MAX_EC_WRAPPED_KEY_BUFLEN); 5962 ecWrapped->wrappedKeyLen <= MAX_EC_WRAPPED_KEY_BUFLE N);
5834 5963
5835 if (ecWrapped->encodedParamLen + ecWrapped->pubValueLen + 5964 if (ecWrapped->encodedParamLen + ecWrapped->pubValueLen +
5836 ecWrapped->wrappedKeyLen > MAX_EC_WRAPPED_KEY_BUFLEN) { 5965 ecWrapped->wrappedKeyLen > MAX_EC_WRAPPED_KEY_BUFLEN) {
5837 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 5966 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
5838 goto loser; 5967 goto loser;
5839 } 5968 }
5840 5969
5841 pubWrapKey.keyType = ecKey; 5970 pubWrapKey.keyType = ecKey;
5842 pubWrapKey.u.ec.size = ecWrapped->size; 5971 pubWrapKey.u.ec.size = ecWrapped->size;
5843 pubWrapKey.u.ec.DEREncodedParams.len = ecWrapped->encodedParamLen; 5972 pubWrapKey.u.ec.DEREncodedParams.len = ecWrapped->encodedParamLen;
5844 pubWrapKey.u.ec.DEREncodedParams.data = ecWrapped->var; 5973 pubWrapKey.u.ec.DEREncodedParams.data = ecWrapped->var;
5845 pubWrapKey.u.ec.publicValue.len = ecWrapped->pubValueLen; 5974 pubWrapKey.u.ec.publicValue.len = ecWrapped->pubValueLen;
5846 pubWrapKey.u.ec.publicValue.data = ecWrapped->var + 5975 pubWrapKey.u.ec.publicValue.data = ecWrapped->var +
5847 ecWrapped->encodedParamLen; 5976 ecWrapped->encodedParamLen;
5848 5977
5849 wrappedKey.len = ecWrapped->wrappedKeyLen; 5978 wrappedKey.len = ecWrapped->wrappedKeyLen;
5850 wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen + 5979 wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen +
5851 ecWrapped->pubValueLen; 5980 ecWrapped->pubValueLen;
5852
5853 /* Derive Ks using ECDH */
5854 Ks = PK11_PubDeriveWithKDF(svrPrivKey, &pubWrapKey, PR_FALSE, NULL,
5855 » » » » NULL, CKM_ECDH1_DERIVE, masterWrapMech,
5856 » » » » CKA_DERIVE, 0, CKD_NULL, NULL, NULL);
5857 if (Ks == NULL) {
5858 goto loser;
5859 }
5860 5981
5861 /* Use Ks to unwrap the wrapping key */ 5982 /* Derive Ks using ECDH */
5862 unwrappedWrappingKey = PK11_UnwrapSymKey(Ks, masterWrapMech, NULL, 5983 Ks = PK11_PubDeriveWithKDF(svrPrivKey, &pubWrapKey, PR_FALSE, NULL,
5863 » » » » » » &wrappedKey, masterWrapMech, 5984 NULL, CKM_ECDH1_DERIVE, masterWrapMech,
5864 » » » » » » CKA_UNWRAP, 0); 5985 CKA_DERIVE, 0, CKD_NULL, NULL, NULL);
5865 PK11_FreeSymKey(Ks); 5986 if (Ks == NULL) {
5866 5987 goto loser;
5867 break; 5988 }
5989
5990 /* Use Ks to unwrap the wrapping key */
5991 unwrappedWrappingKey = PK11_UnwrapSymKey(Ks, masterWrapMech, NULL,
5992 &wrappedKey, masterWrapMech ,
5993 CKA_UNWRAP, 0);
5994 PK11_FreeSymKey(Ks);
5995
5996 break;
5868 #endif 5997 #endif
5869 5998
5870 default: 5999 default:
5871 » /* Assert? */ 6000 /* Assert? */
5872 » SET_ERROR_CODE 6001 SET_ERROR_CODE
5873 » goto loser; 6002 goto loser;
5874 } 6003 }
5875 loser: 6004 loser:
5876 return unwrappedWrappingKey; 6005 return unwrappedWrappingKey;
5877 } 6006 }
5878 6007
5879 /* Each process sharing the server session ID cache has its own array of 6008 /* Each process sharing the server session ID cache has its own array of
5880 * SymKey pointers for the symmetric wrapping keys that are used to wrap 6009 * SymKey pointers for the symmetric wrapping keys that are used to wrap
5881 * the master secrets. There is one key for each KEA type. These Symkeys 6010 * the master secrets. There is one key for each KEA type. These Symkeys
5882 * correspond to the wrapped SymKeys kept in the server session cache. 6011 * correspond to the wrapped SymKeys kept in the server session cache.
5883 */ 6012 */
5884 6013
5885 typedef struct { 6014 typedef struct {
5886 PK11SymKey * symWrapKey[kt_kea_size]; 6015 PK11SymKey *symWrapKey[kt_kea_size];
5887 } ssl3SymWrapKey; 6016 } ssl3SymWrapKey;
5888 6017
5889 static PZLock * symWrapKeysLock = NULL; 6018 static PZLock *symWrapKeysLock = NULL;
5890 static ssl3SymWrapKey symWrapKeys[SSL_NUM_WRAP_MECHS]; 6019 static ssl3SymWrapKey symWrapKeys[SSL_NUM_WRAP_MECHS];
5891 6020
5892 SECStatus ssl_FreeSymWrapKeysLock(void) 6021 SECStatus
6022 ssl_FreeSymWrapKeysLock(void)
5893 { 6023 {
5894 if (symWrapKeysLock) { 6024 if (symWrapKeysLock) {
5895 PZ_DestroyLock(symWrapKeysLock); 6025 PZ_DestroyLock(symWrapKeysLock);
5896 symWrapKeysLock = NULL; 6026 symWrapKeysLock = NULL;
5897 return SECSuccess; 6027 return SECSuccess;
5898 } 6028 }
5899 PORT_SetError(SEC_ERROR_NOT_INITIALIZED); 6029 PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
5900 return SECFailure; 6030 return SECFailure;
5901 } 6031 }
5902 6032
5903 SECStatus 6033 SECStatus
5904 SSL3_ShutdownServerCache(void) 6034 SSL3_ShutdownServerCache(void)
5905 { 6035 {
5906 int i, j; 6036 int i, j;
5907 6037
5908 if (!symWrapKeysLock) 6038 if (!symWrapKeysLock)
5909 » return SECSuccess;» /* lock was never initialized */ 6039 return SECSuccess; /* lock was never initialized */
5910 PZ_Lock(symWrapKeysLock); 6040 PZ_Lock(symWrapKeysLock);
5911 /* get rid of all symWrapKeys */ 6041 /* get rid of all symWrapKeys */
5912 for (i = 0; i < SSL_NUM_WRAP_MECHS; ++i) { 6042 for (i = 0; i < SSL_NUM_WRAP_MECHS; ++i) {
5913 » for (j = 0; j < kt_kea_size; ++j) { 6043 for (j = 0; j < kt_kea_size; ++j) {
5914 » PK11SymKey ** pSymWrapKey; 6044 PK11SymKey **pSymWrapKey;
5915 » pSymWrapKey = &symWrapKeys[i].symWrapKey[j]; 6045 pSymWrapKey = &symWrapKeys[i].symWrapKey[j];
5916 » if (*pSymWrapKey) { 6046 if (*pSymWrapKey) {
5917 » » PK11_FreeSymKey(*pSymWrapKey); 6047 PK11_FreeSymKey(*pSymWrapKey);
5918 » » *pSymWrapKey = NULL; 6048 *pSymWrapKey = NULL;
5919 » } 6049 }
5920 » } 6050 }
5921 } 6051 }
5922 6052
5923 PZ_Unlock(symWrapKeysLock); 6053 PZ_Unlock(symWrapKeysLock);
5924 return SECSuccess; 6054 return SECSuccess;
5925 } 6055 }
5926 6056
5927 SECStatus ssl_InitSymWrapKeysLock(void) 6057 SECStatus
6058 ssl_InitSymWrapKeysLock(void)
5928 { 6059 {
5929 symWrapKeysLock = PZ_NewLock(nssILockOther); 6060 symWrapKeysLock = PZ_NewLock(nssILockOther);
5930 return symWrapKeysLock ? SECSuccess : SECFailure; 6061 return symWrapKeysLock ? SECSuccess : SECFailure;
5931 } 6062 }
5932 6063
5933 /* Try to get wrapping key for mechanism from in-memory array. 6064 /* Try to get wrapping key for mechanism from in-memory array.
5934 * If that fails, look for one on disk. 6065 * If that fails, look for one on disk.
5935 * If that fails, generate a new one, put the new one on disk, 6066 * If that fails, generate a new one, put the new one on disk,
5936 * Put the new key in the in-memory array. 6067 * Put the new key in the in-memory array.
5937 */ 6068 */
5938 static PK11SymKey * 6069 static PK11SymKey *
5939 getWrappingKey( sslSocket * ss, 6070 getWrappingKey(sslSocket *ss,
5940 » » PK11SlotInfo * masterSecretSlot, 6071 PK11SlotInfo *masterSecretSlot,
5941 » » SSL3KEAType exchKeyType, 6072 SSL3KEAType exchKeyType,
5942 CK_MECHANISM_TYPE masterWrapMech, 6073 CK_MECHANISM_TYPE masterWrapMech,
5943 » void * pwArg) 6074 void *pwArg)
5944 { 6075 {
5945 SECKEYPrivateKey * svrPrivKey; 6076 SECKEYPrivateKey *svrPrivKey;
5946 SECKEYPublicKey * svrPubKey = NULL; 6077 SECKEYPublicKey *svrPubKey = NULL;
5947 PK11SymKey * unwrappedWrappingKey = NULL; 6078 PK11SymKey *unwrappedWrappingKey = NULL;
5948 PK11SymKey ** pSymWrapKey; 6079 PK11SymKey **pSymWrapKey;
5949 CK_MECHANISM_TYPE asymWrapMechanism = CKM_INVALID_MECHANISM; 6080 CK_MECHANISM_TYPE asymWrapMechanism = CKM_INVALID_MECHANISM;
5950 int length; 6081 int length;
5951 int symWrapMechIndex; 6082 int symWrapMechIndex;
5952 SECStatus rv; 6083 SECStatus rv;
5953 SECItem wrappedKey; 6084 SECItem wrappedKey;
5954 SSLWrappedSymWrappingKey wswk; 6085 SSLWrappedSymWrappingKey wswk;
5955 #ifndef NSS_DISABLE_ECC 6086 #ifndef NSS_DISABLE_ECC
5956 PK11SymKey * Ks = NULL; 6087 PK11SymKey *Ks = NULL;
5957 SECKEYPublicKey *pubWrapKey = NULL; 6088 SECKEYPublicKey *pubWrapKey = NULL;
5958 SECKEYPrivateKey *privWrapKey = NULL; 6089 SECKEYPrivateKey *privWrapKey = NULL;
5959 ECCWrappedKeyInfo *ecWrapped; 6090 ECCWrappedKeyInfo *ecWrapped;
5960 #endif /* NSS_DISABLE_ECC */ 6091 #endif /* NSS_DISABLE_ECC */
5961 6092
5962 svrPrivKey = ss->serverCerts[exchKeyType].SERVERKEY; 6093 svrPrivKey = ss->serverCerts[exchKeyType].SERVERKEY;
5963 PORT_Assert(svrPrivKey != NULL); 6094 PORT_Assert(svrPrivKey != NULL);
5964 if (!svrPrivKey) { 6095 if (!svrPrivKey) {
5965 » return NULL;» /* why are we here?!? */ 6096 return NULL; /* why are we here?!? */
5966 } 6097 }
5967 6098
5968 symWrapMechIndex = ssl_FindIndexByWrapMechanism(masterWrapMech); 6099 symWrapMechIndex = ssl_FindIndexByWrapMechanism(masterWrapMech);
5969 PORT_Assert(symWrapMechIndex >= 0); 6100 PORT_Assert(symWrapMechIndex >= 0);
5970 if (symWrapMechIndex < 0) 6101 if (symWrapMechIndex < 0)
5971 » return NULL;» /* invalid masterWrapMech. */ 6102 return NULL; /* invalid masterWrapMech. */
5972 6103
5973 pSymWrapKey = &symWrapKeys[symWrapMechIndex].symWrapKey[exchKeyType]; 6104 pSymWrapKey = &symWrapKeys[symWrapMechIndex].symWrapKey[exchKeyType];
5974 6105
5975 ssl_InitSessionCacheLocks(); 6106 ssl_InitSessionCacheLocks();
5976 6107
5977 PZ_Lock(symWrapKeysLock); 6108 PZ_Lock(symWrapKeysLock);
5978 6109
5979 unwrappedWrappingKey = *pSymWrapKey; 6110 unwrappedWrappingKey = *pSymWrapKey;
5980 if (unwrappedWrappingKey != NULL) { 6111 if (unwrappedWrappingKey != NULL) {
5981 » if (PK11_VerifyKeyOK(unwrappedWrappingKey)) { 6112 if (PK11_VerifyKeyOK(unwrappedWrappingKey)) {
5982 » unwrappedWrappingKey = PK11_ReferenceSymKey(unwrappedWrappingKey); 6113 unwrappedWrappingKey = PK11_ReferenceSymKey(unwrappedWrappingKey);
5983 » goto done; 6114 goto done;
5984 » } 6115 }
5985 » /* slot series has changed, so this key is no good any more. */ 6116 /* slot series has changed, so this key is no good any more. */
5986 » PK11_FreeSymKey(unwrappedWrappingKey); 6117 PK11_FreeSymKey(unwrappedWrappingKey);
5987 » *pSymWrapKey = unwrappedWrappingKey = NULL; 6118 *pSymWrapKey = unwrappedWrappingKey = NULL;
5988 } 6119 }
5989 6120
5990 /* Try to get wrapped SymWrapping key out of the (disk) cache. */ 6121 /* Try to get wrapped SymWrapping key out of the (disk) cache. */
5991 /* Following call fills in wswk on success. */ 6122 /* Following call fills in wswk on success. */
5992 if (ssl_GetWrappingKey(symWrapMechIndex, exchKeyType, &wswk)) { 6123 if (ssl_GetWrappingKey(symWrapMechIndex, exchKeyType, &wswk)) {
5993 » /* found the wrapped sym wrapping key on disk. */ 6124 /* found the wrapped sym wrapping key on disk. */
5994 » unwrappedWrappingKey = 6125 unwrappedWrappingKey =
5995 » ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, exchKeyType, 6126 ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, exchKeyType,
5996 masterWrapMech, pwArg); 6127 masterWrapMech, pwArg);
5997 » if (unwrappedWrappingKey) { 6128 if (unwrappedWrappingKey) {
5998 » goto install; 6129 goto install;
5999 » } 6130 }
6000 } 6131 }
6001 6132
6002 if (!masterSecretSlot) » /* caller doesn't want to create a new one. */ 6133 if (!masterSecretSlot) /* caller doesn't want to create a new one. */
6003 » goto loser; 6134 goto loser;
6004 6135
6005 length = PK11_GetBestKeyLength(masterSecretSlot, masterWrapMech); 6136 length = PK11_GetBestKeyLength(masterSecretSlot, masterWrapMech);
6006 /* Zero length means fixed key length algorithm, or error. 6137 /* Zero length means fixed key length algorithm, or error.
6007 * It's ambiguous. 6138 * It's ambiguous.
6008 */ 6139 */
6009 unwrappedWrappingKey = PK11_KeyGen(masterSecretSlot, masterWrapMech, NULL, 6140 unwrappedWrappingKey = PK11_KeyGen(masterSecretSlot, masterWrapMech, NULL,
6010 length, pwArg); 6141 length, pwArg);
6011 if (!unwrappedWrappingKey) { 6142 if (!unwrappedWrappingKey) {
6012 » goto loser; 6143 goto loser;
6013 } 6144 }
6014 6145
6015 /* Prepare the buffer to receive the wrappedWrappingKey, 6146 /* Prepare the buffer to receive the wrappedWrappingKey,
6016 * the symmetric wrapping key wrapped using the server's pub key. 6147 * the symmetric wrapping key wrapped using the server's pub key.
6017 */ 6148 */
6018 PORT_Memset(&wswk, 0, sizeof wswk);»/* eliminate UMRs. */ 6149 PORT_Memset(&wswk, 0, sizeof wswk); /* eliminate UMRs. */
6019 6150
6020 if (ss->serverCerts[exchKeyType].serverKeyPair) { 6151 if (ss->serverCerts[exchKeyType].serverKeyPair) {
6021 » svrPubKey = ss->serverCerts[exchKeyType].serverKeyPair->pubKey; 6152 svrPubKey = ss->serverCerts[exchKeyType].serverKeyPair->pubKey;
6022 } 6153 }
6023 if (svrPubKey == NULL) { 6154 if (svrPubKey == NULL) {
6024 » PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 6155 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6025 » goto loser; 6156 goto loser;
6026 } 6157 }
6027 wrappedKey.type = siBuffer; 6158 wrappedKey.type = siBuffer;
6028 wrappedKey.len = SECKEY_PublicKeyStrength(svrPubKey); 6159 wrappedKey.len = SECKEY_PublicKeyStrength(svrPubKey);
6029 wrappedKey.data = wswk.wrappedSymmetricWrappingkey; 6160 wrappedKey.data = wswk.wrappedSymmetricWrappingkey;
6030 6161
6031 PORT_Assert(wrappedKey.len <= sizeof wswk.wrappedSymmetricWrappingkey); 6162 PORT_Assert(wrappedKey.len <= sizeof wswk.wrappedSymmetricWrappingkey);
6032 if (wrappedKey.len > sizeof wswk.wrappedSymmetricWrappingkey) 6163 if (wrappedKey.len > sizeof wswk.wrappedSymmetricWrappingkey)
6033 » goto loser; 6164 goto loser;
6034 6165
6035 /* wrap symmetric wrapping key in server's public key. */ 6166 /* wrap symmetric wrapping key in server's public key. */
6036 switch (exchKeyType) { 6167 switch (exchKeyType) {
6037 case kt_rsa: 6168 case kt_rsa:
6038 » asymWrapMechanism = CKM_RSA_PKCS; 6169 asymWrapMechanism = CKM_RSA_PKCS;
6039 » rv = PK11_PubWrapSymKey(asymWrapMechanism, svrPubKey, 6170 rv = PK11_PubWrapSymKey(asymWrapMechanism, svrPubKey,
6040 » unwrappedWrappingKey, &wrappedKey); 6171 unwrappedWrappingKey, &wrappedKey);
6041 » break; 6172 break;
6042 6173
6043 #ifndef NSS_DISABLE_ECC 6174 #ifndef NSS_DISABLE_ECC
6044 case kt_ecdh: 6175 case kt_ecdh:
6045 » /* 6176 /*
6046 » * We generate an ephemeral EC key pair. Perform an ECDH 6177 * We generate an ephemeral EC key pair. Perform an ECDH
6047 » * computation involving this ephemeral EC public key and 6178 * computation involving this ephemeral EC public key and
6048 » * the SSL server's (long-term) EC private key. The resulting 6179 * the SSL server's (long-term) EC private key. The resulting
6049 » * shared secret is treated in the same way as Fortezza's Ks, 6180 * shared secret is treated in the same way as Fortezza's Ks,
6050 » * i.e., it is used to wrap the wrapping key. To facilitate 6181 * i.e., it is used to wrap the wrapping key. To facilitate
6051 » * unwrapping in ssl_UnwrapWrappingKey, we also store all 6182 * unwrapping in ssl_UnwrapWrappingKey, we also store all
6052 » * relevant info about the ephemeral EC public key in 6183 * relevant info about the ephemeral EC public key in
6053 » * wswk.wrappedSymmetricWrappingkey and lay it out as 6184 * wswk.wrappedSymmetricWrappingkey and lay it out as
6054 » * described in the ECCWrappedKeyInfo structure. 6185 * described in the ECCWrappedKeyInfo structure.
6055 » */ 6186 */
6056 » PORT_Assert(svrPubKey->keyType == ecKey); 6187 PORT_Assert(svrPubKey->keyType == ecKey);
6057 » if (svrPubKey->keyType != ecKey) { 6188 if (svrPubKey->keyType != ecKey) {
6058 » /* something is wrong in sslsecur.c if this isn't an ecKey */ 6189 /* something is wrong in sslsecur.c if this isn't an ecKey */
6059 » PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 6190 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6060 » rv = SECFailure; 6191 rv = SECFailure;
6061 » goto ec_cleanup; 6192 goto ec_cleanup;
6062 » } 6193 }
6063 6194
6064 » privWrapKey = SECKEY_CreateECPrivateKey( 6195 privWrapKey = SECKEY_CreateECPrivateKey(
6065 » &svrPubKey->u.ec.DEREncodedParams, &pubWrapKey, NULL); 6196 &svrPubKey->u.ec.DEREncodedParams, &pubWrapKey, NULL);
6066 » if ((privWrapKey == NULL) || (pubWrapKey == NULL)) { 6197 if ((privWrapKey == NULL) || (pubWrapKey == NULL)) {
6067 » rv = SECFailure; 6198 rv = SECFailure;
6068 » goto ec_cleanup; 6199 goto ec_cleanup;
6069 » } 6200 }
6070 »
6071 » /* Set the key size in bits */
6072 » if (pubWrapKey->u.ec.size == 0) {
6073 » pubWrapKey->u.ec.size = SECKEY_PublicKeyStrengthInBits(svrPubKey);
6074 » }
6075 6201
6076 » PORT_Assert(pubWrapKey->u.ec.DEREncodedParams.len + 6202 /* Set the key size in bits */
6077 » pubWrapKey->u.ec.publicValue.len < MAX_EC_WRAPPED_KEY_BUFLEN); 6203 if (pubWrapKey->u.ec.size == 0) {
6078 » if (pubWrapKey->u.ec.DEREncodedParams.len + 6204 pubWrapKey->u.ec.size = SECKEY_PublicKeyStrengthInBits(svrPubKey );
6079 » pubWrapKey->u.ec.publicValue.len >= MAX_EC_WRAPPED_KEY_BUFLEN) { 6205 }
6080 » PORT_SetError(SEC_ERROR_INVALID_KEY);
6081 » rv = SECFailure;
6082 » goto ec_cleanup;
6083 » }
6084 6206
6085 » /* Derive Ks using ECDH */ 6207 PORT_Assert(pubWrapKey->u.ec.DEREncodedParams.len +
6086 » Ks = PK11_PubDeriveWithKDF(svrPrivKey, pubWrapKey, PR_FALSE, NULL, 6208 pubWrapKey->u.ec.publicValue.len < MAX_EC_WRAPPED_KE Y_BUFLEN);
6087 » » » » NULL, CKM_ECDH1_DERIVE, masterWrapMech, 6209 if (pubWrapKey->u.ec.DEREncodedParams.len +
6088 » » » » CKA_DERIVE, 0, CKD_NULL, NULL, NULL); 6210 pubWrapKey->u.ec.publicValue.len >= MAX_EC_WRAPPED_KEY_BUFLE N) {
6089 » if (Ks == NULL) { 6211 PORT_SetError(SEC_ERROR_INVALID_KEY);
6090 » rv = SECFailure; 6212 rv = SECFailure;
6091 » goto ec_cleanup; 6213 goto ec_cleanup;
6092 » } 6214 }
6093 6215
6094 » ecWrapped = (ECCWrappedKeyInfo *) (wswk.wrappedSymmetricWrappingkey); 6216 /* Derive Ks using ECDH */
6095 » ecWrapped->size = pubWrapKey->u.ec.size; 6217 Ks = PK11_PubDeriveWithKDF(svrPrivKey, pubWrapKey, PR_FALSE, NULL,
6096 » ecWrapped->encodedParamLen = pubWrapKey->u.ec.DEREncodedParams.len; 6218 NULL, CKM_ECDH1_DERIVE, masterWrapMech,
6097 » PORT_Memcpy(ecWrapped->var, pubWrapKey->u.ec.DEREncodedParams.data, 6219 CKA_DERIVE, 0, CKD_NULL, NULL, NULL);
6098 » pubWrapKey->u.ec.DEREncodedParams.len); 6220 if (Ks == NULL) {
6221 rv = SECFailure;
6222 goto ec_cleanup;
6223 }
6099 6224
6100 » ecWrapped->pubValueLen = pubWrapKey->u.ec.publicValue.len; 6225 ecWrapped = (ECCWrappedKeyInfo *)(wswk.wrappedSymmetricWrappingkey);
6101 » PORT_Memcpy(ecWrapped->var + ecWrapped->encodedParamLen, 6226 ecWrapped->size = pubWrapKey->u.ec.size;
6102 » » pubWrapKey->u.ec.publicValue.data, 6227 ecWrapped->encodedParamLen = pubWrapKey->u.ec.DEREncodedParams.len;
6103 » » pubWrapKey->u.ec.publicValue.len); 6228 PORT_Memcpy(ecWrapped->var, pubWrapKey->u.ec.DEREncodedParams.data,
6229 pubWrapKey->u.ec.DEREncodedParams.len);
6104 6230
6105 » wrappedKey.len = MAX_EC_WRAPPED_KEY_BUFLEN - 6231 ecWrapped->pubValueLen = pubWrapKey->u.ec.publicValue.len;
6106 » (ecWrapped->encodedParamLen + ecWrapped->pubValueLen); 6232 PORT_Memcpy(ecWrapped->var + ecWrapped->encodedParamLen,
6107 » wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen + 6233 pubWrapKey->u.ec.publicValue.data,
6108 » ecWrapped->pubValueLen; 6234 pubWrapKey->u.ec.publicValue.len);
6109 6235
6110 » /* wrap symmetricWrapping key with the local Ks */ 6236 wrappedKey.len = MAX_EC_WRAPPED_KEY_BUFLEN -
6111 » rv = PK11_WrapSymKey(masterWrapMech, NULL, Ks, 6237 (ecWrapped->encodedParamLen + ecWrapped->pubValueLe n);
6112 » » » unwrappedWrappingKey, &wrappedKey); 6238 wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen +
6239 ecWrapped->pubValueLen;
6113 6240
6114 » if (rv != SECSuccess) { 6241 /* wrap symmetricWrapping key with the local Ks */
6115 » goto ec_cleanup; 6242 rv = PK11_WrapSymKey(masterWrapMech, NULL, Ks,
6116 » } 6243 unwrappedWrappingKey, &wrappedKey);
6117 6244
6118 » /* Write down the length of wrapped key in the buffer 6245 if (rv != SECSuccess) {
6119 » * wswk.wrappedSymmetricWrappingkey at the appropriate offset 6246 goto ec_cleanup;
6120 » */ 6247 }
6121 » ecWrapped->wrappedKeyLen = wrappedKey.len;
6122 6248
6123 ec_cleanup: 6249 /* Write down the length of wrapped key in the buffer
6124 » if (privWrapKey) SECKEY_DestroyPrivateKey(privWrapKey); 6250 * wswk.wrappedSymmetricWrappingkey at the appropriate offset
6125 » if (pubWrapKey) SECKEY_DestroyPublicKey(pubWrapKey); 6251 */
6126 » if (Ks) PK11_FreeSymKey(Ks); 6252 ecWrapped->wrappedKeyLen = wrappedKey.len;
6127 » asymWrapMechanism = masterWrapMech; 6253
6128 » break; 6254 ec_cleanup:
6255 if (privWrapKey)
6256 SECKEY_DestroyPrivateKey(privWrapKey);
6257 if (pubWrapKey)
6258 SECKEY_DestroyPublicKey(pubWrapKey);
6259 if (Ks)
6260 PK11_FreeSymKey(Ks);
6261 asymWrapMechanism = masterWrapMech;
6262 break;
6129 #endif /* NSS_DISABLE_ECC */ 6263 #endif /* NSS_DISABLE_ECC */
6130 6264
6131 default: 6265 default:
6132 » rv = SECFailure; 6266 rv = SECFailure;
6133 » break; 6267 break;
6134 } 6268 }
6135 6269
6136 if (rv != SECSuccess) { 6270 if (rv != SECSuccess) {
6137 » ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); 6271 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6138 » goto loser; 6272 goto loser;
6139 } 6273 }
6140 6274
6141 PORT_Assert(asymWrapMechanism != CKM_INVALID_MECHANISM); 6275 PORT_Assert(asymWrapMechanism != CKM_INVALID_MECHANISM);
6142 6276
6143 wswk.symWrapMechanism = masterWrapMech; 6277 wswk.symWrapMechanism = masterWrapMech;
6144 wswk.symWrapMechIndex = symWrapMechIndex; 6278 wswk.symWrapMechIndex = symWrapMechIndex;
6145 wswk.asymWrapMechanism = asymWrapMechanism; 6279 wswk.asymWrapMechanism = asymWrapMechanism;
6146 wswk.exchKeyType = exchKeyType; 6280 wswk.exchKeyType = exchKeyType;
6147 wswk.wrappedSymKeyLen = wrappedKey.len; 6281 wswk.wrappedSymKeyLen = wrappedKey.len;
6148 6282
6149 /* put it on disk. */ 6283 /* put it on disk. */
6150 /* If the wrapping key for this KEA type has already been set, 6284 /* If the wrapping key for this KEA type has already been set,
6151 * then abandon the value we just computed and 6285 * then abandon the value we just computed and
6152 * use the one we got from the disk. 6286 * use the one we got from the disk.
6153 */ 6287 */
6154 if (ssl_SetWrappingKey(&wswk)) { 6288 if (ssl_SetWrappingKey(&wswk)) {
6155 » /* somebody beat us to it. The original contents of our wswk 6289 /* somebody beat us to it. The original contents of our wswk
6156 » * has been replaced with the content on disk. Now, discard 6290 * has been replaced with the content on disk. Now, discard
6157 » * the key we just created and unwrap this new one. 6291 * the key we just created and unwrap this new one.
6158 » */ 6292 */
6159 » PK11_FreeSymKey(unwrappedWrappingKey); 6293 PK11_FreeSymKey(unwrappedWrappingKey);
6160 6294
6161 » unwrappedWrappingKey = 6295 unwrappedWrappingKey =
6162 » ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, exchKeyType, 6296 ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, exchKeyType,
6163 masterWrapMech, pwArg); 6297 masterWrapMech, pwArg);
6164 } 6298 }
6165 6299
6166 install: 6300 install:
6167 if (unwrappedWrappingKey) { 6301 if (unwrappedWrappingKey) {
6168 » *pSymWrapKey = PK11_ReferenceSymKey(unwrappedWrappingKey); 6302 *pSymWrapKey = PK11_ReferenceSymKey(unwrappedWrappingKey);
6169 } 6303 }
6170 6304
6171 loser: 6305 loser:
6172 done: 6306 done:
6173 PZ_Unlock(symWrapKeysLock); 6307 PZ_Unlock(symWrapKeysLock);
6174 return unwrappedWrappingKey; 6308 return unwrappedWrappingKey;
6175 } 6309 }
6176 6310
6177 /* hexEncode hex encodes |length| bytes from |in| and writes it as |length*2| 6311 /* hexEncode hex encodes |length| bytes from |in| and writes it as |length*2|
6178 * bytes to |out|. */ 6312 * bytes to |out|. */
6179 static void 6313 static void
6180 hexEncode(char *out, const unsigned char *in, unsigned int length) 6314 hexEncode(char *out, const unsigned char *in, unsigned int length)
6181 { 6315 {
6182 static const char hextable[] = "0123456789abcdef"; 6316 static const char hextable[] = "0123456789abcdef";
6183 unsigned int i; 6317 unsigned int i;
6184 6318
6185 for (i = 0; i < length; i++) { 6319 for (i = 0; i < length; i++) {
6186 » *(out++) = hextable[in[i] >> 4]; 6320 *(out++) = hextable[in[i] >> 4];
6187 » *(out++) = hextable[in[i] & 15]; 6321 *(out++) = hextable[in[i] & 15];
6188 } 6322 }
6189 } 6323 }
6190 6324
6191 /* Called from ssl3_SendClientKeyExchange(). */ 6325 /* Called from ssl3_SendClientKeyExchange(). */
6192 /* Presently, this always uses PKCS11. There is no bypass for this. */ 6326 /* Presently, this always uses PKCS11. There is no bypass for this. */
6193 static SECStatus 6327 static SECStatus
6194 sendRSAClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey) 6328 sendRSAClientKeyExchange(sslSocket *ss, SECKEYPublicKey *svrPubKey)
6195 { 6329 {
6196 PK11SymKey *» pms » » = NULL; 6330 PK11SymKey *pms = NULL;
6197 SECStatus rv » » = SECFailure; 6331 SECStatus rv = SECFailure;
6198 SECItem » » enc_pms » = {siBuffer, NULL, 0}; 6332 SECItem enc_pms = { siBuffer, NULL, 0 };
6199 PRBool isTLS; 6333 PRBool isTLS;
6200 6334
6201 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 6335 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
6202 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 6336 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
6203 6337
6204 /* Generate the pre-master secret ... */ 6338 /* Generate the pre-master secret ... */
6205 ssl_GetSpecWriteLock(ss); 6339 ssl_GetSpecWriteLock(ss);
6206 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); 6340 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
6207 6341
6208 pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.pwSpec, NULL); 6342 pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.pwSpec, NULL);
6209 ssl_ReleaseSpecWriteLock(ss); 6343 ssl_ReleaseSpecWriteLock(ss);
6210 if (pms == NULL) { 6344 if (pms == NULL) {
6211 » ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); 6345 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6212 » goto loser; 6346 goto loser;
6213 } 6347 }
6214 6348
6215 /* Get the wrapped (encrypted) pre-master secret, enc_pms */ 6349 /* Get the wrapped (encrypted) pre-master secret, enc_pms */
6216 enc_pms.len = SECKEY_PublicKeyStrength(svrPubKey); 6350 enc_pms.len = SECKEY_PublicKeyStrength(svrPubKey);
6217 enc_pms.data = (unsigned char*)PORT_Alloc(enc_pms.len); 6351 enc_pms.data = (unsigned char *)PORT_Alloc(enc_pms.len);
6218 if (enc_pms.data == NULL) { 6352 if (enc_pms.data == NULL) {
6219 » goto loser;» /* err set by PORT_Alloc */ 6353 goto loser; /* err set by PORT_Alloc */
6220 } 6354 }
6221 6355
6222 /* wrap pre-master secret in server's public key. */ 6356 /* wrap pre-master secret in server's public key. */
6223 rv = PK11_PubWrapSymKey(CKM_RSA_PKCS, svrPubKey, pms, &enc_pms); 6357 rv = PK11_PubWrapSymKey(CKM_RSA_PKCS, svrPubKey, pms, &enc_pms);
6224 if (rv != SECSuccess) { 6358 if (rv != SECSuccess) {
6225 » ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); 6359 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6226 » goto loser; 6360 goto loser;
6227 } 6361 }
6228 6362
6229 if (ssl_keylog_iob) { 6363 if (ssl_keylog_iob) {
6230 » SECStatus extractRV = PK11_ExtractKeyValue(pms); 6364 SECStatus extractRV = PK11_ExtractKeyValue(pms);
6231 » if (extractRV == SECSuccess) { 6365 if (extractRV == SECSuccess) {
6232 » SECItem * keyData = PK11_GetKeyData(pms); 6366 SECItem *keyData = PK11_GetKeyData(pms);
6233 » if (keyData && keyData->data && keyData->len) { 6367 if (keyData && keyData->data && keyData->len) {
6234 #ifdef TRACE 6368 #ifdef TRACE
6235 » » if (ssl_trace >= 100) { 6369 if (ssl_trace >= 100) {
6236 » » ssl_PrintBuf(ss, "Pre-Master Secret", 6370 ssl_PrintBuf(ss, "Pre-Master Secret",
6237 » » » » keyData->data, keyData->len); 6371 keyData->data, keyData->len);
6238 » » } 6372 }
6239 #endif 6373 #endif
6240 » » if (ssl_keylog_iob && enc_pms.len >= 8 && keyData->len == 48) { 6374 if (ssl_keylog_iob && enc_pms.len >= 8 && keyData->len == 48) {
6241 » » /* https://developer.mozilla.org/en/NSS_Key_Log_Format */ 6375 /* https://developer.mozilla.org/en/NSS_Key_Log_Format */
6242 6376
6243 » » /* There could be multiple, concurrent writers to the 6377 /* There could be multiple, concurrent writers to the
6244 » » * keylog, so we have to do everything in a single call to 6378 * keylog, so we have to do everything in a single call to
6245 » » * fwrite. */ 6379 * fwrite. */
6246 » » char buf[4 + 8*2 + 1 + 48*2 + 1]; 6380 char buf[4 + 8 * 2 + 1 + 48 * 2 + 1];
6247 6381
6248 » » strcpy(buf, "RSA "); 6382 strcpy(buf, "RSA ");
6249 » » hexEncode(buf + 4, enc_pms.data, 8); 6383 hexEncode(buf + 4, enc_pms.data, 8);
6250 » » buf[20] = ' '; 6384 buf[20] = ' ';
6251 » » hexEncode(buf + 21, keyData->data, 48); 6385 hexEncode(buf + 21, keyData->data, 48);
6252 » » buf[sizeof(buf) - 1] = '\n'; 6386 buf[sizeof(buf) - 1] = '\n';
6253 6387
6254 » » fwrite(buf, sizeof(buf), 1, ssl_keylog_iob); 6388 fwrite(buf, sizeof(buf), 1, ssl_keylog_iob);
6255 » » fflush(ssl_keylog_iob); 6389 fflush(ssl_keylog_iob);
6256 » » } 6390 }
6257 » } 6391 }
6258 » } 6392 }
6259 } 6393 }
6260 6394
6261 rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange, 6395 rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange,
6262 » » » » isTLS ? enc_pms.len + 2 : enc_pms.len); 6396 isTLS ? enc_pms.len + 2
6397 : enc_pms.len);
6263 if (rv != SECSuccess) { 6398 if (rv != SECSuccess) {
6264 » goto loser;» /* err set by ssl3_AppendHandshake* */ 6399 goto loser; /* err set by ssl3_AppendHandshake* */
6265 } 6400 }
6266 if (isTLS) { 6401 if (isTLS) {
6267 » rv = ssl3_AppendHandshakeVariable(ss, enc_pms.data, enc_pms.len, 2); 6402 rv = ssl3_AppendHandshakeVariable(ss, enc_pms.data, enc_pms.len, 2);
6268 } else { 6403 } else {
6269 » rv = ssl3_AppendHandshake(ss, enc_pms.data, enc_pms.len); 6404 rv = ssl3_AppendHandshake(ss, enc_pms.data, enc_pms.len);
6270 } 6405 }
6271 if (rv != SECSuccess) { 6406 if (rv != SECSuccess) {
6272 » goto loser;» /* err set by ssl3_AppendHandshake* */ 6407 goto loser; /* err set by ssl3_AppendHandshake* */
6273 } 6408 }
6274 6409
6275 rv = ssl3_InitPendingCipherSpec(ss, pms); 6410 rv = ssl3_InitPendingCipherSpec(ss, pms);
6276 PK11_FreeSymKey(pms); 6411 PK11_FreeSymKey(pms);
6277 pms = NULL; 6412 pms = NULL;
6278 6413
6279 if (rv != SECSuccess) { 6414 if (rv != SECSuccess) {
6280 » ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); 6415 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6281 » goto loser; 6416 goto loser;
6282 } 6417 }
6283 6418
6284 rv = SECSuccess; 6419 rv = SECSuccess;
6285 6420
6286 loser: 6421 loser:
6287 if (enc_pms.data != NULL) { 6422 if (enc_pms.data != NULL) {
6288 » PORT_Free(enc_pms.data); 6423 PORT_Free(enc_pms.data);
6289 } 6424 }
6290 if (pms != NULL) { 6425 if (pms != NULL) {
6291 » PK11_FreeSymKey(pms); 6426 PK11_FreeSymKey(pms);
6292 } 6427 }
6293 return rv; 6428 return rv;
6294 } 6429 }
6295 6430
6296 /* Called from ssl3_SendClientKeyExchange(). */ 6431 /* Called from ssl3_SendClientKeyExchange(). */
6297 /* Presently, this always uses PKCS11. There is no bypass for this. */ 6432 /* Presently, this always uses PKCS11. There is no bypass for this. */
6298 static SECStatus 6433 static SECStatus
6299 sendDHClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey) 6434 sendDHClientKeyExchange(sslSocket *ss, SECKEYPublicKey *svrPubKey)
6300 { 6435 {
6301 PK11SymKey *» pms » » = NULL; 6436 PK11SymKey *pms = NULL;
6302 SECStatus rv » » = SECFailure; 6437 SECStatus rv = SECFailure;
6303 PRBool isTLS; 6438 PRBool isTLS;
6304 CK_MECHANISM_TYPE» target; 6439 CK_MECHANISM_TYPE target;
6305 6440
6306 SECKEYDHParams» dhParam;» » /* DH parameters */ 6441 SECKEYDHParams dhParam; /* DH parameters */
6307 SECKEYPublicKey» *pubKey = NULL;»» /* Ephemeral DH key */ 6442 SECKEYPublicKey *pubKey = NULL; /* Ephemeral DH key */
6308 SECKEYPrivateKey» *privKey = NULL;» /* Ephemeral DH key */ 6443 SECKEYPrivateKey *privKey = NULL; /* Ephemeral DH key */
6309 6444
6310 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 6445 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
6311 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 6446 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
6312 6447
6313 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); 6448 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
6314 6449
6315 /* Copy DH parameters from server key */ 6450 /* Copy DH parameters from server key */
6316 6451
6317 if (svrPubKey->keyType != dhKey) { 6452 if (svrPubKey->keyType != dhKey) {
6318 » PORT_SetError(SEC_ERROR_BAD_KEY); 6453 PORT_SetError(SEC_ERROR_BAD_KEY);
6319 » goto loser; 6454 goto loser;
6320 } 6455 }
6321 dhParam.prime.data = svrPubKey->u.dh.prime.data; 6456 dhParam.prime.data = svrPubKey->u.dh.prime.data;
6322 dhParam.prime.len = svrPubKey->u.dh.prime.len; 6457 dhParam.prime.len = svrPubKey->u.dh.prime.len;
6323 dhParam.base.data = svrPubKey->u.dh.base.data; 6458 dhParam.base.data = svrPubKey->u.dh.base.data;
6324 dhParam.base.len = svrPubKey->u.dh.base.len; 6459 dhParam.base.len = svrPubKey->u.dh.base.len;
6325 6460
6326 /* Generate ephemeral DH keypair */ 6461 /* Generate ephemeral DH keypair */
6327 privKey = SECKEY_CreateDHPrivateKey(&dhParam, &pubKey, NULL); 6462 privKey = SECKEY_CreateDHPrivateKey(&dhParam, &pubKey, NULL);
6328 if (!privKey || !pubKey) { 6463 if (!privKey || !pubKey) {
6329 » ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL); 6464 ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
6330 » rv = SECFailure; 6465 rv = SECFailure;
6331 » goto loser; 6466 goto loser;
6332 } 6467 }
6333 PRINT_BUF(50, (ss, "DH public value:", 6468 PRINT_BUF(50, (ss, "DH public value:",
6334 » » » » » pubKey->u.dh.publicValue.data, 6469 pubKey->u.dh.publicValue.data,
6335 » » » » » pubKey->u.dh.publicValue.len)); 6470 pubKey->u.dh.publicValue.len));
6336 6471
6337 if (isTLS) target = CKM_TLS_MASTER_KEY_DERIVE_DH; 6472 if (isTLS)
6338 else target = CKM_SSL3_MASTER_KEY_DERIVE_DH; 6473 target = CKM_TLS_MASTER_KEY_DERIVE_DH;
6474 else
6475 target = CKM_SSL3_MASTER_KEY_DERIVE_DH;
6339 6476
6340 /* Determine the PMS */ 6477 /* Determine the PMS */
6341 6478
6342 pms = PK11_PubDerive(privKey, svrPubKey, PR_FALSE, NULL, NULL, 6479 pms = PK11_PubDerive(privKey, svrPubKey, PR_FALSE, NULL, NULL,
6343 » » » CKM_DH_PKCS_DERIVE, target, CKA_DERIVE, 0, NULL); 6480 CKM_DH_PKCS_DERIVE, target, CKA_DERIVE, 0, NULL);
6344 6481
6345 if (pms == NULL) { 6482 if (pms == NULL) {
6346 » ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); 6483 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6347 » goto loser; 6484 goto loser;
6348 } 6485 }
6349 6486
6350 SECKEY_DestroyPrivateKey(privKey); 6487 SECKEY_DestroyPrivateKey(privKey);
6351 privKey = NULL; 6488 privKey = NULL;
6352 6489
6353 rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange, 6490 rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange,
6354 » » » » » pubKey->u.dh.publicValue.len + 2); 6491 pubKey->u.dh.publicValue.len + 2);
6355 if (rv != SECSuccess) { 6492 if (rv != SECSuccess) {
6356 » goto loser;» /* err set by ssl3_AppendHandshake* */ 6493 goto loser; /* err set by ssl3_AppendHandshake* */
6357 } 6494 }
6358 rv = ssl3_AppendHandshakeVariable(ss, 6495 rv = ssl3_AppendHandshakeVariable(ss,
6359 » » » » » pubKey->u.dh.publicValue.data, 6496 pubKey->u.dh.publicValue.data,
6360 » » » » » pubKey->u.dh.publicValue.len, 2); 6497 pubKey->u.dh.publicValue.len, 2);
6361 SECKEY_DestroyPublicKey(pubKey); 6498 SECKEY_DestroyPublicKey(pubKey);
6362 pubKey = NULL; 6499 pubKey = NULL;
6363 6500
6364 if (rv != SECSuccess) { 6501 if (rv != SECSuccess) {
6365 » goto loser;» /* err set by ssl3_AppendHandshake* */ 6502 goto loser; /* err set by ssl3_AppendHandshake* */
6366 } 6503 }
6367 6504
6368 rv = ssl3_InitPendingCipherSpec(ss, pms); 6505 rv = ssl3_InitPendingCipherSpec(ss, pms);
6369 PK11_FreeSymKey(pms); 6506 PK11_FreeSymKey(pms);
6370 pms = NULL; 6507 pms = NULL;
6371 6508
6372 if (rv != SECSuccess) { 6509 if (rv != SECSuccess) {
6373 » ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); 6510 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6374 » goto loser; 6511 goto loser;
6375 } 6512 }
6376 6513
6377 rv = SECSuccess; 6514 rv = SECSuccess;
6378 6515
6379 loser: 6516 loser:
6380 6517
6381 if(pms) PK11_FreeSymKey(pms); 6518 if (pms)
6382 if(privKey) SECKEY_DestroyPrivateKey(privKey); 6519 PK11_FreeSymKey(pms);
6383 if(pubKey) SECKEY_DestroyPublicKey(pubKey); 6520 if (privKey)
6521 SECKEY_DestroyPrivateKey(privKey);
6522 if (pubKey)
6523 SECKEY_DestroyPublicKey(pubKey);
6384 return rv; 6524 return rv;
6385 } 6525 }
6386 6526
6387
6388
6389
6390
6391 /* Called from ssl3_HandleServerHelloDone(). */ 6527 /* Called from ssl3_HandleServerHelloDone(). */
6392 static SECStatus 6528 static SECStatus
6393 ssl3_SendClientKeyExchange(sslSocket *ss) 6529 ssl3_SendClientKeyExchange(sslSocket *ss)
6394 { 6530 {
6395 SECKEYPublicKey *» serverKey » = NULL; 6531 SECKEYPublicKey *serverKey = NULL;
6396 SECStatus » » rv » » = SECFailure; 6532 SECStatus rv = SECFailure;
6397 PRBool isTLS; 6533 PRBool isTLS;
6398 6534
6399 SSL_TRC(3, ("%d: SSL3[%d]: send client_key_exchange handshake", 6535 SSL_TRC(3, ("%d: SSL3[%d]: send client_key_exchange handshake",
6400 » » SSL_GETPID(), ss->fd)); 6536 SSL_GETPID(), ss->fd));
6401 6537
6402 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 6538 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
6403 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 6539 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
6404 6540
6405 if (ss->sec.peerKey == NULL) { 6541 if (ss->sec.peerKey == NULL) {
6406 » serverKey = CERT_ExtractPublicKey(ss->sec.peerCert); 6542 serverKey = CERT_ExtractPublicKey(ss->sec.peerCert);
6407 » if (serverKey == NULL) { 6543 if (serverKey == NULL) {
6408 » ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); 6544 ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
6409 » return SECFailure; 6545 return SECFailure;
6410 » } 6546 }
6411 } else { 6547 } else {
6412 » serverKey = ss->sec.peerKey; 6548 serverKey = ss->sec.peerKey;
6413 » ss->sec.peerKey = NULL; /* we're done with it now */ 6549 ss->sec.peerKey = NULL; /* we're done with it now */
6414 } 6550 }
6415 6551
6416 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); 6552 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
6417 /* enforce limits on kea key sizes. */ 6553 /* enforce limits on kea key sizes. */
6418 if (ss->ssl3.hs.kea_def->is_limited) { 6554 if (ss->ssl3.hs.kea_def->is_limited) {
6419 unsigned int keyLen = SECKEY_PublicKeyStrengthInBits(serverKey); 6555 unsigned int keyLen = SECKEY_PublicKeyStrengthInBits(serverKey);
6420 6556
6421 if (keyLen > ss->ssl3.hs.kea_def->key_size_limit) { 6557 if (keyLen > ss->ssl3.hs.kea_def->key_size_limit) {
6422 » if (isTLS) 6558 if (isTLS)
6423 » » (void)SSL3_SendAlert(ss, alert_fatal, export_restriction); 6559 (void)SSL3_SendAlert(ss, alert_fatal, export_restriction);
6424 » else 6560 else
6425 » » (void)ssl3_HandshakeFailure(ss); 6561 (void)ssl3_HandshakeFailure(ss);
6426 » PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED); 6562 PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED);
6427 » goto loser; 6563 goto loser;
6428 » } 6564 }
6429 } 6565 }
6430 6566
6431 ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType; 6567 ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType;
6432 ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits(serverKey); 6568 ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits(serverKey);
6433 6569
6434 switch (ss->ssl3.hs.kea_def->exchKeyType) { 6570 switch (ss->ssl3.hs.kea_def->exchKeyType) {
6435 case kt_rsa: 6571 case kt_rsa:
6436 » rv = sendRSAClientKeyExchange(ss, serverKey); 6572 rv = sendRSAClientKeyExchange(ss, serverKey);
6437 » break; 6573 break;
6438 6574
6439 case kt_dh: 6575 case kt_dh:
6440 » rv = sendDHClientKeyExchange(ss, serverKey); 6576 rv = sendDHClientKeyExchange(ss, serverKey);
6441 » break; 6577 break;
6442 6578
6443 #ifndef NSS_DISABLE_ECC 6579 #ifndef NSS_DISABLE_ECC
6444 case kt_ecdh: 6580 case kt_ecdh:
6445 » rv = ssl3_SendECDHClientKeyExchange(ss, serverKey); 6581 rv = ssl3_SendECDHClientKeyExchange(ss, serverKey);
6446 » break; 6582 break;
6447 #endif /* NSS_DISABLE_ECC */ 6583 #endif /* NSS_DISABLE_ECC */
6448 6584
6449 default: 6585 default:
6450 » /* got an unknown or unsupported Key Exchange Algorithm. */ 6586 /* got an unknown or unsupported Key Exchange Algorithm. */
6451 » SEND_ALERT 6587 SEND_ALERT
6452 » PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); 6588 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
6453 » break; 6589 break;
6454 } 6590 }
6455 6591
6456 SSL_TRC(3, ("%d: SSL3[%d]: DONE sending client_key_exchange", 6592 SSL_TRC(3, ("%d: SSL3[%d]: DONE sending client_key_exchange",
6457 » » SSL_GETPID(), ss->fd)); 6593 SSL_GETPID(), ss->fd));
6458 6594
6459 loser: 6595 loser:
6460 if (serverKey) 6596 if (serverKey)
6461 » SECKEY_DestroyPublicKey(serverKey); 6597 SECKEY_DestroyPublicKey(serverKey);
6462 return rv;» /* err code already set. */ 6598 return rv; /* err code already set. */
6463 } 6599 }
6464 6600
6465 /* Called from ssl3_HandleServerHelloDone(). */ 6601 /* Called from ssl3_HandleServerHelloDone(). */
6466 static SECStatus 6602 SECStatus
6467 ssl3_SendCertificateVerify(sslSocket *ss) 6603 ssl3_SendCertificateVerify(sslSocket *ss, SECKEYPrivateKey *privKey)
6468 { 6604 {
6469 SECStatus rv» » = SECFailure; 6605 SECStatus rv = SECFailure;
6470 PRBool isTLS; 6606 PRBool isTLS;
6471 PRBool isTLS12; 6607 PRBool isTLS12;
6472 SECItem buf = {siBuffer, NULL, 0}; 6608 PRBool isTLS13;
6473 SSL3Hashes hashes; 6609 SECItem buf = { siBuffer, NULL, 0 };
6474 KeyType keyType; 6610 SSL3Hashes hashes;
6475 unsigned int len; 6611 KeyType keyType;
6612 unsigned int len;
6476 SSLSignatureAndHashAlg sigAndHash; 6613 SSLSignatureAndHashAlg sigAndHash;
6477 6614
6478 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 6615 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
6479 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 6616 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
6480 6617
6481 SSL_TRC(3, ("%d: SSL3[%d]: send certificate_verify handshake", 6618 SSL_TRC(3, ("%d: SSL3[%d]: send certificate_verify handshake",
6482 » » SSL_GETPID(), ss->fd)); 6619 SSL_GETPID(), ss->fd));
6483 6620
6621 isTLS13 = (PRBool)(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
6484 ssl_GetSpecReadLock(ss); 6622 ssl_GetSpecReadLock(ss);
6485 if (ss->ssl3.hs.hashType == handshake_hash_single && 6623 if (ss->ssl3.hs.hashType == handshake_hash_single &&
6486 » ss->ssl3.hs.backupHash) { 6624 ss->ssl3.hs.backupHash) {
6487 » rv = ssl3_ComputeBackupHandshakeHashes(ss, &hashes); 6625 PORT_Assert(!ss->ssl3.hs.backupHash);
6488 » PORT_Assert(!ss->ssl3.hs.backupHash); 6626 PORT_Assert(!isTLS13);
6627 /* TODO(ekr@rtfm.com): The backup hash here contains a SHA-1 hash
6628 * but in TLS 1.3, we always sign H(Context, Hash(handshake))
6629 * where:
6630 *
6631 * H is the negotiated signature hash and
6632 * Hash is the cipher-suite specific handshake hash
6633 * Generally this means that Hash is SHA-256.
6634 *
6635 * We need code to negotiate H but the current code is a mess.
6636 */
6637 if (isTLS13) {
svaldez 2016/04/01 19:50:01 Looks like dead code, probably not worth forking.
6638 /* rv is already set to SECFailure */
6639 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
6640 } else {
6641 rv = ssl3_ComputeBackupHandshakeHashes(ss, &hashes);
6642 }
6489 } else { 6643 } else {
6490 » rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.pwSpec, &hashes, 0); 6644 ssl3CipherSpec *spec;
6645
6646 if (isTLS13) {
6647 /* In TLS 1.3, we are already encrypted. */
6648 spec = ss->ssl3.cwSpec;
6649 } else {
6650 spec = ss->ssl3.pwSpec;
6651 }
6652
6653 rv = ssl3_ComputeHandshakeHashes(ss, spec, &hashes, 0);
6491 } 6654 }
6492 ssl_ReleaseSpecReadLock(ss); 6655 ssl_ReleaseSpecReadLock(ss);
6493 if (rv != SECSuccess) { 6656 if (rv != SECSuccess) {
6494 » goto done;» /* err code was set by ssl3_ComputeHandshakeHashes */ 6657 goto done; /* err code was set by ssl3_ComputeHandshakeHashes */
6658 }
6659
6660 if (isTLS13) {
6661 rv = tls13_AddContextToHashes(ss, &hashes, tls13_GetHash(ss), PR_TRUE);
6662 if (rv != SECSuccess) {
6663 goto done; /* err code was set by tls13_AddContextToHashes */
6664 }
6495 } 6665 }
6496 6666
6497 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); 6667 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
6498 isTLS12 = (PRBool)(ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); 6668 isTLS12 = (PRBool)(ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
6499 if (ss->ssl3.platformClientKey) {
6500 #ifdef NSS_PLATFORM_CLIENT_AUTH
6501 keyType = CERT_GetCertKeyType(
6502 &ss->ssl3.clientCertificate->subjectPublicKeyInfo);
6503 rv = ssl3_PlatformSignHashes(
6504 &hashes, ss->ssl3.platformClientKey, &buf, isTLS, keyType);
6505 ssl_FreePlatformKey(ss->ssl3.platformClientKey);
6506 ss->ssl3.platformClientKey = (PlatformKey)NULL;
6507 #endif /* NSS_PLATFORM_CLIENT_AUTH */
6508 } else {
6509 keyType = ss->ssl3.clientPrivateKey->keyType;
6510 rv = ssl3_SignHashes(&hashes, ss->ssl3.clientPrivateKey, &buf, isTLS);
6511 if (rv == SECSuccess) {
6512 PK11SlotInfo * slot;
6513 sslSessionID * sid = ss->sec.ci.sid;
6514 6669
6515 » /* Remember the info about the slot that did the signing. 6670 keyType = privKey->keyType;
6516 » ** Later, when doing an SSL restart handshake, verify this. 6671 rv = ssl3_SignHashes(&hashes, privKey, &buf, isTLS);
6517 » ** These calls are mere accessors, and can't fail. 6672 if (rv == SECSuccess && !ss->sec.isServer) {
6518 » */ 6673 /* Remember the info about the slot that did the signing.
6519 » slot = PK11_GetSlotFromPrivateKey(ss->ssl3.clientPrivateKey); 6674 ** Later, when doing an SSL restart handshake, verify this.
6520 » sid->u.ssl3.clAuthSeries = PK11_GetSlotSeries(slot); 6675 ** These calls are mere accessors, and can't fail.
6521 » sid->u.ssl3.clAuthSlotID = PK11_GetSlotID(slot); 6676 */
6522 » sid->u.ssl3.clAuthModuleID = PK11_GetModuleID(slot); 6677 PK11SlotInfo *slot;
6523 » sid->u.ssl3.clAuthValid = PR_TRUE; 6678 sslSessionID *sid = ss->sec.ci.sid;
6524 » PK11_FreeSlot(slot); 6679
6525 » } 6680 slot = PK11_GetSlotFromPrivateKey(privKey);
6526 » SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); 6681 sid->u.ssl3.clAuthSeries = PK11_GetSlotSeries(slot);
6527 » ss->ssl3.clientPrivateKey = NULL; 6682 sid->u.ssl3.clAuthSlotID = PK11_GetSlotID(slot);
6683 sid->u.ssl3.clAuthModuleID = PK11_GetModuleID(slot);
6684 sid->u.ssl3.clAuthValid = PR_TRUE;
6685 PK11_FreeSlot(slot);
6528 } 6686 }
6529 if (rv != SECSuccess) { 6687 if (rv != SECSuccess) {
6530 » goto done;» /* err code was set by ssl3_SignHashes */ 6688 goto done; /* err code was set by ssl3_SignHashes */
6531 } 6689 }
6532 6690
6533 len = buf.len + 2 + (isTLS12 ? 2 : 0); 6691 len = buf.len + 2 + (isTLS12 ? 2 : 0);
6534 6692
6535 rv = ssl3_AppendHandshakeHeader(ss, certificate_verify, len); 6693 rv = ssl3_AppendHandshakeHeader(ss, certificate_verify, len);
6536 if (rv != SECSuccess) { 6694 if (rv != SECSuccess) {
6537 » goto done;» /* error code set by AppendHandshake */ 6695 goto done; /* error code set by AppendHandshake */
6538 } 6696 }
6539 if (isTLS12) { 6697 if (isTLS12) {
6540 » rv = ssl3_TLSSignatureAlgorithmForKeyType(keyType, 6698 rv = ssl3_TLSSignatureAlgorithmForKeyType(keyType,
6541 &sigAndHash.sigAlg); 6699 &sigAndHash.sigAlg);
6542 » if (rv != SECSuccess) { 6700 if (rv != SECSuccess) {
6543 » goto done; 6701 goto done;
6544 » } 6702 }
6545 sigAndHash.hashAlg = hashes.hashAlg; 6703 sigAndHash.hashAlg = hashes.hashAlg;
6546 6704
6547 » rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash); 6705 rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash);
6548 » if (rv != SECSuccess) { 6706 if (rv != SECSuccess) {
6549 » goto done; »/* err set by AppendHandshake. */ 6707 goto done; /* err set by AppendHandshake. */
6550 » } 6708 }
6551 } 6709 }
6552 rv = ssl3_AppendHandshakeVariable(ss, buf.data, buf.len, 2); 6710 rv = ssl3_AppendHandshakeVariable(ss, buf.data, buf.len, 2);
6553 if (rv != SECSuccess) { 6711 if (rv != SECSuccess) {
6554 » goto done;» /* error code set by AppendHandshake */ 6712 goto done; /* error code set by AppendHandshake */
6555 } 6713 }
6556 6714
6557 done: 6715 done:
6558 if (buf.data) 6716 if (buf.data)
6559 » PORT_Free(buf.data); 6717 PORT_Free(buf.data);
6560 return rv; 6718 return rv;
6561 } 6719 }
6562 6720
6563 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete 6721 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
6564 * ssl3 ServerHello message. 6722 * ssl3 ServerHello message.
6565 * Caller must hold Handshake and RecvBuf locks. 6723 * Caller must hold Handshake and RecvBuf locks.
6566 */ 6724 */
6567 static SECStatus 6725 static SECStatus
6568 ssl3_HandleServerHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) 6726 ssl3_HandleServerHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
6569 { 6727 {
6570 sslSessionID *sid» » = ss->sec.ci.sid; 6728 sslSessionID *sid = ss->sec.ci.sid;
6571 PRInt32 temp;»» /* allow for consume number failure */ 6729 PRInt32 temp; /* allow for consume number failure */
6572 PRBool suite_found = PR_FALSE; 6730 PRBool suite_found = PR_FALSE;
6573 int i; 6731 int i;
6574 int errCode» = SSL_ERROR_RX_MALFORMED_SERVER_HELLO; 6732 int errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
6575 SECStatus rv; 6733 SECStatus rv;
6576 SECItem sidBytes » = {siBuffer, NULL, 0}; 6734 SECItem sidBytes = { siBuffer, NULL, 0 };
6577 PRBool sid_match; 6735 PRBool sid_match;
6578 PRBool isTLS»» = PR_FALSE; 6736 PRBool isTLS = PR_FALSE;
6579 SSL3AlertDescription desc = illegal_parameter; 6737 SSL3AlertDescription desc = illegal_parameter;
6580 SSL3ProtocolVersion version; 6738 SSL3ProtocolVersion version;
6739 SSL3ProtocolVersion downgradeCheckVersion;
6581 6740
6582 SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello handshake", 6741 SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello handshake",
6583 » SSL_GETPID(), ss->fd)); 6742 SSL_GETPID(), ss->fd));
6584 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 6743 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
6585 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 6744 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
6586 PORT_Assert( ss->ssl3.initialized ); 6745 PORT_Assert(ss->ssl3.initialized);
6587 6746
6588 if (ss->ssl3.hs.ws != wait_server_hello) { 6747 if (ss->ssl3.hs.ws != wait_server_hello) {
6589 errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO; 6748 errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO;
6590 » desc = unexpected_message; 6749 desc = unexpected_message;
6591 » goto alert_loser; 6750 goto alert_loser;
6592 } 6751 }
6593 6752
6594 /* clean up anything left from previous handshake. */ 6753 /* clean up anything left from previous handshake. */
6595 if (ss->ssl3.clientCertChain != NULL) { 6754 if (ss->ssl3.clientCertChain != NULL) {
6596 CERT_DestroyCertificateList(ss->ssl3.clientCertChain); 6755 CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
6597 ss->ssl3.clientCertChain = NULL; 6756 ss->ssl3.clientCertChain = NULL;
6598 } 6757 }
6599 if (ss->ssl3.clientCertificate != NULL) { 6758 if (ss->ssl3.clientCertificate != NULL) {
6600 CERT_DestroyCertificate(ss->ssl3.clientCertificate); 6759 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
6601 ss->ssl3.clientCertificate = NULL; 6760 ss->ssl3.clientCertificate = NULL;
6602 } 6761 }
6603 if (ss->ssl3.clientPrivateKey != NULL) { 6762 if (ss->ssl3.clientPrivateKey != NULL) {
6604 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); 6763 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
6605 ss->ssl3.clientPrivateKey = NULL; 6764 ss->ssl3.clientPrivateKey = NULL;
6606 } 6765 }
6607 #ifdef NSS_PLATFORM_CLIENT_AUTH
6608 if (ss->ssl3.platformClientKey) {
6609 ssl_FreePlatformKey(ss->ssl3.platformClientKey);
6610 ss->ssl3.platformClientKey = (PlatformKey)NULL;
6611 }
6612 #endif /* NSS_PLATFORM_CLIENT_AUTH */
6613 6766
6614 if (ss->ssl3.channelID != NULL) { 6767 if (ss->ssl3.channelID != NULL) {
6615 » SECKEY_DestroyPrivateKey(ss->ssl3.channelID); 6768 SECKEY_DestroyPrivateKey(ss->ssl3.channelID);
6616 » ss->ssl3.channelID = NULL; 6769 ss->ssl3.channelID = NULL;
6617 } 6770 }
6618 if (ss->ssl3.channelIDPub != NULL) { 6771 if (ss->ssl3.channelIDPub != NULL) {
6619 » SECKEY_DestroyPublicKey(ss->ssl3.channelIDPub); 6772 SECKEY_DestroyPublicKey(ss->ssl3.channelIDPub);
6620 » ss->ssl3.channelIDPub = NULL; 6773 ss->ssl3.channelIDPub = NULL;
6621 } 6774 }
6622 6775
6623 temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); 6776 temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
6624 if (temp < 0) { 6777 if (temp < 0) {
6625 » goto loser; » /* alert has been sent */ 6778 goto loser; /* alert has been sent */
6626 } 6779 }
6627 version = (SSL3ProtocolVersion)temp; 6780 version = (SSL3ProtocolVersion)temp;
6628 6781
6629 if (IS_DTLS(ss)) { 6782 if (IS_DTLS(ss)) {
6630 » /* RFC 4347 required that you verify that the server versions 6783 /* RFC 4347 required that you verify that the server versions
6631 » * match (Section 4.2.1) in the HelloVerifyRequest and the 6784 * match (Section 4.2.1) in the HelloVerifyRequest and the
6632 » * ServerHello. 6785 * ServerHello.
6633 » * 6786 *
6634 » * RFC 6347 suggests (SHOULD) that servers always use 1.0 6787 * RFC 6347 suggests (SHOULD) that servers always use 1.0
6635 » * in HelloVerifyRequest and allows the versions not to match, 6788 * in HelloVerifyRequest and allows the versions not to match,
6636 » * especially when 1.2 is being negotiated. 6789 * especially when 1.2 is being negotiated.
6637 » * 6790 *
6638 » * Therefore we do not check for matching here. 6791 * Therefore we do not check for matching here.
6639 » */ 6792 */
6640 » version = dtls_DTLSVersionToTLSVersion(version); 6793 version = dtls_DTLSVersionToTLSVersion(version);
6641 » if (version == 0) { /* Insane version number */ 6794 if (version == 0) { /* Insane version number */
6642 goto alert_loser; 6795 goto alert_loser;
6643 » } 6796 }
6644 } 6797 }
6645 6798
6646 rv = ssl3_NegotiateVersion(ss, version, PR_FALSE); 6799 rv = ssl3_NegotiateVersion(ss, version, PR_FALSE);
6647 if (rv != SECSuccess) { 6800 if (rv != SECSuccess) {
6648 » desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version 6801 desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version
6649 » » » » » » : handshake_failure; 6802 : handshake_failure;
6650 » errCode = SSL_ERROR_UNSUPPORTED_VERSION; 6803 errCode = SSL_ERROR_UNSUPPORTED_VERSION;
6651 » goto alert_loser; 6804 goto alert_loser;
6652 } 6805 }
6653 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version; 6806 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version;
6654 isTLS = (ss->version > SSL_LIBRARY_VERSION_3_0); 6807 isTLS = (ss->version > SSL_LIBRARY_VERSION_3_0);
6655 6808
6656 rv = ssl3_InitHandshakeHashes(ss); 6809 rv = ssl3_InitHandshakeHashes(ss);
6657 if (rv != SECSuccess) { 6810 if (rv != SECSuccess) {
6658 » desc = internal_error; 6811 desc = internal_error;
6659 » errCode = PORT_GetError(); 6812 errCode = PORT_GetError();
6660 » goto alert_loser; 6813 goto alert_loser;
6661 } 6814 }
6662 6815
6663 rv = ssl3_ConsumeHandshake( 6816 rv = ssl3_ConsumeHandshake(
6664 » ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH, &b, &length); 6817 ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH, &b, &length);
6665 if (rv != SECSuccess) { 6818 if (rv != SECSuccess) {
6666 » goto loser; » /* alert has been sent */ 6819 goto loser; /* alert has been sent */
6667 } 6820 }
6668 6821
6669 rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length); 6822 /* Check the ServerHello.random per
6670 if (rv != SECSuccess) { 6823 * [draft-ietf-tls-tls13-11 Section 6.3.1.1].
6671 » goto loser; » /* alert has been sent */ 6824 *
6672 } 6825 * TLS 1.3 clients receiving a TLS 1.2 or below ServerHello MUST check
6673 if (sidBytes.len > SSL3_SESSIONID_BYTES) { 6826 * that the top eight octets are not equal to either of these values.
6674 » if (isTLS) 6827 * TLS 1.2 clients SHOULD also perform this check if the ServerHello
6675 » desc = decode_error; 6828 * indicates TLS 1.1 or below. If a match is found the client MUST
6676 » goto alert_loser;» /* malformed. */ 6829 * abort the handshake with a fatal "illegal_parameter" alert.
6830 */
6831 downgradeCheckVersion = ss->ssl3.downgradeCheckVersion ? ss->ssl3.downgradeC heckVersion
6832 : ss->vrange.max;
6833
6834 if (downgradeCheckVersion >= SSL_LIBRARY_VERSION_TLS_1_2 &&
6835 downgradeCheckVersion > ss->version) {
6836 if (!PORT_Memcmp(ss->ssl3.hs.server_random.rand,
6837 tls13_downgrade_random,
6838 sizeof(tls13_downgrade_random)) ||
6839 !PORT_Memcmp(ss->ssl3.hs.server_random.rand,
6840 tls12_downgrade_random,
6841 sizeof(tls12_downgrade_random))) {
6842 desc = illegal_parameter;
6843 errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
6844 goto alert_loser;
6845 }
6846 }
6847
6848 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
6849 rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length);
6850 if (rv != SECSuccess) {
6851 goto loser; /* alert has been sent */
6852 }
6853 if (sidBytes.len > SSL3_SESSIONID_BYTES) {
6854 if (isTLS)
6855 desc = decode_error;
6856 goto alert_loser; /* malformed. */
6857 }
6677 } 6858 }
6678 6859
6679 /* find selected cipher suite in our list. */ 6860 /* find selected cipher suite in our list. */
6680 temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); 6861 temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
6681 if (temp < 0) { 6862 if (temp < 0) {
6682 » goto loser; » /* alert has been sent */ 6863 goto loser; /* alert has been sent */
6683 } 6864 }
6684 ssl3_config_match_init(ss); 6865 ssl3_config_match_init(ss);
6685 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { 6866 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
6686 » ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i]; 6867 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
6687 » if (temp == suite->cipher_suite) { 6868 if (temp == suite->cipher_suite) {
6688 » SSLVersionRange vrange = {ss->version, ss->version}; 6869 SSLVersionRange vrange = { ss->version, ss->version };
6689 » if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange, ss)) { 6870 if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange, ss)) {
6690 » » /* config_match already checks whether the cipher suite is 6871 /* config_match already checks whether the cipher suite is
6691 » » * acceptable for the version, but the check is repeated here 6872 * acceptable for the version, but the check is repeated here
6692 » » * in order to give a more precise error code. */ 6873 * in order to give a more precise error code. */
6693 » » if (!ssl3_CipherSuiteAllowedForVersionRange(temp, &vrange)) { 6874 if (!ssl3_CipherSuiteAllowedForVersionRange(temp, &vrange)) {
6694 » » desc = handshake_failure; 6875 desc = handshake_failure;
6695 » » errCode = SSL_ERROR_CIPHER_DISALLOWED_FOR_VERSION; 6876 errCode = SSL_ERROR_CIPHER_DISALLOWED_FOR_VERSION;
6696 » » goto alert_loser; 6877 goto alert_loser;
6697 » » } 6878 }
6698 6879
6699 » » break;» /* failure */ 6880 break; /* failure */
6700 » } 6881 }
6701 » 6882
6702 » suite_found = PR_TRUE; 6883 suite_found = PR_TRUE;
6703 » break;» /* success */ 6884 break; /* success */
6704 » } 6885 }
6705 } 6886 }
6706 if (!suite_found) { 6887 if (!suite_found) {
6707 » desc = handshake_failure; 6888 desc = handshake_failure;
6708 » errCode = SSL_ERROR_NO_CYPHER_OVERLAP; 6889 errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
6709 » goto alert_loser; 6890 goto alert_loser;
6710 } 6891 }
6711 ss->ssl3.hs.cipher_suite = (ssl3CipherSuite)temp; 6892 ss->ssl3.hs.cipher_suite = (ssl3CipherSuite)temp;
6712 ss->ssl3.hs.suite_def = ssl_LookupCipherSuiteDef((ssl3CipherSuite)temp); 6893 ss->ssl3.hs.suite_def = ssl_LookupCipherSuiteDef((ssl3CipherSuite)temp);
6713 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_cipher_suite; 6894 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_cipher_suite;
6714 PORT_Assert(ss->ssl3.hs.suite_def); 6895 PORT_Assert(ss->ssl3.hs.suite_def);
6715 if (!ss->ssl3.hs.suite_def) { 6896 if (!ss->ssl3.hs.suite_def) {
6716 » PORT_SetError(errCode = SEC_ERROR_LIBRARY_FAILURE); 6897 errCode = SEC_ERROR_LIBRARY_FAILURE;
6717 » goto loser;» /* we don't send alerts for our screw-ups. */ 6898 PORT_SetError(errCode);
6718 } 6899 goto loser; /* we don't send alerts for our screw-ups. */
6719 6900 }
6720 /* find selected compression method in our list. */ 6901
6721 temp = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length); 6902 ss->ssl3.hs.kea_def = &kea_defs[ss->ssl3.hs.suite_def->key_exchange_alg];
6722 if (temp < 0) { 6903
6723 » goto loser; » /* alert has been sent */ 6904 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
6724 } 6905 /* find selected compression method in our list. */
6725 suite_found = PR_FALSE; 6906 temp = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length);
6726 for (i = 0; i < compressionMethodsCount; i++) { 6907 if (temp < 0) {
6727 » if (temp == compressions[i]) { 6908 goto loser; /* alert has been sent */
6728 » if (!compressionEnabled(ss, compressions[i])) { 6909 }
6729 » » break;» /* failure */ 6910 suite_found = PR_FALSE;
6730 » } 6911 for (i = 0; i < compressionMethodsCount; i++) {
6731 » suite_found = PR_TRUE; 6912 if (temp == compressions[i]) {
6732 » break;» /* success */ 6913 if (!compressionEnabled(ss, compressions[i])) {
6733 » } 6914 break; /* failure */
6734 } 6915 }
6735 if (!suite_found) { 6916 suite_found = PR_TRUE;
6736 » desc = handshake_failure; 6917 break; /* success */
6737 » errCode = SSL_ERROR_NO_COMPRESSION_OVERLAP; 6918 }
6738 » goto alert_loser; 6919 }
6739 } 6920 if (!suite_found) {
6740 ss->ssl3.hs.compression = (SSLCompressionMethod)temp; 6921 desc = handshake_failure;
6922 errCode = SSL_ERROR_NO_COMPRESSION_OVERLAP;
6923 goto alert_loser;
6924 }
6925 ss->ssl3.hs.compression = (SSLCompressionMethod)temp;
6926 } else {
6927 ss->ssl3.hs.compression = ssl_compression_null;
6928 }
6741 6929
6742 /* Note that if !isTLS and the extra stuff is not extensions, we 6930 /* Note that if !isTLS and the extra stuff is not extensions, we
6743 * do NOT goto alert_loser. 6931 * do NOT goto alert_loser.
6744 * There are some old SSL 3.0 implementations that do send stuff 6932 * There are some old SSL 3.0 implementations that do send stuff
6745 * after the end of the server hello, and we deliberately ignore 6933 * after the end of the server hello, and we deliberately ignore
6746 * such stuff in the interest of maximal interoperability (being 6934 * such stuff in the interest of maximal interoperability (being
6747 * "generous in what you accept"). 6935 * "generous in what you accept").
6748 * Update: Starting in NSS 3.12.6, we handle the renegotiation_info 6936 * Update: Starting in NSS 3.12.6, we handle the renegotiation_info
6749 * extension in SSL 3.0. 6937 * extension in SSL 3.0.
6750 */ 6938 */
6751 if (length != 0) { 6939 if (length != 0) {
6752 » SECItem extensions; 6940 SECItem extensions;
6753 » rv = ssl3_ConsumeHandshakeVariable(ss, &extensions, 2, &b, &length); 6941 rv = ssl3_ConsumeHandshakeVariable(ss, &extensions, 2, &b, &length);
6754 » if (rv != SECSuccess || length != 0) { 6942 if (rv != SECSuccess || length != 0) {
6755 » if (isTLS) 6943 if (isTLS)
6756 » » goto alert_loser; 6944 goto alert_loser;
6757 » } else { 6945 } else {
6758 » rv = ssl3_HandleHelloExtensions(ss, &extensions.data, 6946 rv = ssl3_HandleHelloExtensions(ss, &extensions.data,
6759 » » » » » &extensions.len); 6947 &extensions.len, server_hello);
6760 » if (rv != SECSuccess) 6948 if (rv != SECSuccess)
6761 » » goto alert_loser; 6949 goto alert_loser;
6762 » } 6950 }
6763 } 6951 }
6764 if ((ss->opt.requireSafeNegotiation || 6952 if ((ss->opt.requireSafeNegotiation ||
6765 (ss->firstHsDone && (ss->peerRequestedProtection || 6953 (ss->firstHsDone && (ss->peerRequestedProtection ||
6766 » ss->opt.enableRenegotiation == SSL_RENEGOTIATE_REQUIRES_XTN))) && 6954 ss->opt.enableRenegotiation ==
6767 » !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { 6955 SSL_RENEGOTIATE_REQUIRES_XTN))) &&
6768 » desc = handshake_failure; 6956 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
6769 » errCode = ss->firstHsDone ? SSL_ERROR_RENEGOTIATION_NOT_ALLOWED 6957 desc = handshake_failure;
6770 » : SSL_ERROR_UNSAFE_NEGOTIATION; 6958 errCode = ss->firstHsDone ? SSL_ERROR_RENEGOTIATION_NOT_ALLOWED
6771 » goto alert_loser; 6959 : SSL_ERROR_UNSAFE_NEGOTIATION;
6960 goto alert_loser;
6772 } 6961 }
6773 6962
6774 /* Any errors after this point are not "malformed" errors. */ 6963 /* Any errors after this point are not "malformed" errors. */
6775 desc = handshake_failure; 6964 desc = handshake_failure;
6776 6965
6777 /* we need to call ssl3_SetupPendingCipherSpec here so we can check the 6966 /* we need to call ssl3_SetupPendingCipherSpec here so we can check the
6778 * key exchange algorithm. */ 6967 * key exchange algorithm. */
6779 rv = ssl3_SetupPendingCipherSpec(ss); 6968 rv = ssl3_SetupPendingCipherSpec(ss);
6780 if (rv != SECSuccess) { 6969 if (rv != SECSuccess) {
6781 » goto alert_loser;» /* error code is set. */ 6970 goto alert_loser; /* error code is set. */
6782 } 6971 }
6783 6972
6784 /* We may or may not have sent a session id, we may get one back or 6973 /* We may or may not have sent a session id, we may get one back or
6785 * not and if so it may match the one we sent. 6974 * not and if so it may match the one we sent.
6786 * Attempt to restore the master secret to see if this is so... 6975 * Attempt to restore the master secret to see if this is so...
6787 * Don't consider failure to find a matching SID an error. 6976 * Don't consider failure to find a matching SID an error.
6788 */ 6977 */
6789 sid_match = (PRBool)(sidBytes.len > 0 && 6978 sid_match = (PRBool)(sidBytes.len > 0 &&
6790 » sidBytes.len == sid->u.ssl3.sessionIDLength && 6979 sidBytes.len ==
6791 » !PORT_Memcmp(sid->u.ssl3.sessionID, sidBytes.data, sidBytes.len)); 6980 sid->u.ssl3.sessionIDLength &&
6981 !PORT_Memcmp(sid->u.ssl3.sessionID, sidBytes.data, sidB ytes.len));
6792 6982
6793 if (sid_match && 6983 if (sid_match &&
6794 » sid->version == ss->version && 6984 sid->version == ss->version &&
6795 » sid->u.ssl3.cipherSuite == ss->ssl3.hs.cipher_suite) do { 6985 sid->u.ssl3.cipherSuite == ss->ssl3.hs.cipher_suite)
6796 » ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec; 6986 do {
6987 ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec;
6797 6988
6798 » SECItem wrappedMS; /* wrapped master secret. */ 6989 SECItem wrappedMS; /* wrapped master secret. */
6799 6990
6800 /* [draft-ietf-tls-session-hash-06; Section 5.3] 6991 /* [draft-ietf-tls-session-hash-06; Section 5.3]
6801 * 6992 *
6802 * o If the original session did not use the "extended_master_secret" 6993 * o If the original session did not use the "extended_master_secre t"
6803 * extension but the new ServerHello contains the extension, the 6994 * extension but the new ServerHello contains the extension, the
6804 * client MUST abort the handshake. 6995 * client MUST abort the handshake.
6805 */ 6996 */
6806 if (!sid->u.ssl3.keys.extendedMasterSecretUsed && 6997 if (!sid->u.ssl3.keys.extendedMasterSecretUsed &&
6807 ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) { 6998 ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) {
6808 errCode = SSL_ERROR_UNEXPECTED_EXTENDED_MASTER_SECRET; 6999 errCode = SSL_ERROR_UNEXPECTED_EXTENDED_MASTER_SECRET;
6809 goto alert_loser; 7000 goto alert_loser;
6810 } 7001 }
6811 7002
6812 /* 7003 /*
6813 * o If the original session used an extended master secret but the n ew 7004 * o If the original session used an extended master secret but t he new
6814 * ServerHello does not contain the "extended_master_secret" 7005 * ServerHello does not contain the "extended_master_secret"
6815 * extension, the client SHOULD abort the handshake. 7006 * extension, the client SHOULD abort the handshake.
6816 * 7007 *
6817 * TODO(ekr@rtfm.com): Add option to refuse to resume when EMS is not 7008 * TODO(ekr@rtfm.com): Add option to refuse to resume when EMS is no t
6818 * used at all (bug 1176526). 7009 * used at all (bug 1176526).
6819 */ 7010 */
6820 if (sid->u.ssl3.keys.extendedMasterSecretUsed && 7011 if (sid->u.ssl3.keys.extendedMasterSecretUsed &&
6821 !ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) { 7012 !ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) {
6822 errCode = SSL_ERROR_MISSING_EXTENDED_MASTER_SECRET; 7013 errCode = SSL_ERROR_MISSING_EXTENDED_MASTER_SECRET;
6823 goto alert_loser; 7014 goto alert_loser;
6824 } 7015 }
6825 7016
6826 » ss->sec.authAlgorithm = sid->authAlgorithm; 7017 ss->sec.authAlgorithm = sid->authAlgorithm;
6827 » ss->sec.authKeyBits = sid->authKeyBits; 7018 ss->sec.authKeyBits = sid->authKeyBits;
6828 » ss->sec.keaType = sid->keaType; 7019 ss->sec.keaType = sid->keaType;
6829 » ss->sec.keaKeyBits = sid->keaKeyBits; 7020 ss->sec.keaKeyBits = sid->keaKeyBits;
6830 7021
6831 » /* 3 cases here: 7022 /* 3 cases here:
6832 » * a) key is wrapped (implies using PKCS11) 7023 * a) key is wrapped (implies using PKCS11)
6833 » * b) key is unwrapped, but we're still using PKCS11 7024 * b) key is unwrapped, but we're still using PKCS11
6834 » * c) key is unwrapped, and we're bypassing PKCS11. 7025 * c) key is unwrapped, and we're bypassing PKCS11.
6835 » */ 7026 */
6836 » if (sid->u.ssl3.keys.msIsWrapped) { 7027 if (sid->u.ssl3.keys.msIsWrapped) {
6837 » PK11SlotInfo *slot; 7028 PK11SlotInfo *slot;
6838 » PK11SymKey * wrapKey; /* wrapping key */ 7029 PK11SymKey *wrapKey; /* wrapping key */
6839 » CK_FLAGS keyFlags = 0; 7030 CK_FLAGS keyFlags = 0;
6840 7031
6841 #ifndef NO_PKCS11_BYPASS 7032 #ifndef NO_PKCS11_BYPASS
6842 » if (ss->opt.bypassPKCS11) { 7033 if (ss->opt.bypassPKCS11) {
6843 » » /* we cannot restart a non-bypass session in a 7034 /* we cannot restart a non-bypass session in a
6844 » » ** bypass socket. 7035 ** bypass socket.
6845 » » */ 7036 */
6846 » » break; 7037 break;
6847 » } 7038 }
6848 #endif 7039 #endif
6849 » /* unwrap master secret with PKCS11 */ 7040 /* unwrap master secret with PKCS11 */
6850 » slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID, 7041 slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
6851 » » » » sid->u.ssl3.masterSlotID); 7042 sid->u.ssl3.masterSlotID);
6852 » if (slot == NULL) { 7043 if (slot == NULL) {
6853 » » break;» » /* not considered an error. */ 7044 break; /* not considered an error. */
6854 » } 7045 }
6855 » if (!PK11_IsPresent(slot)) { 7046 if (!PK11_IsPresent(slot)) {
6856 » » PK11_FreeSlot(slot); 7047 PK11_FreeSlot(slot);
6857 » » break;» » /* not considered an error. */ 7048 break; /* not considered an error. */
6858 » } 7049 }
6859 » wrapKey = PK11_GetWrapKey(slot, sid->u.ssl3.masterWrapIndex, 7050 wrapKey = PK11_GetWrapKey(slot, sid->u.ssl3.masterWrapIndex,
6860 » » » » sid->u.ssl3.masterWrapMech, 7051 sid->u.ssl3.masterWrapMech,
6861 » » » » sid->u.ssl3.masterWrapSeries, 7052 sid->u.ssl3.masterWrapSeries,
6862 » » » » ss->pkcs11PinArg); 7053 ss->pkcs11PinArg);
6863 » PK11_FreeSlot(slot); 7054 PK11_FreeSlot(slot);
6864 » if (wrapKey == NULL) { 7055 if (wrapKey == NULL) {
6865 » » break;» » /* not considered an error. */ 7056 break; /* not considered an error. */
6866 » } 7057 }
6867 7058
6868 » if (ss->version > SSL_LIBRARY_VERSION_3_0) {» /* isTLS */ 7059 if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
6869 » » keyFlags = CKF_SIGN | CKF_VERIFY; 7060 keyFlags =
6870 » } 7061 CKF_SIGN | CKF_VERIFY;
7062 }
6871 7063
6872 » wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; 7064 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
6873 » wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; 7065 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len;
6874 » pwSpec->master_secret = 7066 pwSpec->master_secret =
6875 » » PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech, 7067 PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMe ch,
6876 » » » NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE, 7068 NULL, &wrappedMS, CKM_SSL3_MASTER _KEY_DERIVE,
6877 » » » CKA_DERIVE, sizeof(SSL3MasterSecret), keyFlags); 7069 CKA_DERIVE, sizeof(SSL3MasterSecr et), keyFlags);
6878 » errCode = PORT_GetError(); 7070 errCode = PORT_GetError();
6879 » PK11_FreeSymKey(wrapKey); 7071 PK11_FreeSymKey(wrapKey);
6880 » if (pwSpec->master_secret == NULL) { 7072 if (pwSpec->master_secret == NULL) {
6881 » » break;» /* errorCode set just after call to UnwrapSymKey. */ 7073 break; /* errorCode set just after call to UnwrapSymKey. */
6882 » } 7074 }
6883 #ifndef NO_PKCS11_BYPASS 7075 #ifndef NO_PKCS11_BYPASS
6884 » } else if (ss->opt.bypassPKCS11) { 7076 } else if (ss->opt.bypassPKCS11) {
6885 » /* MS is not wrapped */ 7077 /* MS is not wrapped */
6886 » wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; 7078 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
6887 » wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; 7079 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len;
6888 » memcpy(pwSpec->raw_master_secret, wrappedMS.data, wrappedMS.len); 7080 memcpy(pwSpec->raw_master_secret, wrappedMS.data, wrappedMS.len) ;
6889 » pwSpec->msItem.data = pwSpec->raw_master_secret; 7081 pwSpec->msItem.data = pwSpec->raw_master_secret;
6890 » pwSpec->msItem.len = wrappedMS.len; 7082 pwSpec->msItem.len = wrappedMS.len;
6891 #endif 7083 #endif
6892 » } else { 7084 } else {
6893 » /* We CAN restart a bypass session in a non-bypass socket. */ 7085 /* We CAN restart a bypass session in a non-bypass socket. */
6894 » /* need to import the raw master secret to session object */ 7086 /* need to import the raw master secret to session object */
6895 » PK11SlotInfo *slot = PK11_GetInternalSlot(); 7087 PK11SlotInfo *slot = PK11_GetInternalSlot();
6896 » wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; 7088 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
6897 » wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; 7089 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len;
6898 » pwSpec->master_secret = 7090 pwSpec->master_secret =
6899 » » PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE, 7091 PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE,
6900 » » » » PK11_OriginUnwrap, CKA_ENCRYPT, 7092 PK11_OriginUnwrap, CKA_ENCRYPT,
6901 » » » » &wrappedMS, NULL); 7093 &wrappedMS, NULL);
6902 » PK11_FreeSlot(slot); 7094 PK11_FreeSlot(slot);
6903 » if (pwSpec->master_secret == NULL) { 7095 if (pwSpec->master_secret == NULL) {
6904 » » break; 7096 break;
6905 » } 7097 }
6906 » } 7098 }
6907 7099
6908 » /* Got a Match */ 7100 /* Got a Match */
6909 » SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_hits ); 7101 SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_hits);
6910 7102
6911 » /* If we sent a session ticket, then this is a stateless resume. */ 7103 /* If we sent a session ticket, then this is a stateless resume. */
6912 » if (ss->xtnData.sentSessionTicketInClientHello) 7104 if (ss->xtnData.sentSessionTicketInClientHello)
6913 » SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_stateless_resumes ); 7105 SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_stateless_resumes);
6914 7106
6915 » if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn)) 7107 if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn))
6916 » ss->ssl3.hs.ws = wait_new_session_ticket; 7108 ss->ssl3.hs.ws = wait_new_session_ticket;
6917 » else 7109 else
6918 » ss->ssl3.hs.ws = wait_change_cipher; 7110 ss->ssl3.hs.ws = wait_change_cipher;
6919 7111
6920 » ss->ssl3.hs.isResuming = PR_TRUE; 7112 ss->ssl3.hs.isResuming = PR_TRUE;
6921 7113
6922 » /* copy the peer cert from the SID */ 7114 /* copy the peer cert from the SID */
6923 » if (sid->peerCert != NULL) { 7115 if (sid->peerCert != NULL) {
6924 » ss->sec.peerCert = CERT_DupCertificate(sid->peerCert); 7116 ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
6925 » ssl3_CopyPeerCertsFromSID(ss, sid); 7117 ssl3_CopyPeerCertsFromSID(ss, sid);
6926 » } 7118 }
6927 7119
6928 » /* NULL value for PMS because we are reusing the old MS */ 7120 /* NULL value for PMS because we are reusing the old MS */
6929 » rv = ssl3_InitPendingCipherSpec(ss, NULL); 7121 rv = ssl3_InitPendingCipherSpec(ss, NULL);
6930 » if (rv != SECSuccess) { 7122 if (rv != SECSuccess) {
6931 » goto alert_loser;» /* err code was set */ 7123 goto alert_loser; /* err code was set */
6932 » } 7124 }
6933 » goto winner; 7125 goto winner;
6934 } while (0); 7126 } while (0);
6935 7127
6936 if (sid_match) 7128 if (sid_match)
6937 » SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_not_ok ); 7129 SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_not_ok);
6938 else 7130 else
6939 » SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_misses ); 7131 SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_misses);
6940 7132
6941 /* throw the old one away */ 7133 /* throw the old one away */
6942 sid->u.ssl3.keys.resumable = PR_FALSE; 7134 sid->u.ssl3.keys.resumable = PR_FALSE;
6943 if (ss->sec.uncache) 7135 if (ss->sec.uncache)
6944 (*ss->sec.uncache)(sid); 7136 (*ss->sec.uncache)(sid);
6945 ssl_FreeSID(sid); 7137 ssl_FreeSID(sid);
6946 7138
6947 /* get a new sid */ 7139 /* get a new sid */
6948 ss->sec.ci.sid = sid = ssl3_NewSessionID(ss, PR_FALSE); 7140 ss->sec.ci.sid = sid = ssl3_NewSessionID(ss, PR_FALSE);
6949 if (sid == NULL) { 7141 if (sid == NULL) {
6950 » goto alert_loser;» /* memory error is set. */ 7142 goto alert_loser; /* memory error is set. */
6951 } 7143 }
6952 7144
6953 sid->version = ss->version; 7145 sid->version = ss->version;
6954 sid->u.ssl3.sessionIDLength = sidBytes.len; 7146 sid->u.ssl3.sessionIDLength = sidBytes.len;
6955 PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data, sidBytes.len); 7147 PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data, sidBytes.len);
6956 7148
6957 sid->u.ssl3.keys.extendedMasterSecretUsed = 7149 sid->u.ssl3.keys.extendedMasterSecretUsed =
6958 ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn); 7150 ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn);
6959 7151
6960 /* Copy Signed Certificate Timestamps, if any. */ 7152 /* Copy Signed Certificate Timestamps, if any. */
6961 if (ss->xtnData.signedCertTimestamps.data) { 7153 if (ss->xtnData.signedCertTimestamps.data) {
6962 » rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.signedCertTimestamps, 7154 rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.signedCertTimestamps,
6963 » » » &ss->xtnData.signedCertTimestamps); 7155 &ss->xtnData.signedCertTimestamps);
6964 » if (rv != SECSuccess) 7156 if (rv != SECSuccess)
6965 » goto loser; 7157 goto loser;
7158 /* Clean up the temporary pointer to the handshake buffer. */
7159 ss->xtnData.signedCertTimestamps.data = NULL;
7160 ss->xtnData.signedCertTimestamps.len = 0;
6966 } 7161 }
6967 7162
6968 ss->ssl3.hs.isResuming = PR_FALSE; 7163 ss->ssl3.hs.isResuming = PR_FALSE;
6969 if (ss->ssl3.hs.kea_def->signKeyType != sign_null) { 7164 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
6970 /* All current cipher suites other than those with sign_null (i.e., 7165 rv = tls13_HandleServerKeyShare(ss);
7166 if (rv != SECSuccess)
7167 goto alert_loser;
7168 TLS13_SET_HS_STATE(ss, wait_encrypted_extensions);
7169 } else if (ss->ssl3.hs.kea_def->signKeyType != ssl_sign_null) {
7170 /* All current cipher suites other than those with ssl_sign_null (i.e.,
6971 * (EC)DH_anon_* suites) require a certificate, so use that signal. */ 7171 * (EC)DH_anon_* suites) require a certificate, so use that signal. */
6972 ss->ssl3.hs.ws = wait_server_cert; 7172 ss->ssl3.hs.ws = wait_server_cert;
6973 } else { 7173 } else {
6974 /* All the remaining cipher suites must be (EC)DH_anon_* and so 7174 /* All the remaining cipher suites must be (EC)DH_anon_* and so
6975 * must be ephemeral. Note, if we ever add PSK this might 7175 * must be ephemeral. Note, if we ever add PSK this might
6976 * change. */ 7176 * change. */
6977 PORT_Assert(ss->ssl3.hs.kea_def->ephemeral); 7177 PORT_Assert(ss->ssl3.hs.kea_def->ephemeral);
6978 ss->ssl3.hs.ws = wait_server_key; 7178 ss->ssl3.hs.ws = wait_server_key;
6979 } 7179 }
6980 7180
6981 winner: 7181 winner:
6982 /* Clean up the temporary pointer to the handshake buffer. */
6983 ss->xtnData.signedCertTimestamps.data = NULL;
6984 ss->xtnData.signedCertTimestamps.len = 0;
6985
6986 /* If we will need a ChannelID key then we make the callback now. This 7182 /* If we will need a ChannelID key then we make the callback now. This
6987 * allows the handshake to be restarted cleanly if the callback returns 7183 * allows the handshake to be restarted cleanly if the callback returns
6988 * SECWouldBlock. */ 7184 * SECWouldBlock. */
6989 if (ssl3_ExtensionNegotiated(ss, ssl_channel_id_xtn)) { 7185 if (ssl3_ExtensionNegotiated(ss, ssl_channel_id_xtn)) {
6990 » rv = ss->getChannelID(ss->getChannelIDArg, ss->fd, 7186 rv = ss->getChannelID(ss->getChannelIDArg, ss->fd,
6991 » » » &ss->ssl3.channelIDPub, &ss->ssl3.channelID); 7187 &ss->ssl3.channelIDPub, &ss->ssl3.channelID);
6992 » if (rv == SECWouldBlock) { 7188 if (rv == SECWouldBlock) {
6993 » ssl3_SetAlwaysBlock(ss); 7189 ssl3_SetAlwaysBlock(ss);
6994 » return rv; 7190 return rv;
6995 » } 7191 }
6996 » if (rv != SECSuccess || 7192 if (rv != SECSuccess ||
6997 » ss->ssl3.channelIDPub == NULL || 7193 ss->ssl3.channelIDPub == NULL ||
6998 » ss->ssl3.channelID == NULL) { 7194 ss->ssl3.channelID == NULL) {
6999 » PORT_SetError(SSL_ERROR_GET_CHANNEL_ID_FAILED); 7195 PORT_SetError(SSL_ERROR_GET_CHANNEL_ID_FAILED);
7000 » desc = internal_error; 7196 desc = internal_error;
7001 » goto alert_loser; 7197 goto alert_loser;
7002 » } 7198 }
7003 } 7199 }
7004 7200
7005 return SECSuccess; 7201 return SECSuccess;
7006 7202
7007 alert_loser: 7203 alert_loser:
7008 (void)SSL3_SendAlert(ss, alert_fatal, desc); 7204 (void)SSL3_SendAlert(ss, alert_fatal, desc);
7009 7205
7010 loser: 7206 loser:
7011 /* Clean up the temporary pointer to the handshake buffer. */ 7207 /* Clean up the temporary pointer to the handshake buffer. */
7012 ss->xtnData.signedCertTimestamps.data = NULL; 7208 ss->xtnData.signedCertTimestamps.data = NULL;
7013 ss->xtnData.signedCertTimestamps.len = 0; 7209 ss->xtnData.signedCertTimestamps.len = 0;
7014 errCode = ssl_MapLowLevelError(errCode); 7210 ssl_MapLowLevelError(errCode);
7015 return SECFailure; 7211 return SECFailure;
7016 } 7212 }
7017 7213
7018 7214 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered a
7019 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete 7215 * complete ssl3 ServerKeyExchange message.
7020 * ssl3 ServerKeyExchange message.
7021 * Caller must hold Handshake and RecvBuf locks. 7216 * Caller must hold Handshake and RecvBuf locks.
7022 */ 7217 */
7023 static SECStatus 7218 static SECStatus
7024 ssl3_HandleServerKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length) 7219 ssl3_HandleServerKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
7025 { 7220 {
7026 PLArenaPool * arena = NULL; 7221 PLArenaPool *arena = NULL;
7027 SECKEYPublicKey *peerKey = NULL; 7222 SECKEYPublicKey *peerKey = NULL;
7028 PRBool isTLS, isTLS12; 7223 PRBool isTLS, isTLS12;
7029 SECStatus rv; 7224 SECStatus rv;
7030 int errCode = SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH; 7225 int errCode = SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH;
7031 SSL3AlertDescription desc = illegal_parameter; 7226 SSL3AlertDescription desc = illegal_parameter;
7032 SSL3Hashes hashes; 7227 SSL3Hashes hashes;
7033 SECItem signature = {siBuffer, NULL, 0}; 7228 SECItem signature = { siBuffer, NULL, 0 };
7034 SSLSignatureAndHashAlg sigAndHash; 7229 SSLSignatureAndHashAlg sigAndHash;
7035 7230
7036 sigAndHash.hashAlg = ssl_hash_none; 7231 sigAndHash.hashAlg = ssl_hash_none;
7037 7232
7038 SSL_TRC(3, ("%d: SSL3[%d]: handle server_key_exchange handshake", 7233 SSL_TRC(3, ("%d: SSL3[%d]: handle server_key_exchange handshake",
7039 » » SSL_GETPID(), ss->fd)); 7234 SSL_GETPID(), ss->fd));
7040 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 7235 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
7041 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 7236 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7042 7237
7043 if (ss->ssl3.hs.ws != wait_server_key) { 7238 if (ss->ssl3.hs.ws != wait_server_key) {
7044 errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH; 7239 errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH;
7045 desc = unexpected_message; 7240 desc = unexpected_message;
7046 goto alert_loser; 7241 goto alert_loser;
7047 } 7242 }
7048 7243
7049 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0); 7244 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
7050 isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); 7245 isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
7051 7246
7052 switch (ss->ssl3.hs.kea_def->exchKeyType) { 7247 switch (ss->ssl3.hs.kea_def->exchKeyType) {
7053 7248
7054 case kt_rsa: { 7249 case kt_rsa: {
7055 » SECItem modulus = {siBuffer, NULL, 0}; 7250 SECItem modulus = { siBuffer, NULL, 0 };
7056 » SECItem exponent = {siBuffer, NULL, 0}; 7251 SECItem exponent = { siBuffer, NULL, 0 };
7057 7252
7058 » rv = ssl3_ConsumeHandshakeVariable(ss, &modulus, 2, &b, &length); 7253 rv = ssl3_ConsumeHandshakeVariable(ss, &modulus, 2, &b, &length);
7059 » if (rv != SECSuccess) { 7254 if (rv != SECSuccess) {
7060 » goto loser;»» /* malformed. */ 7255 goto loser; /* malformed. */
7061 » } 7256 }
7062 /* This exchange method is only used by export cipher suites. 7257 /* This exchange method is only used by export cipher suites.
7063 * Those are broken and so this code will eventually be removed. */ 7258 * Those are broken and so this code will eventually be removed. */
7064 if (SECKEY_BigIntegerBitLength(&modulus) < 512) { 7259 if (SECKEY_BigIntegerBitLength(&modulus) < 512) {
7065 desc = isTLS ? insufficient_security : illegal_parameter; 7260 desc = isTLS ? insufficient_security : illegal_parameter;
7066 goto alert_loser; 7261 goto alert_loser;
7262 }
7263 rv = ssl3_ConsumeHandshakeVariable(ss, &exponent, 2, &b, &length);
7264 if (rv != SECSuccess) {
7265 goto loser; /* malformed. */
7266 }
7267 if (isTLS12) {
7268 rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length,
7269 &sigAndHash);
7270 if (rv != SECSuccess) {
7271 goto loser; /* malformed or unsupported. */
7272 }
7273 rv = ssl3_CheckSignatureAndHashAlgorithmConsistency(ss,
7274 &sigAndHash, ss->sec.peerCert);
7275 if (rv != SECSuccess) {
7276 goto loser;
7277 }
7278 }
7279 rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length);
7280 if (rv != SECSuccess) {
7281 goto loser; /* malformed. */
7282 }
7283 if (length != 0) {
7284 if (isTLS)
7285 desc =
7286 decode_error;
7287 goto alert_loser; /* malformed. */
7288 }
7289
7290 /* failures after this point are not malformed handshakes. */
7291 /* TLS: send decrypt_error if signature failed. */
7292 desc = isTLS ? decrypt_error : handshake_failure;
7293
7294 /*
7295 * check to make sure the hash is signed by right guy
7296 */
7297 rv = ssl3_ComputeExportRSAKeyHash(sigAndHash.hashAlg, modulus, expon ent,
7298 &ss->ssl3.hs.client_random,
7299 &ss->ssl3.hs.server_random,
7300 &hashes, ss->opt.bypassPKCS11);
7301 if (rv != SECSuccess) {
7302 errCode =
7303 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
7304 goto alert_loser;
7305 }
7306 rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature,
7307 isTLS, ss->pkcs11PinArg);
7308 if (rv != SECSuccess) {
7309 errCode =
7310 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
7311 goto alert_loser;
7312 }
7313
7314 /*
7315 * we really need to build a new key here because we can no longer
7316 * ignore calling SECKEY_DestroyPublicKey. Using the key may allocat e
7317 * pkcs11 slots and ID's.
7318 */
7319 arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
7320 if (arena == NULL) {
7321 goto no_memory;
7322 }
7323
7324 peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey);
7325 if (peerKey == NULL) {
7326 goto no_memory;
7327 }
7328
7329 peerKey->arena = arena;
7330 peerKey->keyType = rsaKey;
7331 peerKey->pkcs11Slot = NULL;
7332 peerKey->pkcs11ID = CK_INVALID_HANDLE;
7333 if (SECITEM_CopyItem(arena, &peerKey->u.rsa.modulus, &modulus) ||
7334 SECITEM_CopyItem(arena, &peerKey->u.rsa.publicExponent, &exponen t)) {
7335 goto no_memory;
7336 }
7337 ss->sec.peerKey = peerKey;
7338 ss->ssl3.hs.ws = wait_cert_request;
7339 return SECSuccess;
7067 } 7340 }
7068 » rv = ssl3_ConsumeHandshakeVariable(ss, &exponent, 2, &b, &length); 7341
7069 » if (rv != SECSuccess) { 7342 case kt_dh: {
7070 » goto loser;»» /* malformed. */ 7343 SECItem dh_p = { siBuffer, NULL, 0 };
7071 » } 7344 SECItem dh_g = { siBuffer, NULL, 0 };
7072 » if (isTLS12) { 7345 SECItem dh_Ys = { siBuffer, NULL, 0 };
7073 » rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length, 7346 unsigned dh_p_bits;
7074 » » » » » » &sigAndHash); 7347 unsigned dh_g_bits;
7075 » if (rv != SECSuccess) { 7348 unsigned dh_Ys_bits;
7076 » » goto loser;» /* malformed or unsupported. */ 7349 PRInt32 minDH;
7077 » } 7350
7078 » rv = ssl3_CheckSignatureAndHashAlgorithmConsistency(ss, 7351 rv = ssl3_ConsumeHandshakeVariable(ss, &dh_p, 2, &b, &length);
7079 » » &sigAndHash, ss->sec.peerCert); 7352 if (rv != SECSuccess) {
7080 » if (rv != SECSuccess) { 7353 goto loser; /* malformed. */
7081 » » goto loser; 7354 }
7082 » } 7355
7083 » } 7356 rv = NSS_OptionGet(NSS_DH_MIN_KEY_SIZE, &minDH);
7084 » rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length); 7357 if (rv != SECSuccess) {
7085 » if (rv != SECSuccess) { 7358 minDH = SSL_DH_MIN_P_BITS;
7086 » goto loser;»» /* malformed. */ 7359 }
7087 » } 7360 dh_p_bits = SECKEY_BigIntegerBitLength(&dh_p);
7088 » if (length != 0) { 7361 if (dh_p_bits < minDH) {
7089 » if (isTLS) 7362 errCode = SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY;
7090 » » desc = decode_error; 7363 goto alert_loser;
7091 » goto alert_loser;» » /* malformed. */ 7364 }
7092 » } 7365 rv = ssl3_ConsumeHandshakeVariable(ss, &dh_g, 2, &b, &length);
7093 7366 if (rv != SECSuccess) {
7094 » /* failures after this point are not malformed handshakes. */ 7367 goto loser; /* malformed. */
7095 » /* TLS: send decrypt_error if signature failed. */ 7368 }
7096 » desc = isTLS ? decrypt_error : handshake_failure; 7369 /* Abort if dh_g is 0, 1, or obviously too big. */
7097 7370 dh_g_bits = SECKEY_BigIntegerBitLength(&dh_g);
7098 » /* 7371 if (dh_g_bits > dh_p_bits || dh_g_bits <= 1)
7099 » * check to make sure the hash is signed by right guy 7372 goto alert_loser;
7100 » */ 7373 rv = ssl3_ConsumeHandshakeVariable(ss, &dh_Ys, 2, &b, &length);
7101 rv = ssl3_ComputeExportRSAKeyHash(sigAndHash.hashAlg, modulus, exponent, 7374 if (rv != SECSuccess) {
7102 &ss->ssl3.hs.client_random, 7375 goto loser; /* malformed. */
7103 &ss->ssl3.hs.server_random, 7376 }
7104 &hashes, ss->opt.bypassPKCS11); 7377 dh_Ys_bits = SECKEY_BigIntegerBitLength(&dh_Ys);
7105 if (rv != SECSuccess) { 7378 if (dh_Ys_bits > dh_p_bits || dh_Ys_bits <= 1)
7106 » errCode = 7379 goto alert_loser;
7107 » » ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); 7380 if (isTLS12) {
7108 » goto alert_loser; 7381 rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length,
7109 » } 7382 &sigAndHash);
7110 rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature, 7383 if (rv != SECSuccess) {
7111 » » » » isTLS, ss->pkcs11PinArg); 7384 goto loser; /* malformed or unsupported. */
7112 » if (rv != SECSuccess) { 7385 }
7113 » errCode = 7386 rv = ssl3_CheckSignatureAndHashAlgorithmConsistency(ss,
7114 » » ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); 7387 &sigAndHash, ss->sec.peerCert);
7115 » goto alert_loser; 7388 if (rv != SECSuccess) {
7116 » } 7389 goto loser;
7117 7390 }
7118 » /* 7391 }
7119 » * we really need to build a new key here because we can no longer 7392 rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length);
7120 » * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate 7393 if (rv != SECSuccess) {
7121 » * pkcs11 slots and ID's. 7394 goto loser; /* malformed. */
7122 » */ 7395 }
7123 » arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); 7396 if (length != 0) {
7124 » if (arena == NULL) { 7397 if (isTLS)
7125 » goto no_memory; 7398 desc =
7126 » } 7399 decode_error;
7127 7400 goto alert_loser; /* malformed. */
7128 » peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey); 7401 }
7129 » if (peerKey == NULL) { 7402
7130 » goto no_memory; 7403 PRINT_BUF(60, (NULL, "Server DH p", dh_p.data, dh_p.len));
7131 » } 7404 PRINT_BUF(60, (NULL, "Server DH g", dh_g.data, dh_g.len));
7132 7405 PRINT_BUF(60, (NULL, "Server DH Ys", dh_Ys.data, dh_Ys.len));
7133 » peerKey->arena = arena; 7406
7134 » peerKey->keyType = rsaKey; 7407 /* failures after this point are not malformed handshakes. */
7135 » peerKey->pkcs11Slot = NULL; 7408 /* TLS: send decrypt_error if signature failed. */
7136 » peerKey->pkcs11ID = CK_INVALID_HANDLE; 7409 desc = isTLS ? decrypt_error : handshake_failure;
7137 » if (SECITEM_CopyItem(arena, &peerKey->u.rsa.modulus, &modulus) || 7410
7138 » SECITEM_CopyItem(arena, &peerKey->u.rsa.publicExponent, &exponent)) 7411 /*
7139 » { 7412 * check to make sure the hash is signed by right guy
7140 » goto no_memory; 7413 */
7414 rv = ssl3_ComputeDHKeyHash(sigAndHash.hashAlg, dh_p, dh_g, dh_Ys,
7415 &ss->ssl3.hs.client_random,
7416 &ss->ssl3.hs.server_random,
7417 &hashes, ss->opt.bypassPKCS11);
7418 if (rv != SECSuccess) {
7419 errCode =
7420 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
7421 goto alert_loser;
7422 }
7423 rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature,
7424 isTLS, ss->pkcs11PinArg);
7425 if (rv != SECSuccess) {
7426 errCode =
7427 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
7428 goto alert_loser;
7429 }
7430
7431 /*
7432 * we really need to build a new key here because we can no longer
7433 * ignore calling SECKEY_DestroyPublicKey. Using the key may allocat e
7434 * pkcs11 slots and ID's.
7435 */
7436 arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
7437 if (arena == NULL) {
7438 goto no_memory;
7439 }
7440
7441 peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey);
7442 if (peerKey == NULL) {
7443 goto no_memory;
7444 }
7445
7446 peerKey->arena = arena;
7447 peerKey->keyType = dhKey;
7448 peerKey->pkcs11Slot = NULL;
7449 peerKey->pkcs11ID = CK_INVALID_HANDLE;
7450
7451 if (SECITEM_CopyItem(arena, &peerKey->u.dh.prime, &dh_p) ||
7452 SECITEM_CopyItem(arena, &peerKey->u.dh.base, &dh_g) ||
7453 SECITEM_CopyItem(arena, &peerKey->u.dh.publicValue, &dh_Ys)) {
7454 goto no_memory;
7455 }
7456 ss->sec.peerKey = peerKey;
7457 ss->ssl3.hs.ws = wait_cert_request;
7458 return SECSuccess;
7141 } 7459 }
7142 » ss->sec.peerKey = peerKey; 7460
7143 » ss->ssl3.hs.ws = wait_cert_request; 7461 #ifndef NSS_DISABLE_ECC
7144 » return SECSuccess; 7462 case kt_ecdh:
7463 rv = ssl3_HandleECDHServerKeyExchange(ss, b, length);
7464 return rv;
7465 #endif /* NSS_DISABLE_ECC */
7466
7467 default:
7468 desc = handshake_failure;
7469 errCode = SEC_ERROR_UNSUPPORTED_KEYALG;
7470 break; /* goto alert_loser; */
7145 } 7471 }
7146 7472
7147 case kt_dh: {
7148 SECItem dh_p = {siBuffer, NULL, 0};
7149 SECItem dh_g = {siBuffer, NULL, 0};
7150 SECItem dh_Ys = {siBuffer, NULL, 0};
7151 unsigned dh_p_bits;
7152 unsigned dh_g_bits;
7153 unsigned dh_Ys_bits;
7154 PRInt32 minDH;
7155
7156 rv = ssl3_ConsumeHandshakeVariable(ss, &dh_p, 2, &b, &length);
7157 if (rv != SECSuccess) {
7158 goto loser; /* malformed. */
7159 }
7160
7161 rv = NSS_OptionGet(NSS_DH_MIN_KEY_SIZE, &minDH);
7162 if (rv != SECSuccess) {
7163 minDH = SSL_DH_MIN_P_BITS;
7164 }
7165 dh_p_bits = SECKEY_BigIntegerBitLength(&dh_p);
7166 if (dh_p_bits < minDH) {
7167 errCode = SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY;
7168 goto alert_loser;
7169 }
7170 rv = ssl3_ConsumeHandshakeVariable(ss, &dh_g, 2, &b, &length);
7171 if (rv != SECSuccess) {
7172 goto loser; /* malformed. */
7173 }
7174 /* Abort if dh_g is 0, 1, or obviously too big. */
7175 dh_g_bits = SECKEY_BigIntegerBitLength(&dh_g);
7176 if (dh_g_bits > dh_p_bits || dh_g_bits <= 1)
7177 goto alert_loser;
7178 rv = ssl3_ConsumeHandshakeVariable(ss, &dh_Ys, 2, &b, &length);
7179 if (rv != SECSuccess) {
7180 goto loser; /* malformed. */
7181 }
7182 dh_Ys_bits = SECKEY_BigIntegerBitLength(&dh_Ys);
7183 if (dh_Ys_bits > dh_p_bits || dh_Ys_bits <= 1)
7184 goto alert_loser;
7185 if (isTLS12) {
7186 rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length,
7187 &sigAndHash);
7188 if (rv != SECSuccess) {
7189 goto loser; /* malformed or unsupported. */
7190 }
7191 rv = ssl3_CheckSignatureAndHashAlgorithmConsistency(ss,
7192 &sigAndHash, ss->sec.peerCert);
7193 if (rv != SECSuccess) {
7194 goto loser;
7195 }
7196 }
7197 rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length);
7198 if (rv != SECSuccess) {
7199 goto loser; /* malformed. */
7200 }
7201 if (length != 0) {
7202 if (isTLS)
7203 desc = decode_error;
7204 goto alert_loser; /* malformed. */
7205 }
7206
7207 PRINT_BUF(60, (NULL, "Server DH p", dh_p.data, dh_p.len));
7208 PRINT_BUF(60, (NULL, "Server DH g", dh_g.data, dh_g.len));
7209 PRINT_BUF(60, (NULL, "Server DH Ys", dh_Ys.data, dh_Ys.len));
7210
7211 /* failures after this point are not malformed handshakes. */
7212 /* TLS: send decrypt_error if signature failed. */
7213 desc = isTLS ? decrypt_error : handshake_failure;
7214
7215 /*
7216 * check to make sure the hash is signed by right guy
7217 */
7218 rv = ssl3_ComputeDHKeyHash(sigAndHash.hashAlg, dh_p, dh_g, dh_Ys,
7219 &ss->ssl3.hs.client_random,
7220 &ss->ssl3.hs.server_random,
7221 &hashes, ss->opt.bypassPKCS11);
7222 if (rv != SECSuccess) {
7223 errCode =
7224 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
7225 goto alert_loser;
7226 }
7227 rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature,
7228 isTLS, ss->pkcs11PinArg);
7229 if (rv != SECSuccess) {
7230 errCode =
7231 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
7232 goto alert_loser;
7233 }
7234
7235 /*
7236 * we really need to build a new key here because we can no longer
7237 * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate
7238 * pkcs11 slots and ID's.
7239 */
7240 arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
7241 if (arena == NULL) {
7242 goto no_memory;
7243 }
7244
7245 peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey);
7246 if (peerKey == NULL) {
7247 goto no_memory;
7248 }
7249
7250 peerKey->arena = arena;
7251 peerKey->keyType = dhKey;
7252 peerKey->pkcs11Slot = NULL;
7253 peerKey->pkcs11ID = CK_INVALID_HANDLE;
7254
7255 if (SECITEM_CopyItem(arena, &peerKey->u.dh.prime, &dh_p) ||
7256 SECITEM_CopyItem(arena, &peerKey->u.dh.base, &dh_g) ||
7257 SECITEM_CopyItem(arena, &peerKey->u.dh.publicValue, &dh_Ys))
7258 {
7259 goto no_memory;
7260 }
7261 ss->sec.peerKey = peerKey;
7262 ss->ssl3.hs.ws = wait_cert_request;
7263 return SECSuccess;
7264 }
7265
7266 #ifndef NSS_DISABLE_ECC
7267 case kt_ecdh:
7268 rv = ssl3_HandleECDHServerKeyExchange(ss, b, length);
7269 return rv;
7270 #endif /* NSS_DISABLE_ECC */
7271
7272 default:
7273 desc = handshake_failure;
7274 errCode = SEC_ERROR_UNSUPPORTED_KEYALG;
7275 break; /* goto alert_loser; */
7276 }
7277
7278 alert_loser: 7473 alert_loser:
7279 (void)SSL3_SendAlert(ss, alert_fatal, desc); 7474 (void)SSL3_SendAlert(ss, alert_fatal, desc);
7280 loser: 7475 loser:
7281 if (arena) { 7476 if (arena) {
7282 PORT_FreeArena(arena, PR_FALSE); 7477 PORT_FreeArena(arena, PR_FALSE);
7283 } 7478 }
7284 PORT_SetError( errCode ); 7479 PORT_SetError(errCode);
7285 return SECFailure; 7480 return SECFailure;
7286 7481
7287 no_memory:» /* no-memory error has already been set. */ 7482 no_memory: /* no-memory error has already been set. */
7288 if (arena) { 7483 if (arena) {
7289 PORT_FreeArena(arena, PR_FALSE); 7484 PORT_FreeArena(arena, PR_FALSE);
7290 } 7485 }
7291 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); 7486 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
7292 return SECFailure; 7487 return SECFailure;
7293 } 7488 }
7294 7489
7295 /* 7490 /*
7296 * Returns the TLS signature algorithm for the client authentication key and 7491 * Returns the TLS signature algorithm for the client authentication key and
7297 * whether it is an RSA or DSA key that may be able to sign only SHA-1 hashes. 7492 * whether it is an RSA or DSA key that may be able to sign only SHA-1 hashes.
7298 */ 7493 */
7299 static SECStatus 7494 static SECStatus
7300 ssl3_ExtractClientKeyInfo(sslSocket *ss, 7495 ssl3_ExtractClientKeyInfo(sslSocket *ss,
7301 » » » SSLSignType *sigAlg, 7496 SSLSignType *sigAlg,
7302 » » » PRBool *preferSha1) 7497 PRBool *preferSha1)
7303 { 7498 {
7304 SECStatus rv = SECSuccess; 7499 SECStatus rv = SECSuccess;
7305 SECKEYPublicKey *pubk; 7500 SECKEYPublicKey *pubk;
7306 7501
7307 pubk = CERT_ExtractPublicKey(ss->ssl3.clientCertificate); 7502 pubk = CERT_ExtractPublicKey(ss->ssl3.clientCertificate);
7308 if (pubk == NULL) { 7503 if (pubk == NULL) {
7309 » rv = SECFailure; 7504 rv = SECFailure;
7310 » goto done; 7505 goto done;
7311 } 7506 }
7312 7507
7313 rv = ssl3_TLSSignatureAlgorithmForKeyType(pubk->keyType, sigAlg); 7508 rv = ssl3_TLSSignatureAlgorithmForKeyType(pubk->keyType, sigAlg);
7314 if (rv != SECSuccess) { 7509 if (rv != SECSuccess) {
7315 » goto done; 7510 goto done;
7316 } 7511 }
7317 7512
7318 #if defined(NSS_PLATFORM_CLIENT_AUTH) && defined(_WIN32)
7319 /* If the key is in CAPI, assume conservatively that the CAPI service
7320 * provider may be unable to sign SHA-256 hashes.
7321 */
7322 if (ss->ssl3.platformClientKey->dwKeySpec != CERT_NCRYPT_KEY_SPEC) {
7323 /* CAPI only supports RSA and DSA signatures, so we don't need to
7324 * check the key type. */
7325 *preferSha1 = PR_TRUE;
7326 goto done;
7327 }
7328 #endif /* NSS_PLATFORM_CLIENT_AUTH && _WIN32 */
7329
7330 /* If the key is a 1024-bit RSA or DSA key, assume conservatively that 7513 /* If the key is a 1024-bit RSA or DSA key, assume conservatively that
7331 * it may be unable to sign SHA-256 hashes. This is the case for older 7514 * it may be unable to sign SHA-256 hashes. This is the case for older
7332 * Estonian ID cards that have 1024-bit RSA keys. In FIPS 186-2 and 7515 * Estonian ID cards that have 1024-bit RSA keys. In FIPS 186-2 and
7333 * older, DSA key size is at most 1024 bits and the hash function must 7516 * older, DSA key size is at most 1024 bits and the hash function must
7334 * be SHA-1. 7517 * be SHA-1.
7335 */ 7518 */
7336 if (pubk->keyType == rsaKey || pubk->keyType == dsaKey) { 7519 if (pubk->keyType == rsaKey || pubk->keyType == dsaKey) {
7337 » *preferSha1 = SECKEY_PublicKeyStrength(pubk) <= 128; 7520 *preferSha1 = SECKEY_PublicKeyStrength(pubk) <= 128;
7338 } else { 7521 } else {
7339 » *preferSha1 = PR_FALSE; 7522 *preferSha1 = PR_FALSE;
7340 } 7523 }
7341 7524
7342 done: 7525 done:
7343 if (pubk) 7526 if (pubk)
7344 » SECKEY_DestroyPublicKey(pubk); 7527 SECKEY_DestroyPublicKey(pubk);
7345 return rv; 7528 return rv;
7346 } 7529 }
7347 7530
7348 /* Destroys the backup handshake hash context if we don't need it. Note that 7531 /* Destroys the backup handshake hash context if we don't need it. Note that
7349 * this function selects the hash algorithm for client authentication 7532 * this function selects the hash algorithm for client authentication
7350 * signatures; ssl3_SendCertificateVerify uses the presence of the backup hash 7533 * signatures; ssl3_SendCertificateVerify uses the presence of the backup hash
7351 * to determine whether to use SHA-1 or SHA-256. */ 7534 * to determine whether to use SHA-1 or SHA-256. */
7352 static void 7535 static void
7353 ssl3_DestroyBackupHandshakeHashIfNotNeeded(sslSocket *ss, 7536 ssl3_DestroyBackupHandshakeHashIfNotNeeded(sslSocket *ss,
7354 » » » » » const SECItem *algorithms) 7537 const SECItem *algorithms)
7355 { 7538 {
7356 SECStatus rv; 7539 SECStatus rv;
7357 SSLSignType sigAlg; 7540 SSLSignType sigAlg;
7358 PRBool preferSha1; 7541 PRBool preferSha1 = PR_FALSE;
7359 PRBool supportsSha1 = PR_FALSE; 7542 PRBool supportsSha1 = PR_FALSE;
7360 PRBool supportsSha256 = PR_FALSE; 7543 PRBool supportsSha256 = PR_FALSE;
7361 PRBool needBackupHash = PR_FALSE; 7544 PRBool needBackupHash = PR_FALSE;
7362 unsigned int i; 7545 unsigned int i;
7363 7546
7364 #ifndef NO_PKCS11_BYPASS 7547 #ifndef NO_PKCS11_BYPASS
7365 /* Backup handshake hash is not supported in PKCS #11 bypass mode. */ 7548 /* Backup handshake hash is not supported in PKCS #11 bypass mode. */
7366 if (ss->opt.bypassPKCS11) { 7549 if (ss->opt.bypassPKCS11) {
7367 » PORT_Assert(!ss->ssl3.hs.backupHash); 7550 PORT_Assert(!ss->ssl3.hs.backupHash);
7368 » return; 7551 return;
7369 } 7552 }
7370 #endif 7553 #endif
7371 PORT_Assert(ss->ssl3.hs.backupHash); 7554 PORT_Assert(ss->ssl3.hs.backupHash);
7372 7555
7373 /* Determine the key's signature algorithm and whether it prefers SHA-1. */ 7556 /* Determine the key's signature algorithm and whether it prefers SHA-1. */
7374 rv = ssl3_ExtractClientKeyInfo(ss, &sigAlg, &preferSha1); 7557 rv = ssl3_ExtractClientKeyInfo(ss, &sigAlg, &preferSha1);
7375 if (rv != SECSuccess) { 7558 if (rv != SECSuccess) {
7376 » goto done; 7559 goto done;
7377 } 7560 }
7378 7561
7379 /* Determine the server's hash support for that signature algorithm. */ 7562 /* Determine the server's hash support for that signature algorithm. */
7380 for (i = 0; i < algorithms->len; i += 2) { 7563 for (i = 0; i < algorithms->len; i += 2) {
7381 » if (algorithms->data[i+1] == sigAlg) { 7564 if (algorithms->data[i + 1] == sigAlg) {
7382 » if (algorithms->data[i] == ssl_hash_sha1) { 7565 if (algorithms->data[i] == ssl_hash_sha1) {
7383 » » supportsSha1 = PR_TRUE; 7566 supportsSha1 = PR_TRUE;
7384 » } else if (algorithms->data[i] == ssl_hash_sha256) { 7567 } else if (algorithms->data[i] == ssl_hash_sha256) {
7385 » » supportsSha256 = PR_TRUE; 7568 supportsSha256 = PR_TRUE;
7386 » } 7569 }
7387 » } 7570 }
7388 } 7571 }
7389 7572
7390 /* If either the server does not support SHA-256 or the client key prefers 7573 /* If either the server does not support SHA-256 or the client key prefers
7391 * SHA-1, leave the backup hash. */ 7574 * SHA-1, leave the backup hash. */
7392 if (supportsSha1 && (preferSha1 || !supportsSha256)) { 7575 if (supportsSha1 && (preferSha1 || !supportsSha256)) {
7393 » needBackupHash = PR_TRUE; 7576 needBackupHash = PR_TRUE;
7394 } 7577 }
7395 7578
7396 done: 7579 done:
7397 if (!needBackupHash) { 7580 if (!needBackupHash) {
7398 » PK11_DestroyContext(ss->ssl3.hs.backupHash, PR_TRUE); 7581 PK11_DestroyContext(ss->ssl3.hs.backupHash, PR_TRUE);
7399 » ss->ssl3.hs.backupHash = NULL; 7582 ss->ssl3.hs.backupHash = NULL;
7400 } 7583 }
7401 } 7584 }
7402 7585
7403 typedef struct dnameNode { 7586 typedef struct dnameNode {
7404 struct dnameNode *next; 7587 struct dnameNode *next;
7405 SECItem name; 7588 SECItem name;
7406 } dnameNode; 7589 } dnameNode;
7407 7590
7408 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete 7591 /*
7409 * ssl3 Certificate Request message. 7592 * Parse the ca_list structure in a CertificateRequest.
7593 *
7594 * Called from:
7595 * ssl3_HandleCertificateRequest
7596 * tls13_HandleCertificateRequest
7597 */
7598 SECStatus
7599 ssl3_ParseCertificateRequestCAs(sslSocket *ss, SSL3Opaque **b, PRUint32 *length,
7600 PLArenaPool *arena, CERTDistNames *ca_list)
7601 {
7602 PRInt32 remaining;
7603 int nnames = 0;
7604 dnameNode *node;
7605 int i;
7606
7607 remaining = ssl3_ConsumeHandshakeNumber(ss, 2, b, length);
7608 if (remaining < 0)
7609 return SECFailure; /* malformed, alert has been sent */
7610
7611 if ((PRUint32)remaining > *length)
7612 goto alert_loser;
7613
7614 ca_list->head = node = PORT_ArenaZNew(arena, dnameNode);
7615 if (node == NULL)
7616 goto no_mem;
7617
7618 while (remaining > 0) {
7619 PRInt32 len;
7620
7621 if (remaining < 2)
7622 goto alert_loser; /* malformed */
7623
7624 node->name.len = len = ssl3_ConsumeHandshakeNumber(ss, 2, b, length);
7625 if (len <= 0)
7626 return SECFailure; /* malformed, alert has been sent */
7627
7628 remaining -= 2;
7629 if (remaining < len)
7630 goto alert_loser; /* malformed */
7631
7632 node->name.data = *b;
7633 *b += len;
7634 *length -= len;
7635 remaining -= len;
7636 nnames++;
7637 if (remaining <= 0)
7638 break; /* success */
7639
7640 node->next = PORT_ArenaZNew(arena, dnameNode);
7641 node = node->next;
7642 if (node == NULL)
7643 goto no_mem;
7644 }
7645
7646 ca_list->nnames = nnames;
7647 ca_list->names = PORT_ArenaNewArray(arena, SECItem, nnames);
7648 if (nnames > 0 && ca_list->names == NULL)
7649 goto no_mem;
7650
7651 for (i = 0, node = (dnameNode *)ca_list->head;
7652 i < nnames;
7653 i++, node = node->next) {
7654 ca_list->names[i] = node->name;
7655 }
7656
7657 return SECSuccess;
7658
7659 no_mem:
7660 PORT_SetError(SEC_ERROR_NO_MEMORY);
7661 return SECFailure;
7662
7663 alert_loser:
7664 (void)SSL3_SendAlert(ss, alert_fatal,
7665 ss->version < SSL_LIBRARY_VERSION_TLS_1_0 ? illegal_par ameter
7666 : decode_erro r);
7667 PORT_SetError(SSL_ERROR_RX_MALFORMED_CERT_REQUEST);
7668 return SECFailure;
7669 }
7670
7671 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
7672 * a complete ssl3 Certificate Request message.
7410 * Caller must hold Handshake and RecvBuf locks. 7673 * Caller must hold Handshake and RecvBuf locks.
7411 */ 7674 */
7412 static SECStatus 7675 static SECStatus
7413 ssl3_HandleCertificateRequest(sslSocket *ss, SSL3Opaque *b, PRUint32 length) 7676 ssl3_HandleCertificateRequest(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
7414 { 7677 {
7415 PLArenaPool * arena = NULL; 7678 PLArenaPool *arena = NULL;
7416 dnameNode * node; 7679 PRBool isTLS = PR_FALSE;
7417 PRInt32 remaining; 7680 PRBool isTLS12 = PR_FALSE;
7418 PRBool isTLS = PR_FALSE; 7681 int errCode = SSL_ERROR_RX_MALFORMED_CERT_REQUEST;
7419 PRBool isTLS12 = PR_FALSE; 7682 SECStatus rv;
7420 int i; 7683 SSL3AlertDescription desc = illegal_parameter;
7421 int errCode = SSL_ERROR_RX_MALFORMED_CERT_REQUEST; 7684 SECItem cert_types = { siBuffer, NULL, 0 };
7422 int nnames = 0; 7685 SECItem algorithms = { siBuffer, NULL, 0 };
7423 SECStatus rv; 7686 CERTDistNames ca_list;
7424 SSL3AlertDescription desc = illegal_parameter;
7425 SECItem cert_types = {siBuffer, NULL, 0};
7426 SECItem algorithms = {siBuffer, NULL, 0};
7427 CERTDistNames ca_list;
7428 #ifdef NSS_PLATFORM_CLIENT_AUTH
7429 CERTCertList * platform_cert_list = NULL;
7430 CERTCertListNode * certNode = NULL;
7431 #endif /* NSS_PLATFORM_CLIENT_AUTH */
7432 7687
7433 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_request handshake", 7688 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_request handshake",
7434 » » SSL_GETPID(), ss->fd)); 7689 SSL_GETPID(), ss->fd));
7435 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 7690 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
7436 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 7691 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7437 7692
7438 if (ss->ssl3.hs.ws != wait_cert_request) { 7693 if (ss->ssl3.hs.ws != wait_cert_request) {
7439 desc = unexpected_message; 7694 desc = unexpected_message;
7440 errCode = SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST; 7695 errCode = SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST;
7441 goto alert_loser; 7696 goto alert_loser;
7442 } 7697 }
7443 7698
7444 PORT_Assert(ss->ssl3.clientCertChain == NULL); 7699 PORT_Assert(ss->ssl3.clientCertChain == NULL);
7445 PORT_Assert(ss->ssl3.clientCertificate == NULL); 7700 PORT_Assert(ss->ssl3.clientCertificate == NULL);
7446 PORT_Assert(ss->ssl3.clientPrivateKey == NULL); 7701 PORT_Assert(ss->ssl3.clientPrivateKey == NULL);
7447 PORT_Assert(ss->ssl3.platformClientKey == (PlatformKey)NULL);
7448 7702
7449 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0); 7703 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
7450 isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); 7704 isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
7451 rv = ssl3_ConsumeHandshakeVariable(ss, &cert_types, 1, &b, &length); 7705 rv = ssl3_ConsumeHandshakeVariable(ss, &cert_types, 1, &b, &length);
7452 if (rv != SECSuccess) 7706 if (rv != SECSuccess)
7453 » goto loser;» » /* malformed, alert has been sent */ 7707 goto loser; /* malformed, alert has been sent */
7454 7708
7455 PORT_Assert(!ss->requestedCertTypes); 7709 PORT_Assert(!ss->requestedCertTypes);
7456 ss->requestedCertTypes = &cert_types; 7710 ss->requestedCertTypes = &cert_types;
7457 7711
7458 if (isTLS12) { 7712 if (isTLS12) {
7459 » rv = ssl3_ConsumeHandshakeVariable(ss, &algorithms, 2, &b, &length); 7713 rv = ssl3_ConsumeHandshakeVariable(ss, &algorithms, 2, &b, &length);
7460 » if (rv != SECSuccess) 7714 if (rv != SECSuccess)
7461 » goto loser;»» /* malformed, alert has been sent */ 7715 goto loser; /* malformed, alert has been sent */
7462 » /* An empty or odd-length value is invalid. 7716 /* An empty or odd-length value is invalid.
7463 » * SignatureAndHashAlgorithm 7717 * SignatureAndHashAlgorithm
7464 » * supported_signature_algorithms<2..2^16-2>; 7718 * supported_signature_algorithms<2..2^16-2>;
7465 » */ 7719 */
7466 » if (algorithms.len == 0 || (algorithms.len & 1) != 0) 7720 if (algorithms.len == 0 || (algorithms.len & 1) != 0)
7467 » goto alert_loser; 7721 goto alert_loser;
7468 } 7722 }
7469 7723
7470 arena = ca_list.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); 7724 arena = ca_list.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
7471 if (arena == NULL) 7725 if (arena == NULL)
7472 goto no_mem;
7473
7474 remaining = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
7475 if (remaining < 0)
7476 goto loser; /* malformed, alert has been sent */
7477
7478 if ((PRUint32)remaining > length)
7479 goto alert_loser;
7480
7481 ca_list.head = node = PORT_ArenaZNew(arena, dnameNode);
7482 if (node == NULL)
7483 goto no_mem;
7484
7485 while (remaining > 0) {
7486 PRInt32 len;
7487
7488 if (remaining < 2)
7489 goto alert_loser; /* malformed */
7490
7491 node->name.len = len = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
7492 if (len <= 0)
7493 goto loser; /* malformed, alert has been sent */
7494
7495 remaining -= 2;
7496 if (remaining < len)
7497 goto alert_loser; /* malformed */
7498
7499 node->name.data = b;
7500 b += len;
7501 length -= len;
7502 remaining -= len;
7503 nnames++;
7504 if (remaining <= 0)
7505 break; /* success */
7506
7507 node->next = PORT_ArenaZNew(arena, dnameNode);
7508 node = node->next;
7509 if (node == NULL)
7510 goto no_mem;
7511 }
7512
7513 ca_list.nnames = nnames;
7514 ca_list.names = PORT_ArenaNewArray(arena, SECItem, nnames);
7515 if (nnames > 0 && ca_list.names == NULL)
7516 goto no_mem; 7726 goto no_mem;
7517 7727
7518 for(i = 0, node = (dnameNode*)ca_list.head; 7728 rv = ssl3_ParseCertificateRequestCAs(ss, &b, &length, arena, &ca_list);
7519 » i < nnames; 7729 if (rv != SECSuccess)
7520 » i++, node = node->next) { 7730 goto done; /* alert sent in ssl3_ParseCertificateRequestCAs */
7521 » ca_list.names[i] = node->name;
7522 }
7523 7731
7524 if (length != 0) 7732 if (length != 0)
7525 goto alert_loser; » /* malformed */ 7733 goto alert_loser; /* malformed */
7526 7734
7527 desc = no_certificate; 7735 desc = no_certificate;
7736
7528 ss->ssl3.hs.ws = wait_hello_done; 7737 ss->ssl3.hs.ws = wait_hello_done;
7529 7738
7530 #ifdef NSS_PLATFORM_CLIENT_AUTH 7739 rv = ssl3_CompleteHandleCertificateRequest(ss, &algorithms, &ca_list);
7531 if (ss->getPlatformClientAuthData != NULL) { 7740 if (rv == SECFailure) {
7532 » /* XXX Should pass cert_types and algorithms in this call!! */ 7741 PORT_Assert(0);
7533 rv = (SECStatus)(*ss->getPlatformClientAuthData)( 7742 errCode = SEC_ERROR_LIBRARY_FAILURE;
7534 ss->getPlatformClientAuthDataArg, 7743 desc = internal_error;
7535 ss->fd, &ca_list, 7744 goto alert_loser;
7536 &platform_cert_list,
7537 (void**)&ss->ssl3.platformClientKey,
7538 &ss->ssl3.clientCertificate,
7539 &ss->ssl3.clientPrivateKey);
7540 } else
7541 #endif
7542 if (ss->getClientAuthData != NULL) {
7543 PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==
7544 ssl_preinfo_all);
7545 » /* XXX Should pass cert_types and algorithms in this call!! */
7546 » rv = (SECStatus)(*ss->getClientAuthData)(ss->getClientAuthDataArg,
7547 » » » » » » ss->fd, &ca_list,
7548 » » » » » » &ss->ssl3.clientCertificate,
7549 » » » » » » &ss->ssl3.clientPrivateKey);
7550 } else {
7551 » rv = SECFailure; /* force it to send a no_certificate alert */
7552 }
7553
7554 switch (rv) {
7555 case SECWouldBlock:»/* getClientAuthData has put up a dialog box. */
7556 » ssl3_SetAlwaysBlock(ss);
7557 » break;» /* not an error */
7558
7559 case SECSuccess:
7560 #ifdef NSS_PLATFORM_CLIENT_AUTH
7561 if (!platform_cert_list || CERT_LIST_EMPTY(platform_cert_list) ||
7562 !ss->ssl3.platformClientKey) {
7563 if (platform_cert_list) {
7564 CERT_DestroyCertList(platform_cert_list);
7565 platform_cert_list = NULL;
7566 }
7567 if (ss->ssl3.platformClientKey) {
7568 ssl_FreePlatformKey(ss->ssl3.platformClientKey);
7569 ss->ssl3.platformClientKey = (PlatformKey)NULL;
7570 }
7571 » /* Fall through to NSS client auth check */
7572 } else {
7573 » certNode = CERT_LIST_HEAD(platform_cert_list);
7574 » ss->ssl3.clientCertificate = CERT_DupCertificate(certNode->cert);
7575
7576 » /* Setting ssl3.clientCertChain non-NULL will cause
7577 » * ssl3_HandleServerHelloDone to call SendCertificate.
7578 » * Note: clientCertChain should include the EE cert as
7579 » * clientCertificate is ignored during the actual sending
7580 » */
7581 » ss->ssl3.clientCertChain =
7582 » » hack_NewCertificateListFromCertList(platform_cert_list);
7583 » CERT_DestroyCertList(platform_cert_list);
7584 » platform_cert_list = NULL;
7585 » if (ss->ssl3.clientCertChain == NULL) {
7586 » » if (ss->ssl3.clientCertificate != NULL) {
7587 » » CERT_DestroyCertificate(ss->ssl3.clientCertificate);
7588 » » ss->ssl3.clientCertificate = NULL;
7589 » » }
7590 » » if (ss->ssl3.platformClientKey) {
7591 » » ssl_FreePlatformKey(ss->ssl3.platformClientKey);
7592 » » ss->ssl3.platformClientKey = (PlatformKey)NULL;
7593 » » }
7594 » » goto send_no_certificate;
7595 » }
7596 » if (ss->ssl3.hs.hashType == handshake_hash_single) {
7597 » » ssl3_DestroyBackupHandshakeHashIfNotNeeded(ss, &algorithms);
7598 » }
7599 » break; /* not an error */
7600 » }
7601 #endif /* NSS_PLATFORM_CLIENT_AUTH */
7602 /* check what the callback function returned */
7603 if ((!ss->ssl3.clientCertificate) || (!ss->ssl3.clientPrivateKey)) {
7604 /* we are missing either the key or cert */
7605 if (ss->ssl3.clientCertificate) {
7606 /* got a cert, but no key - free it */
7607 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
7608 ss->ssl3.clientCertificate = NULL;
7609 }
7610 if (ss->ssl3.clientPrivateKey) {
7611 /* got a key, but no cert - free it */
7612 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
7613 ss->ssl3.clientPrivateKey = NULL;
7614 }
7615 goto send_no_certificate;
7616 }
7617 » /* Setting ssl3.clientCertChain non-NULL will cause
7618 » * ssl3_HandleServerHelloDone to call SendCertificate.
7619 » */
7620 » ss->ssl3.clientCertChain = CERT_CertChainFromCert(
7621 » » » » » ss->ssl3.clientCertificate,
7622 » » » » » certUsageSSLClient, PR_FALSE);
7623 » if (ss->ssl3.clientCertChain == NULL) {
7624 » CERT_DestroyCertificate(ss->ssl3.clientCertificate);
7625 » ss->ssl3.clientCertificate = NULL;
7626 » SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
7627 » ss->ssl3.clientPrivateKey = NULL;
7628 » goto send_no_certificate;
7629 » }
7630 » if (ss->ssl3.hs.hashType == handshake_hash_single) {
7631 » ssl3_DestroyBackupHandshakeHashIfNotNeeded(ss, &algorithms);
7632 » }
7633 » break;» /* not an error */
7634
7635 case SECFailure:
7636 default:
7637 send_no_certificate:
7638 » if (isTLS) {
7639 » ss->ssl3.sendEmptyCert = PR_TRUE;
7640 » } else {
7641 » (void)SSL3_SendAlert(ss, alert_warning, no_certificate);
7642 » }
7643 » rv = SECSuccess;
7644 » break;
7645 } 7745 }
7646 goto done; 7746 goto done;
7647 7747
7648 no_mem: 7748 no_mem:
7649 rv = SECFailure; 7749 rv = SECFailure;
7650 PORT_SetError(SEC_ERROR_NO_MEMORY); 7750 PORT_SetError(SEC_ERROR_NO_MEMORY);
7651 goto done; 7751 goto done;
7652 7752
7653 alert_loser: 7753 alert_loser:
7654 if (isTLS && desc == illegal_parameter) 7754 if (isTLS && desc == illegal_parameter)
7655 » desc = decode_error; 7755 desc = decode_error;
7656 (void)SSL3_SendAlert(ss, alert_fatal, desc); 7756 (void)SSL3_SendAlert(ss, alert_fatal, desc);
7657 loser: 7757 loser:
7658 PORT_SetError(errCode); 7758 PORT_SetError(errCode);
7659 rv = SECFailure; 7759 rv = SECFailure;
7660 done: 7760 done:
7661 ss->requestedCertTypes = NULL; 7761 ss->requestedCertTypes = NULL;
7662 if (arena != NULL) 7762 if (arena != NULL)
7663 » PORT_FreeArena(arena, PR_FALSE); 7763 PORT_FreeArena(arena, PR_FALSE);
7664 #ifdef NSS_PLATFORM_CLIENT_AUTH
7665 if (platform_cert_list)
7666 CERT_DestroyCertList(platform_cert_list);
7667 #endif
7668 return rv; 7764 return rv;
7669 } 7765 }
7670 7766
7767 SECStatus
7768 ssl3_CompleteHandleCertificateRequest(sslSocket *ss, SECItem *algorithms,
7769 CERTDistNames *ca_list)
7770 {
7771 SECStatus rv;
7772
7773 if (ss->getClientAuthData != NULL) {
7774 PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==
7775 ssl_preinfo_all);
7776 /* XXX Should pass cert_types and algorithms in this call!! */
7777 rv = (SECStatus)(*ss->getClientAuthData)(ss->getClientAuthDataArg,
7778 ss->fd, ca_list,
7779 &ss->ssl3.clientCertificate,
7780 &ss->ssl3.clientPrivateKey);
7781 } else {
7782 rv = SECFailure; /* force it to send a no_certificate alert */
7783 }
7784 switch (rv) {
7785 case SECWouldBlock: /* getClientAuthData has put up a dialog box. */
7786 ssl3_SetAlwaysBlock(ss);
7787 break; /* not an error */
7788
7789 case SECSuccess:
7790 /* check what the callback function returned */
7791 if ((!ss->ssl3.clientCertificate) || (!ss->ssl3.clientPrivateKey)) {
7792 /* we are missing either the key or cert */
7793 if (ss->ssl3.clientCertificate) {
7794 /* got a cert, but no key - free it */
7795 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
7796 ss->ssl3.clientCertificate = NULL;
7797 }
7798 if (ss->ssl3.clientPrivateKey) {
7799 /* got a key, but no cert - free it */
7800 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
7801 ss->ssl3.clientPrivateKey = NULL;
7802 }
7803 goto send_no_certificate;
7804 }
7805 /* Setting ssl3.clientCertChain non-NULL will cause
7806 * ssl3_HandleServerHelloDone to call SendCertificate.
7807 */
7808 ss->ssl3.clientCertChain = CERT_CertChainFromCert(
7809 ss->ssl3.clientCertificate,
7810 certUsageSSLClient, PR_FALSE);
7811 if (ss->ssl3.clientCertChain == NULL) {
7812 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
7813 ss->ssl3.clientCertificate = NULL;
7814 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
7815 ss->ssl3.clientPrivateKey = NULL;
7816 goto send_no_certificate;
7817 }
7818 if (ss->ssl3.hs.hashType == handshake_hash_single) {
7819 ssl3_DestroyBackupHandshakeHashIfNotNeeded(ss, algorithms);
7820 }
7821 break; /* not an error */
7822
7823 case SECFailure:
7824 default:
7825 send_no_certificate:
7826 if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) {
7827 ss->ssl3.sendEmptyCert = PR_TRUE;
7828 } else {
7829 (void)SSL3_SendAlert(ss, alert_warning, no_certificate);
7830 }
7831 rv = SECSuccess;
7832 break;
7833 }
7834
7835 return rv;
7836 }
7837
7671 /* 7838 /*
7672 * attempt to restart the handshake after asynchronously handling 7839 * attempt to restart the handshake after asynchronously handling
7673 * a request for the client's certificate. 7840 * a request for the client's certificate.
7674 * 7841 *
7675 * inputs: 7842 * inputs:
7676 * cert Client cert chosen by application. 7843 * cert Client cert chosen by application.
7677 * Note: ssl takes this reference, and does not bump the 7844 * Note: ssl takes this reference, and does not bump the
7678 * reference count. The caller should drop its reference 7845 * reference count. The caller should drop its reference
7679 * without calling CERT_DestroyCert after calling this function. 7846 * without calling CERT_DestroyCert after calling this function.
7680 * 7847 *
7681 * key Private key associated with cert. This function takes 7848 * key Private key associated with cert. This function takes
7682 * ownership of the private key, so the caller should drop its 7849 * ownership of the private key, so the caller should drop its
7683 * reference without destroying the private key after this 7850 * reference without destroying the private key after this
7684 * function returns. 7851 * function returns.
7685 * 7852 *
7686 * certChain DER-encoded certs, client cert and its signers. 7853 * certChain DER-encoded certs, client cert and its signers.
7687 * Note: ssl takes this reference, and does not copy the chain. 7854 * Note: ssl takes this reference, and does not copy the chain.
7688 * The caller should drop its reference without destroying the 7855 * The caller should drop its reference without destroying the
7689 * chain. SSL will free the chain when it is done with it. 7856 * chain. SSL will free the chain when it is done with it.
7690 * 7857 *
7691 * Return value: XXX 7858 * Return value: XXX
7692 * 7859 *
7693 * XXX This code only works on the initial handshake on a connection, XXX 7860 * XXX This code only works on the initial handshake on a connection, XXX
7694 * It does not work on a subsequent handshake (redo). 7861 * It does not work on a subsequent handshake (redo).
7695 * 7862 *
7696 * Caller holds 1stHandshakeLock. 7863 * Caller holds 1stHandshakeLock.
7697 */ 7864 */
7698 SECStatus 7865 SECStatus
7699 ssl3_RestartHandshakeAfterCertReq(sslSocket * ss, 7866 ssl3_RestartHandshakeAfterCertReq(sslSocket *ss,
7700 » » » » CERTCertificate * cert, 7867 CERTCertificate *cert,
7701 » » » » SECKEYPrivateKey * key, 7868 SECKEYPrivateKey *key,
7702 » » » » CERTCertificateList *certChain) 7869 CERTCertificateList *certChain)
7703 { 7870 {
7704 SECStatus rv = SECSuccess; 7871 SECStatus rv = SECSuccess;
7705 7872
7706 /* XXX This code only works on the initial handshake on a connection, 7873 /* XXX This code only works on the initial handshake on a connection,
7707 ** XXX It does not work on a subsequent handshake (redo). 7874 ** XXX It does not work on a subsequent handshake (redo).
7708 */ 7875 */
7709 if (ss->handshake != 0) { 7876 if (ss->handshake != 0) {
7710 » ss->handshake = ssl_GatherRecord1stHandshake; 7877 ss->handshake = ssl_GatherRecord1stHandshake;
7711 » ss->ssl3.clientCertificate = cert; 7878 ss->ssl3.clientCertificate = cert;
7712 » ss->ssl3.clientPrivateKey = key; 7879 ss->ssl3.clientPrivateKey = key;
7713 » ss->ssl3.clientCertChain = certChain; 7880 ss->ssl3.clientCertChain = certChain;
7714 if (!cert || !key || !certChain) { 7881 if (!cert || !key || !certChain) {
7715 /* we are missing the key, cert, or cert chain */ 7882 /* we are missing the key, cert, or cert chain */
7716 if (ss->ssl3.clientCertificate) { 7883 if (ss->ssl3.clientCertificate) {
7717 CERT_DestroyCertificate(ss->ssl3.clientCertificate); 7884 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
7718 ss->ssl3.clientCertificate = NULL; 7885 ss->ssl3.clientCertificate = NULL;
7719 } 7886 }
7720 if (ss->ssl3.clientPrivateKey) { 7887 if (ss->ssl3.clientPrivateKey) {
7721 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); 7888 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
7722 ss->ssl3.clientPrivateKey = NULL; 7889 ss->ssl3.clientPrivateKey = NULL;
7723 } 7890 }
7724 if (ss->ssl3.clientCertChain != NULL) { 7891 if (ss->ssl3.clientCertChain != NULL) {
7725 CERT_DestroyCertificateList(ss->ssl3.clientCertChain); 7892 CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
7726 ss->ssl3.clientCertChain = NULL; 7893 ss->ssl3.clientCertChain = NULL;
7727 } 7894 }
7728 if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) { 7895 if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) {
7729 ss->ssl3.sendEmptyCert = PR_TRUE; 7896 ss->ssl3.sendEmptyCert = PR_TRUE;
7730 } else { 7897 } else {
7731 (void)SSL3_SendAlert(ss, alert_warning, no_certificate); 7898 (void)SSL3_SendAlert(ss, alert_warning, no_certificate);
7732 } 7899 }
7733 » } 7900 }
7734 } else { 7901 } else {
7735 » if (cert) { 7902 if (cert) {
7736 » CERT_DestroyCertificate(cert); 7903 CERT_DestroyCertificate(cert);
7737 » } 7904 }
7738 » if (key) { 7905 if (key) {
7739 » SECKEY_DestroyPrivateKey(key); 7906 SECKEY_DestroyPrivateKey(key);
7740 » } 7907 }
7741 » if (certChain) { 7908 if (certChain) {
7742 » CERT_DestroyCertificateList(certChain); 7909 CERT_DestroyCertificateList(certChain);
7743 » } 7910 }
7744 » PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 7911 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
7745 » rv = SECFailure; 7912 rv = SECFailure;
7746 } 7913 }
7747 return rv; 7914 return rv;
7748 } 7915 }
7749 7916
7750 static SECStatus 7917 static SECStatus
7751 ssl3_CheckFalseStart(sslSocket *ss) 7918 ssl3_CheckFalseStart(sslSocket *ss)
7752 { 7919 {
7753 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 7920 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7754 PORT_Assert( !ss->ssl3.hs.authCertificatePending ); 7921 PORT_Assert(!ss->ssl3.hs.authCertificatePending);
7755 PORT_Assert( !ss->ssl3.hs.canFalseStart ); 7922 PORT_Assert(!ss->ssl3.hs.canFalseStart);
7756 7923
7757 if (!ss->canFalseStartCallback) { 7924 if (!ss->canFalseStartCallback) {
7758 » SSL_TRC(3, ("%d: SSL[%d]: no false start callback so no false start", 7925 SSL_TRC(3, ("%d: SSL[%d]: no false start callback so no false start",
7759 » » SSL_GETPID(), ss->fd)); 7926 SSL_GETPID(), ss->fd));
7760 } else { 7927 } else {
7761 » PRBool maybeFalseStart; 7928 PRBool maybeFalseStart;
7762 » SECStatus rv; 7929 SECStatus rv;
7763 7930
7764 » /* An attacker can control the selected ciphersuite so we only wish to 7931 /* An attacker can control the selected ciphersuite so we only wish to
7765 » * do False Start in the case that the selected ciphersuite is 7932 * do False Start in the case that the selected ciphersuite is
7766 » * sufficiently strong that the attack can gain no advantage. 7933 * sufficiently strong that the attack can gain no advantage.
7767 » * Therefore we always require an 80-bit cipher. */ 7934 * Therefore we always require an 80-bit cipher. */
7768 ssl_GetSpecReadLock(ss); 7935 ssl_GetSpecReadLock(ss);
7769 maybeFalseStart = ss->ssl3.cwSpec->cipher_def->secret_key_size >= 10; 7936 maybeFalseStart = ss->ssl3.cwSpec->cipher_def->secret_key_size >= 10;
7770 ssl_ReleaseSpecReadLock(ss); 7937 ssl_ReleaseSpecReadLock(ss);
7771 7938
7772 » if (!maybeFalseStart) { 7939 if (!maybeFalseStart) {
7773 » SSL_TRC(3, ("%d: SSL[%d]: no false start due to weak cipher", 7940 SSL_TRC(3, ("%d: SSL[%d]: no false start due to weak cipher",
7774 » » » SSL_GETPID(), ss->fd)); 7941 SSL_GETPID(), ss->fd));
7775 » } else { 7942 } else {
7776 PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) == 7943 PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==
7777 ssl_preinfo_all); 7944 ssl_preinfo_all);
7778 » rv = (ss->canFalseStartCallback)(ss->fd, 7945 rv = (ss->canFalseStartCallback)(ss->fd,
7779 » » » » » ss->canFalseStartCallbackData, 7946 ss->canFalseStartCallbackData,
7780 » » » » » &ss->ssl3.hs.canFalseStart); 7947 &ss->ssl3.hs.canFalseStart);
7781 » if (rv == SECSuccess) { 7948 if (rv == SECSuccess) {
7782 » » SSL_TRC(3, ("%d: SSL[%d]: false start callback returned %s", 7949 SSL_TRC(3, ("%d: SSL[%d]: false start callback returned %s",
7783 » » » SSL_GETPID(), ss->fd, 7950 SSL_GETPID(), ss->fd,
7784 » » » ss->ssl3.hs.canFalseStart ? "TRUE" : "FALSE")); 7951 ss->ssl3.hs.canFalseStart ? "TRUE"
7785 » } else { 7952 : "FALSE"));
7786 » » SSL_TRC(3, ("%d: SSL[%d]: false start callback failed (%s)", 7953 } else {
7787 » » » SSL_GETPID(), ss->fd, 7954 SSL_TRC(3, ("%d: SSL[%d]: false start callback failed (%s)",
7788 » » » PR_ErrorToName(PR_GetError()))); 7955 SSL_GETPID(), ss->fd,
7789 » } 7956 PR_ErrorToName(PR_GetError())));
7790 » return rv; 7957 }
7791 » } 7958 return rv;
7959 }
7792 } 7960 }
7793 7961
7794 ss->ssl3.hs.canFalseStart = PR_FALSE; 7962 ss->ssl3.hs.canFalseStart = PR_FALSE;
7795 return SECSuccess; 7963 return SECSuccess;
7796 } 7964 }
7797 7965
7798 PRBool 7966 PRBool
7799 ssl3_WaitingForStartOfServerSecondRound(sslSocket *ss) 7967 ssl3_WaitingForServerSecondRound(sslSocket *ss)
7800 { 7968 {
7801 PRBool result; 7969 PRBool result;
7802 7970
7803 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 7971 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7804 7972
7805 switch (ss->ssl3.hs.ws) { 7973 switch (ss->ssl3.hs.ws) {
7806 case wait_new_session_ticket: 7974 case wait_new_session_ticket:
7807 result = PR_TRUE; 7975 case wait_change_cipher:
7808 break; 7976 case wait_finished:
7809 case wait_change_cipher: 7977 result = PR_TRUE;
7810 result = !ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn); 7978 break;
7811 break; 7979 default:
7812 default: 7980 result = PR_FALSE;
7813 result = PR_FALSE; 7981 break;
7814 break;
7815 } 7982 }
7816 7983
7817 return result; 7984 return result;
7818 } 7985 }
7819 7986
7820 static SECStatus ssl3_SendClientSecondRound(sslSocket *ss); 7987 static SECStatus ssl3_SendClientSecondRound(sslSocket *ss);
7821 7988
7822 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete 7989 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
7823 * ssl3 Server Hello Done message. 7990 * a complete ssl3 Server Hello Done message.
7824 * Caller must hold Handshake and RecvBuf locks. 7991 * Caller must hold Handshake and RecvBuf locks.
7825 */ 7992 */
7826 static SECStatus 7993 static SECStatus
7827 ssl3_HandleServerHelloDone(sslSocket *ss) 7994 ssl3_HandleServerHelloDone(sslSocket *ss)
7828 { 7995 {
7829 SECStatus rv; 7996 SECStatus rv;
7830 SSL3WaitState ws = ss->ssl3.hs.ws; 7997 SSL3WaitState ws = ss->ssl3.hs.ws;
7831 7998
7832 SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello_done handshake", 7999 SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello_done handshake",
7833 » » SSL_GETPID(), ss->fd)); 8000 SSL_GETPID(), ss->fd));
7834 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 8001 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
7835 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 8002 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7836 8003
7837 /* Skipping CertificateRequest is always permitted. */ 8004 /* Skipping CertificateRequest is always permitted. */
7838 if (ws != wait_hello_done && 8005 if (ws != wait_hello_done &&
7839 » ws != wait_cert_request) { 8006 ws != wait_cert_request) {
7840 » SSL3_SendAlert(ss, alert_fatal, unexpected_message); 8007 SSL3_SendAlert(ss, alert_fatal, unexpected_message);
7841 » PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE); 8008 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
7842 » return SECFailure; 8009 return SECFailure;
7843 } 8010 }
7844 8011
7845 rv = ssl3_SendClientSecondRound(ss); 8012 rv = ssl3_SendClientSecondRound(ss);
7846 8013
7847 return rv; 8014 return rv;
7848 } 8015 }
7849 8016
7850 /* Called from ssl3_HandleServerHelloDone and ssl3_AuthCertificateComplete. 8017 /* Called from ssl3_HandleServerHelloDone and ssl3_AuthCertificateComplete.
7851 * 8018 *
7852 * Caller must hold Handshake and RecvBuf locks. 8019 * Caller must hold Handshake and RecvBuf locks.
7853 */ 8020 */
7854 static SECStatus 8021 static SECStatus
7855 ssl3_SendClientSecondRound(sslSocket *ss) 8022 ssl3_SendClientSecondRound(sslSocket *ss)
7856 { 8023 {
7857 SECStatus rv; 8024 SECStatus rv;
7858 PRBool sendClientCert; 8025 PRBool sendClientCert;
7859 8026
7860 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 8027 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
7861 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 8028 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
7862 8029
7863 sendClientCert = !ss->ssl3.sendEmptyCert && 8030 sendClientCert = !ss->ssl3.sendEmptyCert &&
7864 » » ss->ssl3.clientCertChain != NULL && 8031 ss->ssl3.clientCertChain != NULL &&
7865 » » (ss->ssl3.platformClientKey || 8032 ss->ssl3.clientPrivateKey != NULL;
7866 » » ss->ssl3.clientPrivateKey != NULL);
7867 8033
7868 if (!sendClientCert && 8034 if (!sendClientCert &&
7869 » ss->ssl3.hs.hashType == handshake_hash_single && 8035 ss->ssl3.hs.hashType == handshake_hash_single &&
7870 » ss->ssl3.hs.backupHash) { 8036 ss->ssl3.hs.backupHash) {
7871 » /* Don't need the backup handshake hash. */ 8037 /* Don't need the backup handshake hash. */
7872 » PK11_DestroyContext(ss->ssl3.hs.backupHash, PR_TRUE); 8038 PK11_DestroyContext(ss->ssl3.hs.backupHash, PR_TRUE);
7873 » ss->ssl3.hs.backupHash = NULL; 8039 ss->ssl3.hs.backupHash = NULL;
7874 } 8040 }
7875 8041
7876 /* We must wait for the server's certificate to be authenticated before 8042 /* We must wait for the server's certificate to be authenticated before
7877 * sending the client certificate in order to disclosing the client 8043 * sending the client certificate in order to disclosing the client
7878 * certificate to an attacker that does not have a valid cert for the 8044 * certificate to an attacker that does not have a valid cert for the
7879 * domain we are connecting to. 8045 * domain we are connecting to.
7880 * 8046 *
7881 * XXX: We should do the same for the NPN extension, but for that we 8047 * XXX: We should do the same for the NPN extension, but for that we
7882 * need an option to give the application the ability to leak the NPN 8048 * need an option to give the application the ability to leak the NPN
7883 * information to get better performance. 8049 * information to get better performance.
7884 * 8050 *
7885 * During the initial handshake on a connection, we never send/receive 8051 * During the initial handshake on a connection, we never send/receive
7886 * application data until we have authenticated the server's certificate; 8052 * application data until we have authenticated the server's certificate;
7887 * i.e. we have fully authenticated the handshake before using the cipher 8053 * i.e. we have fully authenticated the handshake before using the cipher
7888 * specs agreed upon for that handshake. During a renegotiation, we may 8054 * specs agreed upon for that handshake. During a renegotiation, we may
7889 * continue sending and receiving application data during the handshake 8055 * continue sending and receiving application data during the handshake
7890 * interleaved with the handshake records. If we were to send the client's 8056 * interleaved with the handshake records. If we were to send the client's
7891 * second round for a renegotiation before the server's certificate was 8057 * second round for a renegotiation before the server's certificate was
7892 * authenticated, then the application data sent/received after this point 8058 * authenticated, then the application data sent/received after this point
7893 * would be using cipher spec that hadn't been authenticated. By waiting 8059 * would be using cipher spec that hadn't been authenticated. By waiting
7894 * until the server's certificate has been authenticated during 8060 * until the server's certificate has been authenticated during
7895 * renegotiations, we ensure that renegotiations have the same property 8061 * renegotiations, we ensure that renegotiations have the same property
7896 * as initial handshakes; i.e. we have fully authenticated the handshake 8062 * as initial handshakes; i.e. we have fully authenticated the handshake
7897 * before using the cipher specs agreed upon for that handshake for 8063 * before using the cipher specs agreed upon for that handshake for
7898 * application data. 8064 * application data.
7899 */ 8065 */
7900 if (ss->ssl3.hs.restartTarget) { 8066 if (ss->ssl3.hs.restartTarget) {
7901 » PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget"); 8067 PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget");
7902 » PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 8068 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
7903 » return SECFailure; 8069 return SECFailure;
7904 } 8070 }
7905 if (ss->ssl3.hs.authCertificatePending && 8071 if (ss->ssl3.hs.authCertificatePending &&
7906 » (sendClientCert || ss->ssl3.sendEmptyCert || ss->firstHsDone)) { 8072 (sendClientCert || ss->ssl3.sendEmptyCert || ss->firstHsDone)) {
7907 » SSL_TRC(3, ("%d: SSL3[%p]: deferring ssl3_SendClientSecondRound because" 8073 SSL_TRC(3, ("%d: SSL3[%p]: deferring ssl3_SendClientSecondRound because"
7908 » » " certificate authentication is still pending.", 8074 " certificate authentication is still pending.",
7909 » » SSL_GETPID(), ss->fd)); 8075 SSL_GETPID(), ss->fd));
7910 » ss->ssl3.hs.restartTarget = ssl3_SendClientSecondRound; 8076 ss->ssl3.hs.restartTarget = ssl3_SendClientSecondRound;
7911 » return SECWouldBlock; 8077 return SECWouldBlock;
7912 } 8078 }
7913 8079
7914 ssl_GetXmitBufLock(ss);» » /*******************************/ 8080 ssl_GetXmitBufLock(ss); /*******************************/
7915 8081
7916 if (ss->ssl3.sendEmptyCert) { 8082 if (ss->ssl3.sendEmptyCert) {
7917 » ss->ssl3.sendEmptyCert = PR_FALSE; 8083 ss->ssl3.sendEmptyCert = PR_FALSE;
7918 » rv = ssl3_SendEmptyCertificate(ss); 8084 rv = ssl3_SendEmptyCertificate(ss);
7919 » /* Don't send verify */ 8085 /* Don't send verify */
7920 » if (rv != SECSuccess) { 8086 if (rv != SECSuccess) {
7921 » goto loser;»/* error code is set. */ 8087 goto loser; /* error code is set. */
7922 » } 8088 }
7923 } else if (sendClientCert) { 8089 } else if (sendClientCert) {
7924 » rv = ssl3_SendCertificate(ss); 8090 rv = ssl3_SendCertificate(ss);
7925 » if (rv != SECSuccess) { 8091 if (rv != SECSuccess) {
7926 » goto loser;»/* error code is set. */ 8092 goto loser; /* error code is set. */
7927 » } 8093 }
7928 } 8094 }
7929 8095
7930 rv = ssl3_SendClientKeyExchange(ss); 8096 rv = ssl3_SendClientKeyExchange(ss);
7931 if (rv != SECSuccess) { 8097 if (rv != SECSuccess) {
7932 » goto loser;» /* err is set. */ 8098 goto loser; /* err is set. */
7933 } 8099 }
7934 8100
7935 if (sendClientCert) { 8101 if (sendClientCert) {
7936 » rv = ssl3_SendCertificateVerify(ss); 8102 rv = ssl3_SendCertificateVerify(ss, ss->ssl3.clientPrivateKey);
7937 » if (rv != SECSuccess) { 8103 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
7938 » goto loser;»/* err is set. */ 8104 ss->ssl3.clientPrivateKey = NULL;
8105 if (rv != SECSuccess) {
8106 goto loser; /* err is set. */
7939 } 8107 }
7940 } 8108 }
7941 8109
7942 rv = ssl3_SendChangeCipherSpecs(ss); 8110 rv = ssl3_SendChangeCipherSpecs(ss);
7943 if (rv != SECSuccess) { 8111 if (rv != SECSuccess) {
7944 » goto loser;» /* err code was set. */ 8112 goto loser; /* err code was set. */
7945 } 8113 }
7946 8114
7947 /* This must be done after we've set ss->ssl3.cwSpec in 8115 /* This must be done after we've set ss->ssl3.cwSpec in
7948 * ssl3_SendChangeCipherSpecs because SSL_GetChannelInfo uses information 8116 * ssl3_SendChangeCipherSpecs because SSL_GetChannelInfo uses information
7949 * from cwSpec. This must be done before we call ssl3_CheckFalseStart 8117 * from cwSpec. This must be done before we call ssl3_CheckFalseStart
7950 * because the false start callback (if any) may need the information from 8118 * because the false start callback (if any) may need the information from
7951 * the functions that depend on this being set. 8119 * the functions that depend on this being set.
7952 */ 8120 */
7953 ss->enoughFirstHsDone = PR_TRUE; 8121 ss->enoughFirstHsDone = PR_TRUE;
7954 8122
7955 if (!ss->firstHsDone) { 8123 if (!ss->firstHsDone) {
7956 » /* XXX: If the server's certificate hasn't been authenticated by this 8124 /* XXX: If the server's certificate hasn't been authenticated by this
7957 » * point, then we may be leaking this NPN message to an attacker. 8125 * point, then we may be leaking this NPN message to an attacker.
7958 » */ 8126 */
7959 » rv = ssl3_SendNextProto(ss); 8127 rv = ssl3_SendNextProto(ss);
7960 » if (rv != SECSuccess) { 8128 if (rv != SECSuccess) {
7961 » goto loser;»/* err code was set. */ 8129 goto loser; /* err code was set. */
7962 » } 8130 }
7963 } 8131 }
7964 8132
7965 rv = ssl3_SendEncryptedExtensions(ss); 8133 rv = ssl3_SendChannelIDEncryptedExtensions(ss);
7966 if (rv != SECSuccess) { 8134 if (rv != SECSuccess) {
7967 » goto loser; /* err code was set. */ 8135 goto loser; /* err code was set. */
7968 } 8136 }
7969 8137
7970 if (!ss->firstHsDone) { 8138 if (!ss->firstHsDone) {
7971 » if (ss->opt.enableFalseStart) { 8139 if (ss->opt.enableFalseStart) {
7972 » if (!ss->ssl3.hs.authCertificatePending) { 8140 if (!ss->ssl3.hs.authCertificatePending) {
7973 » » /* When we fix bug 589047, we will need to know whether we are 8141 /* When we fix bug 589047, we will need to know whether we are
7974 » » * false starting before we try to flush the client second 8142 * false starting before we try to flush the client second
7975 » » * round to the network. With that in mind, we purposefully 8143 * round to the network. With that in mind, we purposefully
7976 » » * call ssl3_CheckFalseStart before calling ssl3_SendFinished, 8144 * call ssl3_CheckFalseStart before calling ssl3_SendFinished,
7977 » » * which includes a call to ssl3_FlushHandshake, so that 8145 * which includes a call to ssl3_FlushHandshake, so that
7978 » » * no application develops a reliance on such flushing being 8146 * no application develops a reliance on such flushing being
7979 » » * done before its false start callback is called. 8147 * done before its false start callback is called.
7980 » » */ 8148 */
7981 » » ssl_ReleaseXmitBufLock(ss); 8149 ssl_ReleaseXmitBufLock(ss);
7982 » » rv = ssl3_CheckFalseStart(ss); 8150 rv = ssl3_CheckFalseStart(ss);
7983 » » ssl_GetXmitBufLock(ss); 8151 ssl_GetXmitBufLock(ss);
7984 » » if (rv != SECSuccess) { 8152 if (rv != SECSuccess) {
7985 » » goto loser; 8153 goto loser;
7986 » » } 8154 }
7987 » } else { 8155 } else {
7988 » » /* The certificate authentication and the server's Finished 8156 /* The certificate authentication and the server's Finished
7989 » » * message are racing each other. If the certificate 8157 * message are racing each other. If the certificate
7990 » » * authentication wins, then we will try to false start in 8158 * authentication wins, then we will try to false start in
7991 » » * ssl3_AuthCertificateComplete. 8159 * ssl3_AuthCertificateComplete.
7992 » » */ 8160 */
7993 » » SSL_TRC(3, ("%d: SSL3[%p]: deferring false start check because" 8161 SSL_TRC(3, ("%d: SSL3[%p]: deferring false start check because"
7994 » » » " certificate authentication is still pending.", 8162 " certificate authentication is still pending.",
7995 » » » SSL_GETPID(), ss->fd)); 8163 SSL_GETPID(), ss->fd));
7996 » } 8164 }
7997 » } 8165 }
7998 } 8166 }
7999 8167
8000 rv = ssl3_SendFinished(ss, 0); 8168 rv = ssl3_SendFinished(ss, 0);
8001 if (rv != SECSuccess) { 8169 if (rv != SECSuccess) {
8002 » goto loser;» /* err code was set. */ 8170 goto loser; /* err code was set. */
8003 } 8171 }
8004 8172
8005 ssl_ReleaseXmitBufLock(ss);»» /*******************************/ 8173 ssl_ReleaseXmitBufLock(ss); /*******************************/
8006 8174
8007 if (!ss->ssl3.hs.isResuming && 8175 if (!ss->ssl3.hs.isResuming &&
8008 ssl3_ExtensionNegotiated(ss, ssl_channel_id_xtn)) { 8176 ssl3_ExtensionNegotiated(ss, ssl_channel_id_xtn)) {
8009 /* If we are negotiating ChannelID on a full handshake then we record 8177 /* If we are negotiating ChannelID on a full handshake then we record
8010 * the handshake hashes in |sid| at this point. They will be needed in 8178 * the handshake hashes in |sid| at this point. They will be needed in
8011 * the event that we resume this session and use ChannelID on the 8179 * the event that we resume this session and use ChannelID on the
8012 * resumption handshake. */ 8180 * resumption handshake. */
8013 SSL3Hashes hashes; 8181 SSL3Hashes hashes;
8014 SECItem *originalHandshakeHash = 8182 SECItem *originalHandshakeHash =
8015 &ss->sec.ci.sid->u.ssl3.originalHandshakeHash; 8183 &ss->sec.ci.sid->u.ssl3.originalHandshakeHash;
8016 PORT_Assert(ss->sec.ci.sid->cached == never_cached); 8184 PORT_Assert(ss->sec.ci.sid->cached == never_cached);
8017 8185
8018 ssl_GetSpecReadLock(ss); 8186 ssl_GetSpecReadLock(ss);
8019 PORT_Assert(ss->version > SSL_LIBRARY_VERSION_3_0); 8187 PORT_Assert(ss->version > SSL_LIBRARY_VERSION_3_0);
8020 rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.cwSpec, &hashes, 0); 8188 rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.cwSpec, &hashes, 0);
8021 ssl_ReleaseSpecReadLock(ss); 8189 ssl_ReleaseSpecReadLock(ss);
8022 if (rv != SECSuccess) { 8190 if (rv != SECSuccess) {
8023 return rv; 8191 return rv;
8024 } 8192 }
8025 8193
8026 PORT_Assert(originalHandshakeHash->len == 0); 8194 PORT_Assert(originalHandshakeHash->len == 0);
8027 originalHandshakeHash->data = PORT_Alloc(hashes.len); 8195 originalHandshakeHash->data = PORT_Alloc(hashes.len);
8028 if (!originalHandshakeHash->data) 8196 if (!originalHandshakeHash->data)
8029 return SECFailure; 8197 return SECFailure;
8030 originalHandshakeHash->len = hashes.len; 8198 originalHandshakeHash->len = hashes.len;
8031 memcpy(originalHandshakeHash->data, hashes.u.raw, hashes.len); 8199 memcpy(originalHandshakeHash->data, hashes.u.raw, hashes.len);
8032 } 8200 }
8033 8201
8034 if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn)) 8202 if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn))
8035 » ss->ssl3.hs.ws = wait_new_session_ticket; 8203 ss->ssl3.hs.ws = wait_new_session_ticket;
8036 else 8204 else
8037 » ss->ssl3.hs.ws = wait_change_cipher; 8205 ss->ssl3.hs.ws = wait_change_cipher;
8038 8206
8039 PORT_Assert(ssl3_WaitingForStartOfServerSecondRound(ss)); 8207 PORT_Assert(ssl3_WaitingForServerSecondRound(ss));
8040 8208
8041 return SECSuccess; 8209 return SECSuccess;
8042 8210
8043 loser: 8211 loser:
8044 ssl_ReleaseXmitBufLock(ss); 8212 ssl_ReleaseXmitBufLock(ss);
8045 return rv; 8213 return rv;
8046 } 8214 }
8047 8215
8048 /* 8216 /*
8049 * Routines used by servers 8217 * Routines used by servers
8050 */ 8218 */
8051 static SECStatus 8219 static SECStatus
8052 ssl3_SendHelloRequest(sslSocket *ss) 8220 ssl3_SendHelloRequest(sslSocket *ss)
8053 { 8221 {
8054 SECStatus rv; 8222 SECStatus rv;
8055 8223
8056 SSL_TRC(3, ("%d: SSL3[%d]: send hello_request handshake", SSL_GETPID(), 8224 SSL_TRC(3, ("%d: SSL3[%d]: send hello_request handshake", SSL_GETPID(),
8057 » » ss->fd)); 8225 ss->fd));
8058 8226
8059 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 8227 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8060 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); 8228 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
8061 8229
8062 rv = ssl3_AppendHandshakeHeader(ss, hello_request, 0); 8230 rv = ssl3_AppendHandshakeHeader(ss, hello_request, 0);
8063 if (rv != SECSuccess) { 8231 if (rv != SECSuccess) {
8064 » return rv;» /* err set by AppendHandshake */ 8232 return rv; /* err set by AppendHandshake */
8065 } 8233 }
8066 rv = ssl3_FlushHandshake(ss, 0); 8234 rv = ssl3_FlushHandshake(ss, 0);
8067 if (rv != SECSuccess) { 8235 if (rv != SECSuccess) {
8068 » return rv;» /* error code set by ssl3_FlushHandshake */ 8236 return rv; /* error code set by ssl3_FlushHandshake */
8069 } 8237 }
8070 ss->ssl3.hs.ws = wait_client_hello; 8238 ss->ssl3.hs.ws = wait_client_hello;
8071 return SECSuccess; 8239 return SECSuccess;
8072 } 8240 }
8073 8241
8074 /* 8242 /*
8075 * Called from: 8243 * Called from:
8076 *» ssl3_HandleClientHello() 8244 * ssl3_HandleClientHello()
8077 */ 8245 */
8078 static SECComparison 8246 static SECComparison
8079 ssl3_ServerNameCompare(const SECItem *name1, const SECItem *name2) 8247 ssl3_ServerNameCompare(const SECItem *name1, const SECItem *name2)
8080 { 8248 {
8081 if (!name1 != !name2) { 8249 if (!name1 != !name2) {
8082 return SECLessThan; 8250 return SECLessThan;
8083 } 8251 }
8084 if (!name1) { 8252 if (!name1) {
8085 return SECEqual; 8253 return SECEqual;
8086 } 8254 }
8087 if (name1->type != name2->type) { 8255 if (name1->type != name2->type) {
8088 return SECLessThan; 8256 return SECLessThan;
8089 } 8257 }
8090 return SECITEM_CompareItem(name1, name2); 8258 return SECITEM_CompareItem(name1, name2);
8091 } 8259 }
8092 8260
8093 /* Sets memory error when returning NULL. 8261 /* Sets memory error when returning NULL.
8094 * Called from: 8262 * Called from:
8095 *» ssl3_SendClientHello() 8263 * ssl3_SendClientHello()
8096 *» ssl3_HandleServerHello() 8264 * ssl3_HandleServerHello()
8097 *» ssl3_HandleClientHello() 8265 * ssl3_HandleClientHello()
8098 *» ssl3_HandleV2ClientHello() 8266 * ssl3_HandleV2ClientHello()
8099 */ 8267 */
8100 sslSessionID * 8268 sslSessionID *
8101 ssl3_NewSessionID(sslSocket *ss, PRBool is_server) 8269 ssl3_NewSessionID(sslSocket *ss, PRBool is_server)
8102 { 8270 {
8103 sslSessionID *sid; 8271 sslSessionID *sid;
8104 8272
8105 sid = PORT_ZNew(sslSessionID); 8273 sid = PORT_ZNew(sslSessionID);
8106 if (sid == NULL) 8274 if (sid == NULL)
8107 » return sid; 8275 return sid;
8108 8276
8109 if (is_server) { 8277 if (is_server) {
8110 const SECItem * srvName; 8278 const SECItem *srvName;
8111 SECStatus rv = SECSuccess; 8279 SECStatus rv = SECSuccess;
8112 8280
8113 ssl_GetSpecReadLock(ss);» /********************************/ 8281 ssl_GetSpecReadLock(ss); /********************************/
8114 srvName = &ss->ssl3.prSpec->srvVirtName; 8282 srvName = &ss->ssl3.prSpec->srvVirtName;
8115 if (srvName->len && srvName->data) { 8283 if (srvName->len && srvName->data) {
8116 rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.srvName, srvName); 8284 rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.srvName, srvName);
8117 } 8285 }
8118 ssl_ReleaseSpecReadLock(ss); /************************************/ 8286 ssl_ReleaseSpecReadLock(ss); /************************************/
8119 if (rv != SECSuccess) { 8287 if (rv != SECSuccess) {
8120 PORT_Free(sid); 8288 PORT_Free(sid);
8121 return NULL; 8289 return NULL;
8122 } 8290 }
8123 } 8291 }
8124 sid->peerID»» = (ss->peerID == NULL) ? NULL : PORT_Strdup(ss->peerID); 8292 sid->peerID = (ss->peerID == NULL) ? NULL : PORT_Strdup(ss->peerID);
8125 sid->urlSvrName» = (ss->url == NULL) ? NULL : PORT_Strdup(ss->url); 8293 sid->urlSvrName = (ss->url == NULL) ? NULL : PORT_Strdup(ss->url);
8126 sid->addr = ss->sec.ci.peer; 8294 sid->addr = ss->sec.ci.peer;
8127 sid->port = ss->sec.ci.port; 8295 sid->port = ss->sec.ci.port;
8128 sid->references = 1; 8296 sid->references = 1;
8129 sid->cached = never_cached; 8297 sid->cached = never_cached;
8130 sid->version = ss->version; 8298 sid->version = ss->version;
8131 8299
8132 sid->u.ssl3.keys.resumable = PR_TRUE; 8300 sid->u.ssl3.keys.resumable = PR_TRUE;
8133 sid->u.ssl3.policy = SSL_ALLOWED; 8301 sid->u.ssl3.policy = SSL_ALLOWED;
8134 sid->u.ssl3.clientWriteKey = NULL; 8302 sid->u.ssl3.clientWriteKey = NULL;
8135 sid->u.ssl3.serverWriteKey = NULL; 8303 sid->u.ssl3.serverWriteKey = NULL;
8136 sid->u.ssl3.keys.extendedMasterSecretUsed = PR_FALSE; 8304 sid->u.ssl3.keys.extendedMasterSecretUsed = PR_FALSE;
8137 8305
8138 if (is_server) { 8306 if (is_server) {
8139 » SECStatus rv; 8307 SECStatus rv;
8140 » int pid = SSL_GETPID(); 8308 int pid = SSL_GETPID();
8141 8309
8142 » sid->u.ssl3.sessionIDLength = SSL3_SESSIONID_BYTES; 8310 sid->u.ssl3.sessionIDLength = SSL3_SESSIONID_BYTES;
8143 » sid->u.ssl3.sessionID[0] = (pid >> 8) & 0xff; 8311 sid->u.ssl3.sessionID[0] = (pid >> 8) & 0xff;
8144 » sid->u.ssl3.sessionID[1] = pid & 0xff; 8312 sid->u.ssl3.sessionID[1] = pid & 0xff;
8145 » rv = PK11_GenerateRandom(sid->u.ssl3.sessionID + 2, 8313 rv = PK11_GenerateRandom(sid->u.ssl3.sessionID + 2,
8146 » SSL3_SESSIONID_BYTES -2); 8314 SSL3_SESSIONID_BYTES - 2);
8147 » if (rv != SECSuccess) { 8315 if (rv != SECSuccess) {
8148 » ssl_FreeSID(sid); 8316 ssl_FreeSID(sid);
8149 » ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE); 8317 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
8150 » return NULL; 8318 return NULL;
8151 » } 8319 }
8152 } 8320 }
8153 return sid; 8321 return sid;
8154 } 8322 }
8155 8323
8156 /* Called from: ssl3_HandleClientHello, ssl3_HandleV2ClientHello */ 8324 /* Called from: ssl3_HandleClientHello, ssl3_HandleV2ClientHello */
8157 static SECStatus 8325 static SECStatus
8158 ssl3_SendServerHelloSequence(sslSocket *ss) 8326 ssl3_SendServerHelloSequence(sslSocket *ss)
8159 { 8327 {
8160 const ssl3KEADef *kea_def; 8328 const ssl3KEADef *kea_def;
8161 SECStatus rv; 8329 SECStatus rv;
8162 8330
8163 SSL_TRC(3, ("%d: SSL3[%d]: begin send server_hello sequence", 8331 SSL_TRC(3, ("%d: SSL3[%d]: begin send server_hello sequence",
8164 » » SSL_GETPID(), ss->fd)); 8332 SSL_GETPID(), ss->fd));
8165 8333
8166 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 8334 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8167 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); 8335 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
8168 8336
8169 rv = ssl3_SendServerHello(ss); 8337 rv = ssl3_SendServerHello(ss);
8170 if (rv != SECSuccess) { 8338 if (rv != SECSuccess) {
8171 » return rv;» /* err code is set. */ 8339 return rv; /* err code is set. */
8172 } 8340 }
8173 rv = ssl3_SendCertificate(ss); 8341 rv = ssl3_SendCertificate(ss);
8174 if (rv != SECSuccess) { 8342 if (rv != SECSuccess) {
8175 » return rv;» /* error code is set. */ 8343 return rv; /* error code is set. */
8176 } 8344 }
8177 rv = ssl3_SendCertificateStatus(ss); 8345 rv = ssl3_SendCertificateStatus(ss);
8178 if (rv != SECSuccess) { 8346 if (rv != SECSuccess) {
8179 » return rv;» /* error code is set. */ 8347 return rv; /* error code is set. */
8180 } 8348 }
8181 /* We have to do this after the call to ssl3_SendServerHello, 8349 /* We have to do this after the call to ssl3_SendServerHello,
8182 * because kea_def is set up by ssl3_SendServerHello(). 8350 * because kea_def is set up by ssl3_SendServerHello().
8183 */ 8351 */
8184 kea_def = ss->ssl3.hs.kea_def; 8352 kea_def = ss->ssl3.hs.kea_def;
8185 ss->ssl3.hs.usedStepDownKey = PR_FALSE; 8353 ss->ssl3.hs.usedStepDownKey = PR_FALSE;
8186 8354
8187 if (kea_def->is_limited && kea_def->exchKeyType == kt_rsa) { 8355 if (kea_def->is_limited && kea_def->exchKeyType == kt_rsa) {
8188 » /* see if we can legally use the key in the cert. */ 8356 /* see if we can legally use the key in the cert. */
8189 » unsigned int keyLen; /* bytes */ 8357 unsigned int keyLen; /* bytes */
8190 8358
8191 » keyLen = PK11_GetPrivateModulusLen( 8359 keyLen = PK11_GetPrivateModulusLen(
8192 » » » ss->serverCerts[kea_def->exchKeyType].SERVERKEY); 8360 ss->serverCerts[kea_def->exchKeyType].SERVERKEY);
8193 8361
8194 » if (keyLen > 0 && 8362 if (keyLen > 0 &&
8195 » keyLen * BPB <= kea_def->key_size_limit ) { 8363 keyLen * BPB <= kea_def->key_size_limit) {
8196 » /* XXX AND cert is not signing only!! */ 8364 /* XXX AND cert is not signing only!! */
8197 » /* just fall through and use it. */ 8365 /* just fall through and use it. */
8198 » } else if (ss->stepDownKeyPair != NULL) { 8366 } else if (ss->stepDownKeyPair != NULL) {
8199 » ss->ssl3.hs.usedStepDownKey = PR_TRUE; 8367 ss->ssl3.hs.usedStepDownKey = PR_TRUE;
8200 » rv = ssl3_SendServerKeyExchange(ss); 8368 rv = ssl3_SendServerKeyExchange(ss);
8201 » if (rv != SECSuccess) { 8369 if (rv != SECSuccess) {
8202 » » return rv;» /* err code was set. */ 8370 return rv; /* err code was set. */
8203 » } 8371 }
8204 » } else { 8372 } else {
8205 #ifndef HACKED_EXPORT_SERVER 8373 #ifndef HACKED_EXPORT_SERVER
8206 » PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED); 8374 PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED);
8207 » return rv; 8375 return rv;
8208 #endif 8376 #endif
8209 » } 8377 }
8210 } else if (kea_def->ephemeral) { 8378 } else if (kea_def->ephemeral) {
8211 rv = ssl3_SendServerKeyExchange(ss); 8379 rv = ssl3_SendServerKeyExchange(ss);
8212 if (rv != SECSuccess) { 8380 if (rv != SECSuccess) {
8213 return rv;» /* err code was set. */ 8381 return rv; /* err code was set. */
8214 } 8382 }
8215 } 8383 }
8216 8384
8217 if (ss->opt.requestCertificate) { 8385 if (ss->opt.requestCertificate) {
8218 » rv = ssl3_SendCertificateRequest(ss); 8386 rv = ssl3_SendCertificateRequest(ss);
8219 » if (rv != SECSuccess) { 8387 if (rv != SECSuccess) {
8220 » return rv;» » /* err code is set. */ 8388 return rv; /* err code is set. */
8221 » } 8389 }
8222 } 8390 }
8223 rv = ssl3_SendServerHelloDone(ss); 8391 rv = ssl3_SendServerHelloDone(ss);
8224 if (rv != SECSuccess) { 8392 if (rv != SECSuccess) {
8225 » return rv;» » /* err code is set. */ 8393 return rv; /* err code is set. */
8226 } 8394 }
8227 8395
8228 ss->ssl3.hs.ws = (ss->opt.requestCertificate) ? wait_client_cert 8396 ss->ssl3.hs.ws = (ss->opt.requestCertificate) ? wait_client_cert
8229 : wait_client_key; 8397 : wait_client_key;
8230 return SECSuccess; 8398 return SECSuccess;
8231 } 8399 }
8232 8400
8233 /* An empty TLS Renegotiation Info (RI) extension */ 8401 /* An empty TLS Renegotiation Info (RI) extension */
8234 static const PRUint8 emptyRIext[5] = {0xff, 0x01, 0x00, 0x01, 0x00}; 8402 static const PRUint8 emptyRIext[5] = { 0xff, 0x01, 0x00, 0x01, 0x00 };
8235 8403
8236 static PRBool 8404 static PRBool
8237 ssl3_KEAAllowsSessionTicket(SSL3KeyExchangeAlgorithm kea) 8405 ssl3_KEAAllowsSessionTicket(SSL3KeyExchangeAlgorithm kea)
8238 { 8406 {
8239 switch (kea) { 8407 switch (kea) {
8240 » case kea_dhe_dss: 8408 case kea_dhe_dss:
8241 » case kea_dhe_dss_export: 8409 case kea_dhe_dss_export:
8242 » case kea_dh_dss_export: 8410 case kea_dh_dss_export:
8243 » case kea_dh_dss: 8411 case kea_dh_dss:
8244 » /* TODO: Fix session tickets for DSS. The server code rejects the 8412 /* TODO: Fix session tickets for DSS. The server code rejects the
8245 » * session ticket received from the client. Bug 1174677 */ 8413 * session ticket received from the client. Bug 1174677 */
8246 » return PR_FALSE; 8414 return PR_FALSE;
8247 » default: 8415 default:
8248 » return PR_TRUE; 8416 return PR_TRUE;
8249 }; 8417 };
8250 } 8418 }
8251 8419
8420 static void
8421 ssl3_CopyPeerCertsFromSID(sslSocket *ss, sslSessionID *sid)
8422 {
8423 PLArenaPool *arena;
8424 ssl3CertNode *lastCert = NULL;
8425 ssl3CertNode *certs = NULL;
8426 int i;
8427
8428 if (!sid->peerCertChain[0])
8429 return;
8430 PORT_Assert(!ss->ssl3.peerCertArena);
8431 PORT_Assert(!ss->ssl3.peerCertChain);
8432 ss->ssl3.peerCertArena = arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
8433 for (i = 0; i < MAX_PEER_CERT_CHAIN_SIZE && sid->peerCertChain[i]; i++) {
8434 ssl3CertNode *c = PORT_ArenaNew(arena, ssl3CertNode);
8435 c->cert = CERT_DupCertificate(sid->peerCertChain[i]);
8436 c->next = NULL;
8437 if (lastCert) {
8438 lastCert->next = c;
8439 } else {
8440 certs = c;
8441 }
8442 lastCert = c;
8443 }
8444 ss->ssl3.peerCertChain = certs;
8445 }
8446
8447 static void
8448 ssl3_CopyPeerCertsToSID(ssl3CertNode *certs, sslSessionID *sid)
8449 {
8450 int i = 0;
8451 ssl3CertNode *c = certs;
8452 for (; i < MAX_PEER_CERT_CHAIN_SIZE && c; i++, c = c->next) {
8453 PORT_Assert(!sid->peerCertChain[i]);
8454 sid->peerCertChain[i] = CERT_DupCertificate(c->cert);
8455 }
8456 }
8457
8252 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete 8458 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
8253 * ssl3 Client Hello message. 8459 * ssl3 Client Hello message.
8254 * Caller must hold Handshake and RecvBuf locks. 8460 * Caller must hold Handshake and RecvBuf locks.
8255 */ 8461 */
8256 static SECStatus 8462 static SECStatus
8257 ssl3_HandleClientHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) 8463 ssl3_HandleClientHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
8258 { 8464 {
8259 sslSessionID * sid = NULL; 8465 sslSessionID *sid = NULL;
8260 PRInt32» » tmp; 8466 PRInt32 tmp;
8261 unsigned int i; 8467 unsigned int i;
8262 int j; 8468 int j;
8263 SECStatus rv; 8469 SECStatus rv;
8264 int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO; 8470 int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
8265 SSL3AlertDescription desc = illegal_parameter; 8471 SSL3AlertDescription desc = illegal_parameter;
8266 SSL3AlertLevel level = alert_fatal; 8472 SSL3AlertLevel level = alert_fatal;
8267 SSL3ProtocolVersion version; 8473 SSL3ProtocolVersion version;
8268 SECItem sidBytes = {siBuffer, NULL, 0}; 8474 SECItem sidBytes = { siBuffer, NULL, 0 };
8269 SECItem cookieBytes = {siBuffer, NULL, 0}; 8475 SECItem cookieBytes = { siBuffer, NULL, 0 };
8270 SECItem suites = {siBuffer, NULL, 0}; 8476 SECItem suites = { siBuffer, NULL, 0 };
8271 SECItem comps = {siBuffer, NULL, 0}; 8477 SECItem comps = { siBuffer, NULL, 0 };
8272 PRBool haveSpecWriteLock = PR_FALSE; 8478 PRBool haveSpecWriteLock = PR_FALSE;
8273 PRBool haveXmitBufLock = PR_FALSE; 8479 PRBool haveXmitBufLock = PR_FALSE;
8274 PRBool canOfferSessionTicket = PR_FALSE; 8480 PRBool canOfferSessionTicket = PR_FALSE;
8481 PRBool isTLS13 = PR_FALSE;
8275 8482
8276 SSL_TRC(3, ("%d: SSL3[%d]: handle client_hello handshake", 8483 SSL_TRC(3, ("%d: SSL3[%d]: handle client_hello handshake",
8277 » SSL_GETPID(), ss->fd)); 8484 SSL_GETPID(), ss->fd));
8278 8485
8279 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 8486 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
8280 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 8487 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
8281 PORT_Assert( ss->ssl3.initialized ); 8488 PORT_Assert(ss->ssl3.initialized);
8282 ss->ssl3.hs.preliminaryInfo = 0; 8489 ss->ssl3.hs.preliminaryInfo = 0;
8283 8490
8284 if (!ss->sec.isServer || 8491 if (!ss->sec.isServer ||
8285 (ss->ssl3.hs.ws != wait_client_hello && 8492 (ss->ssl3.hs.ws != wait_client_hello &&
8286 ss->ssl3.hs.ws != idle_handshake)) { 8493 ss->ssl3.hs.ws != idle_handshake)) {
8287 desc = unexpected_message; 8494 desc = unexpected_message;
8288 errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO; 8495 errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO;
8289 goto alert_loser; 8496 goto alert_loser;
8290 } 8497 }
8291 if (ss->ssl3.hs.ws == idle_handshake && 8498 if (ss->ssl3.hs.ws == idle_handshake) {
8292 ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) { 8499 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
8293 desc = no_renegotiation; 8500 desc = unexpected_message;
8294 level = alert_warning; 8501 errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
8295 errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED; 8502 goto alert_loser;
8296 goto alert_loser; 8503 }
8504 if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
8505 desc = no_renegotiation;
8506 level = alert_warning;
8507 errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
8508 goto alert_loser;
8509 }
8297 } 8510 }
8298 8511
8299 /* Get peer name of client */ 8512 /* Get peer name of client */
8300 rv = ssl_GetPeerInfo(ss); 8513 rv = ssl_GetPeerInfo(ss);
8301 if (rv != SECSuccess) { 8514 if (rv != SECSuccess) {
8302 » return rv;» » /* error code is set. */ 8515 return rv; /* error code is set. */
8303 } 8516 }
8304 8517
8305 /* Clearing the handshake pointers so that ssl_Do1stHandshake won't 8518 /* Clearing the handshake pointers so that ssl_Do1stHandshake won't
8306 * call ssl2_HandleMessage. 8519 * call ssl2_HandleMessage.
8307 * 8520 *
8308 * The issue here is that TLS ordinarily starts out in 8521 * The issue here is that TLS ordinarily starts out in
8309 * ssl2_HandleV3HandshakeRecord() because of the backward-compatibility 8522 * ssl2_HandleV3HandshakeRecord() because of the backward-compatibility
8310 * code paths. That function zeroes these next pointers. But with DTLS, 8523 * code paths. That function zeroes these next pointers. But with DTLS,
8311 * we don't even try to do the v2 ClientHello so we skip that function 8524 * we don't even try to do the v2 ClientHello so we skip that function
8312 * and need to reset these values here. 8525 * and need to reset these values here.
8313 */ 8526 */
8314 if (IS_DTLS(ss)) { 8527 if (IS_DTLS(ss)) {
8315 » ss->nextHandshake = 0; 8528 ss->nextHandshake = 0;
8316 » ss->securityHandshake = 0; 8529 ss->securityHandshake = 0;
8317 } 8530 }
8318 8531
8319 /* We might be starting session renegotiation in which case we should 8532 /* We might be starting session renegotiation in which case we should
8320 * clear previous state. 8533 * clear previous state.
8321 */ 8534 */
8322 PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData)); 8535 PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
8323 ss->statelessResume = PR_FALSE; 8536 ss->statelessResume = PR_FALSE;
8324 8537
8325 if (IS_DTLS(ss)) { 8538 if (IS_DTLS(ss)) {
8326 » dtls_RehandshakeCleanup(ss); 8539 dtls_RehandshakeCleanup(ss);
8327 } 8540 }
8328 8541
8329 tmp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); 8542 tmp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
8330 if (tmp < 0) 8543 if (tmp < 0)
8331 » goto loser;» » /* malformed, alert already sent */ 8544 goto loser; /* malformed, alert already sent */
8332 8545
8333 /* Translate the version */ 8546 /* Translate the version */
8334 if (IS_DTLS(ss)) { 8547 if (IS_DTLS(ss)) {
8335 » ss->clientHelloVersion = version = 8548 ss->clientHelloVersion = version =
8336 » dtls_DTLSVersionToTLSVersion((SSL3ProtocolVersion)tmp); 8549 dtls_DTLSVersionToTLSVersion((SSL3ProtocolVersion)tmp);
8337 } else { 8550 } else {
8338 » ss->clientHelloVersion = version = (SSL3ProtocolVersion)tmp; 8551 ss->clientHelloVersion = version = (SSL3ProtocolVersion)tmp;
8339 } 8552 }
8340 8553
8341 rv = ssl3_NegotiateVersion(ss, version, PR_TRUE); 8554 rv = ssl3_NegotiateVersion(ss, version, PR_TRUE);
8342 if (rv != SECSuccess) { 8555 if (rv != SECSuccess) {
8343 » desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version 8556 desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version
8344 » : handshake_failure; 8557 : handshake_failure;
8345 » errCode = SSL_ERROR_UNSUPPORTED_VERSION; 8558 errCode = SSL_ERROR_UNSUPPORTED_VERSION;
8346 » goto alert_loser; 8559 goto alert_loser;
8347 } 8560 }
8561 isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3;
8348 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version; 8562 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version;
8349 8563
8350 rv = ssl3_InitHandshakeHashes(ss); 8564 rv = ssl3_InitHandshakeHashes(ss);
8351 if (rv != SECSuccess) { 8565 if (rv != SECSuccess) {
8352 » desc = internal_error; 8566 desc = internal_error;
8353 » errCode = PORT_GetError(); 8567 errCode = PORT_GetError();
8354 » goto alert_loser; 8568 goto alert_loser;
8569 }
8570
8571 /* Generate the Server Random now so it is available
8572 * when we process the ClientKeyShare in TLS 1.3 */
8573 rv = ssl3_GetNewRandom(&ss->ssl3.hs.server_random);
8574 if (rv != SECSuccess) {
8575 errCode = SSL_ERROR_GENERATE_RANDOM_FAILURE;
8576 goto loser;
8577 }
8578
8579 /*
8580 * [draft-ietf-tls-tls13-11 Section 6.3.1.1].
8581 * TLS 1.3 server implementations which respond to a ClientHello with a
8582 * client_version indicating TLS 1.2 or below MUST set the first eight
8583 * bytes of their Random value to the bytes:
8584 *
8585 * 44 4F 57 4E 47 52 44 01
8586 *
8587 * TLS 1.2 server implementations which respond to a ClientHello with a
8588 * client_version indicating TLS 1.1 or below SHOULD set the first eight
8589 * bytes of their Random value to the bytes:
8590 *
8591 * 44 4F 57 4E 47 52 44 00
8592 *
8593 * TODO(ekr@rtfm.com): Note this change was not added in the SSLv2
8594 * compat processing code since that will most likely be removed before
8595 * we ship the final version of TLS 1.3.
8596 */
8597 if (ss->vrange.max > ss->version) {
8598 switch (ss->vrange.max) {
8599 case SSL_LIBRARY_VERSION_TLS_1_3:
8600 PORT_Memcpy(ss->ssl3.hs.server_random.rand,
8601 tls13_downgrade_random,
8602 sizeof(tls13_downgrade_random));
8603 break;
8604 case SSL_LIBRARY_VERSION_TLS_1_2:
8605 PORT_Memcpy(ss->ssl3.hs.server_random.rand,
8606 tls12_downgrade_random,
8607 sizeof(tls12_downgrade_random));
8608 break;
8609 default:
8610 /* Do not change random. */
8611 break;
8612 }
8355 } 8613 }
8356 8614
8357 /* grab the client random data. */ 8615 /* grab the client random data. */
8358 rv = ssl3_ConsumeHandshake( 8616 rv = ssl3_ConsumeHandshake(
8359 » ss, &ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH, &b, &length); 8617 ss, &ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH, &b, &length);
8360 if (rv != SECSuccess) { 8618 if (rv != SECSuccess) {
8361 » goto loser;» » /* malformed */ 8619 goto loser; /* malformed */
8362 } 8620 }
8363 8621
8364 /* grab the client's SID, if present. */ 8622 /* grab the client's SID, if present. */
8365 rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length); 8623 rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length);
8366 if (rv != SECSuccess) { 8624 if (rv != SECSuccess) {
8367 » goto loser;» » /* malformed */ 8625 goto loser; /* malformed */
8368 } 8626 }
8369 8627
8370 /* grab the client's cookie, if present. */ 8628 /* grab the client's cookie, if present. */
8371 if (IS_DTLS(ss)) { 8629 if (IS_DTLS(ss)) {
8372 » rv = ssl3_ConsumeHandshakeVariable(ss, &cookieBytes, 1, &b, &length); 8630 rv = ssl3_ConsumeHandshakeVariable(ss, &cookieBytes, 1, &b, &length);
8373 » if (rv != SECSuccess) { 8631 if (rv != SECSuccess) {
8374 » goto loser;»» /* malformed */ 8632 goto loser; /* malformed */
8375 » } 8633 }
8376 } 8634 }
8377 8635
8378 /* grab the list of cipher suites. */ 8636 /* grab the list of cipher suites. */
8379 rv = ssl3_ConsumeHandshakeVariable(ss, &suites, 2, &b, &length); 8637 rv = ssl3_ConsumeHandshakeVariable(ss, &suites, 2, &b, &length);
8380 if (rv != SECSuccess) { 8638 if (rv != SECSuccess) {
8381 » goto loser;» » /* malformed */ 8639 goto loser; /* malformed */
8382 } 8640 }
8383 8641
8384 /* If the ClientHello version is less than our maximum version, check for a 8642 /* If the ClientHello version is less than our maximum version, check for a
8385 * TLS_FALLBACK_SCSV and reject the connection if found. */ 8643 * TLS_FALLBACK_SCSV and reject the connection if found. */
8386 if (ss->vrange.max > ss->clientHelloVersion) { 8644 if (ss->vrange.max > ss->clientHelloVersion) {
8387 » for (i = 0; i + 1 < suites.len; i += 2) { 8645 for (i = 0; i + 1 < suites.len; i += 2) {
8388 » PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1]; 8646 PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
8389 » if (suite_i != TLS_FALLBACK_SCSV) 8647 if (suite_i != TLS_FALLBACK_SCSV)
8390 » » continue; 8648 continue;
8391 » desc = inappropriate_fallback; 8649 desc = inappropriate_fallback;
8392 » errCode = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT; 8650 errCode = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT;
8393 » goto alert_loser; 8651 goto alert_loser;
8394 » } 8652 }
8395 } 8653 }
8396 8654
8397 /* grab the list of compression methods. */ 8655 /* grab the list of compression methods. */
8398 rv = ssl3_ConsumeHandshakeVariable(ss, &comps, 1, &b, &length); 8656 rv = ssl3_ConsumeHandshakeVariable(ss, &comps, 1, &b, &length);
8399 if (rv != SECSuccess) { 8657 if (rv != SECSuccess) {
8400 » goto loser;» » /* malformed */ 8658 goto loser; /* malformed */
8401 } 8659 }
8402 8660
8403 /* TLS 1.3 requires that compression be empty */ 8661 /* TLS 1.3 requires that compression be empty */
8404 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) { 8662 if (isTLS13) {
8405 if (comps.len != 1 || comps.data[0] != ssl_compression_null) { 8663 if (comps.len != 1 || comps.data[0] != ssl_compression_null) {
8406 goto loser; 8664 goto loser;
8407 } 8665 }
8408 } 8666 }
8409 desc = handshake_failure; 8667 desc = handshake_failure;
8410 8668
8411 /* Handle TLS hello extensions for SSL3 & TLS. We do not know if 8669 /* Handle TLS hello extensions for SSL3 & TLS. We do not know if
8412 * we are restarting a previous session until extensions have been 8670 * we are restarting a previous session until extensions have been
8413 * parsed, since we might have received a SessionTicket extension. 8671 * parsed, since we might have received a SessionTicket extension.
8414 * Note: we allow extensions even when negotiating SSL3 for the sake 8672 * Note: we allow extensions even when negotiating SSL3 for the sake
8415 * of interoperability (and backwards compatibility). 8673 * of interoperability (and backwards compatibility).
8416 */ 8674 */
8417 8675
8418 if (length) { 8676 if (length) {
8419 » /* Get length of hello extensions */ 8677 /* Get length of hello extensions */
8420 » PRInt32 extension_length; 8678 PRInt32 extension_length;
8421 » extension_length = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); 8679 extension_length = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
8422 » if (extension_length < 0) { 8680 if (extension_length < 0) {
8423 » goto loser;»» » » /* alert already sent */ 8681 goto loser; /* alert already sent */
8424 » } 8682 }
8425 » if (extension_length != length) { 8683 if (extension_length != length) {
8426 » ssl3_DecodeError(ss);» » /* send alert */ 8684 ssl3_DecodeError(ss); /* send alert */
8427 » goto loser; 8685 goto loser;
8428 » } 8686 }
8429 » rv = ssl3_HandleHelloExtensions(ss, &b, &length); 8687 rv = ssl3_HandleHelloExtensions(ss, &b, &length, client_hello);
8430 » if (rv != SECSuccess) { 8688 if (rv != SECSuccess) {
8431 » goto loser;»» /* malformed */ 8689 goto loser; /* malformed */
8432 » } 8690 }
8433 } 8691 }
8434 if (!ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { 8692 if (!ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
8435 » /* If we didn't receive an RI extension, look for the SCSV, 8693 /* If we didn't receive an RI extension, look for the SCSV,
8436 » * and if found, treat it just like an empty RI extension 8694 * and if found, treat it just like an empty RI extension
8437 » * by processing a local copy of an empty RI extension. 8695 * by processing a local copy of an empty RI extension.
8438 » */ 8696 */
8439 » for (i = 0; i + 1 < suites.len; i += 2) { 8697 for (i = 0; i + 1 < suites.len; i += 2) {
8440 » PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1]; 8698 PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
8441 » if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) { 8699 if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) {
8442 » » SSL3Opaque * b2 = (SSL3Opaque *)emptyRIext; 8700 SSL3Opaque *b2 = (SSL3Opaque *)emptyRIext;
8443 » » PRUint32 L2 = sizeof emptyRIext; 8701 PRUint32 L2 = sizeof emptyRIext;
8444 » » (void)ssl3_HandleHelloExtensions(ss, &b2, &L2); 8702 (void)ssl3_HandleHelloExtensions(ss, &b2, &L2, client_hello);
8445 » » break; 8703 break;
8446 » } 8704 }
8447 » } 8705 }
8448 } 8706 }
8449 if (ss->firstHsDone && 8707 if (ss->firstHsDone &&
8450 (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_REQUIRES_XTN || 8708 (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_REQUIRES_XTN ||
8451 ss->opt.enableRenegotiation == SSL_RENEGOTIATE_TRANSITIONAL) && 8709 ss->opt.enableRenegotiation == SSL_RENEGOTIATE_TRANSITIONAL) &&
8452 » !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { 8710 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
8453 » desc = no_renegotiation; 8711 desc = no_renegotiation;
8454 » level = alert_warning; 8712 level = alert_warning;
8455 » errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED; 8713 errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
8456 » goto alert_loser; 8714 goto alert_loser;
8457 } 8715 }
8458 if ((ss->opt.requireSafeNegotiation || 8716 if ((ss->opt.requireSafeNegotiation ||
8459 (ss->firstHsDone && ss->peerRequestedProtection)) && 8717 (ss->firstHsDone && ss->peerRequestedProtection)) &&
8460 » !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { 8718 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
8461 » desc = handshake_failure; 8719 desc = handshake_failure;
8462 » errCode = SSL_ERROR_UNSAFE_NEGOTIATION; 8720 errCode = SSL_ERROR_UNSAFE_NEGOTIATION;
8463 » goto alert_loser; 8721 goto alert_loser;
8464 } 8722 }
8465 8723
8466 /* We do stateful resumes only if either of the following 8724 /* We do stateful resumes only if either of the following
8467 * conditions are satisfied: (1) the client does not support the 8725 * conditions are satisfied: (1) the client does not support the
8468 * session ticket extension, or (2) the client support the session 8726 * session ticket extension, or (2) the client support the session
8469 * ticket extension, but sent an empty ticket. 8727 * ticket extension, but sent an empty ticket.
8470 */ 8728 */
8471 if (!ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) || 8729 if (!ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) ||
8472 » ss->xtnData.emptySessionTicket) { 8730 ss->xtnData.emptySessionTicket) {
8473 » if (sidBytes.len > 0 && !ss->opt.noCache) { 8731 if (sidBytes.len > 0 && !ss->opt.noCache) {
8474 » SSL_TRC(7, ("%d: SSL3[%d]: server, lookup client session-id for 0x%0 8x%08x%08x%08x", 8732 SSL_TRC(7, ("%d: SSL3[%d]: server, lookup client session-id for 0x%0 8x%08x%08x%08x",
8475 » » » SSL_GETPID(), ss->fd, ss->sec.ci.peer.pr_s6_addr32[0], 8733 SSL_GETPID(), ss->fd, ss->sec.ci.peer.pr_s6_addr32[0],
8476 » » » ss->sec.ci.peer.pr_s6_addr32[1], 8734 ss->sec.ci.peer.pr_s6_addr32[1],
8477 » » » ss->sec.ci.peer.pr_s6_addr32[2], 8735 ss->sec.ci.peer.pr_s6_addr32[2],
8478 » » » ss->sec.ci.peer.pr_s6_addr32[3])); 8736 ss->sec.ci.peer.pr_s6_addr32[3]));
8479 » if (ssl_sid_lookup) { 8737 if (ssl_sid_lookup) {
8480 » » sid = (*ssl_sid_lookup)(&ss->sec.ci.peer, sidBytes.data, 8738 sid = (*ssl_sid_lookup)(&ss->sec.ci.peer, sidBytes.data,
8481 » » » » » sidBytes.len, ss->dbHandle); 8739 sidBytes.len, ss->dbHandle);
8482 » } else { 8740 } else {
8483 » » errCode = SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED; 8741 errCode = SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED;
8484 » » goto loser; 8742 goto loser;
8485 » } 8743 }
8486 » } 8744 }
8487 } else if (ss->statelessResume) { 8745 } else if (ss->statelessResume) {
8488 » /* Fill in the client's session ID if doing a stateless resume. 8746 /* Fill in the client's session ID if doing a stateless resume.
8489 » * (When doing stateless resumes, server echos client's SessionID.) 8747 * (When doing stateless resumes, server echos client's SessionID.)
8490 » */ 8748 */
8491 » sid = ss->sec.ci.sid; 8749 sid = ss->sec.ci.sid;
8492 » PORT_Assert(sid != NULL); /* Should have already been filled in.*/ 8750 PORT_Assert(sid != NULL); /* Should have already been filled in.*/
8493 8751
8494 » if (sidBytes.len > 0 && sidBytes.len <= SSL3_SESSIONID_BYTES) { 8752 if (sidBytes.len > 0 && sidBytes.len <= SSL3_SESSIONID_BYTES) {
8495 » sid->u.ssl3.sessionIDLength = sidBytes.len; 8753 sid->u.ssl3.sessionIDLength = sidBytes.len;
8496 » PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data, 8754 PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data,
8497 » » sidBytes.len); 8755 sidBytes.len);
8498 » sid->u.ssl3.sessionIDLength = sidBytes.len; 8756 sid->u.ssl3.sessionIDLength = sidBytes.len;
8499 » } else { 8757 } else {
8500 » sid->u.ssl3.sessionIDLength = 0; 8758 sid->u.ssl3.sessionIDLength = 0;
8501 » } 8759 }
8502 » ss->sec.ci.sid = NULL; 8760 ss->sec.ci.sid = NULL;
8503 } 8761 }
8504 8762
8505 /* We only send a session ticket extension if the client supports 8763 /* We only send a session ticket extension if the client supports
8506 * the extension and we are unable to do either a stateful or 8764 * the extension and we are unable to do either a stateful or
8507 * stateless resume. 8765 * stateless resume.
8508 * 8766 *
8509 * TODO: send a session ticket if performing a stateful 8767 * TODO: send a session ticket if performing a stateful
8510 * resumption. (As per RFC4507, a server may issue a session 8768 * resumption. (As per RFC4507, a server may issue a session
8511 * ticket while doing a (stateless or stateful) session resume, 8769 * ticket while doing a (stateless or stateful) session resume,
8512 * but OpenSSL-0.9.8g does not accept session tickets while 8770 * but OpenSSL-0.9.8g does not accept session tickets while
8513 * resuming.) 8771 * resuming.)
8514 */ 8772 */
8515 if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) && sid == NULL) { 8773 if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) && sid == NULL) {
8516 » canOfferSessionTicket = PR_TRUE; 8774 canOfferSessionTicket = PR_TRUE;
8517 } 8775 }
8518 8776
8519 if (sid != NULL) { 8777 if (sid != NULL) {
8520 » /* We've found a session cache entry for this client. 8778 /* We've found a session cache entry for this client.
8521 » * Now, if we're going to require a client-auth cert, 8779 * Now, if we're going to require a client-auth cert,
8522 » * and we don't already have this client's cert in the session cache, 8780 * and we don't already have this client's cert in the session cache,
8523 » * and this is the first handshake on this connection (not a redo), 8781 * and this is the first handshake on this connection (not a redo),
8524 » * then drop this old cache entry and start a new session. 8782 * then drop this old cache entry and start a new session.
8525 » */ 8783 */
8526 » if ((sid->peerCert == NULL) && ss->opt.requestCertificate && 8784 if ((sid->peerCert == NULL) && ss->opt.requestCertificate &&
8527 » ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) || 8785 ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) ||
8528 » (ss->opt.requireCertificate == SSL_REQUIRE_NO_ERROR) || 8786 (ss->opt.requireCertificate == SSL_REQUIRE_NO_ERROR) ||
8529 » ((ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE) 8787 ((ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE) &&
8530 » && !ss->firstHsDone))) { 8788 !ss->firstHsDone))) {
8531 8789
8532 » SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_not_ok ); 8790 SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_not_ok);
8533 » if (ss->sec.uncache) 8791 if (ss->sec.uncache)
8534 ss->sec.uncache(sid); 8792 ss->sec.uncache(sid);
8535 » ssl_FreeSID(sid); 8793 ssl_FreeSID(sid);
8536 » sid = NULL; 8794 sid = NULL;
8537 » } 8795 }
8538 } 8796 }
8539 8797
8540 #ifndef NSS_DISABLE_ECC 8798 #ifndef NSS_DISABLE_ECC
8541 /* Disable any ECC cipher suites for which we have no cert. */ 8799 /* Disable any ECC cipher suites for which we have no cert. */
8542 ssl3_FilterECCipherSuitesByServerCerts(ss); 8800 ssl3_FilterECCipherSuitesByServerCerts(ss);
8543 #endif 8801 #endif
8544 8802
8545 if (IS_DTLS(ss)) { 8803 if (IS_DTLS(ss)) {
8546 » ssl3_DisableNonDTLSSuites(ss); 8804 ssl3_DisableNonDTLSSuites(ss);
8547 }
8548
8549 if (!ssl3_HasGCMSupport()) {
8550 » ssl3_DisableGCMSuites(ss);
8551 } 8805 }
8552 8806
8553 #ifdef PARANOID 8807 #ifdef PARANOID
8554 /* Look for a matching cipher suite. */ 8808 /* Look for a matching cipher suite. */
8555 j = ssl3_config_match_init(ss); 8809 j = ssl3_config_match_init(ss);
8556 if (j <= 0) {» » /* no ciphers are working/supported by PK11 */ 8810 if (j <= 0) { /* no ciphers are working/supported by PK11 * /
8557 » errCode = PORT_GetError();» /* error code is already set. */ 8811 errCode = PORT_GetError(); /* error code is already set. */
8558 » goto alert_loser; 8812 goto alert_loser;
8559 } 8813 }
8560 #endif 8814 #endif
8561 8815
8562 /* If we already have a session for this client, be sure to pick the 8816 /* If we already have a session for this client, be sure to pick the
8563 ** same cipher suite and compression method we picked before. 8817 ** same cipher suite and compression method we picked before.
8564 ** This is not a loop, despite appearances. 8818 ** This is not a loop, despite appearances.
8565 */ 8819 */
8566 if (sid) do { 8820 if (sid)
8567 » ssl3CipherSuiteCfg *suite; 8821 do {
8822 ssl3CipherSuiteCfg *suite;
8568 #ifdef PARANOID 8823 #ifdef PARANOID
8569 » SSLVersionRange vrange = {ss->version, ss->version}; 8824 SSLVersionRange vrange = { ss->version, ss->version };
8570 #endif 8825 #endif
8571 8826
8572 » /* Check that the cached compression method is still enabled. */ 8827 /* Check that the cached compression method is still enabled. */
8573 » if (!compressionEnabled(ss, sid->u.ssl3.compression)) 8828 if (!compressionEnabled(ss, sid->u.ssl3.compression))
8574 » break; 8829 break;
8575 8830
8576 » /* Check that the cached compression method is in the client's list */ 8831 /* Check that the cached compression method is in the client's list */
8577 » for (i = 0; i < comps.len; i++) { 8832 for (i = 0; i < comps.len; i++) {
8578 » if (comps.data[i] == sid->u.ssl3.compression) 8833 if (comps.data[i] == sid->u.ssl3.compression)
8579 » » break; 8834 break;
8580 » } 8835 }
8581 » if (i == comps.len) 8836 if (i == comps.len)
8582 » break; 8837 break;
8583 8838
8584 » suite = ss->cipherSuites; 8839 suite = ss->cipherSuites;
8585 » /* Find the entry for the cipher suite used in the cached session. */ 8840 /* Find the entry for the cipher suite used in the cached session. * /
8586 » for (j = ssl_V3_SUITES_IMPLEMENTED; j > 0; --j, ++suite) { 8841 for (j = ssl_V3_SUITES_IMPLEMENTED; j > 0; --j, ++suite) {
8587 » if (suite->cipher_suite == sid->u.ssl3.cipherSuite) 8842 if (suite->cipher_suite == sid->u.ssl3.cipherSuite)
8588 » » break; 8843 break;
8589 » } 8844 }
8590 » PORT_Assert(j > 0); 8845 PORT_Assert(j > 0);
8591 » if (j <= 0) 8846 if (j <= 0)
8592 » break; 8847 break;
8593 #ifdef PARANOID 8848 #ifdef PARANOID
8594 » /* Double check that the cached cipher suite is still enabled, 8849 /* Double check that the cached cipher suite is still enabled,
8595 » * implemented, and allowed by policy. Might have been disabled. 8850 * implemented, and allowed by policy. Might have been disabled.
8596 » * The product policy won't change during the process lifetime. 8851 * The product policy won't change during the process lifetime.
8597 » * Implemented ("isPresent") shouldn't change for servers. 8852 * Implemented ("isPresent") shouldn't change for servers.
8598 » */ 8853 */
8599 » if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange, ss)) 8854 if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange, ss))
8600 » break; 8855 break;
8601 #else 8856 #else
8602 » if (!suite->enabled) 8857 if (!suite->enabled)
8603 » break; 8858 break;
8604 #endif 8859 #endif
8605 » /* Double check that the cached cipher suite is in the client's list */ 8860 /* Double check that the cached cipher suite is in the client's list */
8606 » for (i = 0; i + 1 < suites.len; i += 2) { 8861 for (i = 0; i + 1 < suites.len; i += 2) {
8607 » PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1]; 8862 PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
8608 » if (suite_i == suite->cipher_suite) { 8863 if (suite_i == suite->cipher_suite) {
8609 » » ss->ssl3.hs.cipher_suite = suite->cipher_suite; 8864 ss->ssl3.hs.cipher_suite =
8610 » » ss->ssl3.hs.suite_def = 8865 suite->cipher_suite;
8611 » » ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite); 8866 ss->ssl3.hs.suite_def =
8612 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_cipher_suite; 8867 ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite);
8868 ss->ssl3.hs.kea_def =
8869 &kea_defs[ss->ssl3.hs.suite_def->key_exchange_alg];
8870 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_cipher_suite;
8613 8871
8614 » » /* Use the cached compression method. */ 8872 /* Use the cached compression method. */
8615 » » ss->ssl3.hs.compression = sid->u.ssl3.compression; 8873 ss->ssl3.hs.compression =
8616 » » goto compression_found; 8874 sid->u.ssl3.compression;
8617 » } 8875 goto compression_found;
8618 » } 8876 }
8619 } while (0); 8877 }
8878 } while (0);
8620 8879
8621 /* START A NEW SESSION */ 8880 /* START A NEW SESSION */
8622 8881
8623 #ifndef PARANOID 8882 #ifndef PARANOID
8624 /* Look for a matching cipher suite. */ 8883 /* Look for a matching cipher suite. */
8625 j = ssl3_config_match_init(ss); 8884 j = ssl3_config_match_init(ss);
8626 if (j <= 0) {» » /* no ciphers are working/supported by PK11 */ 8885 if (j <= 0) { /* no ciphers are working/supported by PK11 * /
8627 » errCode = PORT_GetError();» /* error code is already set. */ 8886 errCode = PORT_GetError(); /* error code is already set. */
8628 » goto alert_loser; 8887 goto alert_loser;
8629 } 8888 }
8630 #endif 8889 #endif
8631 8890
8632 /* Select a cipher suite. 8891 /* Select a cipher suite.
8633 ** 8892 **
8634 ** NOTE: This suite selection algorithm should be the same as the one in 8893 ** NOTE: This suite selection algorithm should be the same as the one in
8635 ** ssl3_HandleV2ClientHello(). 8894 ** ssl3_HandleV2ClientHello().
8636 ** 8895 **
8637 ** If TLS 1.0 is enabled, we could handle the case where the client 8896 ** If TLS 1.0 is enabled, we could handle the case where the client
8638 ** offered TLS 1.1 but offered only export cipher suites by choosing TLS 8897 ** offered TLS 1.1 but offered only export cipher suites by choosing TLS
8639 ** 1.0 and selecting one of those export cipher suites. However, a secure 8898 ** 1.0 and selecting one of those export cipher suites. However, a secure
8640 ** TLS 1.1 client should not have export cipher suites enabled at all, 8899 ** TLS 1.1 client should not have export cipher suites enabled at all,
8641 ** and a TLS 1.1 client should definitely not be offering *only* export 8900 ** and a TLS 1.1 client should definitely not be offering *only* export
8642 ** cipher suites. Therefore, we refuse to negotiate export cipher suites 8901 ** cipher suites. Therefore, we refuse to negotiate export cipher suites
8643 ** with any client that indicates support for TLS 1.1 or higher when we 8902 ** with any client that indicates support for TLS 1.1 or higher when we
8644 ** (the server) have TLS 1.1 support enabled. 8903 ** (the server) have TLS 1.1 support enabled.
8645 */ 8904 */
8646 for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) { 8905 for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) {
8647 » ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j]; 8906 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j];
8648 » SSLVersionRange vrange = {ss->version, ss->version}; 8907 SSLVersionRange vrange = { ss->version, ss->version };
8649 » if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange, ss)) { 8908 if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange, ss)) {
8650 » continue; 8909 continue;
8651 » } 8910 }
8652 » for (i = 0; i + 1 < suites.len; i += 2) { 8911 for (i = 0; i + 1 < suites.len; i += 2) {
8653 » PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1]; 8912 PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
8654 » if (suite_i == suite->cipher_suite) { 8913 if (suite_i == suite->cipher_suite) {
8655 » » ss->ssl3.hs.cipher_suite = suite->cipher_suite; 8914 ss->ssl3.hs.cipher_suite = suite->cipher_suite;
8656 » » ss->ssl3.hs.suite_def = 8915 ss->ssl3.hs.suite_def =
8657 » » ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite); 8916 ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite);
8917 ss->ssl3.hs.kea_def =
8918 &kea_defs[ss->ssl3.hs.suite_def->key_exchange_alg];
8658 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_cipher_suite; 8919 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_cipher_suite;
8659 » » goto suite_found; 8920 goto suite_found;
8660 » } 8921 }
8661 » } 8922 }
8662 } 8923 }
8663 errCode = SSL_ERROR_NO_CYPHER_OVERLAP; 8924 errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
8664 goto alert_loser; 8925 goto alert_loser;
8665 8926
8666 suite_found: 8927 suite_found:
8667 if (canOfferSessionTicket) 8928 if (canOfferSessionTicket)
8668 » canOfferSessionTicket = ssl3_KEAAllowsSessionTicket( 8929 canOfferSessionTicket = ssl3_KEAAllowsSessionTicket(
8669 » » » » ss->ssl3.hs.suite_def->key_exchange_alg); 8930 ss->ssl3.hs.suite_def->key_exchange_alg);
8670 8931
8671 if (canOfferSessionTicket) { 8932 if (canOfferSessionTicket) {
8672 » ssl3_RegisterServerHelloExtensionSender(ss, 8933 ssl3_RegisterServerHelloExtensionSender(ss,
8673 » ssl_session_ticket_xtn, ssl3_SendSessionTicketXtn); 8934 ssl_session_ticket_xtn, ssl3_Sen dSessionTicketXtn);
8674 } 8935 }
8675 8936
8676 /* Select a compression algorithm. */ 8937 /* Select a compression algorithm. */
8677 for (i = 0; i < comps.len; i++) { 8938 for (i = 0; i < comps.len; i++) {
8678 » if (!compressionEnabled(ss, comps.data[i])) 8939 if (!compressionEnabled(ss, comps.data[i]))
8679 » continue; 8940 continue;
8680 » for (j = 0; j < compressionMethodsCount; j++) { 8941 for (j = 0; j < compressionMethodsCount; j++) {
8681 » if (comps.data[i] == compressions[j]) { 8942 if (comps.data[i] == compressions[j]) {
8682 » » ss->ssl3.hs.compression = 8943 ss->ssl3.hs.compression =
8683 » » » » » (SSLCompressionMethod)compressions[j]; 8944 (SSLCompressionMethod)compressions[j];
8684 » » goto compression_found; 8945 goto compression_found;
8685 » } 8946 }
8686 » } 8947 }
8687 } 8948 }
8688 errCode = SSL_ERROR_NO_COMPRESSION_OVERLAP; 8949 errCode = SSL_ERROR_NO_COMPRESSION_OVERLAP;
8689 » » » » /* null compression must be supported */ 8950 /* null compression must be supported */
8690 goto alert_loser; 8951 goto alert_loser;
8691 8952
8692 compression_found: 8953 compression_found:
8693 suites.data = NULL; 8954 suites.data = NULL;
8694 comps.data = NULL; 8955 comps.data = NULL;
8695 8956
8696 ss->sec.send = ssl3_SendApplicationData; 8957 ss->sec.send = ssl3_SendApplicationData;
8697 8958
8698 /* If there are any failures while processing the old sid, 8959 /* If there are any failures while processing the old sid,
8699 * we don't consider them to be errors. Instead, We just behave 8960 * we don't consider them to be errors. Instead, We just behave
8700 * as if the client had sent us no sid to begin with, and make a new one. 8961 * as if the client had sent us no sid to begin with, and make a new one.
8701 * The exception here is attempts to resume extended_master_secret 8962 * The exception here is attempts to resume extended_master_secret
8702 * sessions without the extension, which causes an alert. 8963 * sessions without the extension, which causes an alert.
8703 */ 8964 */
8704 if (sid != NULL) do { 8965 if (sid != NULL)
8705 » ssl3CipherSpec *pwSpec; 8966 do {
8706 » SECItem wrappedMS; » /* wrapped key */ 8967 ssl3CipherSpec *pwSpec;
8707 8968 SECItem wrappedMS; /* wrapped key */
8708 » if (sid->version != ss->version || 8969
8709 » sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite || 8970 if (sid->version != ss->version ||
8710 » sid->u.ssl3.compression != ss->ssl3.hs.compression) { 8971 sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite ||
8711 » break;» /* not an error */ 8972 sid->u.ssl3.compression != ss->ssl3.hs.compression) {
8712 » } 8973 break; /* not an error */
8713 8974 }
8714 /* [draft-ietf-tls-session-hash-06; Section 5.3] 8975
8715 * o If the original session did not use the "extended_master_secret" 8976 /* [draft-ietf-tls-session-hash-06; Section 5.3]
8716 * extension but the new ClientHello contains the extension, then the 8977 * o If the original session did not use the "extended_master_secre t"
8717 * server MUST NOT perform the abbreviated handshake. Instead, it 8978 * extension but the new ClientHello contains the extension, then the
8718 * SHOULD continue with a full handshake (as described in 8979 * server MUST NOT perform the abbreviated handshake. Instead, i t
8719 * Section 5.2) to negotiate a new session. 8980 * SHOULD continue with a full handshake (as described in
8720 * 8981 * Section 5.2) to negotiate a new session.
8721 * o If the original session used the "extended_master_secret" 8982 *
8722 * extension but the new ClientHello does not contain the extension, 8983 * o If the original session used the "extended_master_secret"
8723 * the server MUST abort the abbreviated handshake. 8984 * extension but the new ClientHello does not contain the extensi on,
8724 */ 8985 * the server MUST abort the abbreviated handshake.
8725 if (ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) { 8986 */
8726 if (!sid->u.ssl3.keys.extendedMasterSecretUsed) { 8987 if (ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) {
8727 break;» /* not an error */ 8988 if (!sid->u.ssl3.keys.extendedMasterSecretUsed) {
8728 } 8989 break; /* not an error */
8729 } else { 8990 }
8730 if (sid->u.ssl3.keys.extendedMasterSecretUsed) { 8991 } else {
8731 /* Note: we do not destroy the session */ 8992 if (sid->u.ssl3.keys.extendedMasterSecretUsed) {
8732 desc = handshake_failure; 8993 /* Note: we do not destroy the session */
8733 errCode = SSL_ERROR_MISSING_EXTENDED_MASTER_SECRET; 8994 desc = handshake_failure;
8734 goto alert_loser; 8995 errCode = SSL_ERROR_MISSING_EXTENDED_MASTER_SECRET;
8735 } 8996 goto alert_loser;
8736 } 8997 }
8737 8998 }
8738 » if (ss->sec.ci.sid) { 8999
8739 » if (ss->sec.uncache) 9000 if (ss->sec.ci.sid) {
8740 ss->sec.uncache(ss->sec.ci.sid); 9001 if (ss->sec.uncache)
8741 » PORT_Assert(ss->sec.ci.sid != sid); /* should be impossible, but .. . */ 9002 ss->sec.uncache(ss->sec.ci.sid);
8742 » if (ss->sec.ci.sid != sid) { 9003 PORT_Assert(ss->sec.ci.sid != sid); /* should be impossible, but ... */
8743 » » ssl_FreeSID(ss->sec.ci.sid); 9004 if (ss->sec.ci.sid != sid) {
8744 » } 9005 ssl_FreeSID(ss->sec.ci.sid);
8745 » ss->sec.ci.sid = NULL; 9006 }
8746 » } 9007 ss->sec.ci.sid = NULL;
8747 » /* we need to resurrect the master secret.... */ 9008 }
8748 9009 /* we need to resurrect the master secret.... */
8749 » ssl_GetSpecWriteLock(ss); haveSpecWriteLock = PR_TRUE; 9010
8750 » pwSpec = ss->ssl3.pwSpec; 9011 ssl_GetSpecWriteLock(ss);
8751 » if (sid->u.ssl3.keys.msIsWrapped) { 9012 haveSpecWriteLock = PR_TRUE;
8752 » PK11SymKey * wrapKey; » /* wrapping key */ 9013 pwSpec = ss->ssl3.pwSpec;
8753 » CK_FLAGS keyFlags = 0; 9014 if (sid->u.ssl3.keys.msIsWrapped) {
9015 PK11SymKey *wrapKey; /* wrapping key */
9016 CK_FLAGS keyFlags = 0;
8754 #ifndef NO_PKCS11_BYPASS 9017 #ifndef NO_PKCS11_BYPASS
8755 » if (ss->opt.bypassPKCS11) { 9018 if (ss->opt.bypassPKCS11) {
8756 » » /* we cannot restart a non-bypass session in a 9019 /* we cannot restart a non-bypass session in a
8757 » » ** bypass socket. 9020 ** bypass socket.
8758 » » */ 9021 */
8759 » » break; 9022 break;
8760 » } 9023 }
8761 #endif 9024 #endif
8762 9025
8763 » wrapKey = getWrappingKey(ss, NULL, sid->u.ssl3.exchKeyType, 9026 wrapKey = getWrappingKey(ss, NULL, sid->u.ssl3.exchKeyType,
8764 » » » » sid->u.ssl3.masterWrapMech, 9027 sid->u.ssl3.masterWrapMech,
8765 » » » » ss->pkcs11PinArg); 9028 ss->pkcs11PinArg);
8766 » if (!wrapKey) { 9029 if (!wrapKey) {
8767 » » /* we have a SID cache entry, but no wrapping key for it??? */ 9030 /* we have a SID cache entry, but no wrapping key for it??? */
8768 » » break; 9031 break;
8769 » } 9032 }
8770 9033
8771 » if (ss->version > SSL_LIBRARY_VERSION_3_0) {» /* isTLS */ 9034 if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
8772 » » keyFlags = CKF_SIGN | CKF_VERIFY; 9035 keyFlags =
8773 » } 9036 CKF_SIGN | CKF_VERIFY;
8774 9037 }
8775 » wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; 9038
8776 » wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; 9039 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
8777 9040 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len;
8778 » /* unwrap the master secret. */ 9041
8779 » pwSpec->master_secret = 9042 /* unwrap the master secret. */
8780 » » PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech, 9043 pwSpec->master_secret =
8781 » » » NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE, 9044 PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMe ch,
8782 » » » CKA_DERIVE, sizeof(SSL3MasterSecret), keyFlags); 9045 NULL, &wrappedMS, CKM_SSL3_MASTER _KEY_DERIVE,
8783 » PK11_FreeSymKey(wrapKey); 9046 CKA_DERIVE, sizeof(SSL3MasterSecr et), keyFlags);
8784 » if (pwSpec->master_secret == NULL) { 9047 PK11_FreeSymKey(wrapKey);
8785 » » break;» /* not an error */ 9048 if (pwSpec->master_secret == NULL) {
8786 » } 9049 break; /* not an error */
9050 }
8787 #ifndef NO_PKCS11_BYPASS 9051 #ifndef NO_PKCS11_BYPASS
8788 » } else if (ss->opt.bypassPKCS11) { 9052 } else if (ss->opt.bypassPKCS11) {
8789 » wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; 9053 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
8790 » wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; 9054 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len;
8791 » memcpy(pwSpec->raw_master_secret, wrappedMS.data, wrappedMS.len); 9055 memcpy(pwSpec->raw_master_secret, wrappedMS.data, wrappedMS.len) ;
8792 » pwSpec->msItem.data = pwSpec->raw_master_secret; 9056 pwSpec->msItem.data = pwSpec->raw_master_secret;
8793 » pwSpec->msItem.len = wrappedMS.len; 9057 pwSpec->msItem.len = wrappedMS.len;
8794 #endif 9058 #endif
8795 » } else { 9059 } else {
8796 » /* We CAN restart a bypass session in a non-bypass socket. */ 9060 /* We CAN restart a bypass session in a non-bypass socket. */
8797 » /* need to import the raw master secret to session object */ 9061 /* need to import the raw master secret to session object */
8798 » PK11SlotInfo * slot; 9062 PK11SlotInfo *slot;
8799 » wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; 9063 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
8800 » wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; 9064 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len;
8801 » slot = PK11_GetInternalSlot(); 9065 slot = PK11_GetInternalSlot();
8802 » pwSpec->master_secret = 9066 pwSpec->master_secret =
8803 » » PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE, 9067 PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE,
8804 » » » » PK11_OriginUnwrap, CKA_ENCRYPT, &wrappedMS, 9068 PK11_OriginUnwrap, CKA_ENCRYPT, &wrappedMS ,
8805 » » » » NULL); 9069 NULL);
8806 » PK11_FreeSlot(slot); 9070 PK11_FreeSlot(slot);
8807 » if (pwSpec->master_secret == NULL) { 9071 if (pwSpec->master_secret == NULL) {
8808 » » break;» /* not an error */ 9072 break; /* not an error */
8809 » } 9073 }
8810 » } 9074 }
8811 » ss->sec.ci.sid = sid; 9075 ss->sec.ci.sid = sid;
8812 » if (sid->peerCert != NULL) { 9076 if (sid->peerCert != NULL) {
8813 » ss->sec.peerCert = CERT_DupCertificate(sid->peerCert); 9077 ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
8814 » ssl3_CopyPeerCertsFromSID(ss, sid); 9078 ssl3_CopyPeerCertsFromSID(ss, sid);
8815 » } 9079 }
8816 9080
8817 » /* 9081 /*
8818 » * Old SID passed all tests, so resume this old session. 9082 * Old SID passed all tests, so resume this old session.
8819 » * 9083 *
8820 » * XXX make sure compression still matches 9084 * XXX make sure compression still matches
8821 » */ 9085 */
8822 » SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_hits ); 9086 SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_hits);
8823 » if (ss->statelessResume) 9087 if (ss->statelessResume)
8824 » SSL_AtomicIncrementLong(& ssl3stats.hch_sid_stateless_resumes ); 9088 SSL_AtomicIncrementLong(&ssl3stats.hch_sid_stateless_resumes);
8825 » ss->ssl3.hs.isResuming = PR_TRUE; 9089 ss->ssl3.hs.isResuming = PR_TRUE;
8826 9090
8827 ss->sec.authAlgorithm = sid->authAlgorithm; 9091 ss->sec.authAlgorithm = sid->authAlgorithm;
8828 » ss->sec.authKeyBits = sid->authKeyBits; 9092 ss->sec.authKeyBits = sid->authKeyBits;
8829 » ss->sec.keaType = sid->keaType; 9093 ss->sec.keaType = sid->keaType;
8830 » ss->sec.keaKeyBits = sid->keaKeyBits; 9094 ss->sec.keaKeyBits = sid->keaKeyBits;
8831 9095
8832 » /* server sids don't remember the server cert we previously sent, 9096 /* server sids don't remember the server cert we previously sent,
8833 » ** but they do remember the kea type we originally used, so we 9097 ** but they do remember the kea type we originally used, so we
8834 » ** can locate it again, provided that the current ssl socket 9098 ** can locate it again, provided that the current ssl socket
8835 » ** has had its server certs configured the same as the previous one. 9099 ** has had its server certs configured the same as the previous one.
8836 » */ 9100 */
8837 » ss->sec.localCert = 9101 ss->sec.localCert =
8838 » » CERT_DupCertificate(ss->serverCerts[sid->keaType].serverCert); 9102 CERT_DupCertificate(ss->serverCerts[sid->keaType].serverCert);
8839 9103
8840 /* Copy cached name in to pending spec */ 9104 /* Copy cached name in to pending spec */
8841 if (sid != NULL && 9105 if (sid != NULL &&
8842 sid->version > SSL_LIBRARY_VERSION_3_0 && 9106 sid->version > SSL_LIBRARY_VERSION_3_0 &&
8843 sid->u.ssl3.srvName.len && sid->u.ssl3.srvName.data) { 9107 sid->u.ssl3.srvName.len && sid->u.ssl3.srvName.data) {
8844 /* Set server name from sid */ 9108 /* Set server name from sid */
8845 SECItem *sidName = &sid->u.ssl3.srvName; 9109 SECItem *sidName = &sid->u.ssl3.srvName;
8846 SECItem *pwsName = &ss->ssl3.pwSpec->srvVirtName; 9110 SECItem *pwsName = &ss->ssl3.pwSpec->srvVirtName;
8847 if (pwsName->data) { 9111 if (pwsName->data) {
8848 SECITEM_FreeItem(pwsName, PR_FALSE); 9112 SECITEM_FreeItem(pwsName, PR_FALSE);
8849 } 9113 }
8850 rv = SECITEM_CopyItem(NULL, pwsName, sidName); 9114 rv = SECITEM_CopyItem(NULL, pwsName, sidName);
9115 if (rv != SECSuccess) {
9116 errCode = PORT_GetError();
9117 desc = internal_error;
9118 goto alert_loser;
9119 }
9120 }
9121
9122 /* Clean up sni name array */
9123 if (ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn) &&
9124 ss->xtnData.sniNameArr) {
9125 PORT_Free(ss->xtnData.sniNameArr);
9126 ss->xtnData.sniNameArr = NULL;
9127 ss->xtnData.sniNameArrSize = 0;
9128 }
9129
9130 ssl_GetXmitBufLock(ss);
9131 haveXmitBufLock = PR_TRUE;
9132
9133 rv = ssl3_SendServerHello(ss);
8851 if (rv != SECSuccess) { 9134 if (rv != SECSuccess) {
8852 errCode = PORT_GetError(); 9135 errCode = PORT_GetError();
8853 desc = internal_error; 9136 goto loser;
8854 goto alert_loser; 9137 }
8855 } 9138
8856 } 9139 if (haveSpecWriteLock) {
8857 9140 ssl_ReleaseSpecWriteLock(ss);
8858 /* Clean up sni name array */ 9141 haveSpecWriteLock = PR_FALSE;
8859 if (ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn) && 9142 }
8860 ss->xtnData.sniNameArr) { 9143
8861 PORT_Free(ss->xtnData.sniNameArr); 9144 /* NULL value for PMS because we are re-using the old MS */
8862 ss->xtnData.sniNameArr = NULL; 9145 rv = ssl3_InitPendingCipherSpec(ss, NULL);
8863 ss->xtnData.sniNameArrSize = 0; 9146 if (rv != SECSuccess) {
8864 } 9147 errCode = PORT_GetError();
8865 9148 goto loser;
8866 » ssl_GetXmitBufLock(ss); haveXmitBufLock = PR_TRUE; 9149 }
8867 9150
8868 » rv = ssl3_SendServerHello(ss); 9151 rv = ssl3_SendChangeCipherSpecs(ss);
8869 » if (rv != SECSuccess) { 9152 if (rv != SECSuccess) {
8870 » errCode = PORT_GetError(); 9153 errCode = PORT_GetError();
8871 » goto loser; 9154 goto loser;
8872 » } 9155 }
8873 9156 rv = ssl3_SendFinished(ss, 0);
8874 » if (haveSpecWriteLock) { 9157 ss->ssl3.hs.ws = wait_change_cipher;
8875 » ssl_ReleaseSpecWriteLock(ss); 9158 if (rv != SECSuccess) {
8876 » haveSpecWriteLock = PR_FALSE; 9159 errCode = PORT_GetError();
8877 » } 9160 goto loser;
8878 9161 }
8879 » /* NULL value for PMS because we are re-using the old MS */ 9162
8880 » rv = ssl3_InitPendingCipherSpec(ss, NULL); 9163 if (haveXmitBufLock) {
8881 » if (rv != SECSuccess) { 9164 ssl_ReleaseXmitBufLock(ss);
8882 » errCode = PORT_GetError(); 9165 haveXmitBufLock = PR_FALSE;
8883 » goto loser; 9166 }
8884 » } 9167
8885 9168 return SECSuccess;
8886 » rv = ssl3_SendChangeCipherSpecs(ss); 9169 } while (0);
8887 » if (rv != SECSuccess) {
8888 » errCode = PORT_GetError();
8889 » goto loser;
8890 » }
8891 » rv = ssl3_SendFinished(ss, 0);
8892 » ss->ssl3.hs.ws = wait_change_cipher;
8893 » if (rv != SECSuccess) {
8894 » errCode = PORT_GetError();
8895 » goto loser;
8896 » }
8897
8898 » if (haveXmitBufLock) {
8899 » ssl_ReleaseXmitBufLock(ss);
8900 » haveXmitBufLock = PR_FALSE;
8901 » }
8902
8903 return SECSuccess;
8904 } while (0);
8905 9170
8906 if (haveSpecWriteLock) { 9171 if (haveSpecWriteLock) {
8907 » ssl_ReleaseSpecWriteLock(ss); 9172 ssl_ReleaseSpecWriteLock(ss);
8908 » haveSpecWriteLock = PR_FALSE; 9173 haveSpecWriteLock = PR_FALSE;
8909 } 9174 }
8910 9175
8911 if (sid) { »/* we had a sid, but it's no longer valid, free it */ 9176 if (sid) { /* we had a sid, but it's no longer valid, free it */
8912 » SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_not_ok ); 9177 SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_not_ok);
8913 » if (ss->sec.uncache) 9178 if (ss->sec.uncache)
8914 ss->sec.uncache(sid); 9179 ss->sec.uncache(sid);
8915 » ssl_FreeSID(sid); 9180 ssl_FreeSID(sid);
8916 » sid = NULL; 9181 sid = NULL;
8917 } 9182 }
8918 SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_misses ); 9183 SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_misses);
8919 9184
8920 if (ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn)) { 9185 if (ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn)) {
8921 int ret = 0; 9186 int ret = 0;
8922 if (ss->sniSocketConfig) do { /* not a loop */ 9187 if (ss->sniSocketConfig)
8923 PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) == 9188 do { /* not a loop */
8924 ssl_preinfo_all); 9189 PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==
8925 9190 ssl_preinfo_all);
8926 ret = SSL_SNI_SEND_ALERT; 9191
8927 /* If extension is negotiated, the len of names should > 0. */ 9192 ret = SSL_SNI_SEND_ALERT;
8928 if (ss->xtnData.sniNameArrSize) { 9193 /* If extension is negotiated, the len of names should > 0. */
8929 /* Calling client callback to reconfigure the socket. */ 9194 if (ss->xtnData.sniNameArrSize) {
8930 ret = (SECStatus)(*ss->sniSocketConfig)(ss->fd, 9195 /* Calling client callback to reconfigure the socket. */
8931 ss->xtnData.sniNameArr, 9196 ret = (SECStatus)(*ss->sniSocketConfig)(ss->fd,
8932 ss->xtnData.sniNameArrSize, 9197 ss->xtnData.sniNameA rr,
8933 ss->sniSocketConfigArg); 9198 ss->xtnData.sniNameA rrSize,
8934 } 9199 ss->sniSocketConfigA rg);
8935 if (ret <= SSL_SNI_SEND_ALERT) { 9200 }
8936 /* Application does not know the name or was not able to 9201 if (ret <= SSL_SNI_SEND_ALERT) {
8937 * properly reconfigure the socket. */ 9202 /* Application does not know the name or was not able to
8938 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; 9203 * properly reconfigure the socket. */
8939 desc = unrecognized_name; 9204 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
8940 break; 9205 desc = unrecognized_name;
8941 } else if (ret == SSL_SNI_CURRENT_CONFIG_IS_USED) { 9206 break;
8942 SECStatus rv = SECSuccess; 9207 } else if (ret == SSL_SNI_CURRENT_CONFIG_IS_USED) {
8943 SECItem * cwsName, *pwsName; 9208 SECStatus rv = SECSuccess;
8944 9209 SECItem *cwsName, *pwsName;
8945 ssl_GetSpecWriteLock(ss); /*******************************/ 9210
8946 pwsName = &ss->ssl3.pwSpec->srvVirtName; 9211 ssl_GetSpecWriteLock(ss); /*******************************/
8947 cwsName = &ss->ssl3.cwSpec->srvVirtName; 9212 pwsName = &ss->ssl3.pwSpec->srvVirtName;
9213 cwsName = &ss->ssl3.cwSpec->srvVirtName;
8948 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS 9214 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS
8949 /* not allow name change on the 2d HS */ 9215 /* not allow name change on the 2d HS */
8950 if (ss->firstHsDone) { 9216 if (ss->firstHsDone) {
8951 if (ssl3_ServerNameCompare(pwsName, cwsName)) { 9217 if (ssl3_ServerNameCompare(pwsName, cwsName)) {
8952 ssl_ReleaseSpecWriteLock(ss); /******************/ 9218 ssl_ReleaseSpecWriteLock(ss); /******************/
8953 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; 9219 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
9220 desc = handshake_failure;
9221 ret = SSL_SNI_SEND_ALERT;
9222 break;
9223 }
9224 }
9225 #endif
9226 if (pwsName->data) {
9227 SECITEM_FreeItem(pwsName, PR_FALSE);
9228 }
9229 if (cwsName->data) {
9230 rv = SECITEM_CopyItem(NULL, pwsName, cwsName);
9231 }
9232 ssl_ReleaseSpecWriteLock(ss); /**************************/
9233 if (rv != SECSuccess) {
9234 errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
9235 desc = internal_error;
9236 ret = SSL_SNI_SEND_ALERT;
9237 break;
9238 }
9239 } else if ((unsigned int)ret < ss->xtnData.sniNameArrSize) {
9240 /* Application has configured new socket info. Lets check it
9241 * and save the name. */
9242 SECStatus rv;
9243 SECItem *name = &ss->xtnData.sniNameArr[ret];
9244 int configedCiphers;
9245 SECItem *pwsName;
9246
9247 /* get rid of the old name and save the newly picked. */
9248 /* This code is protected by ssl3HandshakeLock. */
9249 ssl_GetSpecWriteLock(ss); /*******************************/
9250 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS
9251 /* not allow name change on the 2d HS */
9252 if (ss->firstHsDone) {
9253 SECItem *cwsName = &ss->ssl3.cwSpec->srvVirtName;
9254 if (ssl3_ServerNameCompare(name, cwsName)) {
9255 ssl_ReleaseSpecWriteLock(ss); /******************/
9256 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
9257 desc = handshake_failure;
9258 ret = SSL_SNI_SEND_ALERT;
9259 break;
9260 }
9261 }
9262 #endif
9263 pwsName = &ss->ssl3.pwSpec->srvVirtName;
9264 if (pwsName->data) {
9265 SECITEM_FreeItem(pwsName, PR_FALSE);
9266 }
9267 rv = SECITEM_CopyItem(NULL, pwsName, name);
9268 ssl_ReleaseSpecWriteLock(ss); /***************************/
9269 if (rv != SECSuccess) {
9270 errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
9271 desc = internal_error;
9272 ret = SSL_SNI_SEND_ALERT;
9273 break;
9274 }
9275 configedCiphers = ssl3_config_match_init(ss);
9276 if (configedCiphers <= 0) {
9277 /* no ciphers are working/supported */
9278 errCode = PORT_GetError();
8954 desc = handshake_failure; 9279 desc = handshake_failure;
8955 ret = SSL_SNI_SEND_ALERT; 9280 ret = SSL_SNI_SEND_ALERT;
8956 break; 9281 break;
8957 } 9282 }
8958 } 9283 /* Need to tell the client that application has picked
8959 #endif 9284 * the name from the offered list and reconfigured the socke t.
8960 if (pwsName->data) { 9285 */
8961 SECITEM_FreeItem(pwsName, PR_FALSE); 9286 ssl3_RegisterServerHelloExtensionSender(ss, ssl_server_name_ xtn,
8962 } 9287 ssl3_SendServerNameX tn);
8963 if (cwsName->data) { 9288 } else {
8964 rv = SECITEM_CopyItem(NULL, pwsName, cwsName); 9289 /* Callback returned index outside of the boundary. */
8965 } 9290 PORT_Assert((unsigned int)ret < ss->xtnData.sniNameArrSize);
8966 ssl_ReleaseSpecWriteLock(ss); /**************************/
8967 if (rv != SECSuccess) {
8968 errCode = SSL_ERROR_INTERNAL_ERROR_ALERT; 9291 errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
8969 desc = internal_error; 9292 desc = internal_error;
8970 ret = SSL_SNI_SEND_ALERT; 9293 ret = SSL_SNI_SEND_ALERT;
8971 break; 9294 break;
8972 } 9295 }
8973 } else if ((unsigned int)ret < ss->xtnData.sniNameArrSize) { 9296 } while (0);
8974 /* Application has configured new socket info. Lets check it
8975 * and save the name. */
8976 SECStatus rv;
8977 SECItem * name = &ss->xtnData.sniNameArr[ret];
8978 int configedCiphers;
8979 SECItem * pwsName;
8980
8981 /* get rid of the old name and save the newly picked. */
8982 /* This code is protected by ssl3HandshakeLock. */
8983 ssl_GetSpecWriteLock(ss); /*******************************/
8984 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS
8985 /* not allow name change on the 2d HS */
8986 if (ss->firstHsDone) {
8987 SECItem *cwsName = &ss->ssl3.cwSpec->srvVirtName;
8988 if (ssl3_ServerNameCompare(name, cwsName)) {
8989 ssl_ReleaseSpecWriteLock(ss); /******************/
8990 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
8991 desc = handshake_failure;
8992 ret = SSL_SNI_SEND_ALERT;
8993 break;
8994 }
8995 }
8996 #endif
8997 pwsName = &ss->ssl3.pwSpec->srvVirtName;
8998 if (pwsName->data) {
8999 SECITEM_FreeItem(pwsName, PR_FALSE);
9000 }
9001 rv = SECITEM_CopyItem(NULL, pwsName, name);
9002 ssl_ReleaseSpecWriteLock(ss); /***************************/
9003 if (rv != SECSuccess) {
9004 errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
9005 desc = internal_error;
9006 ret = SSL_SNI_SEND_ALERT;
9007 break;
9008 }
9009 configedCiphers = ssl3_config_match_init(ss);
9010 if (configedCiphers <= 0) {
9011 /* no ciphers are working/supported */
9012 errCode = PORT_GetError();
9013 desc = handshake_failure;
9014 ret = SSL_SNI_SEND_ALERT;
9015 break;
9016 }
9017 /* Need to tell the client that application has picked
9018 * the name from the offered list and reconfigured the socket.
9019 */
9020 ssl3_RegisterServerHelloExtensionSender(ss, ssl_server_name_xtn,
9021 ssl3_SendServerNameXtn);
9022 } else {
9023 /* Callback returned index outside of the boundary. */
9024 PORT_Assert((unsigned int)ret < ss->xtnData.sniNameArrSize);
9025 errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
9026 desc = internal_error;
9027 ret = SSL_SNI_SEND_ALERT;
9028 break;
9029 }
9030 } while (0);
9031 /* Free sniNameArr. The data that each SECItem in the array 9297 /* Free sniNameArr. The data that each SECItem in the array
9032 * points into is the data from the input buffer "b". It will 9298 * points into is the data from the input buffer "b". It will
9033 * not be available outside the scope of this or it's child 9299 * not be available outside the scope of this or it's child
9034 * functions.*/ 9300 * functions.*/
9035 if (ss->xtnData.sniNameArr) { 9301 if (ss->xtnData.sniNameArr) {
9036 PORT_Free(ss->xtnData.sniNameArr); 9302 PORT_Free(ss->xtnData.sniNameArr);
9037 ss->xtnData.sniNameArr = NULL; 9303 ss->xtnData.sniNameArr = NULL;
9038 ss->xtnData.sniNameArrSize = 0; 9304 ss->xtnData.sniNameArrSize = 0;
9039 } 9305 }
9040 if (ret <= SSL_SNI_SEND_ALERT) { 9306 if (ret <= SSL_SNI_SEND_ALERT) {
9041 /* desc and errCode should be set. */ 9307 /* desc and errCode should be set. */
9042 goto alert_loser; 9308 goto alert_loser;
9043 } 9309 }
9044 } 9310 }
9045 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS 9311 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS
9046 else if (ss->firstHsDone) { 9312 else if (ss->firstHsDone) {
9047 /* Check that we don't have the name is current spec 9313 /* Check that we don't have the name is current spec
9048 * if this extension was not negotiated on the 2d hs. */ 9314 * if this extension was not negotiated on the 2d hs. */
9049 PRBool passed = PR_TRUE; 9315 PRBool passed = PR_TRUE;
9050 ssl_GetSpecReadLock(ss); /*******************************/ 9316 ssl_GetSpecReadLock(ss); /*******************************/
9051 if (ss->ssl3.cwSpec->srvVirtName.data) { 9317 if (ss->ssl3.cwSpec->srvVirtName.data) {
9052 passed = PR_FALSE; 9318 passed = PR_FALSE;
9053 } 9319 }
9054 ssl_ReleaseSpecReadLock(ss); /***************************/ 9320 ssl_ReleaseSpecReadLock(ss); /***************************/
9055 if (!passed) { 9321 if (!passed) {
9056 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; 9322 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
9057 desc = handshake_failure; 9323 desc = handshake_failure;
9058 goto alert_loser; 9324 goto alert_loser;
9059 } 9325 }
9060 } 9326 }
9061 #endif 9327 #endif
9062 9328
9329 /* If this is TLS 1.3 we are expecting a ClientKeyShare
9330 * extension. Missing/absent extension cause failure
9331 * below. */
9332 if (isTLS13) {
9333 rv = tls13_HandleClientKeyShare(ss);
9334 if (rv != SECSuccess) {
9335 errCode = PORT_GetError();
9336 goto alert_loser;
9337 }
9338 }
9339
9063 sid = ssl3_NewSessionID(ss, PR_TRUE); 9340 sid = ssl3_NewSessionID(ss, PR_TRUE);
9064 if (sid == NULL) { 9341 if (sid == NULL) {
9065 » errCode = PORT_GetError(); 9342 errCode = PORT_GetError();
9066 » goto loser;» /* memory error is set. */ 9343 goto loser; /* memory error is set. */
9067 } 9344 }
9068 ss->sec.ci.sid = sid; 9345 ss->sec.ci.sid = sid;
9069 9346
9070 sid->u.ssl3.keys.extendedMasterSecretUsed = 9347 sid->u.ssl3.keys.extendedMasterSecretUsed =
9071 ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn); 9348 ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn);
9072 ss->ssl3.hs.isResuming = PR_FALSE; 9349 ss->ssl3.hs.isResuming = PR_FALSE;
9350
9073 ssl_GetXmitBufLock(ss); 9351 ssl_GetXmitBufLock(ss);
9074 rv = ssl3_SendServerHelloSequence(ss); 9352 if (isTLS13) {
9353 rv = tls13_SendServerHelloSequence(ss);
9354 } else {
9355 rv = ssl3_SendServerHelloSequence(ss);
9356 }
9075 ssl_ReleaseXmitBufLock(ss); 9357 ssl_ReleaseXmitBufLock(ss);
9076 if (rv != SECSuccess) { 9358 if (rv != SECSuccess) {
9077 errCode = PORT_GetError(); 9359 errCode = PORT_GetError();
9078 desc = handshake_failure; 9360 desc = handshake_failure;
9079 goto alert_loser; 9361 goto alert_loser;
9080 } 9362 }
9081 9363
9082 if (haveXmitBufLock) { 9364 if (haveXmitBufLock) {
9083 » ssl_ReleaseXmitBufLock(ss); 9365 ssl_ReleaseXmitBufLock(ss);
9084 » haveXmitBufLock = PR_FALSE; 9366 haveXmitBufLock = PR_FALSE;
9085 } 9367 }
9086 9368
9087 return SECSuccess; 9369 return SECSuccess;
9088 9370
9089 alert_loser: 9371 alert_loser:
9090 if (haveSpecWriteLock) { 9372 if (haveSpecWriteLock) {
9091 » ssl_ReleaseSpecWriteLock(ss); 9373 ssl_ReleaseSpecWriteLock(ss);
9092 » haveSpecWriteLock = PR_FALSE; 9374 haveSpecWriteLock = PR_FALSE;
9093 } 9375 }
9094 (void)SSL3_SendAlert(ss, level, desc); 9376 (void)SSL3_SendAlert(ss, level, desc);
9095 /* FALLTHRU */ 9377 /* FALLTHRU */
9096 loser: 9378 loser:
9097 if (haveSpecWriteLock) { 9379 if (haveSpecWriteLock) {
9098 » ssl_ReleaseSpecWriteLock(ss); 9380 ssl_ReleaseSpecWriteLock(ss);
9099 » haveSpecWriteLock = PR_FALSE; 9381 haveSpecWriteLock = PR_FALSE;
9100 } 9382 }
9101 9383
9102 if (haveXmitBufLock) { 9384 if (haveXmitBufLock) {
9103 » ssl_ReleaseXmitBufLock(ss); 9385 ssl_ReleaseXmitBufLock(ss);
9104 » haveXmitBufLock = PR_FALSE; 9386 haveXmitBufLock = PR_FALSE;
9105 } 9387 }
9106 9388
9107 PORT_SetError(errCode); 9389 PORT_SetError(errCode);
9108 return SECFailure; 9390 return SECFailure;
9109 } 9391 }
9110 9392
9111 /* 9393 /*
9112 * ssl3_HandleV2ClientHello is used when a V2 formatted hello comes 9394 * ssl3_HandleV2ClientHello is used when a V2 formatted hello comes
9113 * in asking to use the V3 handshake. 9395 * in asking to use the V3 handshake.
9114 * Called from ssl2_HandleClientHelloMessage() in sslcon.c 9396 * Called from ssl2_HandleClientHelloMessage() in sslcon.c
9115 */ 9397 */
9116 SECStatus 9398 SECStatus
9117 ssl3_HandleV2ClientHello(sslSocket *ss, unsigned char *buffer, int length) 9399 ssl3_HandleV2ClientHello(sslSocket *ss, unsigned char *buffer, int length)
9118 { 9400 {
9119 sslSessionID * sid » » = NULL; 9401 sslSessionID *sid = NULL;
9120 unsigned char * suites; 9402 unsigned char *suites;
9121 unsigned char * random; 9403 unsigned char *random;
9122 SSL3ProtocolVersion version; 9404 SSL3ProtocolVersion version;
9123 SECStatus rv; 9405 SECStatus rv;
9124 int i; 9406 int i;
9125 int j; 9407 int j;
9126 int sid_length; 9408 int sid_length;
9127 int suite_length; 9409 int suite_length;
9128 int rand_length; 9410 int rand_length;
9129 int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO; 9411 int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
9130 SSL3AlertDescription desc = handshake_failure; 9412 SSL3AlertDescription desc = handshake_failure;
9131 9413
9132 SSL_TRC(3, ("%d: SSL3[%d]: handle v2 client_hello", SSL_GETPID(), ss->fd)); 9414 SSL_TRC(3, ("%d: SSL3[%d]: handle v2 client_hello", SSL_GETPID(), ss->fd));
9133 9415
9134 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 9416 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
9135 9417
9136 ssl_GetSSL3HandshakeLock(ss); 9418 ssl_GetSSL3HandshakeLock(ss);
9137 9419
9138 PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData)); 9420 PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
9139 9421
9140 rv = ssl3_InitState(ss); 9422 rv = ssl3_InitState(ss);
9141 if (rv != SECSuccess) { 9423 if (rv != SECSuccess) {
9142 » ssl_ReleaseSSL3HandshakeLock(ss); 9424 ssl_ReleaseSSL3HandshakeLock(ss);
9143 » return rv;» » /* ssl3_InitState has set the error code. */ 9425 return rv; /* ssl3_InitState has set the error code. */
9144 } 9426 }
9145 rv = ssl3_RestartHandshakeHashes(ss); 9427 rv = ssl3_RestartHandshakeHashes(ss);
9146 if (rv != SECSuccess) { 9428 if (rv != SECSuccess) {
9147 » ssl_ReleaseSSL3HandshakeLock(ss); 9429 ssl_ReleaseSSL3HandshakeLock(ss);
9148 » return rv; 9430 return rv;
9149 } 9431 }
9150 9432
9151 if (ss->ssl3.hs.ws != wait_client_hello) { 9433 if (ss->ssl3.hs.ws != wait_client_hello) {
9152 » desc = unexpected_message; 9434 desc = unexpected_message;
9153 » errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO; 9435 errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO;
9154 » goto loser;» /* alert_loser */ 9436 goto loser; /* alert_loser */
9155 } 9437 }
9156 9438
9157 version = (buffer[1] << 8) | buffer[2]; 9439 version = (buffer[1] << 8) | buffer[2];
9158 suite_length = (buffer[3] << 8) | buffer[4]; 9440 suite_length = (buffer[3] << 8) | buffer[4];
9159 sid_length = (buffer[5] << 8) | buffer[6]; 9441 sid_length = (buffer[5] << 8) | buffer[6];
9160 rand_length = (buffer[7] << 8) | buffer[8]; 9442 rand_length = (buffer[7] << 8) | buffer[8];
9161 ss->clientHelloVersion = version; 9443 ss->clientHelloVersion = version;
9162 9444
9445 if (version >= SSL_LIBRARY_VERSION_TLS_1_3) {
9446 /* [draft-ietf-tls-tls-11; C.3] forbids sending a TLS 1.3
9447 * ClientHello using the backwards-compatible format. */
9448 desc = illegal_parameter;
9449 errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
9450 goto loser;
9451 }
9452
9163 rv = ssl3_NegotiateVersion(ss, version, PR_TRUE); 9453 rv = ssl3_NegotiateVersion(ss, version, PR_TRUE);
9164 if (rv != SECSuccess) { 9454 if (rv != SECSuccess) {
9165 » /* send back which ever alert client will understand. */ 9455 /* send back which ever alert client will understand. */
9166 » desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version 9456 desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version
9167 » : handshake_failure; 9457 : handshake_failure;
9168 » errCode = SSL_ERROR_UNSUPPORTED_VERSION; 9458 errCode = SSL_ERROR_UNSUPPORTED_VERSION;
9169 » goto alert_loser; 9459 goto alert_loser;
9170 } 9460 }
9171 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version; 9461 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version;
9172 9462
9173 rv = ssl3_InitHandshakeHashes(ss); 9463 rv = ssl3_InitHandshakeHashes(ss);
9174 if (rv != SECSuccess) { 9464 if (rv != SECSuccess) {
9175 » desc = internal_error; 9465 desc = internal_error;
9176 » errCode = PORT_GetError(); 9466 errCode = PORT_GetError();
9177 » goto alert_loser; 9467 goto alert_loser;
9178 } 9468 }
9179 9469
9180 /* if we get a non-zero SID, just ignore it. */ 9470 /* if we get a non-zero SID, just ignore it. */
9181 if (length != 9471 if (length !=
9182 SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length + rand_length) { 9472 SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length + rand_length) {
9183 » SSL_DBG(("%d: SSL3[%d]: bad v2 client hello message, len=%d should=%d", 9473 SSL_DBG(("%d: SSL3[%d]: bad v2 client hello message, len=%d should=%d",
9184 » » SSL_GETPID(), ss->fd, length, 9474 SSL_GETPID(), ss->fd, length,
9185 » » SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length + 9475 SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length +
9186 » » rand_length)); 9476 rand_length));
9187 » goto loser;» /* malformed */»/* alert_loser */ 9477 goto loser; /* malformed */ /* alert_loser */
9188 } 9478 }
9189 9479
9190 suites = buffer + SSL_HL_CLIENT_HELLO_HBYTES; 9480 suites = buffer + SSL_HL_CLIENT_HELLO_HBYTES;
9191 random = suites + suite_length + sid_length; 9481 random = suites + suite_length + sid_length;
9192 9482
9193 if (rand_length < SSL_MIN_CHALLENGE_BYTES || 9483 if (rand_length < SSL_MIN_CHALLENGE_BYTES ||
9194 » rand_length > SSL_MAX_CHALLENGE_BYTES) { 9484 rand_length > SSL_MAX_CHALLENGE_BYTES) {
9195 » goto loser;» /* malformed */»/* alert_loser */ 9485 goto loser; /* malformed */ /* alert_loser */
9196 } 9486 }
9197 9487
9198 PORT_Assert(SSL_MAX_CHALLENGE_BYTES == SSL3_RANDOM_LENGTH); 9488 PORT_Assert(SSL_MAX_CHALLENGE_BYTES == SSL3_RANDOM_LENGTH);
9199 9489
9200 PORT_Memset(&ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH); 9490 PORT_Memset(&ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH);
9201 PORT_Memcpy( 9491 PORT_Memcpy(
9202 » &ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - rand_length], 9492 &ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - rand_length],
9203 » random, rand_length); 9493 random, rand_length);
9204 9494
9205 PRINT_BUF(60, (ss, "client random:", &ss->ssl3.hs.client_random.rand[0], 9495 PRINT_BUF(60, (ss, "client random:", &ss->ssl3.hs.client_random.rand[0],
9206 » » SSL3_RANDOM_LENGTH)); 9496 SSL3_RANDOM_LENGTH));
9207 #ifndef NSS_DISABLE_ECC 9497 #ifndef NSS_DISABLE_ECC
9208 /* Disable any ECC cipher suites for which we have no cert. */ 9498 /* Disable any ECC cipher suites for which we have no cert. */
9209 ssl3_FilterECCipherSuitesByServerCerts(ss); 9499 ssl3_FilterECCipherSuitesByServerCerts(ss);
9210 #endif 9500 #endif
9211 i = ssl3_config_match_init(ss); 9501 i = ssl3_config_match_init(ss);
9212 if (i <= 0) { 9502 if (i <= 0) {
9213 » errCode = PORT_GetError();» /* error code is already set. */ 9503 errCode = PORT_GetError(); /* error code is already set. */
9214 » goto alert_loser; 9504 goto alert_loser;
9215 } 9505 }
9216 9506
9217 /* Select a cipher suite. 9507 /* Select a cipher suite.
9218 ** 9508 **
9219 ** NOTE: This suite selection algorithm should be the same as the one in 9509 ** NOTE: This suite selection algorithm should be the same as the one in
9220 ** ssl3_HandleClientHello(). 9510 ** ssl3_HandleClientHello().
9221 ** 9511 **
9222 ** See the comments about export cipher suites in ssl3_HandleClientHello(). 9512 ** See the comments about export cipher suites in ssl3_HandleClientHello().
9223 */ 9513 */
9224 for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) { 9514 for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) {
9225 » ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j]; 9515 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j];
9226 » SSLVersionRange vrange = {ss->version, ss->version}; 9516 SSLVersionRange vrange = { ss->version, ss->version };
9227 » if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange, ss)) { 9517 if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange, ss)) {
9228 » continue; 9518 continue;
9229 » } 9519 }
9230 » for (i = 0; i+2 < suite_length; i += 3) { 9520 for (i = 0; i + 2 < suite_length; i += 3) {
9231 » PRUint32 suite_i = (suites[i] << 16)|(suites[i+1] << 8)|suites[i+2]; 9521 PRUint32 suite_i = (suites[i] << 16) | (suites[i + 1] << 8) | suites [i + 2];
9232 » if (suite_i == suite->cipher_suite) { 9522 if (suite_i == suite->cipher_suite) {
9233 » » ss->ssl3.hs.cipher_suite = suite->cipher_suite; 9523 ss->ssl3.hs.cipher_suite = suite->cipher_suite;
9234 » » ss->ssl3.hs.suite_def = 9524 ss->ssl3.hs.suite_def =
9235 » » ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite); 9525 ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite);
9526 ss->ssl3.hs.kea_def =
9527 &kea_defs[ss->ssl3.hs.suite_def->key_exchange_alg];
9236 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_cipher_suite; 9528 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_cipher_suite;
9237 » » goto suite_found; 9529 goto suite_found;
9238 » } 9530 }
9239 » } 9531 }
9240 } 9532 }
9241 errCode = SSL_ERROR_NO_CYPHER_OVERLAP; 9533 errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
9242 goto alert_loser; 9534 goto alert_loser;
9243 9535
9244 suite_found: 9536 suite_found:
9245 9537
9246 /* Look for the SCSV, and if found, treat it just like an empty RI 9538 /* Look for the SCSV, and if found, treat it just like an empty RI
9247 * extension by processing a local copy of an empty RI extension. 9539 * extension by processing a local copy of an empty RI extension.
9248 */ 9540 */
9249 for (i = 0; i+2 < suite_length; i += 3) { 9541 for (i = 0; i + 2 < suite_length; i += 3) {
9250 » PRUint32 suite_i = (suites[i] << 16) | (suites[i+1] << 8) | suites[i+2]; 9542 PRUint32 suite_i = (suites[i] << 16) | (suites[i + 1] << 8) | suites[i + 2];
9251 » if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) { 9543 if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) {
9252 » SSL3Opaque * b2 = (SSL3Opaque *)emptyRIext; 9544 SSL3Opaque *b2 = (SSL3Opaque *)emptyRIext;
9253 » PRUint32 L2 = sizeof emptyRIext; 9545 PRUint32 L2 = sizeof emptyRIext;
9254 » (void)ssl3_HandleHelloExtensions(ss, &b2, &L2); 9546 (void)ssl3_HandleHelloExtensions(ss, &b2, &L2, client_hello);
9255 » break; 9547 break;
9256 » } 9548 }
9257 } 9549 }
9258 9550
9259 if (ss->opt.requireSafeNegotiation && 9551 if (ss->opt.requireSafeNegotiation &&
9260 » !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { 9552 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
9261 » desc = handshake_failure; 9553 desc = handshake_failure;
9262 » errCode = SSL_ERROR_UNSAFE_NEGOTIATION; 9554 errCode = SSL_ERROR_UNSAFE_NEGOTIATION;
9263 » goto alert_loser; 9555 goto alert_loser;
9264 } 9556 }
9265 9557
9266 ss->ssl3.hs.compression = ssl_compression_null; 9558 ss->ssl3.hs.compression = ssl_compression_null;
9267 ss->sec.send = ssl3_SendApplicationData; 9559 ss->sec.send = ssl3_SendApplicationData;
9268 9560
9269 /* we don't even search for a cache hit here. It's just a miss. */ 9561 /* we don't even search for a cache hit here. It's just a miss. */
9270 SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_misses ); 9562 SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_misses);
9271 sid = ssl3_NewSessionID(ss, PR_TRUE); 9563 sid = ssl3_NewSessionID(ss, PR_TRUE);
9272 if (sid == NULL) { 9564 if (sid == NULL) {
9273 » errCode = PORT_GetError(); 9565 errCode = PORT_GetError();
9274 » goto loser;» /* memory error is set. */ 9566 goto loser; /* memory error is set. */
9275 } 9567 }
9276 ss->sec.ci.sid = sid; 9568 ss->sec.ci.sid = sid;
9277 /* do not worry about memory leak of sid since it now belongs to ci */ 9569 /* do not worry about memory leak of sid since it now belongs to ci */
9278 9570
9279 /* We have to update the handshake hashes before we can send stuff */ 9571 /* We have to update the handshake hashes before we can send stuff */
9280 rv = ssl3_UpdateHandshakeHashes(ss, buffer, length); 9572 rv = ssl3_UpdateHandshakeHashes(ss, buffer, length);
9281 if (rv != SECSuccess) { 9573 if (rv != SECSuccess) {
9282 » errCode = PORT_GetError(); 9574 errCode = PORT_GetError();
9283 » goto loser; 9575 goto loser;
9284 } 9576 }
9285 9577
9286 ssl_GetXmitBufLock(ss); 9578 ssl_GetXmitBufLock(ss);
9287 rv = ssl3_SendServerHelloSequence(ss); 9579 rv = ssl3_SendServerHelloSequence(ss);
9288 ssl_ReleaseXmitBufLock(ss); 9580 ssl_ReleaseXmitBufLock(ss);
9289 if (rv != SECSuccess) { 9581 if (rv != SECSuccess) {
9290 » errCode = PORT_GetError(); 9582 errCode = PORT_GetError();
9291 » goto loser; 9583 goto loser;
9292 } 9584 }
9293 9585
9294 /* XXX_1 » The call stack to here is: 9586 /* XXX_1 The call stack to here is:
9295 * ssl_Do1stHandshake -> ssl2_HandleClientHelloMessage -> here. 9587 * ssl_Do1stHandshake -> ssl2_HandleClientHelloMessage -> here.
9296 * ssl2_HandleClientHelloMessage returns whatever we return here. 9588 * ssl2_HandleClientHelloMessage returns whatever we return here.
9297 * ssl_Do1stHandshake will continue looping if it gets back either 9589 * ssl_Do1stHandshake will continue looping if it gets back either
9298 *» » SECSuccess or SECWouldBlock. 9590 * SECSuccess or SECWouldBlock.
9299 * SECSuccess is preferable here. See XXX_1 in sslgathr.c. 9591 * SECSuccess is preferable here. See XXX_1 in sslgathr.c.
9300 */ 9592 */
9301 ssl_ReleaseSSL3HandshakeLock(ss); 9593 ssl_ReleaseSSL3HandshakeLock(ss);
9302 return SECSuccess; 9594 return SECSuccess;
9303 9595
9304 alert_loser: 9596 alert_loser:
9305 SSL3_SendAlert(ss, alert_fatal, desc); 9597 SSL3_SendAlert(ss, alert_fatal, desc);
9306 loser: 9598 loser:
9307 ssl_ReleaseSSL3HandshakeLock(ss); 9599 ssl_ReleaseSSL3HandshakeLock(ss);
9308 PORT_SetError(errCode); 9600 PORT_SetError(errCode);
9309 return SECFailure; 9601 return SECFailure;
9310 } 9602 }
9311 9603
9312 /* The negotiated version number has been already placed in ss->version. 9604 /* The negotiated version number has been already placed in ss->version.
9313 ** 9605 **
9314 ** Called from: ssl3_HandleClientHello (resuming session), 9606 ** Called from: ssl3_HandleClientHello (resuming session),
9315 ** » ssl3_SendServerHelloSequence <- ssl3_HandleClientHello (new session), 9607 ** ssl3_SendServerHelloSequence <- ssl3_HandleClientHello (new session),
9316 ** » ssl3_SendServerHelloSequence <- ssl3_HandleV2ClientHello (new session) 9608 ** ssl3_SendServerHelloSequence <- ssl3_HandleV2ClientHello (new session)
9317 */ 9609 */
9318 static SECStatus 9610 SECStatus
9319 ssl3_SendServerHello(sslSocket *ss) 9611 ssl3_SendServerHello(sslSocket *ss)
9320 { 9612 {
9321 sslSessionID *sid; 9613 sslSessionID *sid;
9322 SECStatus rv; 9614 SECStatus rv;
9323 PRUint32 maxBytes = 65535; 9615 PRUint32 maxBytes = 65535;
9324 PRUint32 length; 9616 PRUint32 length;
9325 PRInt32 extensions_len = 0; 9617 PRInt32 extensions_len = 0;
9326 SSL3ProtocolVersion version; 9618 SSL3ProtocolVersion version;
9327 9619
9328 SSL_TRC(3, ("%d: SSL3[%d]: send server_hello handshake", SSL_GETPID(), 9620 SSL_TRC(3, ("%d: SSL3[%d]: send server_hello handshake", SSL_GETPID(),
9329 » » ss->fd)); 9621 ss->fd));
9330 9622
9331 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 9623 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
9332 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 9624 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9333 9625
9334 if (!IS_DTLS(ss)) { 9626 if (!IS_DTLS(ss)) {
9335 » PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_3_0)); 9627 PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_3_0));
9336 9628
9337 » if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_3_0)) { 9629 if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_3_0)) {
9338 » PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); 9630 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
9339 » return SECFailure; 9631 return SECFailure;
9340 » } 9632 }
9341 } else { 9633 } else {
9342 » PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_DTLS_1_0)); 9634 PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_DTLS_1_0));
9343 9635
9344 » if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_DTLS_1_0)) { 9636 if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_DTLS_1_0)) {
9345 » PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); 9637 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
9346 » return SECFailure; 9638 return SECFailure;
9347 » } 9639 }
9348 } 9640 }
9349 9641
9350 sid = ss->sec.ci.sid; 9642 sid = ss->sec.ci.sid;
9351 9643
9352 extensions_len = ssl3_CallHelloExtensionSenders(ss, PR_FALSE, maxBytes, 9644 extensions_len = ssl3_CallHelloExtensionSenders(
9353 » » » » » &ss->xtnData.serverSenders[0]); 9645 ss, PR_FALSE, maxBytes, &ss->xtnData.serverHelloSenders[0]);
9354 if (extensions_len > 0) 9646 if (extensions_len > 0)
9355 » extensions_len += 2; /* Add sizeof total extension length */ 9647 extensions_len += 2; /* Add sizeof total extension length */
9356 9648
9357 length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH + 1 + 9649 /* TLS 1.3 doesn't use the session_id or compression_method
9358 ((sid == NULL) ? 0: sid->u.ssl3.sessionIDLength) + 9650 * fields in the ServerHello. */
9359 » sizeof(ssl3CipherSuite) + 1 + extensions_len; 9651 length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH;
9652 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
9653 length += 1 + ((sid == NULL) ? 0 : sid->u.ssl3.sessionIDLength);
9654 }
9655 length += sizeof(ssl3CipherSuite);
9656 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
9657 length += 1; /* Compression */
9658 }
9659 length += extensions_len;
9660
9360 rv = ssl3_AppendHandshakeHeader(ss, server_hello, length); 9661 rv = ssl3_AppendHandshakeHeader(ss, server_hello, length);
9361 if (rv != SECSuccess) { 9662 if (rv != SECSuccess) {
9362 » return rv;» /* err set by AppendHandshake. */ 9663 return rv; /* err set by AppendHandshake. */
9363 } 9664 }
9364 9665
9365 if (IS_DTLS(ss)) { 9666 if (IS_DTLS(ss)) {
9366 » version = dtls_TLSVersionToDTLSVersion(ss->version); 9667 version = dtls_TLSVersionToDTLSVersion(ss->version);
9367 } else { 9668 } else {
9368 » version = ss->version; 9669 version = ss->version;
9369 } 9670 }
9370 9671
9371 rv = ssl3_AppendHandshakeNumber(ss, version, 2); 9672 rv = ssl3_AppendHandshakeNumber(ss, version, 2);
9372 if (rv != SECSuccess) { 9673 if (rv != SECSuccess) {
9373 » return rv;» /* err set by AppendHandshake. */ 9674 return rv; /* err set by AppendHandshake. */
9374 } 9675 }
9375 rv = ssl3_GetNewRandom(&ss->ssl3.hs.server_random); 9676 /* Random already generated in ssl3_HandleClientHello */
9677 rv = ssl3_AppendHandshake(
9678 ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH);
9376 if (rv != SECSuccess) { 9679 if (rv != SECSuccess) {
9377 » ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE); 9680 return rv; /* err set by AppendHandshake. */
9378 » return rv;
9379 }
9380 rv = ssl3_AppendHandshake(
9381 » ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH);
9382 if (rv != SECSuccess) {
9383 » return rv;» /* err set by AppendHandshake. */
9384 } 9681 }
9385 9682
9386 if (sid) 9683 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
9387 » rv = ssl3_AppendHandshakeVariable( 9684 if (sid) {
9388 » ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1); 9685 rv = ssl3_AppendHandshakeVariable(
9389 else 9686 ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1);
9390 » rv = ssl3_AppendHandshakeNumber(ss, 0, 1); 9687 } else {
9391 if (rv != SECSuccess) { 9688 rv = ssl3_AppendHandshakeNumber(ss, 0, 1);
9392 » return rv;» /* err set by AppendHandshake. */ 9689 }
9690 if (rv != SECSuccess) {
9691 return rv; /* err set by AppendHandshake. */
9692 }
9393 } 9693 }
9394 9694
9395 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.cipher_suite, 2); 9695 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.cipher_suite, 2);
9396 if (rv != SECSuccess) { 9696 if (rv != SECSuccess) {
9397 » return rv;» /* err set by AppendHandshake. */ 9697 return rv; /* err set by AppendHandshake. */
9398 } 9698 }
9399 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.compression, 1); 9699 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
9400 if (rv != SECSuccess) { 9700 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.compression, 1);
9401 » return rv;» /* err set by AppendHandshake. */ 9701 if (rv != SECSuccess) {
9702 return rv; /* err set by AppendHandshake. */
9703 }
9402 } 9704 }
9403 if (extensions_len) { 9705 if (extensions_len) {
9404 » PRInt32 sent_len; 9706 PRInt32 sent_len;
9405 9707
9406 » extensions_len -= 2; 9708 extensions_len -= 2;
9407 » rv = ssl3_AppendHandshakeNumber(ss, extensions_len, 2); 9709 rv = ssl3_AppendHandshakeNumber(ss, extensions_len, 2);
9408 » if (rv != SECSuccess) 9710 if (rv != SECSuccess)
9409 » return rv;» /* err set by ssl3_SetupPendingCipherSpec */ 9711 return rv; /* err set by ssl3_AppendHandshakeNumber */
9410 » sent_len = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, extensions_len, 9712 sent_len = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, extensions_len,
9411 » » » » » &ss->xtnData.serverSenders[0]); 9713 &ss->xtnData.serverHelloSender s[0]);
9412 PORT_Assert(sent_len == extensions_len); 9714 PORT_Assert(sent_len == extensions_len);
9413 » if (sent_len != extensions_len) { 9715 if (sent_len != extensions_len) {
9414 » if (sent_len >= 0) 9716 if (sent_len >= 0)
9415 » » PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 9717 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
9416 » return SECFailure; 9718 return SECFailure;
9417 » } 9719 }
9418 } 9720 }
9419 rv = ssl3_SetupPendingCipherSpec(ss); 9721 rv = ssl3_SetupPendingCipherSpec(ss);
9420 if (rv != SECSuccess) { 9722 if (rv != SECSuccess) {
9421 » return rv;» /* err set by ssl3_SetupPendingCipherSpec */ 9723 return rv; /* err set by ssl3_SetupPendingCipherSpec */
9422 } 9724 }
9423 9725
9424 return SECSuccess; 9726 return SECSuccess;
9425 } 9727 }
9426 9728
9427 static SECStatus 9729 static SECStatus
9428 ssl3_PickSignatureHashAlgorithm(sslSocket *ss, 9730 ssl3_PickSignatureHashAlgorithm(sslSocket *ss,
9429 » » » » SSLSignatureAndHashAlg* out); 9731 SSLSignatureAndHashAlg *out);
9430 9732
9431 static SECStatus 9733 static SECStatus
9432 ssl3_SendDHServerKeyExchange(sslSocket *ss) 9734 ssl3_SendDHServerKeyExchange(sslSocket *ss)
9433 { 9735 {
9434 const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def; 9736 const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def;
9435 SECStatus rv = SECFailure; 9737 SECStatus rv = SECFailure;
9436 int length; 9738 int length;
9437 PRBool isTLS; 9739 PRBool isTLS;
9438 SECItem signed_hash = {siBuffer, NULL, 0}; 9740 SECItem signed_hash = { siBuffer, NULL, 0 };
9439 SSL3Hashes hashes; 9741 SSL3Hashes hashes;
9440 SSLSignatureAndHashAlg sigAndHash; 9742 SSLSignatureAndHashAlg sigAndHash;
9441 SECKEYDHParams dhParam; 9743 SECKEYDHParams dhParam;
9442 9744
9443 ssl3KeyPair *keyPair = NULL; 9745 ssl3KeyPair *keyPair = NULL;
9444 SECKEYPublicKey *pubKey = NULL; /* Ephemeral DH key */ 9746 SECKEYPublicKey *pubKey = NULL; /* Ephemeral DH key */
9445 SECKEYPrivateKey *privKey = NULL; /* Ephemeral DH key */ 9747 SECKEYPrivateKey *privKey = NULL; /* Ephemeral DH key */
9446 int certIndex = -1; 9748 int certIndex = -1;
9447 9749
9448 if (kea_def->kea != kea_dhe_dss && kea_def->kea != kea_dhe_rsa) { 9750 if (kea_def->kea != kea_dhe_dss && kea_def->kea != kea_dhe_rsa) {
9449 » /* TODO: Support DH_anon. It might be sufficient to drop the signature. 9751 /* TODO: Support DH_anon. It might be sufficient to drop the signature.
9450 » See bug 1170510. */ 9752 See bug 1170510. */
9451 » PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); 9753 PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
9452 » return SECFailure; 9754 return SECFailure;
9453 } 9755 }
9454 9756
9455 dhParam.prime.data = ss->dheParams->prime.data; 9757 dhParam.prime.data = ss->dheParams->prime.data;
9456 dhParam.prime.len = ss->dheParams->prime.len; 9758 dhParam.prime.len = ss->dheParams->prime.len;
9457 dhParam.base.data = ss->dheParams->base.data; 9759 dhParam.base.data = ss->dheParams->base.data;
9458 dhParam.base.len = ss->dheParams->base.len; 9760 dhParam.base.len = ss->dheParams->base.len;
9459 9761
9460 PRINT_BUF(60, (NULL, "Server DH p", dhParam.prime.data, 9762 PRINT_BUF(60, (NULL, "Server DH p", dhParam.prime.data,
9461 dhParam.prime.len)); 9763 dhParam.prime.len));
9462 PRINT_BUF(60, (NULL, "Server DH g", dhParam.base.data, 9764 PRINT_BUF(60, (NULL, "Server DH g", dhParam.base.data,
(...skipping 38 matching lines...) Expand 10 before | Expand all | Expand 10 after
9501 * ssl_auth_* instead. Investigate what to do. See bug 102794. */ 9803 * ssl_auth_* instead. Investigate what to do. See bug 102794. */
9502 if (kea_def->kea == kea_dhe_rsa) 9804 if (kea_def->kea == kea_dhe_rsa)
9503 certIndex = ssl_kea_rsa; 9805 certIndex = ssl_kea_rsa;
9504 else 9806 else
9505 certIndex = ssl_kea_dh; 9807 certIndex = ssl_kea_dh;
9506 9808
9507 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); 9809 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
9508 rv = ssl3_SignHashes(&hashes, ss->serverCerts[certIndex].SERVERKEY, 9810 rv = ssl3_SignHashes(&hashes, ss->serverCerts[certIndex].SERVERKEY,
9509 &signed_hash, isTLS); 9811 &signed_hash, isTLS);
9510 if (rv != SECSuccess) { 9812 if (rv != SECSuccess) {
9511 goto loser;» » /* ssl3_SignHashes has set err. */ 9813 goto loser; /* ssl3_SignHashes has set err. */
9512 } 9814 }
9513 if (signed_hash.data == NULL) { 9815 if (signed_hash.data == NULL) {
9514 PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); 9816 PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
9515 goto loser; 9817 goto loser;
9516 } 9818 }
9517 length = 2 + pubKey->u.dh.prime.len + 9819 length = 2 + pubKey->u.dh.prime.len +
9518 2 + pubKey->u.dh.base.len + 9820 2 + pubKey->u.dh.base.len +
9519 2 + pubKey->u.dh.publicValue.len + 9821 2 + pubKey->u.dh.publicValue.len +
9520 2 + signed_hash.len; 9822 2 + signed_hash.len;
9521 9823
9522 if (ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { 9824 if (ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
9523 » length += 2; 9825 length += 2;
9524 } 9826 }
9525 9827
9526 rv = ssl3_AppendHandshakeHeader(ss, server_key_exchange, length); 9828 rv = ssl3_AppendHandshakeHeader(ss, server_key_exchange, length);
9527 if (rv != SECSuccess) { 9829 if (rv != SECSuccess) {
9528 goto loser; » /* err set by AppendHandshake. */ 9830 goto loser; /* err set by AppendHandshake. */
9529 } 9831 }
9530 9832
9531 rv = ssl3_AppendHandshakeVariable(ss, pubKey->u.dh.prime.data, 9833 rv = ssl3_AppendHandshakeVariable(ss, pubKey->u.dh.prime.data,
9532 pubKey->u.dh.prime.len, 2); 9834 pubKey->u.dh.prime.len, 2);
9533 if (rv != SECSuccess) { 9835 if (rv != SECSuccess) {
9534 goto loser; » /* err set by AppendHandshake. */ 9836 goto loser; /* err set by AppendHandshake. */
9535 } 9837 }
9536 9838
9537 rv = ssl3_AppendHandshakeVariable(ss, pubKey->u.dh.base.data, 9839 rv = ssl3_AppendHandshakeVariable(ss, pubKey->u.dh.base.data,
9538 pubKey->u.dh.base.len, 2); 9840 pubKey->u.dh.base.len, 2);
9539 if (rv != SECSuccess) { 9841 if (rv != SECSuccess) {
9540 goto loser; » /* err set by AppendHandshake. */ 9842 goto loser; /* err set by AppendHandshake. */
9541 } 9843 }
9542 9844
9543 rv = ssl3_AppendHandshakeVariable(ss, pubKey->u.dh.publicValue.data, 9845 rv = ssl3_AppendHandshakeVariable(ss, pubKey->u.dh.publicValue.data,
9544 pubKey->u.dh.publicValue.len, 2); 9846 pubKey->u.dh.publicValue.len, 2);
9545 if (rv != SECSuccess) { 9847 if (rv != SECSuccess) {
9546 goto loser; » /* err set by AppendHandshake. */ 9848 goto loser; /* err set by AppendHandshake. */
9547 } 9849 }
9548 9850
9549 if (ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { 9851 if (ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
9550 » rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash); 9852 rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash);
9551 » if (rv != SECSuccess) { 9853 if (rv != SECSuccess) {
9552 » goto loser; /* err set by AppendHandshake. */ 9854 goto loser; /* err set by AppendHandshake. */
9553 » } 9855 }
9554 } 9856 }
9555 9857
9556 rv = ssl3_AppendHandshakeVariable(ss, signed_hash.data, 9858 rv = ssl3_AppendHandshakeVariable(ss, signed_hash.data,
9557 signed_hash.len, 2); 9859 signed_hash.len, 2);
9558 if (rv != SECSuccess) { 9860 if (rv != SECSuccess) {
9559 goto loser; » /* err set by AppendHandshake. */ 9861 goto loser; /* err set by AppendHandshake. */
9560 } 9862 }
9561 PORT_Free(signed_hash.data); 9863 PORT_Free(signed_hash.data);
9562 ss->dheKeyPair = keyPair; 9864 ss->dheKeyPair = keyPair;
9563 return SECSuccess; 9865 return SECSuccess;
9564 9866
9565 loser: 9867 loser:
9566 if (signed_hash.data) 9868 if (signed_hash.data)
9567 PORT_Free(signed_hash.data); 9869 PORT_Free(signed_hash.data);
9568 if (privKey) 9870 if (privKey)
9569 SECKEY_DestroyPrivateKey(privKey); 9871 SECKEY_DestroyPrivateKey(privKey);
9570 if (pubKey) 9872 if (pubKey)
9571 SECKEY_DestroyPublicKey(pubKey); 9873 SECKEY_DestroyPublicKey(pubKey);
9572 return SECFailure; 9874 return SECFailure;
9573 } 9875 }
9574 9876
9575 /* ssl3_PickSignatureHashAlgorithm selects a hash algorithm to use when signing 9877 /* ssl3_PickSignatureHashAlgorithm selects a hash algorithm to use when signing
9576 * elements of the handshake. (The negotiated cipher suite determines the 9878 * elements of the handshake. (The negotiated cipher suite determines the
9577 * signature algorithm.) Prior to TLS 1.2, the MD5/SHA1 combination is always 9879 * signature algorithm.) Prior to TLS 1.2, the MD5/SHA1 combination is always
9578 * used. With TLS 1.2, a client may advertise its support for signature and 9880 * used. With TLS 1.2, a client may advertise its support for signature and
9579 * hash combinations. */ 9881 * hash combinations. */
9580 static SECStatus 9882 static SECStatus
9581 ssl3_PickSignatureHashAlgorithm(sslSocket *ss, 9883 ssl3_PickSignatureHashAlgorithm(sslSocket *ss,
9582 SSLSignatureAndHashAlg* out) 9884 SSLSignatureAndHashAlg *out)
9583 { 9885 {
9584 SSLSignType sigAlg;
9585 PRUint32 policy; 9886 PRUint32 policy;
9586 unsigned int i, j; 9887 unsigned int i, j;
9587 9888
9588 switch (ss->ssl3.hs.kea_def->kea) { 9889 out->sigAlg = ss->ssl3.hs.kea_def->signKeyType;
9589 case kea_rsa:
9590 case kea_rsa_export:
9591 case kea_rsa_export_1024:
9592 case kea_dh_rsa:
9593 case kea_dh_rsa_export:
9594 case kea_dhe_rsa:
9595 case kea_dhe_rsa_export:
9596 case kea_rsa_fips:
9597 case kea_ecdh_rsa:
9598 case kea_ecdhe_rsa:
9599 sigAlg = ssl_sign_rsa;
9600 break;
9601 case kea_dh_dss:
9602 case kea_dh_dss_export:
9603 case kea_dhe_dss:
9604 case kea_dhe_dss_export:
9605 sigAlg = ssl_sign_dsa;
9606 break;
9607 case kea_ecdh_ecdsa:
9608 case kea_ecdhe_ecdsa:
9609 sigAlg = ssl_sign_ecdsa;
9610 break;
9611 default:
9612 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
9613 return SECFailure;
9614 }
9615 out->sigAlg = sigAlg;
9616 9890
9617 if (ss->version <= SSL_LIBRARY_VERSION_TLS_1_1) { 9891 if (ss->version <= SSL_LIBRARY_VERSION_TLS_1_1) {
9618 /* SEC_OID_UNKNOWN means the MD5/SHA1 combo hash used in TLS 1.1 and 9892 /* SEC_OID_UNKNOWN means the MD5/SHA1 combo hash used in TLS 1.1 and
9619 * prior. */ 9893 * prior. */
9620 out->hashAlg = ssl_hash_none; 9894 out->hashAlg = ssl_hash_none;
9621 return SECSuccess; 9895 return SECSuccess;
9622 } 9896 }
9623 9897
9624 if (ss->ssl3.hs.numClientSigAndHash == 0) { 9898 if (ss->ssl3.hs.numClientSigAndHash == 0) {
9625 /* If the client didn't provide any signature_algorithms extension then 9899 /* If the client didn't provide any signature_algorithms extension then
9626 * we can assume that they support SHA-1: 9900 * we can assume that they support SHA-1:
9627 * https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */ 9901 * https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
9628 out->hashAlg = ssl_hash_sha1; 9902 out->hashAlg = ssl_hash_sha1;
9629 return SECSuccess; 9903 return SECSuccess;
9630 } 9904 }
9631 9905
9632 /* Here we look for the first server preference that the client has 9906 /* Here we look for the first server preference that the client has
9633 * indicated support for in their signature_algorithms extension. */ 9907 * indicated support for in their signature_algorithms extension. */
9634 for (i = 0; i < ss->ssl3.signatureAlgorithmCount; ++i) { 9908 for (i = 0; i < ss->ssl3.signatureAlgorithmCount; ++i) {
9635 const SSLSignatureAndHashAlg *serverPref = 9909 const SSLSignatureAndHashAlg *serverPref =
9636 &ss->ssl3.signatureAlgorithms[i]; 9910 &ss->ssl3.signatureAlgorithms[i];
9637 » SECOidTag hashOID; 9911 SECOidTag hashOID;
9638 if (serverPref->sigAlg != sigAlg) { 9912 if (serverPref->sigAlg != out->sigAlg) {
9639 continue; 9913 continue;
9640 } 9914 }
9641 hashOID = ssl3_TLSHashAlgorithmToOID(serverPref->hashAlg); 9915 hashOID = ssl3_TLSHashAlgorithmToOID(serverPref->hashAlg);
9642 » if ((NSS_GetAlgorithmPolicy(hashOID, &policy) != SECSuccess) 9916 if ((NSS_GetAlgorithmPolicy(hashOID, &policy) == SECSuccess) &&
9643 » || !(policy & NSS_USE_ALG_IN_SSL_KX)) { 9917 !(policy & NSS_USE_ALG_IN_SSL_KX)) {
9644 » /* we ignore hashes we don't support */ 9918 /* we ignore hashes we don't support */
9645 » continue; 9919 continue;
9646 » } 9920 }
9647 for (j = 0; j < ss->ssl3.hs.numClientSigAndHash; j++) { 9921 for (j = 0; j < ss->ssl3.hs.numClientSigAndHash; j++) {
9648 const SSLSignatureAndHashAlg *clientPref = 9922 const SSLSignatureAndHashAlg *clientPref =
9649 &ss->ssl3.hs.clientSigAndHash[j]; 9923 &ss->ssl3.hs.clientSigAndHash[j];
9650 if (clientPref->hashAlg == serverPref->hashAlg && 9924 if (clientPref->hashAlg == serverPref->hashAlg &&
9651 clientPref->sigAlg == sigAlg) { 9925 clientPref->sigAlg == out->sigAlg) {
9652 out->hashAlg = serverPref->hashAlg; 9926 out->hashAlg = serverPref->hashAlg;
9653 return SECSuccess; 9927 return SECSuccess;
9654 } 9928 }
9655 } 9929 }
9656 } 9930 }
9657 9931
9658 PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM); 9932 PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
9659 return SECFailure; 9933 return SECFailure;
9660 } 9934 }
9661 9935
9662
9663 static SECStatus 9936 static SECStatus
9664 ssl3_SendServerKeyExchange(sslSocket *ss) 9937 ssl3_SendServerKeyExchange(sslSocket *ss)
9665 { 9938 {
9666 const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def; 9939 const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def;
9667 SECStatus rv = SECFailure; 9940 SECStatus rv = SECFailure;
9668 int length; 9941 int length;
9669 PRBool isTLS; 9942 PRBool isTLS;
9670 SECItem signed_hash = {siBuffer, NULL, 0}; 9943 SECItem signed_hash = { siBuffer, NULL, 0 };
9671 SSL3Hashes hashes; 9944 SSL3Hashes hashes;
9672 SECKEYPublicKey * sdPub;» /* public key for step-down */ 9945 SECKEYPublicKey *sdPub; /* public key for step-down */
9673 SSLSignatureAndHashAlg sigAndHash; 9946 SSLSignatureAndHashAlg sigAndHash;
9674 9947
9675 SSL_TRC(3, ("%d: SSL3[%d]: send server_key_exchange handshake", 9948 SSL_TRC(3, ("%d: SSL3[%d]: send server_key_exchange handshake",
9676 » » SSL_GETPID(), ss->fd)); 9949 SSL_GETPID(), ss->fd));
9677 9950
9678 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 9951 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
9679 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 9952 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9680 9953
9681 if (ssl3_PickSignatureHashAlgorithm(ss, &sigAndHash) != SECSuccess) { 9954 if (ssl3_PickSignatureHashAlgorithm(ss, &sigAndHash) != SECSuccess) {
9682 » return SECFailure; 9955 return SECFailure;
9683 } 9956 }
9684 9957
9685 switch (kea_def->exchKeyType) { 9958 switch (kea_def->exchKeyType) {
9686 case kt_rsa: 9959 case kt_rsa:
9687 » /* Perform SSL Step-Down here. */ 9960 /* Perform SSL Step-Down here. */
9688 » sdPub = ss->stepDownKeyPair->pubKey; 9961 sdPub = ss->stepDownKeyPair->pubKey;
9689 » PORT_Assert(sdPub != NULL); 9962 PORT_Assert(sdPub != NULL);
9690 » if (!sdPub) { 9963 if (!sdPub) {
9691 » PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); 9964 PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
9692 » return SECFailure; 9965 return SECFailure;
9693 » } 9966 }
9694 » rv = ssl3_ComputeExportRSAKeyHash(sigAndHash.hashAlg, 9967 rv = ssl3_ComputeExportRSAKeyHash(sigAndHash.hashAlg,
9695 » » » » » sdPub->u.rsa.modulus, 9968 sdPub->u.rsa.modulus,
9696 » » » » » sdPub->u.rsa.publicExponent, 9969 sdPub->u.rsa.publicExponent,
9697 » &ss->ssl3.hs.client_random, 9970 &ss->ssl3.hs.client_random,
9698 » &ss->ssl3.hs.server_random, 9971 &ss->ssl3.hs.server_random,
9699 » » » » » &hashes, ss->opt.bypassPKCS11); 9972 &hashes, ss->opt.bypassPKCS11);
9700 if (rv != SECSuccess) { 9973 if (rv != SECSuccess) {
9701 » ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); 9974 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
9702 » return rv; 9975 return rv;
9703 » } 9976 }
9704 9977
9705 » isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); 9978 isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0) ;
9706 » rv = ssl3_SignHashes(&hashes, ss->serverCerts[kt_rsa].SERVERKEY, 9979 rv = ssl3_SignHashes(&hashes, ss->serverCerts[kt_rsa].SERVERKEY,
9707 » &signed_hash, isTLS); 9980 &signed_hash, isTLS);
9708 if (rv != SECSuccess) { 9981 if (rv != SECSuccess) {
9709 » goto loser;»» /* ssl3_SignHashes has set err. */ 9982 goto loser; /* ssl3_SignHashes has set err. */
9710 » } 9983 }
9711 » if (signed_hash.data == NULL) { 9984 if (signed_hash.data == NULL) {
9712 » /* how can this happen and rv == SECSuccess ?? */ 9985 /* how can this happen and rv == SECSuccess ?? */
9713 » PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); 9986 PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
9714 » goto loser; 9987 goto loser;
9715 » } 9988 }
9716 » length = 2 + sdPub->u.rsa.modulus.len + 9989 length = 2 + sdPub->u.rsa.modulus.len +
9717 » 2 + sdPub->u.rsa.publicExponent.len + 9990 2 + sdPub->u.rsa.publicExponent.len +
9718 » 2 + signed_hash.len; 9991 2 + signed_hash.len;
9719 9992
9720 » if (ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { 9993 if (ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
9721 » length += 2; 9994 length += 2;
9722 » } 9995 }
9723 9996
9724 » rv = ssl3_AppendHandshakeHeader(ss, server_key_exchange, length); 9997 rv = ssl3_AppendHandshakeHeader(ss, server_key_exchange, length);
9725 » if (rv != SECSuccess) { 9998 if (rv != SECSuccess) {
9726 » goto loser; » /* err set by AppendHandshake. */ 9999 goto loser; /* err set by AppendHandshake. */
9727 » } 10000 }
9728 10001
9729 » rv = ssl3_AppendHandshakeVariable(ss, sdPub->u.rsa.modulus.data, 10002 rv = ssl3_AppendHandshakeVariable(ss, sdPub->u.rsa.modulus.data,
9730 » » » » » sdPub->u.rsa.modulus.len, 2); 10003 sdPub->u.rsa.modulus.len, 2);
9731 » if (rv != SECSuccess) { 10004 if (rv != SECSuccess) {
9732 » goto loser; » /* err set by AppendHandshake. */ 10005 goto loser; /* err set by AppendHandshake. */
9733 » } 10006 }
9734 10007
9735 » rv = ssl3_AppendHandshakeVariable( 10008 rv = ssl3_AppendHandshakeVariable(
9736 » » » » ss, sdPub->u.rsa.publicExponent.data, 10009 ss, sdPub->u.rsa.publicExponent.data,
9737 » » » » sdPub->u.rsa.publicExponent.len, 2); 10010 sdPub->u.rsa.publicExponent.len, 2);
9738 » if (rv != SECSuccess) { 10011 if (rv != SECSuccess) {
9739 » goto loser; » /* err set by AppendHandshake. */ 10012 goto loser; /* err set by AppendHandshake. */
9740 » } 10013 }
9741 10014
9742 » if (ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { 10015 if (ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
9743 » rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash); 10016 rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash);
9744 » if (rv != SECSuccess) { 10017 if (rv != SECSuccess) {
9745 » » goto loser; » /* err set by AppendHandshake. */ 10018 goto loser; /* err set by AppendHandshake. */
9746 » } 10019 }
9747 » } 10020 }
9748 10021
9749 » rv = ssl3_AppendHandshakeVariable(ss, signed_hash.data, 10022 rv = ssl3_AppendHandshakeVariable(ss, signed_hash.data,
9750 » signed_hash.len, 2); 10023 signed_hash.len, 2);
9751 » if (rv != SECSuccess) { 10024 if (rv != SECSuccess) {
9752 » goto loser; » /* err set by AppendHandshake. */ 10025 goto loser; /* err set by AppendHandshake. */
9753 » } 10026 }
9754 » PORT_Free(signed_hash.data); 10027 PORT_Free(signed_hash.data);
9755 » return SECSuccess; 10028 return SECSuccess;
9756 10029
9757 case ssl_kea_dh: { 10030 case ssl_kea_dh: {
9758 » rv = ssl3_SendDHServerKeyExchange(ss); 10031 rv = ssl3_SendDHServerKeyExchange(ss);
9759 » return rv; 10032 return rv;
9760 } 10033 }
9761 10034
9762 #ifndef NSS_DISABLE_ECC 10035 #ifndef NSS_DISABLE_ECC
9763 case kt_ecdh: { 10036 case kt_ecdh: {
9764 » rv = ssl3_SendECDHServerKeyExchange(ss, &sigAndHash); 10037 rv = ssl3_SendECDHServerKeyExchange(ss, &sigAndHash);
9765 » return rv; 10038 return rv;
9766 } 10039 }
9767 #endif /* NSS_DISABLE_ECC */ 10040 #endif /* NSS_DISABLE_ECC */
9768 10041
9769 case kt_null: 10042 case kt_null:
9770 default: 10043 default:
9771 » PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); 10044 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
9772 » break; 10045 break;
9773 } 10046 }
9774 loser: 10047 loser:
9775 if (signed_hash.data != NULL) 10048 if (signed_hash.data != NULL)
9776 » PORT_Free(signed_hash.data); 10049 PORT_Free(signed_hash.data);
9777 return SECFailure; 10050 return SECFailure;
9778 } 10051 }
9779 10052
9780 static SECStatus 10053 SECStatus
9781 ssl3_EncodeCertificateRequestSigAlgs(sslSocket *ss, PRUint8 *buf, 10054 ssl3_EncodeCertificateRequestSigAlgs(sslSocket *ss, PRUint8 *buf,
9782 unsigned maxLen, PRUint32 *len) 10055 unsigned maxLen, PRUint32 *len)
9783 { 10056 {
9784 unsigned int i; 10057 unsigned int i;
9785 10058
9786 PORT_Assert(maxLen >= ss->ssl3.signatureAlgorithmCount * 2); 10059 PORT_Assert(maxLen >= ss->ssl3.signatureAlgorithmCount * 2);
9787 if (maxLen < ss->ssl3.signatureAlgorithmCount * 2) { 10060 if (maxLen < ss->ssl3.signatureAlgorithmCount * 2) {
9788 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 10061 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
9789 return SECFailure; 10062 return SECFailure;
9790 } 10063 }
(...skipping 10 matching lines...) Expand all
9801 } 10074 }
9802 } 10075 }
9803 10076
9804 if (*len == 0) { 10077 if (*len == 0) {
9805 PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM); 10078 PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM);
9806 return SECFailure; 10079 return SECFailure;
9807 } 10080 }
9808 return SECSuccess; 10081 return SECSuccess;
9809 } 10082 }
9810 10083
10084 void
10085 ssl3_GetCertificateRequestCAs(sslSocket *ss, int *calen, SECItem **names,
10086 int *nnames)
10087 {
10088 SECItem *name;
10089 CERTDistNames *ca_list;
10090 int i;
10091
10092 *calen = 0;
10093 *names = NULL;
10094 *nnames = 0;
10095
10096 /* ssl3.ca_list is initialized to NULL, and never changed. */
10097 ca_list = ss->ssl3.ca_list;
10098 if (!ca_list) {
10099 ca_list = ssl3_server_ca_list;
10100 }
10101
10102 if (ca_list != NULL) {
10103 *names = ca_list->names;
10104 *nnames = ca_list->nnames;
10105 }
10106
10107 for (i = 0, name = *names; i < *nnames; i++, name++) {
10108 *calen += 2 + name->len;
10109 }
10110 }
10111
9811 static SECStatus 10112 static SECStatus
9812 ssl3_SendCertificateRequest(sslSocket *ss) 10113 ssl3_SendCertificateRequest(sslSocket *ss)
9813 { 10114 {
9814 PRBool isTLS12; 10115 PRBool isTLS12;
9815 SECItem * name;
9816 CERTDistNames *ca_list;
9817 const PRUint8 *certTypes; 10116 const PRUint8 *certTypes;
9818 SECItem * names» = NULL; 10117 SECStatus rv;
9819 SECStatus rv; 10118 int length;
9820 int length; 10119 SECItem *names;
9821 int i; 10120 int calen;
9822 int calen» = 0; 10121 int nnames;
9823 int nnames» = 0; 10122 SECItem *name;
9824 int certTypesLength; 10123 int i;
9825 PRUint8 sigAlgs[MAX_SIGNATURE_ALGORITHMS * 2]; 10124 int certTypesLength;
9826 unsigned int sigAlgsLength = 0; 10125 PRUint8 sigAlgs[MAX_SIGNATURE_ALGORITHMS * 2];
10126 unsigned int sigAlgsLength = 0;
9827 10127
9828 SSL_TRC(3, ("%d: SSL3[%d]: send certificate_request handshake", 10128 SSL_TRC(3, ("%d: SSL3[%d]: send certificate_request handshake",
9829 » » SSL_GETPID(), ss->fd)); 10129 SSL_GETPID(), ss->fd));
9830 10130
9831 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 10131 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
9832 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 10132 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9833 10133
9834 isTLS12 = (PRBool)(ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); 10134 isTLS12 = (PRBool)(ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
9835 10135
9836 /* ssl3.ca_list is initialized to NULL, and never changed. */ 10136 ssl3_GetCertificateRequestCAs(ss, &calen, &names, &nnames);
9837 ca_list = ss->ssl3.ca_list; 10137 certTypes = certificate_types;
9838 if (!ca_list) {
9839 » ca_list = ssl3_server_ca_list;
9840 }
9841
9842 if (ca_list != NULL) {
9843 » names = ca_list->names;
9844 » nnames = ca_list->nnames;
9845 }
9846
9847 for (i = 0, name = names; i < nnames; i++, name++) {
9848 » calen += 2 + name->len;
9849 }
9850
9851 certTypes = certificate_types;
9852 certTypesLength = sizeof certificate_types; 10138 certTypesLength = sizeof certificate_types;
9853 10139
9854 length = 1 + certTypesLength + 2 + calen; 10140 length = 1 + certTypesLength + 2 + calen;
9855 if (isTLS12) { 10141 if (isTLS12) {
9856 rv = ssl3_EncodeCertificateRequestSigAlgs(ss, sigAlgs, sizeof(sigAlgs), 10142 rv = ssl3_EncodeCertificateRequestSigAlgs(ss, sigAlgs, sizeof(sigAlgs),
9857 &sigAlgsLength); 10143 &sigAlgsLength);
9858 if (rv != SECSuccess) { 10144 if (rv != SECSuccess) {
9859 return rv; 10145 return rv;
9860 } 10146 }
9861 length += 2 + sigAlgsLength; 10147 length += 2 + sigAlgsLength;
9862 } 10148 }
9863 10149
9864 rv = ssl3_AppendHandshakeHeader(ss, certificate_request, length); 10150 rv = ssl3_AppendHandshakeHeader(ss, certificate_request, length);
9865 if (rv != SECSuccess) { 10151 if (rv != SECSuccess) {
9866 » return rv; » » /* err set by AppendHandshake. */ 10152 return rv; /* err set by AppendHandshake. */
9867 } 10153 }
9868 rv = ssl3_AppendHandshakeVariable(ss, certTypes, certTypesLength, 1); 10154 rv = ssl3_AppendHandshakeVariable(ss, certTypes, certTypesLength, 1);
9869 if (rv != SECSuccess) { 10155 if (rv != SECSuccess) {
9870 » return rv; » » /* err set by AppendHandshake. */ 10156 return rv; /* err set by AppendHandshake. */
9871 } 10157 }
9872 if (isTLS12) { 10158 if (isTLS12) {
9873 » rv = ssl3_AppendHandshakeVariable(ss, sigAlgs, sigAlgsLength, 2); 10159 rv = ssl3_AppendHandshakeVariable(ss, sigAlgs, sigAlgsLength, 2);
9874 » if (rv != SECSuccess) { 10160 if (rv != SECSuccess) {
9875 » return rv; »» /* err set by AppendHandshake. */ 10161 return rv; /* err set by AppendHandshake. */
9876 » } 10162 }
9877 } 10163 }
9878 rv = ssl3_AppendHandshakeNumber(ss, calen, 2); 10164 rv = ssl3_AppendHandshakeNumber(ss, calen, 2);
9879 if (rv != SECSuccess) { 10165 if (rv != SECSuccess) {
9880 » return rv; » » /* err set by AppendHandshake. */ 10166 return rv; /* err set by AppendHandshake. */
9881 } 10167 }
9882 for (i = 0, name = names; i < nnames; i++, name++) { 10168 for (i = 0, name = names; i < nnames; i++, name++) {
9883 » rv = ssl3_AppendHandshakeVariable(ss, name->data, name->len, 2); 10169 rv = ssl3_AppendHandshakeVariable(ss, name->data, name->len, 2);
9884 » if (rv != SECSuccess) { 10170 if (rv != SECSuccess) {
9885 » return rv; »» /* err set by AppendHandshake. */ 10171 return rv; /* err set by AppendHandshake. */
9886 » } 10172 }
9887 } 10173 }
9888 10174
9889 return SECSuccess; 10175 return SECSuccess;
9890 } 10176 }
9891 10177
9892 static SECStatus 10178 static SECStatus
9893 ssl3_SendServerHelloDone(sslSocket *ss) 10179 ssl3_SendServerHelloDone(sslSocket *ss)
9894 { 10180 {
9895 SECStatus rv; 10181 SECStatus rv;
9896 10182
9897 SSL_TRC(3, ("%d: SSL3[%d]: send server_hello_done handshake", 10183 SSL_TRC(3, ("%d: SSL3[%d]: send server_hello_done handshake",
9898 » » SSL_GETPID(), ss->fd)); 10184 SSL_GETPID(), ss->fd));
9899 10185
9900 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 10186 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
9901 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 10187 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9902 10188
9903 rv = ssl3_AppendHandshakeHeader(ss, server_hello_done, 0); 10189 rv = ssl3_AppendHandshakeHeader(ss, server_hello_done, 0);
9904 if (rv != SECSuccess) { 10190 if (rv != SECSuccess) {
9905 » return rv; » » /* err set by AppendHandshake. */ 10191 return rv; /* err set by AppendHandshake. */
9906 } 10192 }
9907 rv = ssl3_FlushHandshake(ss, 0); 10193 rv = ssl3_FlushHandshake(ss, 0);
9908 if (rv != SECSuccess) { 10194 if (rv != SECSuccess) {
9909 » return rv;» /* error code set by ssl3_FlushHandshake */ 10195 return rv; /* error code set by ssl3_FlushHandshake */
9910 } 10196 }
9911 return SECSuccess; 10197 return SECSuccess;
9912 } 10198 }
9913 10199
9914 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete 10200 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
9915 * ssl3 Certificate Verify message 10201 * a complete ssl3 Certificate Verify message
9916 * Caller must hold Handshake and RecvBuf locks. 10202 * Caller must hold Handshake and RecvBuf locks.
9917 */ 10203 */
9918 static SECStatus 10204 static SECStatus
9919 ssl3_HandleCertificateVerify(sslSocket *ss, SSL3Opaque *b, PRUint32 length, 10205 ssl3_HandleCertificateVerify(sslSocket *ss, SSL3Opaque *b, PRUint32 length,
9920 » » » SSL3Hashes *hashes) 10206 SSL3Hashes *hashes)
9921 { 10207 {
9922 SECItem signed_hash = {siBuffer, NULL, 0}; 10208 SECItem signed_hash = { siBuffer, NULL, 0 };
9923 SECStatus rv; 10209 SECStatus rv;
9924 int errCode = SSL_ERROR_RX_MALFORMED_CERT_VERIFY; 10210 int errCode = SSL_ERROR_RX_MALFORMED_CERT_VERIFY;
9925 SSL3AlertDescription desc = handshake_failure; 10211 SSL3AlertDescription desc = handshake_failure;
9926 PRBool isTLS, isTLS12; 10212 PRBool isTLS, isTLS12;
9927 SSLSignatureAndHashAlg sigAndHash; 10213 SSLSignatureAndHashAlg sigAndHash;
9928 10214
9929 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_verify handshake", 10215 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_verify handshake",
9930 » » SSL_GETPID(), ss->fd)); 10216 SSL_GETPID(), ss->fd));
9931 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 10217 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
9932 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 10218 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
9933 10219
9934 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0); 10220 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
9935 isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); 10221 isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
9936 10222
9937 if (ss->ssl3.hs.ws != wait_cert_verify) { 10223 if (ss->ssl3.hs.ws != wait_cert_verify) {
9938 » desc = unexpected_message; 10224 desc = unexpected_message;
9939 » errCode = SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY; 10225 errCode = SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY;
9940 » goto alert_loser; 10226 goto alert_loser;
9941 } 10227 }
9942 10228
9943 if (!hashes) { 10229 if (!hashes) {
9944 PORT_Assert(0); 10230 PORT_Assert(0);
9945 » desc = internal_error; 10231 desc = internal_error;
9946 » errCode = SEC_ERROR_LIBRARY_FAILURE; 10232 errCode = SEC_ERROR_LIBRARY_FAILURE;
9947 » goto alert_loser; 10233 goto alert_loser;
9948 } 10234 }
9949 10235
9950 if (isTLS12) { 10236 if (isTLS12) {
9951 » rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length, 10237 rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length,
9952 » » » » » » &sigAndHash); 10238 &sigAndHash);
9953 » if (rv != SECSuccess) { 10239 if (rv != SECSuccess) {
9954 » goto loser;»/* malformed or unsupported. */ 10240 goto loser; /* malformed or unsupported. */
9955 » } 10241 }
9956 » rv = ssl3_CheckSignatureAndHashAlgorithmConsistency( 10242 rv = ssl3_CheckSignatureAndHashAlgorithmConsistency(
9957 ss, &sigAndHash, ss->sec.peerCert); 10243 ss, &sigAndHash, ss->sec.peerCert);
9958 » if (rv != SECSuccess) { 10244 if (rv != SECSuccess) {
9959 » errCode = PORT_GetError(); 10245 errCode = PORT_GetError();
9960 » desc = decrypt_error; 10246 desc = decrypt_error;
9961 » goto alert_loser; 10247 goto alert_loser;
9962 » } 10248 }
9963 10249
9964 » /* We only support CertificateVerify messages that use the handshake 10250 /* We only support CertificateVerify messages that use the handshake
9965 » * hash. */ 10251 * hash. */
9966 if (sigAndHash.hashAlg != hashes->hashAlg) { 10252 if (sigAndHash.hashAlg != hashes->hashAlg) {
9967 » errCode = SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM; 10253 errCode = SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM;
9968 » desc = decrypt_error; 10254 desc = decrypt_error;
9969 » goto alert_loser; 10255 goto alert_loser;
9970 » } 10256 }
9971 } 10257 }
9972 10258
9973 rv = ssl3_ConsumeHandshakeVariable(ss, &signed_hash, 2, &b, &length); 10259 rv = ssl3_ConsumeHandshakeVariable(ss, &signed_hash, 2, &b, &length);
9974 if (rv != SECSuccess) { 10260 if (rv != SECSuccess) {
9975 » goto loser;» » /* malformed. */ 10261 goto loser; /* malformed. */
9976 } 10262 }
9977 10263
9978 /* XXX verify that the key & kea match */ 10264 /* XXX verify that the key & kea match */
9979 rv = ssl3_VerifySignedHashes(hashes, ss->sec.peerCert, &signed_hash, 10265 rv = ssl3_VerifySignedHashes(hashes, ss->sec.peerCert, &signed_hash,
9980 » » » » isTLS, ss->pkcs11PinArg); 10266 isTLS, ss->pkcs11PinArg);
9981 if (rv != SECSuccess) { 10267 if (rv != SECSuccess) {
9982 » errCode = PORT_GetError(); 10268 errCode = PORT_GetError();
9983 » desc = isTLS ? decrypt_error : handshake_failure; 10269 desc = isTLS ? decrypt_error : handshake_failure;
9984 » goto alert_loser; 10270 goto alert_loser;
9985 } 10271 }
9986 10272
9987 signed_hash.data = NULL; 10273 signed_hash.data = NULL;
9988 10274
9989 if (length != 0) { 10275 if (length != 0) {
9990 » desc = isTLS ? decode_error : illegal_parameter; 10276 desc = isTLS ? decode_error : illegal_parameter;
9991 » goto alert_loser;» /* malformed */ 10277 goto alert_loser; /* malformed */
9992 } 10278 }
9993 ss->ssl3.hs.ws = wait_change_cipher; 10279 ss->ssl3.hs.ws = wait_change_cipher;
9994 return SECSuccess; 10280 return SECSuccess;
9995 10281
9996 alert_loser: 10282 alert_loser:
9997 SSL3_SendAlert(ss, alert_fatal, desc); 10283 SSL3_SendAlert(ss, alert_fatal, desc);
9998 loser: 10284 loser:
9999 PORT_SetError(errCode); 10285 PORT_SetError(errCode);
10000 return SECFailure; 10286 return SECFailure;
10001 } 10287 }
10002 10288
10003
10004 /* find a slot that is able to generate a PMS and wrap it with RSA. 10289 /* find a slot that is able to generate a PMS and wrap it with RSA.
10005 * Then generate and return the PMS. 10290 * Then generate and return the PMS.
10006 * If the serverKeySlot parameter is non-null, this function will use 10291 * If the serverKeySlot parameter is non-null, this function will use
10007 * that slot to do the job, otherwise it will find a slot. 10292 * that slot to do the job, otherwise it will find a slot.
10008 * 10293 *
10009 * Called from ssl3_DeriveConnectionKeysPKCS11() (above) 10294 * Called from ssl3_DeriveConnectionKeysPKCS11() (above)
10010 *» » sendRSAClientKeyExchange() (above) 10295 * sendRSAClientKeyExchange() (above)
10011 *» » ssl3_HandleRSAClientKeyExchange() (below) 10296 * ssl3_HandleRSAClientKeyExchange() (below)
10012 * Caller must hold the SpecWriteLock, the SSL3HandshakeLock 10297 * Caller must hold the SpecWriteLock, the SSL3HandshakeLock
10013 */ 10298 */
10014 static PK11SymKey * 10299 static PK11SymKey *
10015 ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec, 10300 ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec,
10016 PK11SlotInfo * serverKeySlot) 10301 PK11SlotInfo *serverKeySlot)
10017 { 10302 {
10018 PK11SymKey * pms» » = NULL; 10303 PK11SymKey *pms = NULL;
10019 PK11SlotInfo * slot» » = serverKeySlot; 10304 PK11SlotInfo *slot = serverKeySlot;
10020 void *» pwArg » » = ss->pkcs11PinArg; 10305 void *pwArg = ss->pkcs11PinArg;
10021 SECItem param; 10306 SECItem param;
10022 CK_VERSION » version; 10307 CK_VERSION version;
10023 CK_MECHANISM_TYPE mechanism_array[3]; 10308 CK_MECHANISM_TYPE mechanism_array[3];
10024 10309
10025 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 10310 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10026 10311
10027 if (slot == NULL) { 10312 if (slot == NULL) {
10028 » SSLCipherAlgorithm calg; 10313 SSLCipherAlgorithm calg;
10029 » /* The specReadLock would suffice here, but we cannot assert on 10314 /* The specReadLock would suffice here, but we cannot assert on
10030 » ** read locks. Also, all the callers who call with a non-null 10315 ** read locks. Also, all the callers who call with a non-null
10031 » ** slot already hold the SpecWriteLock. 10316 ** slot already hold the SpecWriteLock.
10032 » */ 10317 */
10033 » PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); 10318 PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
10034 » PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); 10319 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
10035 10320
10036 calg = spec->cipher_def->calg; 10321 calg = spec->cipher_def->calg;
10037 PORT_Assert(alg2Mech[calg].calg == calg);
10038 10322
10039 » /* First get an appropriate slot. */ 10323 /* First get an appropriate slot. */
10040 » mechanism_array[0] = CKM_SSL3_PRE_MASTER_KEY_GEN; 10324 mechanism_array[0] = CKM_SSL3_PRE_MASTER_KEY_GEN;
10041 » mechanism_array[1] = CKM_RSA_PKCS; 10325 mechanism_array[1] = CKM_RSA_PKCS;
10042 » mechanism_array[2] = alg2Mech[calg].cmech; 10326 mechanism_array[2] = ssl3_Alg2Mech(calg);
10043 10327
10044 » slot = PK11_GetBestSlotMultiple(mechanism_array, 3, pwArg); 10328 slot = PK11_GetBestSlotMultiple(mechanism_array, 3, pwArg);
10045 » if (slot == NULL) { 10329 if (slot == NULL) {
10046 » /* can't find a slot with all three, find a slot with the minimum */ 10330 /* can't find a slot with all three, find a slot with the minimum */
10047 » slot = PK11_GetBestSlotMultiple(mechanism_array, 2, pwArg); 10331 slot = PK11_GetBestSlotMultiple(mechanism_array, 2, pwArg);
10048 » if (slot == NULL) { 10332 if (slot == NULL) {
10049 » » PORT_SetError(SSL_ERROR_TOKEN_SLOT_NOT_FOUND); 10333 PORT_SetError(SSL_ERROR_TOKEN_SLOT_NOT_FOUND);
10050 » » return pms;» /* which is NULL */ 10334 return pms; /* which is NULL */
10051 » } 10335 }
10052 » } 10336 }
10053 } 10337 }
10054 10338
10055 /* Generate the pre-master secret ... */ 10339 /* Generate the pre-master secret ... */
10056 if (IS_DTLS(ss)) { 10340 if (IS_DTLS(ss)) {
10057 » SSL3ProtocolVersion temp; 10341 SSL3ProtocolVersion temp;
10058 10342
10059 » temp = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion); 10343 temp = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion);
10060 » version.major = MSB(temp); 10344 version.major = MSB(temp);
10061 » version.minor = LSB(temp); 10345 version.minor = LSB(temp);
10062 } else { 10346 } else {
10063 » version.major = MSB(ss->clientHelloVersion); 10347 version.major = MSB(ss->clientHelloVersion);
10064 » version.minor = LSB(ss->clientHelloVersion); 10348 version.minor = LSB(ss->clientHelloVersion);
10065 } 10349 }
10066 10350
10067 param.data = (unsigned char *)&version; 10351 param.data = (unsigned char *)&version;
10068 param.len = sizeof version; 10352 param.len = sizeof version;
10069 10353
10070 pms = PK11_KeyGen(slot, CKM_SSL3_PRE_MASTER_KEY_GEN, &param, 0, pwArg); 10354 pms = PK11_KeyGen(slot, CKM_SSL3_PRE_MASTER_KEY_GEN, &param, 0, pwArg);
10071 if (!serverKeySlot) 10355 if (!serverKeySlot)
10072 » PK11_FreeSlot(slot); 10356 PK11_FreeSlot(slot);
10073 if (pms == NULL) { 10357 if (pms == NULL) {
10074 » ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); 10358 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
10075 } 10359 }
10076 return pms; 10360 return pms;
10077 } 10361 }
10078 10362
10079 /* Note: The Bleichenbacher attack on PKCS#1 necessitates that we NEVER 10363 /* Note: The Bleichenbacher attack on PKCS#1 necessitates that we NEVER
10080 * return any indication of failure of the Client Key Exchange message, 10364 * return any indication of failure of the Client Key Exchange message,
10081 * where that failure is caused by the content of the client's message. 10365 * where that failure is caused by the content of the client's message.
10082 * This function must not return SECFailure for any reason that is directly 10366 * This function must not return SECFailure for any reason that is directly
10083 * or indirectly caused by the content of the client's encrypted PMS. 10367 * or indirectly caused by the content of the client's encrypted PMS.
10084 * We must not send an alert and also not drop the connection. 10368 * We must not send an alert and also not drop the connection.
10085 * Instead, we generate a random PMS. This will cause a failure 10369 * Instead, we generate a random PMS. This will cause a failure
10086 * in the processing the finished message, which is exactly where 10370 * in the processing the finished message, which is exactly where
10087 * the failure must occur. 10371 * the failure must occur.
10088 * 10372 *
10089 * Called from ssl3_HandleClientKeyExchange 10373 * Called from ssl3_HandleClientKeyExchange
10090 */ 10374 */
10091 static SECStatus 10375 static SECStatus
10092 ssl3_HandleRSAClientKeyExchange(sslSocket *ss, 10376 ssl3_HandleRSAClientKeyExchange(sslSocket *ss,
10093 SSL3Opaque *b, 10377 SSL3Opaque *b,
10094 » » » » PRUint32 length, 10378 PRUint32 length,
10095 » » » » SECKEYPrivateKey *serverKey) 10379 SECKEYPrivateKey *serverKey)
10096 { 10380 {
10097 #ifndef NO_PKCS11_BYPASS 10381 #ifndef NO_PKCS11_BYPASS
10098 unsigned char * cr = (unsigned char *)&ss->ssl3.hs.client_random; 10382 unsigned char *cr = (unsigned char *)&ss->ssl3.hs.client_random;
10099 unsigned char * sr = (unsigned char *)&ss->ssl3.hs.server_random; 10383 unsigned char *sr = (unsigned char *)&ss->ssl3.hs.server_random;
10100 ssl3CipherSpec * pwSpec = ss->ssl3.pwSpec; 10384 ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec;
10101 unsigned int outLen = 0; 10385 unsigned int outLen = 0;
10102 PRBool isTLS = PR_FALSE; 10386 PRBool isTLS = PR_FALSE;
10103 SECItem pmsItem = {siBuffer, NULL, 0}; 10387 SECItem pmsItem = { siBuffer, NULL, 0 };
10104 unsigned char rsaPmsBuf[SSL3_RSA_PMS_LENGTH]; 10388 unsigned char rsaPmsBuf[SSL3_RSA_PMS_LENGTH];
10105 #endif 10389 #endif
10106 SECStatus rv; 10390 SECStatus rv;
10107 SECItem enc_pms; 10391 SECItem enc_pms;
10108 10392
10109 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 10393 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
10110 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 10394 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10111 PORT_Assert( ss->ssl3.prSpec == ss->ssl3.pwSpec ); 10395 PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
10112 10396
10113 enc_pms.data = b; 10397 enc_pms.data = b;
10114 enc_pms.len = length; 10398 enc_pms.len = length;
10115 #ifndef NO_PKCS11_BYPASS 10399 #ifndef NO_PKCS11_BYPASS
10116 pmsItem.data = rsaPmsBuf; 10400 pmsItem.data = rsaPmsBuf;
10117 pmsItem.len = sizeof rsaPmsBuf; 10401 pmsItem.len = sizeof rsaPmsBuf;
10118 #endif 10402 #endif
10119 10403
10120 if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */ 10404 if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
10121 » PRInt32 kLen; 10405 PRInt32 kLen;
10122 » kLen = ssl3_ConsumeHandshakeNumber(ss, 2, &enc_pms.data, &enc_pms.len); 10406 kLen = ssl3_ConsumeHandshakeNumber(ss, 2, &enc_pms.data, &enc_pms.len);
10123 » if (kLen < 0) { 10407 if (kLen < 0) {
10124 » PORT_SetError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); 10408 PORT_SetError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
10125 » return SECFailure; 10409 return SECFailure;
10126 » } 10410 }
10127 » if ((unsigned)kLen < enc_pms.len) { 10411 if ((unsigned)kLen < enc_pms.len) {
10128 » enc_pms.len = kLen; 10412 enc_pms.len = kLen;
10129 » } 10413 }
10130 #ifndef NO_PKCS11_BYPASS 10414 #ifndef NO_PKCS11_BYPASS
10131 » isTLS = PR_TRUE; 10415 isTLS = PR_TRUE;
10132 #endif 10416 #endif
10133 } else { 10417 } else {
10134 #ifndef NO_PKCS11_BYPASS 10418 #ifndef NO_PKCS11_BYPASS
10135 » isTLS = (PRBool)(ss->ssl3.hs.kea_def->tls_keygen != 0); 10419 isTLS = (PRBool)(ss->ssl3.hs.kea_def->tls_keygen != 0);
10136 #endif 10420 #endif
10137 } 10421 }
10138 10422
10139 #ifndef NO_PKCS11_BYPASS 10423 #ifndef NO_PKCS11_BYPASS
10140 if (ss->opt.bypassPKCS11) { 10424 if (ss->opt.bypassPKCS11) {
10141 /* We have not implemented a tls_ExtendedMasterKeyDeriveBypass 10425 /* We have not implemented a tls_ExtendedMasterKeyDeriveBypass
10142 * and will not negotiate this extension in bypass mode. This 10426 * and will not negotiate this extension in bypass mode. This
10143 * assert just double-checks that. 10427 * assert just double-checks that.
10144 */ 10428 */
10145 PORT_Assert( 10429 PORT_Assert(
10146 !ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)); 10430 !ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn));
10147 10431
10148 » /* TRIPLE BYPASS, get PMS directly from RSA decryption. 10432 /* TRIPLE BYPASS, get PMS directly from RSA decryption.
10149 » * Use PK11_PrivDecryptPKCS1 to decrypt the PMS to a buffer, 10433 * Use PK11_PrivDecryptPKCS1 to decrypt the PMS to a buffer,
10150 » * then, check for version rollback attack, then 10434 * then, check for version rollback attack, then
10151 » * do the equivalent of ssl3_DeriveMasterSecret, placing the MS in 10435 * do the equivalent of ssl3_DeriveMasterSecret, placing the MS in
10152 » * pwSpec->msItem. Finally call ssl3_InitPendingCipherSpec with 10436 * pwSpec->msItem. Finally call ssl3_InitPendingCipherSpec with
10153 » * ss and NULL, so that it will use the MS we've already derived here. 10437 * ss and NULL, so that it will use the MS we've already derived here.
10154 » */ 10438 */
10155 10439
10156 » rv = PK11_PrivDecryptPKCS1(serverKey, rsaPmsBuf, &outLen, 10440 rv = PK11_PrivDecryptPKCS1(serverKey, rsaPmsBuf, &outLen,
10157 » » » » sizeof rsaPmsBuf, enc_pms.data, enc_pms.len); 10441 sizeof rsaPmsBuf, enc_pms.data, enc_pms.len);
10158 » if (rv != SECSuccess) { 10442 if (rv != SECSuccess) {
10159 » /* triple bypass failed. Let's try for a double bypass. */ 10443 /* triple bypass failed. Let's try for a double bypass. */
10160 » goto double_bypass; 10444 goto double_bypass;
10161 » } else if (ss->opt.detectRollBack) { 10445 } else if (ss->opt.detectRollBack) {
10162 » SSL3ProtocolVersion client_version = 10446 SSL3ProtocolVersion client_version =
10163 » » » » » (rsaPmsBuf[0] << 8) | rsaPmsBuf[1]; 10447 (rsaPmsBuf[0] << 8) | rsaPmsBuf[1];
10164 10448
10165 » if (IS_DTLS(ss)) { 10449 if (IS_DTLS(ss)) {
10166 » » client_version = dtls_DTLSVersionToTLSVersion(client_version); 10450 client_version = dtls_DTLSVersionToTLSVersion(client_version);
10167 » } 10451 }
10168 10452
10169 » if (client_version != ss->clientHelloVersion) { 10453 if (client_version != ss->clientHelloVersion) {
10170 » » /* Version roll-back detected. ensure failure. */ 10454 /* Version roll-back detected. ensure failure. */
10171 » » rv = PK11_GenerateRandom(rsaPmsBuf, sizeof rsaPmsBuf); 10455 rv = PK11_GenerateRandom(rsaPmsBuf, sizeof rsaPmsBuf);
10172 » } 10456 }
10173 » } 10457 }
10174 » /* have PMS, build MS without PKCS11 */ 10458 /* have PMS, build MS without PKCS11 */
10175 » rv = ssl3_MasterSecretDeriveBypass(pwSpec, cr, sr, &pmsItem, isTLS, 10459 rv = ssl3_MasterSecretDeriveBypass(pwSpec, cr, sr, &pmsItem, isTLS,
10176 PR_TRUE); 10460 PR_TRUE);
10177 » if (rv != SECSuccess) { 10461 if (rv != SECSuccess) {
10178 » pwSpec->msItem.data = pwSpec->raw_master_secret; 10462 pwSpec->msItem.data = pwSpec->raw_master_secret;
10179 » pwSpec->msItem.len = SSL3_MASTER_SECRET_LENGTH; 10463 pwSpec->msItem.len = SSL3_MASTER_SECRET_LENGTH;
10180 » PK11_GenerateRandom(pwSpec->msItem.data, pwSpec->msItem.len); 10464 PK11_GenerateRandom(pwSpec->msItem.data, pwSpec->msItem.len);
10181 » } 10465 }
10182 » rv = ssl3_InitPendingCipherSpec(ss, NULL); 10466 rv = ssl3_InitPendingCipherSpec(ss, NULL);
10183 } else 10467 } else
10184 #endif 10468 #endif
10185 { 10469 {
10186 PK11SymKey *tmpPms[2] = {NULL, NULL}; 10470 PK11SymKey *tmpPms[2] = { NULL, NULL };
10187 PK11SlotInfo *slot; 10471 PK11SlotInfo *slot;
10188 int useFauxPms = 0; 10472 int useFauxPms = 0;
10189 #define currentPms tmpPms[!useFauxPms] 10473 #define currentPms tmpPms[!useFauxPms]
10190 #define unusedPms tmpPms[useFauxPms] 10474 #define unusedPms tmpPms[useFauxPms]
10191 #define realPms tmpPms[1] 10475 #define realPms tmpPms[1]
10192 #define fauxPms tmpPms[0] 10476 #define fauxPms tmpPms[0]
10193 10477
10194 #ifndef NO_PKCS11_BYPASS 10478 #ifndef NO_PKCS11_BYPASS
10195 double_bypass: 10479 double_bypass:
10196 #endif 10480 #endif
10197 10481
10198 /* 10482 /*
10199 * Get as close to algorithm 2 from RFC 5246; Section 7.4.7.1 10483 * Get as close to algorithm 2 from RFC 5246; Section 7.4.7.1
10200 * as we can within the constraints of the PKCS#11 interface. 10484 * as we can within the constraints of the PKCS#11 interface.
10201 * 10485 *
10202 * 1. Unconditionally generate a bogus PMS (what RFC 5246 10486 * 1. Unconditionally generate a bogus PMS (what RFC 5246
10203 * calls R). 10487 * calls R).
10204 * 2. Attempt the RSA decryption to recover the PMS (what 10488 * 2. Attempt the RSA decryption to recover the PMS (what
10205 * RFC 5246 calls M). 10489 * RFC 5246 calls M).
(...skipping 26 matching lines...) Expand all
10232 return SECFailure; 10516 return SECFailure;
10233 } 10517 }
10234 } 10518 }
10235 10519
10236 ssl_GetSpecWriteLock(ss); 10520 ssl_GetSpecWriteLock(ss);
10237 fauxPms = ssl3_GenerateRSAPMS(ss, ss->ssl3.prSpec, slot); 10521 fauxPms = ssl3_GenerateRSAPMS(ss, ss->ssl3.prSpec, slot);
10238 ssl_ReleaseSpecWriteLock(ss); 10522 ssl_ReleaseSpecWriteLock(ss);
10239 PK11_FreeSlot(slot); 10523 PK11_FreeSlot(slot);
10240 10524
10241 if (fauxPms == NULL) { 10525 if (fauxPms == NULL) {
10242 » ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); 10526 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
10243 » return SECFailure; 10527 return SECFailure;
10244 » } 10528 }
10245 10529
10246 » /* 10530 /*
10247 » * unwrap pms out of the incoming buffer 10531 * unwrap pms out of the incoming buffer
10248 » * Note: CKM_SSL3_MASTER_KEY_DERIVE is NOT the mechanism used to do 10532 * Note: CKM_SSL3_MASTER_KEY_DERIVE is NOT the mechanism used to do
10249 » *» the unwrap. Rather, it is the mechanism with which the 10533 * the unwrap. Rather, it is the mechanism with which the
10250 » * unwrapped pms will be used. 10534 * unwrapped pms will be used.
10251 » */ 10535 */
10252 » realPms = PK11_PubUnwrapSymKey(serverKey, &enc_pms, 10536 realPms = PK11_PubUnwrapSymKey(serverKey, &enc_pms,
10253 CKM_SSL3_MASTER_KEY_DERIVE, CKA_DERIVE , 0); 10537 CKM_SSL3_MASTER_KEY_DERIVE, CKA_DERIVE, 0 );
10254 /* Temporarily use the PMS if unwrapping the real PMS fails. */ 10538 /* Temporarily use the PMS if unwrapping the real PMS fails. */
10255 useFauxPms |= (realPms == NULL); 10539 useFauxPms |= (realPms == NULL);
10256 10540
10257 /* Attempt to derive the MS from the PMS. This is the only way to 10541 /* Attempt to derive the MS from the PMS. This is the only way to
10258 * check the version field in the RSA PMS. If this fails, we 10542 * check the version field in the RSA PMS. If this fails, we
10259 * then use the faux PMS in place of the PMS. Note that this 10543 * then use the faux PMS in place of the PMS. Note that this
10260 * operation should never fail if we are using the faux PMS 10544 * operation should never fail if we are using the faux PMS
10261 * since it is correctly formatted. */ 10545 * since it is correctly formatted. */
10262 rv = ssl3_ComputeMasterSecret(ss, currentPms, NULL); 10546 rv = ssl3_ComputeMasterSecret(ss, currentPms, NULL);
10263 10547
10264 /* If we succeeded, then select the true PMS and discard the 10548 /* If we succeeded, then select the true PMS and discard the
10265 * FPMS. Else, select the FPMS and select the true PMS */ 10549 * FPMS. Else, select the FPMS and select the true PMS */
10266 useFauxPms |= (rv != SECSuccess); 10550 useFauxPms |= (rv != SECSuccess);
10267 10551
10268 if (unusedPms) { 10552 if (unusedPms) {
10269 PK11_FreeSymKey(unusedPms); 10553 PK11_FreeSymKey(unusedPms);
10270 } 10554 }
10271 10555
10272 » /* This step will derive the MS from the PMS, among other things. */ 10556 /* This step will derive the MS from the PMS, among other things. */
10273 rv = ssl3_InitPendingCipherSpec(ss, currentPms); 10557 rv = ssl3_InitPendingCipherSpec(ss, currentPms);
10274 PK11_FreeSymKey(currentPms); 10558 PK11_FreeSymKey(currentPms);
10275 } 10559 }
10276 10560
10277 if (rv != SECSuccess) { 10561 if (rv != SECSuccess) {
10278 » SEND_ALERT 10562 SEND_ALERT
10279 » return SECFailure; /* error code set by ssl3_InitPendingCipherSpec */ 10563 return SECFailure; /* error code set by ssl3_InitPendingCipherSpec */
10280 } 10564 }
10281 10565
10282 #undef currentPms 10566 #undef currentPms
10283 #undef unusedPms 10567 #undef unusedPms
10284 #undef realPms 10568 #undef realPms
10285 #undef fauxPms 10569 #undef fauxPms
10286 10570
10287 return SECSuccess; 10571 return SECSuccess;
10288 } 10572 }
10289 10573
10290 static SECStatus 10574 static SECStatus
10291 ssl3_HandleDHClientKeyExchange(sslSocket *ss, 10575 ssl3_HandleDHClientKeyExchange(sslSocket *ss,
10292 SSL3Opaque *b, 10576 SSL3Opaque *b,
10293 PRUint32 length, 10577 PRUint32 length,
10294 SECKEYPublicKey *srvrPubKey, 10578 SECKEYPublicKey *srvrPubKey,
10295 SECKEYPrivateKey *serverKey) 10579 SECKEYPrivateKey *serverKey)
10296 { 10580 {
10297 PK11SymKey *pms; 10581 PK11SymKey *pms;
10298 SECStatus rv; 10582 SECStatus rv;
10299 SECKEYPublicKey clntPubKey; 10583 SECKEYPublicKey clntPubKey;
10300 CK_MECHANISM_TYPE» target; 10584 CK_MECHANISM_TYPE target;
10301 PRBool isTLS; 10585 PRBool isTLS;
10302 10586
10303 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 10587 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
10304 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 10588 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10305 PORT_Assert( srvrPubKey ); 10589 PORT_Assert(srvrPubKey);
10306 10590
10307 clntPubKey.keyType = dhKey; 10591 clntPubKey.keyType = dhKey;
10308 clntPubKey.u.dh.prime.len = srvrPubKey->u.dh.prime.len; 10592 clntPubKey.u.dh.prime.len = srvrPubKey->u.dh.prime.len;
10309 clntPubKey.u.dh.prime.data = srvrPubKey->u.dh.prime.data; 10593 clntPubKey.u.dh.prime.data = srvrPubKey->u.dh.prime.data;
10310 clntPubKey.u.dh.base.len = srvrPubKey->u.dh.base.len; 10594 clntPubKey.u.dh.base.len = srvrPubKey->u.dh.base.len;
10311 clntPubKey.u.dh.base.data = srvrPubKey->u.dh.base.data; 10595 clntPubKey.u.dh.base.data = srvrPubKey->u.dh.base.data;
10312 10596
10313 rv = ssl3_ConsumeHandshakeVariable(ss, &clntPubKey.u.dh.publicValue, 10597 rv = ssl3_ConsumeHandshakeVariable(ss, &clntPubKey.u.dh.publicValue,
10314 » 2, &b, &length); 10598 2, &b, &length);
10315 if (rv != SECSuccess) { 10599 if (rv != SECSuccess) {
10316 » goto loser; 10600 goto loser;
10317 } 10601 }
10318 10602
10319 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0); 10603 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
10320 10604
10321 if (isTLS) target = CKM_TLS_MASTER_KEY_DERIVE_DH; 10605 if (isTLS)
10322 else target = CKM_SSL3_MASTER_KEY_DERIVE_DH; 10606 target = CKM_TLS_MASTER_KEY_DERIVE_DH;
10607 else
10608 target = CKM_SSL3_MASTER_KEY_DERIVE_DH;
10323 10609
10324 /* Determine the PMS */ 10610 /* Determine the PMS */
10325 pms = PK11_PubDerive(serverKey, &clntPubKey, PR_FALSE, NULL, NULL, 10611 pms = PK11_PubDerive(serverKey, &clntPubKey, PR_FALSE, NULL, NULL,
10326 CKM_DH_PKCS_DERIVE, target, CKA_DERIVE, 0, NULL); 10612 CKM_DH_PKCS_DERIVE, target, CKA_DERIVE, 0, NULL);
10327 if (pms == NULL) { 10613 if (pms == NULL) {
10328 » ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); 10614 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
10329 » goto loser; 10615 goto loser;
10330 } 10616 }
10331 10617
10332 rv = ssl3_InitPendingCipherSpec(ss, pms); 10618 rv = ssl3_InitPendingCipherSpec(ss, pms);
10333 PK11_FreeSymKey(pms); pms = NULL; 10619 PK11_FreeSymKey(pms);
10620 pms = NULL;
10334 10621
10335 loser: 10622 loser:
10336 if (ss->dheKeyPair) { 10623 if (ss->dheKeyPair) {
10337 ssl3_FreeKeyPair(ss->dheKeyPair); 10624 ssl3_FreeKeyPair(ss->dheKeyPair);
10338 ss->dheKeyPair = NULL; 10625 ss->dheKeyPair = NULL;
10339 } 10626 }
10340 return rv; 10627 return rv;
10341 } 10628 }
10342 10629
10343 10630 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
10344 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete 10631 * a complete ssl3 ClientKeyExchange message from the remote client
10345 * ssl3 ClientKeyExchange message from the remote client
10346 * Caller must hold Handshake and RecvBuf locks. 10632 * Caller must hold Handshake and RecvBuf locks.
10347 */ 10633 */
10348 static SECStatus 10634 static SECStatus
10349 ssl3_HandleClientKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length) 10635 ssl3_HandleClientKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
10350 { 10636 {
10351 SECKEYPrivateKey *serverKey = NULL; 10637 SECKEYPrivateKey *serverKey = NULL;
10352 SECStatus rv; 10638 SECStatus rv;
10353 const ssl3KEADef *kea_def; 10639 const ssl3KEADef *kea_def;
10354 ssl3KeyPair *serverKeyPair = NULL; 10640 ssl3KeyPair *serverKeyPair = NULL;
10355 SECKEYPublicKey *serverPubKey = NULL; 10641 SECKEYPublicKey *serverPubKey = NULL;
10356 10642
10357 SSL_TRC(3, ("%d: SSL3[%d]: handle client_key_exchange handshake", 10643 SSL_TRC(3, ("%d: SSL3[%d]: handle client_key_exchange handshake",
10358 » » SSL_GETPID(), ss->fd)); 10644 SSL_GETPID(), ss->fd));
10359 10645
10360 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 10646 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
10361 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 10647 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10362 10648
10363 if (ss->ssl3.hs.ws != wait_client_key) { 10649 if (ss->ssl3.hs.ws != wait_client_key) {
10364 » SSL3_SendAlert(ss, alert_fatal, unexpected_message); 10650 SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10365 » PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH); 10651 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
10366 » return SECFailure; 10652 return SECFailure;
10367 } 10653 }
10368 10654
10369 kea_def = ss->ssl3.hs.kea_def; 10655 kea_def = ss->ssl3.hs.kea_def;
10370 10656
10371 if (ss->ssl3.hs.usedStepDownKey) { 10657 if (ss->ssl3.hs.usedStepDownKey) {
10372 » PORT_Assert(kea_def->is_limited /* XXX OR cert is signing only */ 10658 PORT_Assert(kea_def->is_limited /* XXX OR cert is signing only */
10373 » » && kea_def->exchKeyType == kt_rsa 10659 &&
10374 » » && ss->stepDownKeyPair != NULL); 10660 kea_def->exchKeyType == kt_rsa &&
10375 » if (!kea_def->is_limited || 10661 ss->stepDownKeyPair != NULL);
10376 » kea_def->exchKeyType != kt_rsa || 10662 if (!kea_def->is_limited ||
10377 » ss->stepDownKeyPair == NULL) { 10663 kea_def->exchKeyType != kt_rsa ||
10378 » » /* shouldn't happen, don't use step down if it does */ 10664 ss->stepDownKeyPair == NULL) {
10379 » » goto skip; 10665 /* shouldn't happen, don't use step down if it does */
10380 » } 10666 goto skip;
10381 » serverKeyPair = ss->stepDownKeyPair; 10667 }
10382 » ss->sec.keaKeyBits = EXPORT_RSA_KEY_LENGTH * BPB; 10668 serverKeyPair = ss->stepDownKeyPair;
10383 } else 10669 ss->sec.keaKeyBits = EXPORT_RSA_KEY_LENGTH * BPB;
10384 skip: 10670 } else
10671 skip:
10385 if (kea_def->kea == kea_dhe_dss || 10672 if (kea_def->kea == kea_dhe_dss ||
10386 kea_def->kea == kea_dhe_rsa) { 10673 kea_def->kea == kea_dhe_rsa) {
10387 if (ss->dheKeyPair) { 10674 if (ss->dheKeyPair) {
10388 serverKeyPair = ss->dheKeyPair; 10675 serverKeyPair = ss->dheKeyPair;
10389 if (serverKeyPair->pubKey) { 10676 if (serverKeyPair->pubKey) {
10390 ss->sec.keaKeyBits = 10677 ss->sec.keaKeyBits =
10391 SECKEY_PublicKeyStrengthInBits(serverKeyPair->pubKey); 10678 SECKEY_PublicKeyStrengthInBits(serverKeyPair->pubKey);
10392 } 10679 }
10393 } 10680 }
10394 } else 10681 } else
10395 #ifndef NSS_DISABLE_ECC 10682 #ifndef NSS_DISABLE_ECC
10396 /* XXX Using SSLKEAType to index server certifiates 10683 /* XXX Using SSLKEAType to index server certifiates
10397 * does not work for (EC)DHE ciphers. Until we have 10684 * does not work for (EC)DHE ciphers. Until we have
10398 * an indexing mechanism general enough for all key 10685 * an indexing mechanism general enough for all key
10399 * exchange algorithms, we'll need to deal with each 10686 * exchange algorithms, we'll need to deal with each
10400 * one seprately. 10687 * one seprately.
10401 */ 10688 */
10402 if ((kea_def->kea == kea_ecdhe_rsa) || 10689 if ((kea_def->kea == kea_ecdhe_rsa) ||
10403 (kea_def->kea == kea_ecdhe_ecdsa)) { 10690 (kea_def->kea == kea_ecdhe_ecdsa)) {
10404 » if (ss->ephemeralECDHKeyPair != NULL) { 10691 if (ss->ephemeralECDHKeyPair != NULL) {
10405 » serverKeyPair = ss->ephemeralECDHKeyPair; 10692 serverKeyPair = ss->ephemeralECDHKeyPair;
10406 » if (serverKeyPair->pubKey) { 10693 if (serverKeyPair->pubKey) {
10407 » » ss->sec.keaKeyBits = 10694 ss->sec.keaKeyBits =
10408 » » SECKEY_PublicKeyStrengthInBits(serverKeyPair->pubKey); 10695 SECKEY_PublicKeyStrengthInBits(serverKeyPair->pubKey);
10409 » } 10696 }
10410 » } 10697 }
10411 } else 10698 } else
10412 #endif 10699 #endif
10413 { 10700 {
10414 » sslServerCerts * sc = ss->serverCerts + kea_def->exchKeyType; 10701 sslServerCerts *sc = ss->serverCerts + kea_def->exchKeyType;
10415 » serverKeyPair = sc->serverKeyPair; 10702 serverKeyPair = sc->serverKeyPair;
10416 » ss->sec.keaKeyBits = sc->serverKeyBits; 10703 ss->sec.keaKeyBits = sc->serverKeyBits;
10417 } 10704 }
10418 10705
10419 if (serverKeyPair) { 10706 if (serverKeyPair) {
10420 » serverKey = serverKeyPair->privKey; 10707 serverKey = serverKeyPair->privKey;
10421 } 10708 }
10422 10709
10423 if (serverKey == NULL) { 10710 if (serverKey == NULL) {
10424 » SEND_ALERT 10711 SEND_ALERT
10425 » PORT_SetError(SSL_ERROR_NO_SERVER_KEY_FOR_ALG); 10712 PORT_SetError(SSL_ERROR_NO_SERVER_KEY_FOR_ALG);
10426 » return SECFailure; 10713 return SECFailure;
10427 } 10714 }
10428 10715
10429 ss->sec.keaType = kea_def->exchKeyType; 10716 ss->sec.keaType = kea_def->exchKeyType;
10430 10717
10431 switch (kea_def->exchKeyType) { 10718 switch (kea_def->exchKeyType) {
10432 case kt_rsa: 10719 case kt_rsa:
10433 » rv = ssl3_HandleRSAClientKeyExchange(ss, b, length, serverKey); 10720 rv = ssl3_HandleRSAClientKeyExchange(ss, b, length, serverKey);
10434 » if (rv != SECSuccess) { 10721 if (rv != SECSuccess) {
10435 » SEND_ALERT 10722 SEND_ALERT
10436 » return SECFailure;» /* error code set */ 10723 return SECFailure; /* error code set */
10437 » } 10724 }
10438 » break; 10725 break;
10439 10726
10440 case ssl_kea_dh: 10727 case ssl_kea_dh:
10441 » if (ss->dheKeyPair && ss->dheKeyPair->pubKey) { 10728 if (ss->dheKeyPair && ss->dheKeyPair->pubKey) {
10442 » serverPubKey = ss->dheKeyPair->pubKey; 10729 serverPubKey = ss->dheKeyPair->pubKey;
10443 » } 10730 }
10444 » if (!serverPubKey) { 10731 if (!serverPubKey) {
10445 » PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); 10732 PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
10446 » return SECFailure; 10733 return SECFailure;
10447 » } 10734 }
10448 » rv = ssl3_HandleDHClientKeyExchange(ss, b, length, 10735 rv = ssl3_HandleDHClientKeyExchange(ss, b, length,
10449 serverPubKey, serverKey); 10736 serverPubKey, serverKey);
10450 » if (rv != SECSuccess) { 10737 if (rv != SECSuccess) {
10451 » SSL3_SendAlert(ss, alert_fatal, handshake_failure); 10738 SSL3_SendAlert(ss, alert_fatal, handshake_failure);
10452 » return SECFailure;» /* error code set */ 10739 return SECFailure; /* error code set */
10453 » } 10740 }
10454 » break; 10741 break;
10455 10742
10456 #ifndef NSS_DISABLE_ECC 10743 #ifndef NSS_DISABLE_ECC
10457 case kt_ecdh: 10744 case kt_ecdh:
10458 » /* XXX We really ought to be able to store multiple 10745 /* XXX We really ought to be able to store multiple
10459 » * EC certs (a requirement if we wish to support both 10746 * EC certs (a requirement if we wish to support both
10460 » * ECDH-RSA and ECDH-ECDSA key exchanges concurrently). 10747 * ECDH-RSA and ECDH-ECDSA key exchanges concurrently).
10461 » * When we make that change, we'll need an index other 10748 * When we make that change, we'll need an index other
10462 » * than kt_ecdh to pick the right EC certificate. 10749 * than kt_ecdh to pick the right EC certificate.
10463 » */ 10750 */
10464 » if (serverKeyPair) { 10751 if (serverKeyPair) {
10465 » serverPubKey = serverKeyPair->pubKey; 10752 serverPubKey = serverKeyPair->pubKey;
10466 } 10753 }
10467 » if (serverPubKey == NULL) { 10754 if (serverPubKey == NULL) {
10468 » /* XXX Is this the right error code? */ 10755 /* XXX Is this the right error code? */
10469 » PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); 10756 PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
10470 » return SECFailure; 10757 return SECFailure;
10471 » } 10758 }
10472 » rv = ssl3_HandleECDHClientKeyExchange(ss, b, length, 10759 rv = ssl3_HandleECDHClientKeyExchange(ss, b, length,
10473 » » » » » serverPubKey, serverKey); 10760 serverPubKey, serverKey);
10474 » if (ss->ephemeralECDHKeyPair) { 10761 if (ss->ephemeralECDHKeyPair) {
10475 » ssl3_FreeKeyPair(ss->ephemeralECDHKeyPair); 10762 ssl3_FreeKeyPair(ss->ephemeralECDHKeyPair);
10476 » ss->ephemeralECDHKeyPair = NULL; 10763 ss->ephemeralECDHKeyPair = NULL;
10477 » } 10764 }
10478 » if (rv != SECSuccess) { 10765 if (rv != SECSuccess) {
10479 » return SECFailure;» /* error code set */ 10766 return SECFailure; /* error code set */
10480 » } 10767 }
10481 » break; 10768 break;
10482 #endif /* NSS_DISABLE_ECC */ 10769 #endif /* NSS_DISABLE_ECC */
10483 10770
10484 default: 10771 default:
10485 » (void) ssl3_HandshakeFailure(ss); 10772 (void)ssl3_HandshakeFailure(ss);
10486 » PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); 10773 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
10487 » return SECFailure; 10774 return SECFailure;
10488 } 10775 }
10489 ss->ssl3.hs.ws = ss->sec.peerCert ? wait_cert_verify : wait_change_cipher; 10776 ss->ssl3.hs.ws = ss->sec.peerCert ? wait_cert_verify : wait_change_cipher;
10490 return SECSuccess; 10777 return SECSuccess;
10491
10492 } 10778 }
10493 10779
10494 /* This is TLS's equivalent of sending a no_certificate alert. */ 10780 /* This is TLS's equivalent of sending a no_certificate alert. */
10495 static SECStatus 10781 SECStatus
10496 ssl3_SendEmptyCertificate(sslSocket *ss) 10782 ssl3_SendEmptyCertificate(sslSocket *ss)
10497 { 10783 {
10498 SECStatus rv; 10784 SECStatus rv;
10785 unsigned int len = 0;
10786 PRBool isTLS13 = PR_FALSE;
10499 10787
10500 rv = ssl3_AppendHandshakeHeader(ss, certificate, 3); 10788 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
10501 if (rv == SECSuccess) { 10789 len = ss->ssl3.hs.certReqContextLen + 1;
10502 » rv = ssl3_AppendHandshakeNumber(ss, 0, 3); 10790 isTLS13 = PR_TRUE;
10503 } 10791 }
10504 return rv;» /* error, if any, set by functions called above. */ 10792
10793 rv = ssl3_AppendHandshakeHeader(ss, certificate, len + 3);
10794 if (rv != SECSuccess) {
10795 return rv;
10796 }
10797
10798 if (isTLS13) {
10799 rv = ssl3_AppendHandshakeVariable(ss, ss->ssl3.hs.certReqContext,
10800 ss->ssl3.hs.certReqContextLen, 1);
10801 if (rv != SECSuccess) {
10802 return rv;
10803 }
10804 }
10805
10806 return ssl3_AppendHandshakeNumber(ss, 0, 3);
10505 } 10807 }
10506 10808
10507 SECStatus 10809 SECStatus
10508 ssl3_HandleNewSessionTicket(sslSocket *ss, SSL3Opaque *b, PRUint32 length) 10810 ssl3_HandleNewSessionTicket(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
10509 { 10811 {
10510 SECStatus rv; 10812 SECStatus rv;
10511 SECItem ticketData; 10813 SECItem ticketData;
10512 10814
10513 SSL_TRC(3, ("%d: SSL3[%d]: handle session_ticket handshake", 10815 SSL_TRC(3, ("%d: SSL3[%d]: handle session_ticket handshake",
10514 » » SSL_GETPID(), ss->fd)); 10816 SSL_GETPID(), ss->fd));
10515 10817
10516 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 10818 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
10517 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 10819 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10518 10820
10519 PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data); 10821 PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data);
10520 PORT_Assert(!ss->ssl3.hs.receivedNewSessionTicket); 10822 PORT_Assert(!ss->ssl3.hs.receivedNewSessionTicket);
10521 10823
10522 if (ss->ssl3.hs.ws != wait_new_session_ticket) { 10824 if (ss->ssl3.hs.ws != wait_new_session_ticket) {
10523 » SSL3_SendAlert(ss, alert_fatal, unexpected_message); 10825 SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10524 » PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET); 10826 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
10525 » return SECFailure; 10827 return SECFailure;
10526 } 10828 }
10527 10829
10528 /* RFC5077 Section 3.3: "The client MUST NOT treat the ticket as valid 10830 /* RFC5077 Section 3.3: "The client MUST NOT treat the ticket as valid
10529 * until it has verified the server's Finished message." See the comment in 10831 * until it has verified the server's Finished message." See the comment in
10530 * ssl3_FinishHandshake for more details. 10832 * ssl3_FinishHandshake for more details.
10531 */ 10833 */
10532 ss->ssl3.hs.newSessionTicket.received_timestamp = ssl_Time(); 10834 ss->ssl3.hs.newSessionTicket.received_timestamp = ssl_Time();
10533 if (length < 4) { 10835 if (length < 4) {
10534 » (void)SSL3_SendAlert(ss, alert_fatal, decode_error); 10836 (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
10535 » PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET); 10837 PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
10536 » return SECFailure; 10838 return SECFailure;
10537 } 10839 }
10538 ss->ssl3.hs.newSessionTicket.ticket_lifetime_hint = 10840 ss->ssl3.hs.newSessionTicket.ticket_lifetime_hint =
10539 » (PRUint32)ssl3_ConsumeHandshakeNumber(ss, 4, &b, &length); 10841 (PRUint32)ssl3_ConsumeHandshakeNumber(ss, 4, &b, &length);
10540 10842
10541 rv = ssl3_ConsumeHandshakeVariable(ss, &ticketData, 2, &b, &length); 10843 rv = ssl3_ConsumeHandshakeVariable(ss, &ticketData, 2, &b, &length);
10542 if (rv != SECSuccess || length != 0) { 10844 if (rv != SECSuccess || length != 0) {
10543 » (void)SSL3_SendAlert(ss, alert_fatal, decode_error); 10845 (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
10544 » PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET); 10846 PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
10545 » return SECFailure; /* malformed */ 10847 return SECFailure; /* malformed */
10546 } 10848 }
10547 /* If the server sent a zero-length ticket, ignore it and keep the 10849 /* If the server sent a zero-length ticket, ignore it and keep the
10548 * existing ticket. */ 10850 * existing ticket. */
10549 if (ticketData.len != 0) { 10851 if (ticketData.len != 0) {
10550 » rv = SECITEM_CopyItem(NULL, &ss->ssl3.hs.newSessionTicket.ticket, 10852 rv = SECITEM_CopyItem(NULL, &ss->ssl3.hs.newSessionTicket.ticket,
10551 » » » &ticketData); 10853 &ticketData);
10552 » if (rv != SECSuccess) { 10854 if (rv != SECSuccess) {
10553 » return rv; 10855 return rv;
10554 » } 10856 }
10555 » ss->ssl3.hs.receivedNewSessionTicket = PR_TRUE; 10857 ss->ssl3.hs.receivedNewSessionTicket = PR_TRUE;
10556 } 10858 }
10557 10859
10558 ss->ssl3.hs.ws = wait_change_cipher; 10860 ss->ssl3.hs.ws = wait_change_cipher;
10559 return SECSuccess; 10861 return SECSuccess;
10560 } 10862 }
10561 10863
10562 #ifdef NISCC_TEST 10864 #ifdef NISCC_TEST
10563 static PRInt32 connNum = 0; 10865 static PRInt32 connNum = 0;
10564 10866
10565 static SECStatus 10867 static SECStatus
10566 get_fake_cert(SECItem *pCertItem, int *pIndex) 10868 get_fake_cert(SECItem *pCertItem, int *pIndex)
10567 { 10869 {
10568 PRFileDesc *cf; 10870 PRFileDesc *cf;
10569 char * testdir; 10871 char *testdir;
10570 char * startat; 10872 char *startat;
10571 char * stopat; 10873 char *stopat;
10572 const char *extension; 10874 const char *extension;
10573 int fileNum; 10875 int fileNum;
10574 PRInt32 numBytes = 0; 10876 PRInt32 numBytes = 0;
10575 PRStatus prStatus; 10877 PRStatus prStatus;
10576 PRFileInfo info; 10878 PRFileInfo info;
10577 char cfn[100]; 10879 char cfn[100];
10578 10880
10579 pCertItem->data = 0; 10881 pCertItem->data = 0;
10580 if ((testdir = PR_GetEnv("NISCC_TEST")) == NULL) { 10882 if ((testdir = PR_GetEnvSecure("NISCC_TEST")) == NULL) {
10581 » return SECSuccess; 10883 return SECSuccess;
10582 } 10884 }
10583 *pIndex = (NULL != strstr(testdir, "root")); 10885 *pIndex = (NULL != strstr(testdir, "root"));
10584 extension = (strstr(testdir, "simple") ? "" : ".der"); 10886 extension = (strstr(testdir, "simple") ? "" : ".der");
10585 fileNum = PR_ATOMIC_INCREMENT(&connNum) - 1; 10887 fileNum = PR_ATOMIC_INCREMENT(&connNum) - 1;
10586 if ((startat = PR_GetEnv("START_AT")) != NULL) { 10888 if ((startat = PR_GetEnvSecure("START_AT")) != NULL) {
10587 » fileNum += atoi(startat); 10889 fileNum += atoi(startat);
10588 } 10890 }
10589 if ((stopat = PR_GetEnv("STOP_AT")) != NULL && 10891 if ((stopat = PR_GetEnvSecure("STOP_AT")) != NULL &&
10590 » fileNum >= atoi(stopat)) { 10892 fileNum >= atoi(stopat)) {
10591 » *pIndex = -1; 10893 *pIndex = -1;
10592 » return SECSuccess; 10894 return SECSuccess;
10593 } 10895 }
10594 sprintf(cfn, "%s/%08d%s", testdir, fileNum, extension); 10896 sprintf(cfn, "%s/%08d%s", testdir, fileNum, extension);
10595 cf = PR_Open(cfn, PR_RDONLY, 0); 10897 cf = PR_Open(cfn, PR_RDONLY, 0);
10596 if (!cf) { 10898 if (!cf) {
10597 » goto loser; 10899 goto loser;
10598 } 10900 }
10599 prStatus = PR_GetOpenFileInfo(cf, &info); 10901 prStatus = PR_GetOpenFileInfo(cf, &info);
10600 if (prStatus != PR_SUCCESS) { 10902 if (prStatus != PR_SUCCESS) {
10601 » PR_Close(cf); 10903 PR_Close(cf);
10602 » goto loser; 10904 goto loser;
10603 } 10905 }
10604 pCertItem = SECITEM_AllocItem(NULL, pCertItem, info.size); 10906 pCertItem = SECITEM_AllocItem(NULL, pCertItem, info.size);
10605 if (pCertItem) { 10907 if (pCertItem) {
10606 » numBytes = PR_Read(cf, pCertItem->data, info.size); 10908 numBytes = PR_Read(cf, pCertItem->data, info.size);
10607 } 10909 }
10608 PR_Close(cf); 10910 PR_Close(cf);
10609 if (numBytes != info.size) { 10911 if (numBytes != info.size) {
10610 » SECITEM_FreeItem(pCertItem, PR_FALSE); 10912 SECITEM_FreeItem(pCertItem, PR_FALSE);
10611 » PORT_SetError(SEC_ERROR_IO); 10913 PORT_SetError(SEC_ERROR_IO);
10612 » goto loser; 10914 goto loser;
10613 } 10915 }
10614 fprintf(stderr, "using %s\n", cfn); 10916 fprintf(stderr, "using %s\n", cfn);
10615 return SECSuccess; 10917 return SECSuccess;
10616 10918
10617 loser: 10919 loser:
10618 fprintf(stderr, "failed to use %s\n", cfn); 10920 fprintf(stderr, "failed to use %s\n", cfn);
10619 *pIndex = -1; 10921 *pIndex = -1;
10620 return SECFailure; 10922 return SECFailure;
10621 } 10923 }
10622 #endif 10924 #endif
10623 10925
10624 /* 10926 /*
10625 * Used by both client and server. 10927 * Used by both client and server.
10626 * Called from HandleServerHelloDone and from SendServerHelloSequence. 10928 * Called from HandleServerHelloDone and from SendServerHelloSequence.
10627 */ 10929 */
10628 static SECStatus 10930 SECStatus
10629 ssl3_SendCertificate(sslSocket *ss) 10931 ssl3_SendCertificate(sslSocket *ss)
10630 { 10932 {
10631 SECStatus rv; 10933 SECStatus rv;
10632 CERTCertificateList *certChain; 10934 CERTCertificateList *certChain;
10633 int len » » = 0; 10935 int certChainLen = 0;
10634 int i; 10936 int i;
10635 SSL3KEAType certIndex; 10937 SSL3KEAType certIndex;
10636 #ifdef NISCC_TEST 10938 #ifdef NISCC_TEST
10637 SECItem fakeCert; 10939 SECItem fakeCert;
10638 int ndex = -1; 10940 int ndex = -1;
10639 #endif 10941 #endif
10942 PRBool isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3;
10943 unsigned int contextLen = 0;
10640 10944
10641 SSL_TRC(3, ("%d: SSL3[%d]: send certificate handshake", 10945 SSL_TRC(3, ("%d: SSL3[%d]: send certificate handshake",
10642 » » SSL_GETPID(), ss->fd)); 10946 SSL_GETPID(), ss->fd));
10643 10947
10644 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 10948 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
10645 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 10949 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10646 10950
10647 if (ss->sec.localCert) 10951 if (ss->sec.localCert)
10648 » CERT_DestroyCertificate(ss->sec.localCert); 10952 CERT_DestroyCertificate(ss->sec.localCert);
10649 if (ss->sec.isServer) { 10953 if (ss->sec.isServer) {
10650 » sslServerCerts * sc = NULL; 10954 sslServerCerts *sc = NULL;
10651 10955
10652 » /* XXX SSLKEAType isn't really a good choice for 10956 /* XXX SSLKEAType isn't really a good choice for
10653 » * indexing certificates (it breaks when we deal 10957 * indexing certificates (it breaks when we deal
10654 » * with (EC)DHE-* cipher suites. This hack ensures 10958 * with (EC)DHE-* cipher suites. This hack ensures
10655 » * the RSA cert is picked for (EC)DHE-RSA. 10959 * the RSA cert is picked for (EC)DHE-RSA.
10656 » * Revisit this when we add server side support 10960 * Revisit this when we add server side support
10657 » * for ECDHE-ECDSA or client-side authentication 10961 * for ECDHE-ECDSA or client-side authentication
10658 » * using EC certificates. 10962 * using EC certificates.
10659 » */ 10963 */
10660 » if ((ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) || 10964 if ((ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) ||
10661 » (ss->ssl3.hs.kea_def->kea == kea_dhe_rsa)) { 10965 (ss->ssl3.hs.kea_def->kea == kea_dhe_rsa)) {
10662 » certIndex = kt_rsa; 10966 certIndex = kt_rsa;
10663 » } else { 10967 } else {
10664 » certIndex = ss->ssl3.hs.kea_def->exchKeyType; 10968 certIndex = ss->ssl3.hs.kea_def->exchKeyType;
10665 » } 10969 }
10666 » sc = ss->serverCerts + certIndex; 10970 sc = ss->serverCerts + certIndex;
10667 » certChain = sc->serverCertChain; 10971 certChain = sc->serverCertChain;
10668 » ss->sec.authKeyBits = sc->serverKeyBits; 10972 ss->sec.authKeyBits = sc->serverKeyBits;
10669 » ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType; 10973 ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType;
10670 » ss->sec.localCert = CERT_DupCertificate(sc->serverCert); 10974 ss->sec.localCert = CERT_DupCertificate(sc->serverCert);
10671 } else { 10975 } else {
10672 » certChain = ss->ssl3.clientCertChain; 10976 certChain = ss->ssl3.clientCertChain;
10673 » ss->sec.localCert = CERT_DupCertificate(ss->ssl3.clientCertificate); 10977 ss->sec.localCert = CERT_DupCertificate(ss->ssl3.clientCertificate);
10674 } 10978 }
10675 10979
10676 #ifdef NISCC_TEST 10980 #ifdef NISCC_TEST
10677 rv = get_fake_cert(&fakeCert, &ndex); 10981 rv = get_fake_cert(&fakeCert, &ndex);
10678 #endif 10982 #endif
10679 10983
10680 if (certChain) { 10984 if (isTLS13) {
10681 » for (i = 0; i < certChain->len; i++) { 10985 contextLen = 1; /* Length of the context */
10682 #ifdef NISCC_TEST 10986 if (!ss->sec.isServer) {
10683 » if (fakeCert.len > 0 && i == ndex) { 10987 contextLen += ss->ssl3.hs.certReqContextLen;
10684 » » len += fakeCert.len + 3; 10988 }
10685 » } else {
10686 » » len += certChain->certs[i].len + 3;
10687 » }
10688 #else
10689 » len += certChain->certs[i].len + 3;
10690 #endif
10691 » }
10692 }
10693
10694 rv = ssl3_AppendHandshakeHeader(ss, certificate, len + 3);
10695 if (rv != SECSuccess) {
10696 » return rv; » » /* err set by AppendHandshake. */
10697 }
10698 rv = ssl3_AppendHandshakeNumber(ss, len, 3);
10699 if (rv != SECSuccess) {
10700 » return rv; » » /* err set by AppendHandshake. */
10701 } 10989 }
10702 if (certChain) { 10990 if (certChain) {
10703 for (i = 0; i < certChain->len; i++) { 10991 for (i = 0; i < certChain->len; i++) {
10992 #ifdef NISCC_TEST
10993 if (fakeCert.len > 0 && i == ndex) {
10994 certChainLen += fakeCert.len + 3;
10995 } else {
10996 certChainLen += certChain->certs[i].len + 3;
10997 }
10998 #else
10999 certChainLen += certChain->certs[i].len + 3;
11000 #endif
11001 }
11002 }
11003
11004 rv = ssl3_AppendHandshakeHeader(ss, certificate,
11005 contextLen + certChainLen + 3);
11006 if (rv != SECSuccess) {
11007 return rv; /* err set by AppendHandshake. */
11008 }
11009
11010 if (isTLS13) {
11011 if (ss->sec.isServer) {
11012 rv = ssl3_AppendHandshakeNumber(ss, 0, 1);
11013 } else {
11014 rv = ssl3_AppendHandshakeVariable(ss,
11015 ss->ssl3.hs.certReqContext,
11016 ss->ssl3.hs.certReqContextLen, 1);
11017 }
11018 if (rv != SECSuccess) {
11019 return rv; /* err set by AppendHandshake. */
11020 }
11021 }
11022
11023 rv = ssl3_AppendHandshakeNumber(ss, certChainLen, 3);
11024 if (rv != SECSuccess) {
11025 return rv; /* err set by AppendHandshake. */
11026 }
11027 if (certChain) {
11028 for (i = 0; i < certChain->len; i++) {
10704 #ifdef NISCC_TEST 11029 #ifdef NISCC_TEST
10705 if (fakeCert.len > 0 && i == ndex) { 11030 if (fakeCert.len > 0 && i == ndex) {
10706 rv = ssl3_AppendHandshakeVariable(ss, fakeCert.data, 11031 rv = ssl3_AppendHandshakeVariable(ss, fakeCert.data,
10707 fakeCert.len, 3); 11032 fakeCert.len, 3);
10708 SECITEM_FreeItem(&fakeCert, PR_FALSE); 11033 SECITEM_FreeItem(&fakeCert, PR_FALSE);
10709 } else { 11034 } else {
10710 rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data, 11035 rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
10711 certChain->certs[i].len, 3); 11036 certChain->certs[i].len, 3);
10712 } 11037 }
10713 #else 11038 #else
10714 rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data, 11039 rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
10715 certChain->certs[i].len, 3); 11040 certChain->certs[i].len, 3);
10716 #endif 11041 #endif
10717 if (rv != SECSuccess) { 11042 if (rv != SECSuccess) {
10718 return rv; » » /* err set by AppendHandshake. */ 11043 return rv; /* err set by AppendHandshake. */
10719 } 11044 }
10720 } 11045 }
10721 } 11046 }
10722 11047
10723 return SECSuccess; 11048 return SECSuccess;
10724 } 11049 }
10725 11050
10726 /* 11051 /*
10727 * Used by server only. 11052 * Used by server only.
10728 * single-stapling, send only a single cert status 11053 * single-stapling, send only a single cert status
10729 */ 11054 */
10730 static SECStatus 11055 SECStatus
10731 ssl3_SendCertificateStatus(sslSocket *ss) 11056 ssl3_SendCertificateStatus(sslSocket *ss)
10732 { 11057 {
10733 SECStatus rv; 11058 SECStatus rv;
10734 int len = 0; 11059 int len = 0;
10735 SECItemArray *statusToSend = NULL; 11060 SECItemArray *statusToSend = NULL;
10736 SSL3KEAType certIndex; 11061 SSL3KEAType certIndex;
10737 11062
10738 SSL_TRC(3, ("%d: SSL3[%d]: send certificate status handshake", 11063 SSL_TRC(3, ("%d: SSL3[%d]: send certificate status handshake",
10739 » » SSL_GETPID(), ss->fd)); 11064 SSL_GETPID(), ss->fd));
10740 11065
10741 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 11066 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
10742 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 11067 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10743 PORT_Assert( ss->sec.isServer); 11068 PORT_Assert(ss->sec.isServer);
10744 11069
10745 if (!ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn)) 11070 if (!ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn))
10746 » return SECSuccess; 11071 return SECSuccess;
10747 11072
10748 /* Use certStatus based on the cert being used. */ 11073 /* Use certStatus based on the cert being used. */
10749 if ((ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) || 11074 if ((ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) ||
10750 » (ss->ssl3.hs.kea_def->kea == kea_dhe_rsa)) { 11075 (ss->ssl3.hs.kea_def->kea == kea_dhe_rsa)) {
10751 » certIndex = kt_rsa; 11076 certIndex = kt_rsa;
10752 } else { 11077 } else {
10753 » certIndex = ss->ssl3.hs.kea_def->exchKeyType; 11078 certIndex = ss->ssl3.hs.kea_def->exchKeyType;
10754 } 11079 }
10755 if (ss->certStatusArray[certIndex] && ss->certStatusArray[certIndex]->len) { 11080 if (ss->certStatusArray[certIndex] && ss->certStatusArray[certIndex]->len) {
10756 » statusToSend = ss->certStatusArray[certIndex]; 11081 statusToSend = ss->certStatusArray[certIndex];
10757 } 11082 }
10758 if (!statusToSend) 11083 if (!statusToSend)
10759 » return SECSuccess; 11084 return SECSuccess;
10760 11085
10761 /* Use the array's first item only (single stapling) */ 11086 /* Use the array's first item only (single stapling) */
10762 len = 1 + statusToSend->items[0].len + 3; 11087 len = 1 + statusToSend->items[0].len + 3;
10763 11088
10764 rv = ssl3_AppendHandshakeHeader(ss, certificate_status, len); 11089 rv = ssl3_AppendHandshakeHeader(ss, certificate_status, len);
10765 if (rv != SECSuccess) { 11090 if (rv != SECSuccess) {
10766 » return rv; » » /* err set by AppendHandshake. */ 11091 return rv; /* err set by AppendHandshake. */
10767 } 11092 }
10768 rv = ssl3_AppendHandshakeNumber(ss, 1 /*ocsp*/, 1); 11093 rv = ssl3_AppendHandshakeNumber(ss, 1 /*ocsp*/, 1);
10769 if (rv != SECSuccess) 11094 if (rv != SECSuccess)
10770 » return rv; » » /* err set by AppendHandshake. */ 11095 return rv; /* err set by AppendHandshake. */
10771 11096
10772 rv = ssl3_AppendHandshakeVariable(ss, 11097 rv = ssl3_AppendHandshakeVariable(ss,
10773 » » » » statusToSend->items[0].data, 11098 statusToSend->items[0].data,
10774 » » » » statusToSend->items[0].len, 11099 statusToSend->items[0].len,
10775 » » » » 3); 11100 3);
10776 if (rv != SECSuccess) 11101 if (rv != SECSuccess)
10777 » return rv; » » /* err set by AppendHandshake. */ 11102 return rv; /* err set by AppendHandshake. */
10778 11103
10779 return SECSuccess; 11104 return SECSuccess;
10780 } 11105 }
10781 11106
10782 /* This is used to delete the CA certificates in the peer certificate chain 11107 /* This is used to delete the CA certificates in the peer certificate chain
10783 * from the cert database after they've been validated. 11108 * from the cert database after they've been validated.
10784 */ 11109 */
10785 static void 11110 static void
10786 ssl3_CleanupPeerCerts(sslSocket *ss) 11111 ssl3_CleanupPeerCerts(sslSocket *ss)
10787 { 11112 {
10788 PLArenaPool * arena = ss->ssl3.peerCertArena; 11113 PLArenaPool *arena = ss->ssl3.peerCertArena;
10789 ssl3CertNode *certs = (ssl3CertNode *)ss->ssl3.peerCertChain; 11114 ssl3CertNode *certs = (ssl3CertNode *)ss->ssl3.peerCertChain;
10790 11115
10791 for (; certs; certs = certs->next) { 11116 for (; certs; certs = certs->next) {
10792 » CERT_DestroyCertificate(certs->cert); 11117 CERT_DestroyCertificate(certs->cert);
10793 } 11118 }
10794 if (arena) PORT_FreeArena(arena, PR_FALSE); 11119 if (arena)
11120 PORT_FreeArena(arena, PR_FALSE);
10795 ss->ssl3.peerCertArena = NULL; 11121 ss->ssl3.peerCertArena = NULL;
10796 ss->ssl3.peerCertChain = NULL; 11122 ss->ssl3.peerCertChain = NULL;
10797 } 11123 }
10798 11124
10799 static void 11125 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
10800 ssl3_CopyPeerCertsFromSID(sslSocket *ss, sslSessionID *sid) 11126 * a complete ssl3 CertificateStatus message.
10801 {
10802 PLArenaPool *arena;
10803 ssl3CertNode *lastCert = NULL;
10804 ssl3CertNode *certs = NULL;
10805 int i;
10806
10807 if (!sid->peerCertChain[0])
10808 » return;
10809 PORT_Assert(!ss->ssl3.peerCertArena);
10810 PORT_Assert(!ss->ssl3.peerCertChain);
10811 ss->ssl3.peerCertArena = arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
10812 for (i = 0; i < MAX_PEER_CERT_CHAIN_SIZE && sid->peerCertChain[i]; i++) {
10813 » ssl3CertNode *c = PORT_ArenaNew(arena, ssl3CertNode);
10814 » c->cert = CERT_DupCertificate(sid->peerCertChain[i]);
10815 » c->next = NULL;
10816 » if (lastCert) {
10817 » lastCert->next = c;
10818 » } else {
10819 » certs = c;
10820 » }
10821 » lastCert = c;
10822 }
10823 ss->ssl3.peerCertChain = certs;
10824 }
10825
10826 static void
10827 ssl3_CopyPeerCertsToSID(ssl3CertNode *certs, sslSessionID *sid)
10828 {
10829 int i = 0;
10830 ssl3CertNode *c = certs;
10831 for (; i < MAX_PEER_CERT_CHAIN_SIZE && c; i++, c = c->next) {
10832 » PORT_Assert(!sid->peerCertChain[i]);
10833 » sid->peerCertChain[i] = CERT_DupCertificate(c->cert);
10834 }
10835 }
10836
10837 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
10838 * ssl3 CertificateStatus message.
10839 * Caller must hold Handshake and RecvBuf locks. 11127 * Caller must hold Handshake and RecvBuf locks.
10840 * This is always called before ssl3_HandleCertificate, even if the Certificate
10841 * message is sent first.
10842 */ 11128 */
10843 static SECStatus 11129 static SECStatus
10844 ssl3_HandleCertificateStatus(sslSocket *ss, SSL3Opaque *b, PRUint32 length) 11130 ssl3_HandleCertificateStatus(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
10845 { 11131 {
10846 PRInt32 status, len;
10847
10848 if (ss->ssl3.hs.ws != wait_certificate_status) { 11132 if (ss->ssl3.hs.ws != wait_certificate_status) {
10849 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 11133 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10850 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_STATUS); 11134 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_STATUS);
10851 return SECFailure; 11135 return SECFailure;
10852 } 11136 }
10853 11137
11138 return ssl3_CompleteHandleCertificateStatus(ss, b, length);
11139 }
11140
11141 /* Called from:
11142 * ssl3_HandleCertificateStatus
11143 * tls13_HandleCertificateStatus
11144 */
11145 SECStatus
11146 ssl3_CompleteHandleCertificateStatus(sslSocket *ss, SSL3Opaque *b,
11147 PRUint32 length)
11148 {
11149 PRInt32 status, len;
11150
10854 PORT_Assert(!ss->sec.isServer); 11151 PORT_Assert(!ss->sec.isServer);
10855 11152
10856 /* Consume the CertificateStatusType enum */ 11153 /* Consume the CertificateStatusType enum */
10857 status = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length); 11154 status = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length);
10858 if (status != 1 /* ocsp */) { 11155 if (status != 1 /* ocsp */) {
10859 goto format_loser; 11156 goto format_loser;
10860 } 11157 }
10861 11158
10862 len = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length); 11159 len = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
10863 if (len != length) { 11160 if (len != length) {
10864 goto format_loser; 11161 goto format_loser;
10865 } 11162 }
10866 11163
10867 #define MAX_CERTSTATUS_LEN 0x1ffff /* 128k - 1 */ 11164 #define MAX_CERTSTATUS_LEN 0x1ffff /* 128k - 1 */
10868 if (length > MAX_CERTSTATUS_LEN) 11165 if (length > MAX_CERTSTATUS_LEN)
10869 goto format_loser; 11166 goto format_loser;
10870 #undef MAX_CERTSTATUS_LEN 11167 #undef MAX_CERTSTATUS_LEN
10871 11168
10872 /* Array size 1, because we currently implement single-stapling only */ 11169 /* Array size 1, because we currently implement single-stapling only */
10873 SECITEM_AllocArray(NULL, &ss->sec.ci.sid->peerCertStatus, 1); 11170 SECITEM_AllocArray(NULL, &ss->sec.ci.sid->peerCertStatus, 1);
10874 if (!ss->sec.ci.sid->peerCertStatus.items) 11171 if (!ss->sec.ci.sid->peerCertStatus.items)
10875 return SECFailure; 11172 return SECFailure;
10876 11173
10877 ss->sec.ci.sid->peerCertStatus.items[0].data = PORT_Alloc(length); 11174 ss->sec.ci.sid->peerCertStatus.items[0].data = PORT_Alloc(length);
10878 11175
10879 if (!ss->sec.ci.sid->peerCertStatus.items[0].data) { 11176 if (!ss->sec.ci.sid->peerCertStatus.items[0].data) {
10880 SECITEM_FreeArray(&ss->sec.ci.sid->peerCertStatus, PR_FALSE); 11177 SECITEM_FreeArray(&ss->sec.ci.sid->peerCertStatus, PR_FALSE);
10881 return SECFailure; 11178 return SECFailure;
10882 } 11179 }
10883 11180
10884 PORT_Memcpy(ss->sec.ci.sid->peerCertStatus.items[0].data, b, length); 11181 PORT_Memcpy(ss->sec.ci.sid->peerCertStatus.items[0].data, b, length);
10885 ss->sec.ci.sid->peerCertStatus.items[0].len = length; 11182 ss->sec.ci.sid->peerCertStatus.items[0].len = length;
10886 ss->sec.ci.sid->peerCertStatus.items[0].type = siBuffer; 11183 ss->sec.ci.sid->peerCertStatus.items[0].type = siBuffer;
10887 11184
10888 return ssl3_AuthCertificate(ss); 11185 return ssl3_AuthCertificate(ss);
10889 11186
10890 format_loser: 11187 format_loser:
10891 return ssl3_DecodeError(ss); 11188 return ssl3_DecodeError(ss);
10892 } 11189 }
10893 11190
10894 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete 11191 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
10895 * ssl3 Certificate message. 11192 * a complete ssl3 Certificate message.
10896 * Caller must hold Handshake and RecvBuf locks. 11193 * Caller must hold Handshake and RecvBuf locks.
10897 */ 11194 */
10898 static SECStatus 11195 static SECStatus
10899 ssl3_HandleCertificate(sslSocket *ss, SSL3Opaque *b, PRUint32 length) 11196 ssl3_HandleCertificate(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
10900 { 11197 {
10901 ssl3CertNode * c; 11198 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate handshake",
10902 ssl3CertNode * lastCert » = NULL; 11199 SSL_GETPID(), ss->fd));
10903 PRInt32 remaining = 0; 11200 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
10904 PRInt32 size; 11201 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
10905 SECStatus rv;
10906 PRBool isServer» = (PRBool)(!!ss->sec.isServer);
10907 PRBool isTLS;
10908 SSL3AlertDescription desc;
10909 int errCode = SSL_ERROR_RX_MALFORMED_CERTIFICATE;
10910 SECItem certItem;
10911 11202
10912 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate handshake", 11203 if ((ss->sec.isServer && ss->ssl3.hs.ws != wait_client_cert) ||
10913 » » SSL_GETPID(), ss->fd)); 11204 (!ss->sec.isServer && ss->ssl3.hs.ws != wait_server_cert)) {
10914 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 11205 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10915 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 11206 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERTIFICATE);
10916 11207 return SECFailure;
10917 if ((isServer && ss->ssl3.hs.ws != wait_client_cert) ||
10918 (!isServer && ss->ssl3.hs.ws != wait_server_cert)) {
10919 desc = unexpected_message;
10920 errCode = SSL_ERROR_RX_UNEXPECTED_CERTIFICATE;
10921 goto alert_loser;
10922 } 11208 }
10923 11209
11210 return ssl3_CompleteHandleCertificate(ss, b, length);
11211 }
11212
11213 /* Called from ssl3_HandleCertificate
11214 */
11215 SECStatus
11216 ssl3_CompleteHandleCertificate(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
11217 {
11218 ssl3CertNode *c;
11219 ssl3CertNode *lastCert = NULL;
11220 PRInt32 remaining = 0;
11221 PRInt32 size;
11222 SECStatus rv;
11223 PRBool isServer = (PRBool)(!!ss->sec.isServer);
11224 PRBool isTLS;
11225 SSL3AlertDescription desc;
11226 int errCode = SSL_ERROR_RX_MALFORMED_CERTIFICATE;
11227 SECItem certItem;
11228
10924 if (ss->sec.peerCert != NULL) { 11229 if (ss->sec.peerCert != NULL) {
10925 » if (ss->sec.peerKey) { 11230 if (ss->sec.peerKey) {
10926 » SECKEY_DestroyPublicKey(ss->sec.peerKey); 11231 SECKEY_DestroyPublicKey(ss->sec.peerKey);
10927 » ss->sec.peerKey = NULL; 11232 ss->sec.peerKey = NULL;
10928 » } 11233 }
10929 » CERT_DestroyCertificate(ss->sec.peerCert); 11234 CERT_DestroyCertificate(ss->sec.peerCert);
10930 » ss->sec.peerCert = NULL; 11235 ss->sec.peerCert = NULL;
10931 } 11236 }
10932 11237
10933 ssl3_CleanupPeerCerts(ss); 11238 ssl3_CleanupPeerCerts(ss);
10934 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0); 11239 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
10935 11240
10936 /* It is reported that some TLS client sends a Certificate message 11241 /* It is reported that some TLS client sends a Certificate message
10937 ** with a zero-length message body. We'll treat that case like a 11242 ** with a zero-length message body. We'll treat that case like a
10938 ** normal no_certificates message to maximize interoperability. 11243 ** normal no_certificates message to maximize interoperability.
10939 */ 11244 */
10940 if (length) { 11245 if (length) {
10941 » remaining = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length); 11246 remaining = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
10942 » if (remaining < 0) 11247 if (remaining < 0)
10943 » goto loser;»/* fatal alert already sent by ConsumeHandshake. */ 11248 goto loser; /* fatal alert already sent by ConsumeHandshake. */
10944 » if ((PRUint32)remaining > length) 11249 if ((PRUint32)remaining > length)
10945 » goto decode_loser; 11250 goto decode_loser;
10946 } 11251 }
10947 11252
10948 if (!remaining) { 11253 if (!remaining) {
10949 » if (!(isTLS && isServer)) { 11254 if (!(isTLS && isServer)) {
10950 » desc = bad_certificate; 11255 desc = bad_certificate;
10951 » goto alert_loser; 11256 goto alert_loser;
10952 » } 11257 }
10953 » /* This is TLS's version of a no_certificate alert. */ 11258 /* This is TLS's version of a no_certificate alert. */
10954 » /* I'm a server. I've requested a client cert. He hasn't got one. */ 11259 /* I'm a server. I've requested a client cert. He hasn't got one. */
10955 » rv = ssl3_HandleNoCertificate(ss); 11260 rv = ssl3_HandleNoCertificate(ss);
10956 » if (rv != SECSuccess) { 11261 if (rv != SECSuccess) {
10957 » errCode = PORT_GetError(); 11262 errCode = PORT_GetError();
10958 » goto loser; 11263 goto loser;
10959 » } 11264 }
10960 ss->ssl3.hs.ws = wait_client_key; 11265
10961 return SECSuccess; 11266 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
11267 ss->ssl3.hs.ws = wait_client_key;
11268 } else {
11269 TLS13_SET_HS_STATE(ss, wait_finished);
11270 }
11271 return SECSuccess;
10962 } 11272 }
10963 11273
10964 ss->ssl3.peerCertArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); 11274 ss->ssl3.peerCertArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
10965 if (ss->ssl3.peerCertArena == NULL) { 11275 if (ss->ssl3.peerCertArena == NULL) {
10966 » goto loser;» /* don't send alerts on memory errors */ 11276 goto loser; /* don't send alerts on memory errors */
10967 } 11277 }
10968 11278
10969 /* First get the peer cert. */ 11279 /* First get the peer cert. */
10970 remaining -= 3; 11280 remaining -= 3;
10971 if (remaining < 0) 11281 if (remaining < 0)
10972 » goto decode_loser; 11282 goto decode_loser;
10973 11283
10974 size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length); 11284 size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
10975 if (size <= 0) 11285 if (size <= 0)
10976 » goto loser;» /* fatal alert already sent by ConsumeHandshake. */ 11286 goto loser; /* fatal alert already sent by ConsumeHandshake. */
10977 11287
10978 if (remaining < size) 11288 if (remaining < size)
10979 » goto decode_loser; 11289 goto decode_loser;
10980 11290
10981 certItem.data = b; 11291 certItem.data = b;
10982 certItem.len = size; 11292 certItem.len = size;
10983 b += size; 11293 b += size;
10984 length -= size; 11294 length -= size;
10985 remaining -= size; 11295 remaining -= size;
10986 11296
10987 ss->sec.peerCert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL, 11297 ss->sec.peerCert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
10988 PR_FALSE, PR_TRUE); 11298 PR_FALSE, PR_TRUE);
10989 if (ss->sec.peerCert == NULL) { 11299 if (ss->sec.peerCert == NULL) {
10990 » /* We should report an alert if the cert was bad, but not if the 11300 /* We should report an alert if the cert was bad, but not if the
10991 » * problem was just some local problem, like memory error. 11301 * problem was just some local problem, like memory error.
10992 » */ 11302 */
10993 » goto ambiguous_err; 11303 goto ambiguous_err;
10994 } 11304 }
10995 11305
10996 /* Now get all of the CA certs. */ 11306 /* Now get all of the CA certs. */
10997 while (remaining > 0) { 11307 while (remaining > 0) {
10998 » remaining -= 3; 11308 remaining -= 3;
10999 » if (remaining < 0) 11309 if (remaining < 0)
11000 » goto decode_loser; 11310 goto decode_loser;
11001 11311
11002 » size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length); 11312 size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
11003 » if (size <= 0) 11313 if (size <= 0)
11004 » goto loser;»/* fatal alert already sent by ConsumeHandshake. */ 11314 goto loser; /* fatal alert already sent by ConsumeHandshake. */
11005 11315
11006 » if (remaining < size) 11316 if (remaining < size)
11007 » goto decode_loser; 11317 goto decode_loser;
11008 11318
11009 » certItem.data = b; 11319 certItem.data = b;
11010 » certItem.len = size; 11320 certItem.len = size;
11011 » b += size; 11321 b += size;
11012 » length -= size; 11322 length -= size;
11013 » remaining -= size; 11323 remaining -= size;
11014 11324
11015 » c = PORT_ArenaNew(ss->ssl3.peerCertArena, ssl3CertNode); 11325 c = PORT_ArenaNew(ss->ssl3.peerCertArena, ssl3CertNode);
11016 » if (c == NULL) { 11326 if (c == NULL) {
11017 » goto loser;»/* don't send alerts on memory errors */ 11327 goto loser; /* don't send alerts on memory errors */
11018 » } 11328 }
11019 11329
11020 » c->cert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL, 11330 c->cert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
11021 » PR_FALSE, PR_TRUE); 11331 PR_FALSE, PR_TRUE);
11022 » if (c->cert == NULL) { 11332 if (c->cert == NULL) {
11023 » goto ambiguous_err; 11333 goto ambiguous_err;
11024 » } 11334 }
11025 11335
11026 » c->next = NULL; 11336 c->next = NULL;
11027 » if (lastCert) { 11337 if (lastCert) {
11028 » lastCert->next = c; 11338 lastCert->next = c;
11029 » } else { 11339 } else {
11030 » ss->ssl3.peerCertChain = c; 11340 ss->ssl3.peerCertChain = c;
11031 » } 11341 }
11032 » lastCert = c; 11342 lastCert = c;
11033 } 11343 }
11034 11344
11035 if (remaining != 0) 11345 if (remaining != 0)
11036 goto decode_loser; 11346 goto decode_loser;
11037 11347
11038 SECKEY_UpdateCertPQG(ss->sec.peerCert); 11348 SECKEY_UpdateCertPQG(ss->sec.peerCert);
11039 11349
11040 if (!isServer && ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn)) { 11350 if (!isServer && ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn)) {
11041 ss->ssl3.hs.ws = wait_certificate_status; 11351 ss->ssl3.hs.ws = wait_certificate_status;
11042 rv = SECSuccess; 11352 rv = SECSuccess;
11043 } else { 11353 } else {
11044 rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */ 11354 rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
11045 } 11355 }
11046 11356
11047 return rv; 11357 return rv;
11048 11358
11049 ambiguous_err: 11359 ambiguous_err:
11050 errCode = PORT_GetError(); 11360 errCode = PORT_GetError();
11051 switch (errCode) { 11361 switch (errCode) {
11052 case PR_OUT_OF_MEMORY_ERROR: 11362 case PR_OUT_OF_MEMORY_ERROR:
11053 case SEC_ERROR_BAD_DATABASE: 11363 case SEC_ERROR_BAD_DATABASE:
11054 case SEC_ERROR_NO_MEMORY: 11364 case SEC_ERROR_NO_MEMORY:
11055 if (isTLS) { 11365 if (isTLS) {
11056 desc = internal_error; 11366 desc = internal_error;
11057 goto alert_loser; 11367 goto alert_loser;
11058 } 11368 }
11059 goto loser; 11369 goto loser;
11060 } 11370 }
11061 ssl3_SendAlertForCertError(ss, errCode); 11371 ssl3_SendAlertForCertError(ss, errCode);
11062 goto loser; 11372 goto loser;
11063 11373
11064 decode_loser: 11374 decode_loser:
11065 desc = isTLS ? decode_error : bad_certificate; 11375 desc = isTLS ? decode_error : bad_certificate;
11066 11376
11067 alert_loser: 11377 alert_loser:
11068 (void)SSL3_SendAlert(ss, alert_fatal, desc); 11378 (void)SSL3_SendAlert(ss, alert_fatal, desc);
11069 11379
11070 loser: 11380 loser:
11071 (void)ssl_MapLowLevelError(errCode); 11381 (void)ssl_MapLowLevelError(errCode);
11072 return SECFailure; 11382 return SECFailure;
11073 } 11383 }
11074 11384
11075 static SECStatus 11385 static SECStatus
11076 ssl3_AuthCertificate(sslSocket *ss) 11386 ssl3_AuthCertificate(sslSocket *ss)
11077 { 11387 {
11078 SECStatus rv; 11388 SECStatus rv;
11079 PRBool isServer = (PRBool)(!!ss->sec.isServer); 11389 PRBool isServer = (PRBool)(!!ss->sec.isServer);
11080 int errCode; 11390 int errCode;
11081 11391
11082 ss->ssl3.hs.authCertificatePending = PR_FALSE; 11392 ss->ssl3.hs.authCertificatePending = PR_FALSE;
11083 11393
11084 PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) == 11394 PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==
11085 ssl_preinfo_all); 11395 ssl_preinfo_all);
11086 /* 11396 /*
11087 * Ask caller-supplied callback function to validate cert chain. 11397 * Ask caller-supplied callback function to validate cert chain.
11088 */ 11398 */
11089 rv = (SECStatus)(*ss->authCertificate)(ss->authCertificateArg, ss->fd, 11399 rv = (SECStatus)(*ss->authCertificate)(ss->authCertificateArg, ss->fd,
11090 » » » » » PR_TRUE, isServer); 11400 PR_TRUE, isServer);
11091 if (rv) { 11401 if (rv != SECSuccess) {
11092 » errCode = PORT_GetError(); 11402 errCode = PORT_GetError();
11093 » if (rv != SECWouldBlock) { 11403 if (rv != SECWouldBlock) {
11094 » if (ss->handleBadCert) { 11404 if (ss->handleBadCert) {
11095 » » rv = (*ss->handleBadCert)(ss->badCertArg, ss->fd); 11405 rv = (*ss->handleBadCert)(ss->badCertArg, ss->fd);
11096 » } 11406 }
11097 » } 11407 }
11098 11408
11099 » if (rv == SECWouldBlock) { 11409 if (rv == SECWouldBlock) {
11100 » if (ss->sec.isServer) { 11410 if (ss->sec.isServer) {
11101 » » errCode = SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS; 11411 errCode = SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS;
11102 » » rv = SECFailure; 11412 rv = SECFailure;
11103 » » goto loser; 11413 goto loser;
11104 » } 11414 }
11415 /* TODO(ekr@rtfm.com): Reenable for TLS 1.3 */
11416 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
11417 errCode = SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_VERSION;
11418 rv = SECFailure;
11419 goto loser;
11420 }
11105 11421
11106 » ss->ssl3.hs.authCertificatePending = PR_TRUE; 11422 ss->ssl3.hs.authCertificatePending = PR_TRUE;
11107 » rv = SECSuccess; 11423 rv = SECSuccess;
11108 » } 11424 }
11109 11425
11110 » if (rv != SECSuccess) { 11426 if (rv != SECSuccess) {
11111 » ssl3_SendAlertForCertError(ss, errCode); 11427 ssl3_SendAlertForCertError(ss, errCode);
11112 » goto loser; 11428 goto loser;
11113 » } 11429 }
11114 } 11430 }
11115 11431
11116 ss->sec.ci.sid->peerCert = CERT_DupCertificate(ss->sec.peerCert); 11432 ss->sec.ci.sid->peerCert = CERT_DupCertificate(ss->sec.peerCert);
11117 ssl3_CopyPeerCertsToSID(ss->ssl3.peerCertChain, ss->sec.ci.sid); 11433 ssl3_CopyPeerCertsToSID(ss->ssl3.peerCertChain, ss->sec.ci.sid);
11118 11434
11119 if (!ss->sec.isServer) { 11435 if (!ss->sec.isServer) {
11120 CERTCertificate *cert = ss->sec.peerCert; 11436 CERTCertificate *cert = ss->sec.peerCert;
11121 11437
11122 » /* set the server authentication and key exchange types and sizes 11438 /* set the server authentication type and size from the value
11123 » ** from the value in the cert. If the key exchange key is different, 11439 ** in the cert. */
11124 » ** it will get fixed when we handle the server key exchange message. 11440 SECKEYPublicKey *pubKey = CERT_ExtractPublicKey(cert);
11125 » */ 11441 ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType;
11126 » SECKEYPublicKey * pubKey = CERT_ExtractPublicKey(cert); 11442 ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType;
11127 » ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType; 11443 if (pubKey) {
11128 » ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType; 11444 KeyType pubKeyType;
11129 » if (pubKey) { 11445 PRInt32 minKey;
11130 » KeyType pubKeyType; 11446 /* This partly fixes Bug 124230 and may cause problems for
11131 » PRInt32 minKey; 11447 * callers which depend on the old (wrong) behavior. */
11132 » ss->sec.keaKeyBits = ss->sec.authKeyBits = 11448 ss->sec.authKeyBits = SECKEY_PublicKeyStrengthInBits(pubKey);
11133 » » SECKEY_PublicKeyStrengthInBits(pubKey);
11134 pubKeyType = SECKEY_GetPublicKeyType(pubKey); 11449 pubKeyType = SECKEY_GetPublicKeyType(pubKey);
11135 » minKey = ss->sec.authKeyBits; 11450 minKey = ss->sec.authKeyBits;
11136 » switch (pubKeyType) { 11451 switch (pubKeyType) {
11137 » case rsaKey: 11452 case rsaKey:
11138 » case rsaPssKey: 11453 case rsaPssKey:
11139 » case rsaOaepKey: 11454 case rsaOaepKey:
11140 » » rv = NSS_OptionGet(NSS_RSA_MIN_KEY_SIZE, &minKey); 11455 rv =
11141 » » if (rv != SECSuccess) { 11456 NSS_OptionGet(NSS_RSA_MIN_KEY_SIZE, &minKey);
11142 » » minKey = SSL_RSA_MIN_MODULUS_BITS; 11457 if (rv !=
11143 » » } 11458 SECSuccess) {
11144 » » break; 11459 minKey =
11145 » case dsaKey: 11460 SSL_RSA_MIN_MODULUS_BITS;
11146 » » rv = NSS_OptionGet(NSS_DSA_MIN_KEY_SIZE, &minKey); 11461 }
11147 » » if (rv != SECSuccess) { 11462 break;
11148 » » minKey = SSL_DSA_MIN_P_BITS; 11463 case dsaKey:
11149 » » } 11464 rv =
11150 » » break; 11465 NSS_OptionGet(NSS_DSA_MIN_KEY_SIZE, &minKey);
11151 » case dhKey: 11466 if (rv !=
11152 » » rv = NSS_OptionGet(NSS_DH_MIN_KEY_SIZE, &minKey); 11467 SECSuccess) {
11153 » » if (rv != SECSuccess) { 11468 minKey =
11154 » » minKey = SSL_DH_MIN_P_BITS; 11469 SSL_DSA_MIN_P_BITS;
11155 » » } 11470 }
11156 » » break; 11471 break;
11157 » default: 11472 case dhKey:
11158 » » break; 11473 rv =
11159 » } 11474 NSS_OptionGet(NSS_DH_MIN_KEY_SIZE, &minKey);
11475 if (rv !=
11476 SECSuccess) {
11477 minKey =
11478 SSL_DH_MIN_P_BITS;
11479 }
11480 break;
11481 default:
11482 break;
11483 }
11160 11484
11161 /* Too small: not good enough. Send a fatal alert. */ 11485 /* Too small: not good enough. Send a fatal alert. */
11162 /* We aren't checking EC here on the understanding that we only 11486 /* We aren't checking EC here on the understanding that we only
11163 * support curves we like, a decision that might need revisiting. */ 11487 * support curves we like, a decision that might need revisiting. */
11164 if ( ss->sec.authKeyBits < minKey) { 11488 if (ss->sec.authKeyBits < minKey) {
11165 PORT_SetError(SSL_ERROR_WEAK_SERVER_CERT_KEY); 11489 PORT_SetError(SSL_ERROR_WEAK_SERVER_CERT_KEY);
11166 (void)SSL3_SendAlert(ss, alert_fatal, 11490 (void)SSL3_SendAlert(ss, alert_fatal,
11167 ss->version >= SSL_LIBRARY_VERSION_TLS_1_0 11491 ss->version >= SSL_LIBRARY_VERSION_TLS_1_0
11168 ? insufficient_security 11492 ? insufficient_security
11169 : illegal_parameter); 11493 : illegal_parameter);
11170 SECKEY_DestroyPublicKey(pubKey); 11494 SECKEY_DestroyPublicKey(pubKey);
11171 return SECFailure; 11495 return SECFailure;
11172 } 11496 }
11173 » SECKEY_DestroyPublicKey(pubKey); 11497 SECKEY_DestroyPublicKey(pubKey);
11174 » pubKey = NULL; 11498 pubKey = NULL;
11175 » } 11499 }
11176 11500
11177 /* Ephemeral suites require ServerKeyExchange. Export cipher suites 11501 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
11178 * with RSA key exchange also require ServerKeyExchange if the 11502 TLS13_SET_HS_STATE(ss, wait_cert_verify);
11179 * authentication key exceeds the key size limit. */
11180 if (ss->ssl3.hs.kea_def->ephemeral ||
11181 (ss->ssl3.hs.kea_def->is_limited &&
11182 ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_rsa &&
11183 ss->sec.authKeyBits > ss->ssl3.hs.kea_def->key_size_limit)) {
11184 ss->ssl3.hs.ws = wait_server_key; /* require server_key_exchange */
11185 } else { 11503 } else {
11186 ss->ssl3.hs.ws = wait_cert_request; /* disallow server_key_exchange */ 11504 /* Ephemeral suites require ServerKeyExchange. Export cipher suites
11505 * with RSA key exchange also require ServerKeyExchange if the
11506 * authentication key exceeds the key size limit. */
11507 if (ss->ssl3.hs.kea_def->ephemeral ||
11508 (ss->ssl3.hs.kea_def->is_limited &&
11509 ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_rsa &&
11510 ss->sec.authKeyBits > ss->ssl3.hs.kea_def->key_size_limit)) {
11511 /* require server_key_exchange */
11512 ss->ssl3.hs.ws = wait_server_key;
11513 } else {
11514 /* disallow server_key_exchange */
11515 ss->ssl3.hs.ws = wait_cert_request;
11516 /* This is static RSA key exchange so set the key bits to
11517 * auth bits. */
11518 ss->sec.keaKeyBits = ss->sec.authKeyBits;
11519 }
11187 } 11520 }
11188 } else { 11521 } else {
11189 » ss->ssl3.hs.ws = wait_client_key; 11522 /* Server */
11523 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
11524 ss->ssl3.hs.ws = wait_client_key;
11525 } else {
11526 TLS13_SET_HS_STATE(ss, wait_cert_verify);
11527 }
11190 } 11528 }
11191 11529
11192 PORT_Assert(rv == SECSuccess); 11530 PORT_Assert(rv == SECSuccess);
11193 if (rv != SECSuccess) { 11531 if (rv != SECSuccess) {
11194 » errCode = SEC_ERROR_LIBRARY_FAILURE; 11532 errCode = SEC_ERROR_LIBRARY_FAILURE;
11195 » rv = SECFailure; 11533 rv = SECFailure;
11196 » goto loser; 11534 goto loser;
11197 } 11535 }
11198 11536
11199 return rv; 11537 return rv;
11200 11538
11201 loser: 11539 loser:
11202 (void)ssl_MapLowLevelError(errCode); 11540 (void)ssl_MapLowLevelError(errCode);
11203 return SECFailure; 11541 return SECFailure;
11204 } 11542 }
11205 11543
11206 static SECStatus ssl3_FinishHandshake(sslSocket *ss); 11544 static SECStatus ssl3_FinishHandshake(sslSocket *ss);
11207 11545
11208 static SECStatus 11546 static SECStatus
11209 ssl3_AlwaysFail(sslSocket * ss) 11547 ssl3_AlwaysFail(sslSocket *ss)
11210 { 11548 {
11211 PORT_SetError(PR_INVALID_STATE_ERROR); 11549 PORT_SetError(PR_INVALID_STATE_ERROR);
11212 return SECFailure; 11550 return SECFailure;
11213 } 11551 }
11214 11552
11215 /* Caller must hold 1stHandshakeLock. 11553 /* Caller must hold 1stHandshakeLock.
11216 */ 11554 */
11217 SECStatus 11555 SECStatus
11218 ssl3_AuthCertificateComplete(sslSocket *ss, PRErrorCode error) 11556 ssl3_AuthCertificateComplete(sslSocket *ss, PRErrorCode error)
11219 { 11557 {
11220 SECStatus rv; 11558 SECStatus rv;
11221 11559
11222 PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); 11560 PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss));
11223 11561
11224 if (ss->sec.isServer) { 11562 if (ss->sec.isServer) {
11225 » PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS); 11563 PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS);
11226 » return SECFailure; 11564 return SECFailure;
11227 } 11565 }
11228 11566
11229 ssl_GetRecvBufLock(ss); 11567 ssl_GetRecvBufLock(ss);
11230 ssl_GetSSL3HandshakeLock(ss); 11568 ssl_GetSSL3HandshakeLock(ss);
11231 11569
11232 if (!ss->ssl3.hs.authCertificatePending) { 11570 if (!ss->ssl3.hs.authCertificatePending) {
11233 » PORT_SetError(PR_INVALID_STATE_ERROR); 11571 PORT_SetError(PR_INVALID_STATE_ERROR);
11234 » rv = SECFailure; 11572 rv = SECFailure;
11235 » goto done; 11573 goto done;
11236 } 11574 }
11237 11575
11238 ss->ssl3.hs.authCertificatePending = PR_FALSE; 11576 ss->ssl3.hs.authCertificatePending = PR_FALSE;
11239 11577
11240 if (error != 0) { 11578 if (error != 0) {
11241 » ss->ssl3.hs.restartTarget = ssl3_AlwaysFail; 11579 ss->ssl3.hs.restartTarget = ssl3_AlwaysFail;
11242 » ssl3_SendAlertForCertError(ss, error); 11580 ssl3_SendAlertForCertError(ss, error);
11243 » rv = SECSuccess; 11581 rv = SECSuccess;
11244 } else if (ss->ssl3.hs.restartTarget != NULL) { 11582 } else if (ss->ssl3.hs.restartTarget != NULL) {
11245 » sslRestartTarget target = ss->ssl3.hs.restartTarget; 11583 sslRestartTarget target = ss->ssl3.hs.restartTarget;
11246 » ss->ssl3.hs.restartTarget = NULL; 11584 ss->ssl3.hs.restartTarget = NULL;
11247 11585
11248 » if (target == ssl3_FinishHandshake) { 11586 if (target == ssl3_FinishHandshake) {
11249 » SSL_TRC(3,("%d: SSL3[%p]: certificate authentication lost the race" 11587 SSL_TRC(3, ("%d: SSL3[%p]: certificate authentication lost the race"
11250 » » " with peer's finished message", SSL_GETPID(), ss->fd)); 11588 " with peer's finished message",
11251 » } 11589 SSL_GETPID(), ss->fd));
11590 }
11252 11591
11253 » rv = target(ss); 11592 rv = target(ss);
11254 » /* Even if we blocked here, we have accomplished enough to claim 11593 /* Even if we blocked here, we have accomplished enough to claim
11255 » * success. Any remaining work will be taken care of by subsequent 11594 * success. Any remaining work will be taken care of by subsequent
11256 » * calls to SSL_ForceHandshake/PR_Send/PR_Read/etc. 11595 * calls to SSL_ForceHandshake/PR_Send/PR_Read/etc.
11257 » */ 11596 */
11258 » if (rv == SECWouldBlock) { 11597 if (rv == SECWouldBlock) {
11259 » rv = SECSuccess; 11598 rv = SECSuccess;
11260 » } 11599 }
11261 } else { 11600 } else {
11262 » SSL_TRC(3, ("%d: SSL3[%p]: certificate authentication won the race with" 11601 SSL_TRC(3, ("%d: SSL3[%p]: certificate authentication won the race with"
11263 » " peer's finished message", SSL_GETPID(), ss->fd)); 11602 " peer's finished message",
11603 SSL_GETPID(), ss->fd));
11264 11604
11265 » PORT_Assert(!ss->ssl3.hs.isResuming); 11605 PORT_Assert(!ss->ssl3.hs.isResuming);
11266 » PORT_Assert(ss->ssl3.hs.ws != idle_handshake); 11606 PORT_Assert(ss->ssl3.hs.ws != idle_handshake);
11267 11607
11268 » if (ss->opt.enableFalseStart && 11608 if (ss->opt.enableFalseStart &&
11269 » !ss->firstHsDone && 11609 !ss->firstHsDone &&
11270 » !ss->ssl3.hs.isResuming && 11610 !ss->ssl3.hs.isResuming &&
11271 » ssl3_WaitingForStartOfServerSecondRound(ss)) { 11611 ssl3_WaitingForServerSecondRound(ss)) {
11272 » /* ssl3_SendClientSecondRound deferred the false start check because 11612 /* ssl3_SendClientSecondRound deferred the false start check because
11273 » * certificate authentication was pending, so we do it now if we sti ll 11613 * certificate authentication was pending, so we do it now if we sti ll
11274 » * haven't received any of the server's second round yet. 11614 * haven't received all of the server's second round yet.
11275 » */ 11615 */
11276 » rv = ssl3_CheckFalseStart(ss); 11616 rv = ssl3_CheckFalseStart(ss);
11277 » } else { 11617 } else {
11278 » rv = SECSuccess; 11618 rv = SECSuccess;
11279 » } 11619 }
11280 } 11620 }
11281 11621
11282 done: 11622 done:
11283 ssl_ReleaseSSL3HandshakeLock(ss); 11623 ssl_ReleaseSSL3HandshakeLock(ss);
11284 ssl_ReleaseRecvBufLock(ss); 11624 ssl_ReleaseRecvBufLock(ss);
11285 11625
11286 return rv; 11626 return rv;
11287 } 11627 }
11288 11628
11289 static SECStatus 11629 static SECStatus
11290 ssl3_ComputeTLSFinished(ssl3CipherSpec *spec, 11630 ssl3_ComputeTLSFinished(ssl3CipherSpec *spec,
11291 » » » PRBool isServer, 11631 PRBool isServer,
11292 const SSL3Hashes * hashes, 11632 const SSL3Hashes *hashes,
11293 TLSFinished * tlsFinished) 11633 TLSFinished *tlsFinished)
11294 { 11634 {
11295 SECStatus rv; 11635 SECStatus rv;
11296 CK_TLS_MAC_PARAMS tls_mac_params; 11636 CK_TLS_MAC_PARAMS tls_mac_params;
11297 SECItem param = {siBuffer, NULL, 0}; 11637 SECItem param = { siBuffer, NULL, 0 };
11298 PK11Context *prf_context; 11638 PK11Context *prf_context;
11299 unsigned int retLen; 11639 unsigned int retLen;
11300 11640
11301 if (!spec->master_secret || spec->bypassCiphers) { 11641 if (!spec->master_secret || spec->bypassCiphers) {
11302 » const char *label = isServer ? "server finished" : "client finished"; 11642 const char *label = isServer ? "server finished" : "client finished";
11303 » unsigned int len = 15; 11643 unsigned int len = 15;
11304 11644
11305 » return ssl3_TLSPRFWithMasterSecret(spec, label, len, hashes->u.raw, 11645 return ssl3_TLSPRFWithMasterSecret(spec, label, len, hashes->u.raw,
11306 » hashes->len, tlsFinished->verify_data, 11646 hashes->len, tlsFinished->verify_data ,
11307 » sizeof tlsFinished->verify_data); 11647 sizeof tlsFinished->verify_data);
11308 } 11648 }
11309 11649
11310 if (spec->version < SSL_LIBRARY_VERSION_TLS_1_2) { 11650 if (spec->version < SSL_LIBRARY_VERSION_TLS_1_2) {
11311 » tls_mac_params.prfMechanism = CKM_TLS_PRF; 11651 tls_mac_params.prfMechanism = CKM_TLS_PRF;
11312 } else { 11652 } else {
11313 » tls_mac_params.prfMechanism = CKM_SHA256; 11653 tls_mac_params.prfMechanism = CKM_SHA256;
11314 } 11654 }
11315 tls_mac_params.ulMacLength = 12; 11655 tls_mac_params.ulMacLength = 12;
11316 tls_mac_params.ulServerOrClient = isServer ? 1 : 2; 11656 tls_mac_params.ulServerOrClient = isServer ? 1 : 2;
11317 param.data = (unsigned char *)&tls_mac_params; 11657 param.data = (unsigned char *)&tls_mac_params;
11318 param.len = sizeof(tls_mac_params); 11658 param.len = sizeof(tls_mac_params);
11319 prf_context = PK11_CreateContextBySymKey(CKM_TLS_MAC, CKA_SIGN, 11659 prf_context = PK11_CreateContextBySymKey(CKM_TLS_MAC, CKA_SIGN,
11320 » » » » » spec->master_secret, &param); 11660 spec->master_secret, &param);
11321 if (!prf_context) 11661 if (!prf_context)
11322 » return SECFailure; 11662 return SECFailure;
11323 11663
11324 rv = PK11_DigestBegin(prf_context); 11664 rv = PK11_DigestBegin(prf_context);
11325 rv |= PK11_DigestOp(prf_context, hashes->u.raw, hashes->len); 11665 rv |= PK11_DigestOp(prf_context, hashes->u.raw, hashes->len);
11326 rv |= PK11_DigestFinal(prf_context, tlsFinished->verify_data, &retLen, 11666 rv |= PK11_DigestFinal(prf_context, tlsFinished->verify_data, &retLen,
11327 » » » sizeof tlsFinished->verify_data); 11667 sizeof tlsFinished->verify_data);
11328 PORT_Assert(rv != SECSuccess || retLen == sizeof tlsFinished->verify_data); 11668 PORT_Assert(rv != SECSuccess || retLen == sizeof tlsFinished->verify_data);
11329 11669
11330 PK11_DestroyContext(prf_context, PR_TRUE); 11670 PK11_DestroyContext(prf_context, PR_TRUE);
11331 11671
11332 return rv; 11672 return rv;
11333 } 11673 }
11334 11674
11335 /* The calling function must acquire and release the appropriate 11675 /* The calling function must acquire and release the appropriate
11336 * lock (e.g., ssl_GetSpecReadLock / ssl_ReleaseSpecReadLock for 11676 * lock (e.g., ssl_GetSpecReadLock / ssl_ReleaseSpecReadLock for
11337 * ss->ssl3.crSpec). 11677 * ss->ssl3.crSpec).
11338 */ 11678 */
11339 SECStatus 11679 SECStatus
11340 ssl3_TLSPRFWithMasterSecret(ssl3CipherSpec *spec, const char *label, 11680 ssl3_TLSPRFWithMasterSecret(ssl3CipherSpec *spec, const char *label,
11341 unsigned int labelLen, const unsigned char *val, unsigned int valLen, 11681 unsigned int labelLen, const unsigned char *val, uns igned int valLen,
11342 unsigned char *out, unsigned int outLen) 11682 unsigned char *out, unsigned int outLen)
11343 { 11683 {
11344 SECStatus rv = SECSuccess; 11684 SECStatus rv = SECSuccess;
11345 11685
11346 if (spec->master_secret && !spec->bypassCiphers) { 11686 if (spec->master_secret && !spec->bypassCiphers) {
11347 » SECItem param = {siBuffer, NULL, 0}; 11687 SECItem param = { siBuffer, NULL, 0 };
11348 » CK_MECHANISM_TYPE mech = CKM_TLS_PRF_GENERAL; 11688 CK_MECHANISM_TYPE mech = CKM_TLS_PRF_GENERAL;
11349 » PK11Context *prf_context; 11689 PK11Context *prf_context;
11350 » unsigned int retLen; 11690 unsigned int retLen;
11351 11691
11352 » if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { 11692 if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
11353 » mech = CKM_NSS_TLS_PRF_GENERAL_SHA256; 11693 mech = CKM_NSS_TLS_PRF_GENERAL_SHA256;
11354 » } 11694 }
11355 » prf_context = PK11_CreateContextBySymKey(mech, CKA_SIGN, 11695 prf_context = PK11_CreateContextBySymKey(mech, CKA_SIGN,
11356 » » » » » » spec->master_secret, &param); 11696 spec->master_secret, &param);
11357 » if (!prf_context) 11697 if (!prf_context)
11358 » return SECFailure; 11698 return SECFailure;
11359 11699
11360 » rv = PK11_DigestBegin(prf_context); 11700 rv = PK11_DigestBegin(prf_context);
11361 » rv |= PK11_DigestOp(prf_context, (unsigned char *) label, labelLen); 11701 rv |= PK11_DigestOp(prf_context, (unsigned char *)label, labelLen);
11362 » rv |= PK11_DigestOp(prf_context, val, valLen); 11702 rv |= PK11_DigestOp(prf_context, val, valLen);
11363 » rv |= PK11_DigestFinal(prf_context, out, &retLen, outLen); 11703 rv |= PK11_DigestFinal(prf_context, out, &retLen, outLen);
11364 » PORT_Assert(rv != SECSuccess || retLen == outLen); 11704 PORT_Assert(rv != SECSuccess || retLen == outLen);
11365 11705
11366 » PK11_DestroyContext(prf_context, PR_TRUE); 11706 PK11_DestroyContext(prf_context, PR_TRUE);
11367 } else { 11707 } else {
11368 » /* bypass PKCS11 */ 11708 /* bypass PKCS11 */
11369 #ifdef NO_PKCS11_BYPASS 11709 #ifdef NO_PKCS11_BYPASS
11370 » PORT_Assert(spec->master_secret); 11710 PORT_Assert(spec->master_secret);
11371 » PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 11711 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
11372 » rv = SECFailure; 11712 rv = SECFailure;
11373 #else 11713 #else
11374 » SECItem inData = { siBuffer, }; 11714 SECItem inData = { siBuffer };
11375 » SECItem outData = { siBuffer, }; 11715 SECItem outData = { siBuffer };
11376 » PRBool isFIPS = PR_FALSE; 11716 PRBool isFIPS = PR_FALSE;
11377 11717
11378 » inData.data = (unsigned char *) val; 11718 inData.data = (unsigned char *)val;
11379 » inData.len = valLen; 11719 inData.len = valLen;
11380 » outData.data = out; 11720 outData.data = out;
11381 » outData.len = outLen; 11721 outData.len = outLen;
11382 » if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { 11722 if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
11383 » rv = TLS_P_hash(HASH_AlgSHA256, &spec->msItem, label, &inData, 11723 rv = TLS_P_hash(HASH_AlgSHA256, &spec->msItem, label, &inData,
11384 » » » &outData, isFIPS); 11724 &outData, isFIPS);
11385 » } else { 11725 } else {
11386 » rv = TLS_PRF(&spec->msItem, label, &inData, &outData, isFIPS); 11726 rv = TLS_PRF(&spec->msItem, label, &inData, &outData, isFIPS);
11387 » } 11727 }
11388 » PORT_Assert(rv != SECSuccess || outData.len == outLen); 11728 PORT_Assert(rv != SECSuccess || outData.len == outLen);
11389 #endif 11729 #endif
11390 } 11730 }
11391 return rv; 11731 return rv;
11392 } 11732 }
11393 11733
11394 /* called from ssl3_SendClientSecondRound 11734 /* called from ssl3_SendClientSecondRound
11395 * ssl3_HandleFinished 11735 * ssl3_HandleFinished
11396 */ 11736 */
11397 static SECStatus 11737 static SECStatus
11398 ssl3_SendNextProto(sslSocket *ss) 11738 ssl3_SendNextProto(sslSocket *ss)
11399 { 11739 {
11400 SECStatus rv; 11740 SECStatus rv;
11401 int padding_len; 11741 int padding_len;
11402 static const unsigned char padding[32] = {0}; 11742 static const unsigned char padding[32] = { 0 };
11403 11743
11404 if (ss->ssl3.nextProto.len == 0 || 11744 if (ss->ssl3.nextProto.len == 0 ||
11405 » ss->ssl3.nextProtoState == SSL_NEXT_PROTO_SELECTED) { 11745 ss->ssl3.nextProtoState == SSL_NEXT_PROTO_SELECTED) {
11406 » return SECSuccess; 11746 return SECSuccess;
11407 } 11747 }
11408 11748
11409 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 11749 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
11410 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 11750 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11411 11751
11412 padding_len = 32 - ((ss->ssl3.nextProto.len + 2) % 32); 11752 padding_len = 32 - ((ss->ssl3.nextProto.len + 2) % 32);
11413 11753
11414 rv = ssl3_AppendHandshakeHeader(ss, next_proto, ss->ssl3.nextProto.len + 11754 rv = ssl3_AppendHandshakeHeader(ss, next_proto, ss->ssl3.nextProto.len +
11415 » » » » » » 2 + padding_len); 11755 2 +
11756 padding_len);
11416 if (rv != SECSuccess) { 11757 if (rv != SECSuccess) {
11417 » return rv;» /* error code set by AppendHandshakeHeader */ 11758 return rv; /* error code set by AppendHandshakeHeader */
11418 } 11759 }
11419 rv = ssl3_AppendHandshakeVariable(ss, ss->ssl3.nextProto.data, 11760 rv = ssl3_AppendHandshakeVariable(ss, ss->ssl3.nextProto.data,
11420 » » » » ss->ssl3.nextProto.len, 1); 11761 ss->ssl3.nextProto.len, 1);
11421 if (rv != SECSuccess) { 11762 if (rv != SECSuccess) {
11422 » return rv;» /* error code set by AppendHandshake */ 11763 return rv; /* error code set by AppendHandshake */
11423 } 11764 }
11424 rv = ssl3_AppendHandshakeVariable(ss, padding, padding_len, 1); 11765 rv = ssl3_AppendHandshakeVariable(ss, padding, padding_len, 1);
11425 if (rv != SECSuccess) { 11766 if (rv != SECSuccess) {
11426 » return rv;» /* error code set by AppendHandshake */ 11767 return rv; /* error code set by AppendHandshake */
11427 } 11768 }
11428 return rv; 11769 return rv;
11429 } 11770 }
11430 11771
11431 /* called from ssl3_SendFinished 11772 /* called from ssl3_SendFinished
11432 * 11773 *
11433 * This function is simply a debugging aid and therefore does not return a 11774 * This function is simply a debugging aid and therefore does not return a
11434 * SECStatus. */ 11775 * SECStatus. */
11435 static void 11776 static void
11436 ssl3_RecordKeyLog(sslSocket *ss) 11777 ssl3_RecordKeyLog(sslSocket *ss)
11437 { 11778 {
11438 SECStatus rv; 11779 SECStatus rv;
11439 SECItem *keyData; 11780 SECItem *keyData;
11440 char buf[14 /* "CLIENT_RANDOM " */ + 11781 char buf[14 /* "CLIENT_RANDOM " */ +
11441 » SSL3_RANDOM_LENGTH*2 /* client_random */ + 11782 SSL3_RANDOM_LENGTH * 2 /* client_random */ +
11442 » 1 /* " " */ + 11783 1 /* " " */ +
11443 » 48*2 /* master secret */ + 11784 48 * 2 /* master secret */ +
11444 1 /* new line */]; 11785 1 /* new line */];
11445 unsigned int j; 11786 unsigned int j;
11446 11787
11447 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 11788 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11448 11789
11449 if (!ssl_keylog_iob) 11790 if (!ssl_keylog_iob)
11450 » return; 11791 return;
11451 11792
11452 rv = PK11_ExtractKeyValue(ss->ssl3.cwSpec->master_secret); 11793 rv = PK11_ExtractKeyValue(ss->ssl3.cwSpec->master_secret);
11453 if (rv != SECSuccess) 11794 if (rv != SECSuccess)
11454 » return; 11795 return;
11455 11796
11456 ssl_GetSpecReadLock(ss); 11797 ssl_GetSpecReadLock(ss);
11457 11798
11458 /* keyData does not need to be freed. */ 11799 /* keyData does not need to be freed. */
11459 keyData = PK11_GetKeyData(ss->ssl3.cwSpec->master_secret); 11800 keyData = PK11_GetKeyData(ss->ssl3.cwSpec->master_secret);
11460 if (!keyData || !keyData->data || keyData->len != 48) { 11801 if (!keyData || !keyData->data || keyData->len != 48) {
11461 » ssl_ReleaseSpecReadLock(ss); 11802 ssl_ReleaseSpecReadLock(ss);
11462 » return; 11803 return;
11463 } 11804 }
11464 11805
11465 /* https://developer.mozilla.org/en/NSS_Key_Log_Format */ 11806 /* https://developer.mozilla.org/en/NSS_Key_Log_Format */
11466 11807
11467 /* There could be multiple, concurrent writers to the 11808 /* There could be multiple, concurrent writers to the
11468 * keylog, so we have to do everything in a single call to 11809 * keylog, so we have to do everything in a single call to
11469 * fwrite. */ 11810 * fwrite. */
11470 11811
11471 memcpy(buf, "CLIENT_RANDOM ", 14); 11812 memcpy(buf, "CLIENT_RANDOM ", 14);
11472 j = 14; 11813 j = 14;
11473 hexEncode(buf + j, ss->ssl3.hs.client_random.rand, SSL3_RANDOM_LENGTH); 11814 hexEncode(buf + j, ss->ssl3.hs.client_random.rand, SSL3_RANDOM_LENGTH);
11474 j += SSL3_RANDOM_LENGTH*2; 11815 j += SSL3_RANDOM_LENGTH * 2;
11475 buf[j++] = ' '; 11816 buf[j++] = ' ';
11476 hexEncode(buf + j, keyData->data, 48); 11817 hexEncode(buf + j, keyData->data, 48);
11477 j += 48*2; 11818 j += 48 * 2;
11478 buf[j++] = '\n'; 11819 buf[j++] = '\n';
11479 11820
11480 PORT_Assert(j == sizeof(buf)); 11821 PORT_Assert(j == sizeof(buf));
11481 11822
11482 ssl_ReleaseSpecReadLock(ss); 11823 ssl_ReleaseSpecReadLock(ss);
11483 11824
11484 if (fwrite(buf, sizeof(buf), 1, ssl_keylog_iob) != 1) 11825 if (fwrite(buf, sizeof(buf), 1, ssl_keylog_iob) != 1)
11485 return; 11826 return;
11486 fflush(ssl_keylog_iob); 11827 fflush(ssl_keylog_iob);
11487 return; 11828 return;
11488 } 11829 }
11489 11830
11490 /* called from ssl3_SendClientSecondRound 11831 /* called from ssl3_SendClientSecondRound
11491 * ssl3_HandleFinished 11832 * ssl3_HandleFinished
11492 */ 11833 */
11493 static SECStatus 11834 static SECStatus
11494 ssl3_SendEncryptedExtensions(sslSocket *ss) 11835 ssl3_SendChannelIDEncryptedExtensions(sslSocket *ss)
11495 { 11836 {
11496 static const char CHANNEL_ID_MAGIC[] = "TLS Channel ID signature"; 11837 static const char CHANNEL_ID_MAGIC[] = "TLS Channel ID signature";
11497 static const char CHANNEL_ID_RESUMPTION_MAGIC[] = "Resumption"; 11838 static const char CHANNEL_ID_RESUMPTION_MAGIC[] = "Resumption";
11498 /* This is the ASN.1 prefix for a P-256 public key. Specifically it's: 11839 /* This is the ASN.1 prefix for a P-256 public key. Specifically it's:
11499 * SEQUENCE 11840 * SEQUENCE
11500 * SEQUENCE 11841 * SEQUENCE
11501 * OID id-ecPublicKey 11842 * OID id-ecPublicKey
11502 * OID prime256v1 11843 * OID prime256v1
11503 * BIT STRING, length 66, 0 trailing bits: 0x04 11844 * BIT STRING, length 66, 0 trailing bits: 0x04
11504 * 11845 *
11505 * The 0x04 in the BIT STRING is the prefix for an uncompressed, X9.62 11846 * The 0x04 in the BIT STRING is the prefix for an uncompressed, X9.62
11506 * public key. Following that are the two field elements as 32-byte, 11847 * public key. Following that are the two field elements as 32-byte,
11507 * big-endian numbers, as required by the Channel ID. */ 11848 * big-endian numbers, as required by the Channel ID. */
11508 static const unsigned char P256_SPKI_PREFIX[] = { 11849 static const unsigned char P256_SPKI_PREFIX[] = {
11509 » 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 11850 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86,
11510 » 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 11851 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a,
11511 » 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 11852 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03,
11512 » 0x42, 0x00, 0x04 11853 0x42, 0x00, 0x04
11513 }; 11854 };
11514 /* ChannelIDs are always 128 bytes long: 64 bytes of P-256 public key and 64 11855 /* ChannelIDs are always 128 bytes long: 64 bytes of P-256 public key and 64
11515 * bytes of ECDSA signature. */ 11856 * bytes of ECDSA signature. */
11516 static const int CHANNEL_ID_PUBLIC_KEY_LENGTH = 64; 11857 static const int CHANNEL_ID_PUBLIC_KEY_LENGTH = 64;
11517 static const int CHANNEL_ID_LENGTH = 128; 11858 static const int CHANNEL_ID_LENGTH = 128;
11518 11859
11519 SECStatus rv = SECFailure; 11860 SECStatus rv = SECFailure;
11520 SECItem *spki = NULL; 11861 SECItem *spki = NULL;
11521 SSL3Hashes hashes; 11862 SSL3Hashes hashes;
11522 const unsigned char *pub_bytes; 11863 const unsigned char *pub_bytes;
11523 unsigned char signed_data[sizeof(CHANNEL_ID_MAGIC) + 11864 unsigned char signed_data[sizeof(CHANNEL_ID_MAGIC) +
11524 sizeof(CHANNEL_ID_RESUMPTION_MAGIC) + 11865 sizeof(CHANNEL_ID_RESUMPTION_MAGIC) +
11525 sizeof(SSL3Hashes)*2]; 11866 sizeof(SSL3Hashes) * 2];
11526 size_t signed_data_len; 11867 size_t signed_data_len;
11527 unsigned char digest[SHA256_LENGTH]; 11868 unsigned char digest[SHA256_LENGTH];
11528 SECItem digest_item; 11869 SECItem digest_item;
11529 unsigned char signature[64]; 11870 unsigned char signature[64];
11530 SECItem signature_item; 11871 SECItem signature_item;
11531 11872
11532 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 11873 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
11533 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 11874 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11534 11875
11535 if (ss->ssl3.channelID == NULL) 11876 if (ss->ssl3.channelID == NULL)
11536 » return SECSuccess; 11877 return SECSuccess;
11537 11878
11538 PORT_Assert(ssl3_ExtensionNegotiated(ss, ssl_channel_id_xtn)); 11879 PORT_Assert(ssl3_ExtensionNegotiated(ss, ssl_channel_id_xtn));
11539 11880
11540 if (SECKEY_GetPrivateKeyType(ss->ssl3.channelID) != ecKey || 11881 if (SECKEY_GetPrivateKeyType(ss->ssl3.channelID) != ecKey ||
11541 » PK11_SignatureLen(ss->ssl3.channelID) != sizeof(signature)) { 11882 PK11_SignatureLen(ss->ssl3.channelID) != sizeof(signature)) {
11542 » PORT_SetError(SSL_ERROR_INVALID_CHANNEL_ID_KEY); 11883 PORT_SetError(SSL_ERROR_INVALID_CHANNEL_ID_KEY);
11543 » rv = SECFailure; 11884 rv = SECFailure;
11544 » goto loser; 11885 goto loser;
11545 } 11886 }
11546 11887
11547 ssl_GetSpecReadLock(ss); 11888 ssl_GetSpecReadLock(ss);
11548 rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.cwSpec, &hashes, 0); 11889 rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.cwSpec, &hashes, 0);
11549 ssl_ReleaseSpecReadLock(ss); 11890 ssl_ReleaseSpecReadLock(ss);
11550 11891
11551 if (rv != SECSuccess) 11892 if (rv != SECSuccess)
11552 » goto loser; 11893 goto loser;
11553 11894
11554 rv = ssl3_AppendHandshakeHeader(ss, encrypted_extensions, 11895 rv = ssl3_AppendHandshakeHeader(ss, channelid_encrypted_extensions,
11555 » » » » 2 + 2 + CHANNEL_ID_LENGTH); 11896 2 + 2 + CHANNEL_ID_LENGTH);
11556 if (rv != SECSuccess) 11897 if (rv != SECSuccess)
11557 » goto loser;» /* error code set by AppendHandshakeHeader */ 11898 goto loser; /* error code set by AppendHandshakeHeader */
11558 rv = ssl3_AppendHandshakeNumber(ss, ssl_channel_id_xtn, 2); 11899 rv = ssl3_AppendHandshakeNumber(ss, ssl_channel_id_xtn, 2);
11559 if (rv != SECSuccess) 11900 if (rv != SECSuccess)
11560 » goto loser;» /* error code set by AppendHandshake */ 11901 goto loser; /* error code set by AppendHandshake */
11561 rv = ssl3_AppendHandshakeNumber(ss, CHANNEL_ID_LENGTH, 2); 11902 rv = ssl3_AppendHandshakeNumber(ss, CHANNEL_ID_LENGTH, 2);
11562 if (rv != SECSuccess) 11903 if (rv != SECSuccess)
11563 » goto loser;» /* error code set by AppendHandshake */ 11904 goto loser; /* error code set by AppendHandshake */
11564 11905
11565 spki = SECKEY_EncodeDERSubjectPublicKeyInfo(ss->ssl3.channelIDPub); 11906 spki = SECKEY_EncodeDERSubjectPublicKeyInfo(ss->ssl3.channelIDPub);
11566 11907
11567 if (spki->len != sizeof(P256_SPKI_PREFIX) + CHANNEL_ID_PUBLIC_KEY_LENGTH || 11908 if (spki->len != sizeof(P256_SPKI_PREFIX) + CHANNEL_ID_PUBLIC_KEY_LENGTH ||
11568 » memcmp(spki->data, P256_SPKI_PREFIX, sizeof(P256_SPKI_PREFIX)) != 0) { 11909 memcmp(spki->data, P256_SPKI_PREFIX, sizeof(P256_SPKI_PREFIX)) != 0) {
11569 » PORT_SetError(SSL_ERROR_INVALID_CHANNEL_ID_KEY); 11910 PORT_SetError(SSL_ERROR_INVALID_CHANNEL_ID_KEY);
11570 » rv = SECFailure; 11911 rv = SECFailure;
11571 » goto loser; 11912 goto loser;
11572 } 11913 }
11573 11914
11574 pub_bytes = spki->data + sizeof(P256_SPKI_PREFIX); 11915 pub_bytes = spki->data + sizeof(P256_SPKI_PREFIX);
11575 11916
11576 signed_data_len = 0; 11917 signed_data_len = 0;
11577 memcpy(signed_data + signed_data_len, CHANNEL_ID_MAGIC, 11918 memcpy(signed_data + signed_data_len, CHANNEL_ID_MAGIC,
11578 sizeof(CHANNEL_ID_MAGIC)); 11919 sizeof(CHANNEL_ID_MAGIC));
11579 signed_data_len += sizeof(CHANNEL_ID_MAGIC); 11920 signed_data_len += sizeof(CHANNEL_ID_MAGIC);
11580 if (ss->ssl3.hs.isResuming) { 11921 if (ss->ssl3.hs.isResuming) {
11581 SECItem *originalHandshakeHash = 11922 SECItem *originalHandshakeHash =
11582 &ss->sec.ci.sid->u.ssl3.originalHandshakeHash; 11923 &ss->sec.ci.sid->u.ssl3.originalHandshakeHash;
11583 PORT_Assert(originalHandshakeHash->len > 0); 11924 PORT_Assert(originalHandshakeHash->len > 0);
11584 11925
11585 memcpy(signed_data + signed_data_len, CHANNEL_ID_RESUMPTION_MAGIC, 11926 memcpy(signed_data + signed_data_len, CHANNEL_ID_RESUMPTION_MAGIC,
11586 sizeof(CHANNEL_ID_RESUMPTION_MAGIC)); 11927 sizeof(CHANNEL_ID_RESUMPTION_MAGIC));
11587 signed_data_len += sizeof(CHANNEL_ID_RESUMPTION_MAGIC); 11928 signed_data_len += sizeof(CHANNEL_ID_RESUMPTION_MAGIC);
11588 memcpy(signed_data + signed_data_len, originalHandshakeHash->data, 11929 memcpy(signed_data + signed_data_len, originalHandshakeHash->data,
11589 originalHandshakeHash->len); 11930 originalHandshakeHash->len);
11590 signed_data_len += originalHandshakeHash->len; 11931 signed_data_len += originalHandshakeHash->len;
11591 } 11932 }
11592 memcpy(signed_data + signed_data_len, hashes.u.raw, hashes.len); 11933 memcpy(signed_data + signed_data_len, hashes.u.raw, hashes.len);
11593 signed_data_len += hashes.len; 11934 signed_data_len += hashes.len;
11594 11935
11595 rv = PK11_HashBuf(SEC_OID_SHA256, digest, signed_data, signed_data_len); 11936 rv = PK11_HashBuf(SEC_OID_SHA256, digest, signed_data, signed_data_len);
11596 if (rv != SECSuccess) 11937 if (rv != SECSuccess)
11597 » goto loser; 11938 goto loser;
11598 11939
11599 digest_item.data = digest; 11940 digest_item.data = digest;
11600 digest_item.len = sizeof(digest); 11941 digest_item.len = sizeof(digest);
11601 11942
11602 signature_item.data = signature; 11943 signature_item.data = signature;
11603 signature_item.len = sizeof(signature); 11944 signature_item.len = sizeof(signature);
11604 11945
11605 rv = PK11_Sign(ss->ssl3.channelID, &signature_item, &digest_item); 11946 rv = PK11_Sign(ss->ssl3.channelID, &signature_item, &digest_item);
11606 if (rv != SECSuccess) 11947 if (rv != SECSuccess)
11607 » goto loser; 11948 goto loser;
11608 11949
11609 rv = ssl3_AppendHandshake(ss, pub_bytes, CHANNEL_ID_PUBLIC_KEY_LENGTH); 11950 rv = ssl3_AppendHandshake(ss, pub_bytes, CHANNEL_ID_PUBLIC_KEY_LENGTH);
11610 if (rv != SECSuccess) 11951 if (rv != SECSuccess)
11611 » goto loser; 11952 goto loser;
11612 rv = ssl3_AppendHandshake(ss, signature, sizeof(signature)); 11953 rv = ssl3_AppendHandshake(ss, signature, sizeof(signature));
11613 11954
11614 loser: 11955 loser:
11615 if (spki) 11956 if (spki)
11616 » SECITEM_FreeItem(spki, PR_TRUE); 11957 SECITEM_FreeItem(spki, PR_TRUE);
11617 if (ss->ssl3.channelID) { 11958 if (ss->ssl3.channelID) {
11618 » SECKEY_DestroyPrivateKey(ss->ssl3.channelID); 11959 SECKEY_DestroyPrivateKey(ss->ssl3.channelID);
11619 » ss->ssl3.channelID = NULL; 11960 ss->ssl3.channelID = NULL;
11620 } 11961 }
11621 if (ss->ssl3.channelIDPub) { 11962 if (ss->ssl3.channelIDPub) {
11622 » SECKEY_DestroyPublicKey(ss->ssl3.channelIDPub); 11963 SECKEY_DestroyPublicKey(ss->ssl3.channelIDPub);
11623 » ss->ssl3.channelIDPub = NULL; 11964 ss->ssl3.channelIDPub = NULL;
11624 } 11965 }
11625 11966
11626 return rv; 11967 return rv;
11627 } 11968 }
11628 11969
11629 /* ssl3_RestartHandshakeAfterChannelIDReq is called to restart a handshake 11970 /* ssl3_RestartHandshakeAfterChannelIDReq is called to restart a handshake
11630 * after a ChannelID callback returned SECWouldBlock. At this point we have 11971 * after a ChannelID callback returned SECWouldBlock. At this point we have
11631 * processed the server's ServerHello but not yet any further messages. We will 11972 * processed the server's ServerHello but not yet any further messages. We will
11632 * always get a message from the server after a ServerHello so either they are 11973 * always get a message from the server after a ServerHello so either they are
11633 * waiting in the buffer or we'll get network I/O. */ 11974 * waiting in the buffer or we'll get network I/O. */
11634 SECStatus 11975 SECStatus
11635 ssl3_RestartHandshakeAfterChannelIDReq(sslSocket *ss, 11976 ssl3_RestartHandshakeAfterChannelIDReq(sslSocket *ss,
11636 » » » » SECKEYPublicKey *channelIDPub, 11977 SECKEYPublicKey *channelIDPub,
11637 » » » » SECKEYPrivateKey *channelID) 11978 SECKEYPrivateKey *channelID)
11638 { 11979 {
11639 if (ss->handshake == 0) { 11980 if (ss->handshake == 0) {
11640 » SECKEY_DestroyPublicKey(channelIDPub); 11981 SECKEY_DestroyPublicKey(channelIDPub);
11641 » SECKEY_DestroyPrivateKey(channelID); 11982 SECKEY_DestroyPrivateKey(channelID);
11642 » PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 11983 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
11643 » return SECFailure; 11984 return SECFailure;
11644 } 11985 }
11645 11986
11646 if (channelIDPub == NULL || 11987 if (channelIDPub == NULL ||
11647 » channelID == NULL) { 11988 channelID == NULL) {
11648 » if (channelIDPub) 11989 if (channelIDPub)
11649 » SECKEY_DestroyPublicKey(channelIDPub); 11990 SECKEY_DestroyPublicKey(channelIDPub);
11650 » if (channelID) 11991 if (channelID)
11651 » SECKEY_DestroyPrivateKey(channelID); 11992 SECKEY_DestroyPrivateKey(channelID);
11652 » PORT_SetError(PR_INVALID_ARGUMENT_ERROR); 11993 PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
11653 » return SECFailure; 11994 return SECFailure;
11654 } 11995 }
11655 11996
11656 if (ss->ssl3.channelID) 11997 if (ss->ssl3.channelID)
11657 » SECKEY_DestroyPrivateKey(ss->ssl3.channelID); 11998 SECKEY_DestroyPrivateKey(ss->ssl3.channelID);
11658 if (ss->ssl3.channelIDPub) 11999 if (ss->ssl3.channelIDPub)
11659 » SECKEY_DestroyPublicKey(ss->ssl3.channelIDPub); 12000 SECKEY_DestroyPublicKey(ss->ssl3.channelIDPub);
11660 12001
11661 ss->handshake = ssl_GatherRecord1stHandshake; 12002 ss->handshake = ssl_GatherRecord1stHandshake;
11662 ss->ssl3.channelID = channelID; 12003 ss->ssl3.channelID = channelID;
11663 ss->ssl3.channelIDPub = channelIDPub; 12004 ss->ssl3.channelIDPub = channelIDPub;
11664 12005
11665 return SECSuccess; 12006 return SECSuccess;
11666 } 12007 }
11667 12008
11668 /* called from ssl3_SendClientSecondRound 12009 /* called from ssl3_SendClientSecondRound
11669 * ssl3_HandleClientHello 12010 * ssl3_HandleClientHello
11670 * ssl3_HandleFinished 12011 * ssl3_HandleFinished
11671 */ 12012 */
11672 static SECStatus 12013 static SECStatus
11673 ssl3_SendFinished(sslSocket *ss, PRInt32 flags) 12014 ssl3_SendFinished(sslSocket *ss, PRInt32 flags)
11674 { 12015 {
11675 ssl3CipherSpec *cwSpec; 12016 ssl3CipherSpec *cwSpec;
11676 PRBool isTLS; 12017 PRBool isTLS;
11677 PRBool isServer = ss->sec.isServer; 12018 PRBool isServer = ss->sec.isServer;
11678 SECStatus rv; 12019 SECStatus rv;
11679 SSL3Sender sender = isServer ? sender_server : sender_client; 12020 SSL3Sender sender = isServer ? sender_server : sender_client;
11680 SSL3Hashes hashes; 12021 SSL3Hashes hashes;
11681 TLSFinished tlsFinished; 12022 TLSFinished tlsFinished;
11682 12023
11683 SSL_TRC(3, ("%d: SSL3[%d]: send finished handshake", SSL_GETPID(), ss->fd)); 12024 SSL_TRC(3, ("%d: SSL3[%d]: send finished handshake", SSL_GETPID(), ss->fd));
11684 12025
11685 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 12026 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
11686 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 12027 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11687 12028
11688 ssl_GetSpecReadLock(ss); 12029 ssl_GetSpecReadLock(ss);
11689 cwSpec = ss->ssl3.cwSpec; 12030 cwSpec = ss->ssl3.cwSpec;
11690 isTLS = (PRBool)(cwSpec->version > SSL_LIBRARY_VERSION_3_0); 12031 isTLS = (PRBool)(cwSpec->version > SSL_LIBRARY_VERSION_3_0);
11691 rv = ssl3_ComputeHandshakeHashes(ss, cwSpec, &hashes, sender); 12032 rv = ssl3_ComputeHandshakeHashes(ss, cwSpec, &hashes, sender);
11692 if (isTLS && rv == SECSuccess) { 12033 if (isTLS && rv == SECSuccess) {
11693 » rv = ssl3_ComputeTLSFinished(cwSpec, isServer, &hashes, &tlsFinished); 12034 rv = ssl3_ComputeTLSFinished(cwSpec, isServer, &hashes, &tlsFinished);
11694 } 12035 }
11695 ssl_ReleaseSpecReadLock(ss); 12036 ssl_ReleaseSpecReadLock(ss);
11696 if (rv != SECSuccess) { 12037 if (rv != SECSuccess) {
11697 » goto fail;» /* err code was set by ssl3_ComputeHandshakeHashes */ 12038 goto fail; /* err code was set by ssl3_ComputeHandshakeHashes */
11698 } 12039 }
11699 12040
11700 if (isTLS) { 12041 if (isTLS) {
11701 » if (isServer) 12042 if (isServer)
11702 » ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished; 12043 ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished;
11703 » else 12044 else
11704 » ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished; 12045 ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished;
11705 » ss->ssl3.hs.finishedBytes = sizeof tlsFinished; 12046 ss->ssl3.hs.finishedBytes = sizeof tlsFinished;
11706 » rv = ssl3_AppendHandshakeHeader(ss, finished, sizeof tlsFinished); 12047 rv = ssl3_AppendHandshakeHeader(ss, finished, sizeof tlsFinished);
11707 » if (rv != SECSuccess) 12048 if (rv != SECSuccess)
11708 » goto fail; »» /* err set by AppendHandshake. */ 12049 goto fail; /* err set by AppendHandshake. */
11709 » rv = ssl3_AppendHandshake(ss, &tlsFinished, sizeof tlsFinished); 12050 rv = ssl3_AppendHandshake(ss, &tlsFinished, sizeof tlsFinished);
11710 » if (rv != SECSuccess) 12051 if (rv != SECSuccess)
11711 » goto fail; »» /* err set by AppendHandshake. */ 12052 goto fail; /* err set by AppendHandshake. */
11712 } else { 12053 } else {
11713 » if (isServer) 12054 if (isServer)
11714 » ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes.u.s; 12055 ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes.u.s;
11715 » else 12056 else
11716 » ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes.u.s; 12057 ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes.u.s;
11717 » PORT_Assert(hashes.len == sizeof hashes.u.s); 12058 PORT_Assert(hashes.len == sizeof hashes.u.s);
11718 » ss->ssl3.hs.finishedBytes = sizeof hashes.u.s; 12059 ss->ssl3.hs.finishedBytes = sizeof hashes.u.s;
11719 » rv = ssl3_AppendHandshakeHeader(ss, finished, sizeof hashes.u.s); 12060 rv = ssl3_AppendHandshakeHeader(ss, finished, sizeof hashes.u.s);
11720 » if (rv != SECSuccess) 12061 if (rv != SECSuccess)
11721 » goto fail; »» /* err set by AppendHandshake. */ 12062 goto fail; /* err set by AppendHandshake. */
11722 » rv = ssl3_AppendHandshake(ss, &hashes.u.s, sizeof hashes.u.s); 12063 rv = ssl3_AppendHandshake(ss, &hashes.u.s, sizeof hashes.u.s);
11723 » if (rv != SECSuccess) 12064 if (rv != SECSuccess)
11724 » goto fail; »» /* err set by AppendHandshake. */ 12065 goto fail; /* err set by AppendHandshake. */
11725 } 12066 }
11726 rv = ssl3_FlushHandshake(ss, flags); 12067 rv = ssl3_FlushHandshake(ss, flags);
11727 if (rv != SECSuccess) { 12068 if (rv != SECSuccess) {
11728 » goto fail;» /* error code set by ssl3_FlushHandshake */ 12069 goto fail; /* error code set by ssl3_FlushHandshake */
11729 } 12070 }
11730 12071
11731 ssl3_RecordKeyLog(ss); 12072 ssl3_RecordKeyLog(ss);
11732 12073
11733 return SECSuccess; 12074 return SECSuccess;
11734 12075
11735 fail: 12076 fail:
11736 return rv; 12077 return rv;
11737 } 12078 }
11738 12079
11739 /* wrap the master secret, and put it into the SID. 12080 /* wrap the master secret, and put it into the SID.
11740 * Caller holds the Spec read lock. 12081 * Caller holds the Spec read lock.
11741 */ 12082 */
11742 SECStatus 12083 SECStatus
11743 ssl3_CacheWrappedMasterSecret(sslSocket *ss, sslSessionID *sid, 12084 ssl3_CacheWrappedMasterSecret(sslSocket *ss, sslSessionID *sid,
11744 ssl3CipherSpec *spec, SSL3KEAType effectiveExchKeyType) 12085 ssl3CipherSpec *spec, SSL3KEAType effectiveExchKey Type)
11745 { 12086 {
11746 PK11SymKey * wrappingKey = NULL; 12087 PK11SymKey *wrappingKey = NULL;
11747 PK11SlotInfo * symKeySlot; 12088 PK11SlotInfo *symKeySlot;
11748 void * pwArg = ss->pkcs11PinArg; 12089 void *pwArg = ss->pkcs11PinArg;
11749 SECStatus rv = SECFailure; 12090 SECStatus rv = SECFailure;
11750 PRBool isServer = ss->sec.isServer; 12091 PRBool isServer = ss->sec.isServer;
11751 CK_MECHANISM_TYPE mechanism = CKM_INVALID_MECHANISM; 12092 CK_MECHANISM_TYPE mechanism = CKM_INVALID_MECHANISM;
11752 symKeySlot = PK11_GetSlotFromKey(spec->master_secret); 12093 symKeySlot = PK11_GetSlotFromKey(spec->master_secret);
11753 if (!isServer) { 12094 if (!isServer) {
11754 » int wrapKeyIndex; 12095 int wrapKeyIndex;
11755 » int incarnation; 12096 int incarnation;
11756 12097
11757 » /* these next few functions are mere accessors and don't fail. */ 12098 /* these next few functions are mere accessors and don't fail. */
11758 » sid->u.ssl3.masterWrapIndex = wrapKeyIndex = 12099 sid->u.ssl3.masterWrapIndex = wrapKeyIndex =
11759 » » » » PK11_GetCurrentWrapIndex(symKeySlot); 12100 PK11_GetCurrentWrapIndex(symKeySlot);
11760 » PORT_Assert(wrapKeyIndex == 0);»/* array has only one entry! */ 12101 PORT_Assert(wrapKeyIndex == 0); /* array has only one entry! */
11761 12102
11762 » sid->u.ssl3.masterWrapSeries = incarnation = 12103 sid->u.ssl3.masterWrapSeries = incarnation =
11763 » » » » PK11_GetSlotSeries(symKeySlot); 12104 PK11_GetSlotSeries(symKeySlot);
11764 » sid->u.ssl3.masterSlotID = PK11_GetSlotID(symKeySlot); 12105 sid->u.ssl3.masterSlotID = PK11_GetSlotID(symKeySlot);
11765 » sid->u.ssl3.masterModuleID = PK11_GetModuleID(symKeySlot); 12106 sid->u.ssl3.masterModuleID = PK11_GetModuleID(symKeySlot);
11766 » sid->u.ssl3.masterValid = PR_TRUE; 12107 sid->u.ssl3.masterValid = PR_TRUE;
11767 » /* Get the default wrapping key, for wrapping the master secret before 12108 /* Get the default wrapping key, for wrapping the master secret before
11768 » * placing it in the SID cache entry. */ 12109 * placing it in the SID cache entry. */
11769 » wrappingKey = PK11_GetWrapKey(symKeySlot, wrapKeyIndex, 12110 wrappingKey = PK11_GetWrapKey(symKeySlot, wrapKeyIndex,
11770 » » » » CKM_INVALID_MECHANISM, incarnation, 12111 CKM_INVALID_MECHANISM, incarnation,
11771 » » » » pwArg); 12112 pwArg);
11772 » if (wrappingKey) { 12113 if (wrappingKey) {
11773 » mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */ 12114 mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
11774 » } else { 12115 } else {
11775 » int keyLength; 12116 int keyLength;
11776 » /* if the wrappingKey doesn't exist, attempt to create it. 12117 /* if the wrappingKey doesn't exist, attempt to create it.
11777 » * Note: we intentionally ignore errors here. If we cannot 12118 * Note: we intentionally ignore errors here. If we cannot
11778 » * generate a wrapping key, it is not fatal to this SSL connection, 12119 * generate a wrapping key, it is not fatal to this SSL connection,
11779 » * but we will not be able to restart this session. 12120 * but we will not be able to restart this session.
11780 » */ 12121 */
11781 » mechanism = PK11_GetBestWrapMechanism(symKeySlot); 12122 mechanism = PK11_GetBestWrapMechanism(symKeySlot);
11782 » keyLength = PK11_GetBestKeyLength(symKeySlot, mechanism); 12123 keyLength = PK11_GetBestKeyLength(symKeySlot, mechanism);
11783 » /* Zero length means fixed key length algorithm, or error. 12124 /* Zero length means fixed key length algorithm, or error.
11784 » * It's ambiguous. 12125 * It's ambiguous.
11785 » */ 12126 */
11786 » wrappingKey = PK11_KeyGen(symKeySlot, mechanism, NULL, 12127 wrappingKey = PK11_KeyGen(symKeySlot, mechanism, NULL,
11787 » » » » keyLength, pwArg); 12128 keyLength, pwArg);
11788 » if (wrappingKey) { 12129 if (wrappingKey) {
11789 » » PK11_SetWrapKey(symKeySlot, wrapKeyIndex, wrappingKey); 12130 PK11_SetWrapKey(symKeySlot, wrapKeyIndex, wrappingKey);
11790 » } 12131 }
11791 » } 12132 }
11792 } else { 12133 } else {
11793 » /* server socket using session cache. */ 12134 /* server socket using session cache. */
11794 » mechanism = PK11_GetBestWrapMechanism(symKeySlot); 12135 mechanism = PK11_GetBestWrapMechanism(symKeySlot);
11795 » if (mechanism != CKM_INVALID_MECHANISM) { 12136 if (mechanism != CKM_INVALID_MECHANISM) {
11796 » wrappingKey = 12137 wrappingKey =
11797 » » getWrappingKey(ss, symKeySlot, effectiveExchKeyType, 12138 getWrappingKey(ss, symKeySlot, effectiveExchKeyType,
11798 » » » mechanism, pwArg); 12139 mechanism, pwArg);
11799 » if (wrappingKey) { 12140 if (wrappingKey) {
11800 » » mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */ 12141 mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
11801 » } 12142 }
11802 » } 12143 }
11803 } 12144 }
11804 12145
11805 sid->u.ssl3.masterWrapMech = mechanism; 12146 sid->u.ssl3.masterWrapMech = mechanism;
11806 PK11_FreeSlot(symKeySlot); 12147 PK11_FreeSlot(symKeySlot);
11807 12148
11808 if (wrappingKey) { 12149 if (wrappingKey) {
11809 » SECItem wmsItem; 12150 SECItem wmsItem;
11810 12151
11811 » wmsItem.data = sid->u.ssl3.keys.wrapped_master_secret; 12152 wmsItem.data = sid->u.ssl3.keys.wrapped_master_secret;
11812 » wmsItem.len = sizeof sid->u.ssl3.keys.wrapped_master_secret; 12153 wmsItem.len = sizeof sid->u.ssl3.keys.wrapped_master_secret;
11813 » rv = PK11_WrapSymKey(mechanism, NULL, wrappingKey, 12154 rv = PK11_WrapSymKey(mechanism, NULL, wrappingKey,
11814 » » » spec->master_secret, &wmsItem); 12155 spec->master_secret, &wmsItem);
11815 » /* rv is examined below. */ 12156 /* rv is examined below. */
11816 » sid->u.ssl3.keys.wrapped_master_secret_len = wmsItem.len; 12157 sid->u.ssl3.keys.wrapped_master_secret_len = wmsItem.len;
11817 » PK11_FreeSymKey(wrappingKey); 12158 PK11_FreeSymKey(wrappingKey);
11818 } 12159 }
11819 return rv; 12160 return rv;
11820 } 12161 }
11821 12162
11822 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete 12163 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
11823 * ssl3 Finished message from the peer. 12164 * a complete ssl3 Finished message from the peer.
11824 * Caller must hold Handshake and RecvBuf locks. 12165 * Caller must hold Handshake and RecvBuf locks.
11825 */ 12166 */
11826 static SECStatus 12167 static SECStatus
11827 ssl3_HandleFinished(sslSocket *ss, SSL3Opaque *b, PRUint32 length, 12168 ssl3_HandleFinished(sslSocket *ss, SSL3Opaque *b, PRUint32 length,
11828 » » const SSL3Hashes *hashes) 12169 const SSL3Hashes *hashes)
11829 { 12170 {
11830 sslSessionID * sid» = ss->sec.ci.sid; 12171 sslSessionID *sid = ss->sec.ci.sid;
11831 SECStatus rv = SECSuccess; 12172 SECStatus rv = SECSuccess;
11832 PRBool isServer = ss->sec.isServer; 12173 PRBool isServer = ss->sec.isServer;
11833 PRBool isTLS; 12174 PRBool isTLS;
11834 SSL3KEAType effectiveExchKeyType; 12175 SSL3KEAType effectiveExchKeyType;
11835 12176
11836 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 12177 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
11837 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 12178 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
11838 12179
11839 SSL_TRC(3, ("%d: SSL3[%d]: handle finished handshake", 12180 SSL_TRC(3, ("%d: SSL3[%d]: handle finished handshake",
11840 » SSL_GETPID(), ss->fd)); 12181 SSL_GETPID(), ss->fd));
11841 12182
11842 if (ss->ssl3.hs.ws != wait_finished) { 12183 if (ss->ssl3.hs.ws != wait_finished) {
11843 » SSL3_SendAlert(ss, alert_fatal, unexpected_message); 12184 SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11844 » PORT_SetError(SSL_ERROR_RX_UNEXPECTED_FINISHED); 12185 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_FINISHED);
11845 » return SECFailure; 12186 return SECFailure;
11846 } 12187 }
11847 12188
11848 if (!hashes) { 12189 if (!hashes) {
11849 PORT_Assert(0); 12190 PORT_Assert(0);
11850 » SSL3_SendAlert(ss, alert_fatal, internal_error); 12191 SSL3_SendAlert(ss, alert_fatal, internal_error);
11851 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 12192 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
11852 return SECFailure; 12193 return SECFailure;
11853 } 12194 }
11854 12195
11855 isTLS = (PRBool)(ss->ssl3.crSpec->version > SSL_LIBRARY_VERSION_3_0); 12196 isTLS = (PRBool)(ss->ssl3.crSpec->version > SSL_LIBRARY_VERSION_3_0);
11856 if (isTLS) { 12197 if (isTLS) {
11857 » TLSFinished tlsFinished; 12198 TLSFinished tlsFinished;
11858 12199
11859 » if (length != sizeof tlsFinished) { 12200 if (length != sizeof tlsFinished) {
11860 » (void)SSL3_SendAlert(ss, alert_fatal, decode_error); 12201 (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
11861 » PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED); 12202 PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
11862 » return SECFailure; 12203 return SECFailure;
11863 » } 12204 }
11864 » rv = ssl3_ComputeTLSFinished(ss->ssl3.crSpec, !isServer, 12205 rv = ssl3_ComputeTLSFinished(ss->ssl3.crSpec, !isServer,
11865 » hashes, &tlsFinished); 12206 hashes, &tlsFinished);
11866 » if (!isServer) 12207 if (!isServer)
11867 » ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished; 12208 ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished;
11868 » else 12209 else
11869 » ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished; 12210 ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished;
11870 » ss->ssl3.hs.finishedBytes = sizeof tlsFinished; 12211 ss->ssl3.hs.finishedBytes = sizeof tlsFinished;
11871 » if (rv != SECSuccess || 12212 if (rv != SECSuccess ||
11872 » 0 != NSS_SecureMemcmp(&tlsFinished, b, length)) { 12213 0 != NSS_SecureMemcmp(&tlsFinished, b, length)) {
11873 » (void)SSL3_SendAlert(ss, alert_fatal, decrypt_error); 12214 (void)SSL3_SendAlert(ss, alert_fatal, decrypt_error);
11874 » PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); 12215 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
11875 » return SECFailure; 12216 return SECFailure;
11876 » } 12217 }
11877 } else { 12218 } else {
11878 » if (length != sizeof(SSL3Finished)) { 12219 if (length != sizeof(SSL3Finished)) {
11879 » (void)ssl3_IllegalParameter(ss); 12220 (void)ssl3_IllegalParameter(ss);
11880 » PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED); 12221 PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
11881 » return SECFailure; 12222 return SECFailure;
11882 » } 12223 }
11883 12224
11884 » if (!isServer) 12225 if (!isServer)
11885 » ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes->u.s; 12226 ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes->u.s;
11886 » else 12227 else
11887 » ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes->u.s; 12228 ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes->u.s;
11888 » PORT_Assert(hashes->len == sizeof hashes->u.s); 12229 PORT_Assert(hashes->len == sizeof hashes->u.s);
11889 » ss->ssl3.hs.finishedBytes = sizeof hashes->u.s; 12230 ss->ssl3.hs.finishedBytes = sizeof hashes->u.s;
11890 » if (0 != NSS_SecureMemcmp(&hashes->u.s, b, length)) { 12231 if (0 != NSS_SecureMemcmp(&hashes->u.s, b, length)) {
11891 » (void)ssl3_HandshakeFailure(ss); 12232 (void)ssl3_HandshakeFailure(ss);
11892 » PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); 12233 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
11893 » return SECFailure; 12234 return SECFailure;
11894 » } 12235 }
11895 } 12236 }
11896 12237
11897 ssl_GetXmitBufLock(ss);» /*************************************/ 12238 ssl_GetXmitBufLock(ss); /*************************************/
11898 12239
11899 if ((isServer && !ss->ssl3.hs.isResuming) || 12240 if ((isServer && !ss->ssl3.hs.isResuming) ||
11900 » (!isServer && ss->ssl3.hs.isResuming)) { 12241 (!isServer && ss->ssl3.hs.isResuming)) {
11901 » PRInt32 flags = 0; 12242 PRInt32 flags = 0;
11902 12243
11903 » /* Send a NewSessionTicket message if the client sent us 12244 /* Send a NewSessionTicket message if the client sent us
11904 » * either an empty session ticket, or one that did not verify. 12245 * either an empty session ticket, or one that did not verify.
11905 » * (Note that if either of these conditions was met, then the 12246 * (Note that if either of these conditions was met, then the
11906 » * server has sent a SessionTicket extension in the 12247 * server has sent a SessionTicket extension in the
11907 » * ServerHello message.) 12248 * ServerHello message.)
11908 » */ 12249 */
11909 » if (isServer && !ss->ssl3.hs.isResuming && 12250 if (isServer && !ss->ssl3.hs.isResuming &&
11910 » ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) && 12251 ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) &&
11911 » ssl3_KEAAllowsSessionTicket(ss->ssl3.hs.suite_def->key_exchange_alg) ) { 12252 ssl3_KEAAllowsSessionTicket(ss->ssl3.hs.suite_def->key_exchange_alg) ) {
11912 » /* RFC 5077 Section 3.3: "In the case of a full handshake, the 12253 /* RFC 5077 Section 3.3: "In the case of a full handshake, the
11913 » * server MUST verify the client's Finished message before sending 12254 * server MUST verify the client's Finished message before sending
11914 » * the ticket." Presumably, this also means that the client's 12255 * the ticket." Presumably, this also means that the client's
11915 » * certificate, if any, must be verified beforehand too. 12256 * certificate, if any, must be verified beforehand too.
11916 » */ 12257 */
11917 » rv = ssl3_SendNewSessionTicket(ss); 12258 rv = ssl3_SendNewSessionTicket(ss);
11918 » if (rv != SECSuccess) { 12259 if (rv != SECSuccess) {
11919 » » goto xmit_loser; 12260 goto xmit_loser;
11920 » } 12261 }
11921 » } 12262 }
11922 12263
11923 » rv = ssl3_SendChangeCipherSpecs(ss); 12264 rv = ssl3_SendChangeCipherSpecs(ss);
11924 » if (rv != SECSuccess) { 12265 if (rv != SECSuccess) {
11925 » goto xmit_loser;» /* err is set. */ 12266 goto xmit_loser; /* err is set. */
11926 » } 12267 }
11927 » /* If this thread is in SSL_SecureSend (trying to write some data) 12268 /* If this thread is in SSL_SecureSend (trying to write some data)
11928 » ** then set the ssl_SEND_FLAG_FORCE_INTO_BUFFER flag, so that the 12269 ** then set the ssl_SEND_FLAG_FORCE_INTO_BUFFER flag, so that the
11929 » ** last two handshake messages (change cipher spec and finished) 12270 ** last two handshake messages (change cipher spec and finished)
11930 » ** will be sent in the same send/write call as the application data. 12271 ** will be sent in the same send/write call as the application data.
11931 » */ 12272 */
11932 » if (ss->writerThread == PR_GetCurrentThread()) { 12273 if (ss->writerThread == PR_GetCurrentThread()) {
11933 » flags = ssl_SEND_FLAG_FORCE_INTO_BUFFER; 12274 flags = ssl_SEND_FLAG_FORCE_INTO_BUFFER;
11934 » } 12275 }
11935 12276
11936 » if (!isServer) { 12277 if (!isServer) {
11937 » if (!ss->firstHsDone) { 12278 if (!ss->firstHsDone) {
11938 » » rv = ssl3_SendNextProto(ss); 12279 rv = ssl3_SendNextProto(ss);
11939 » » if (rv != SECSuccess) { 12280 if (rv != SECSuccess) {
11940 » » goto xmit_loser; /* err code was set. */ 12281 goto xmit_loser; /* err code was set. */
11941 » » } 12282 }
11942 » } 12283 }
11943 » rv = ssl3_SendEncryptedExtensions(ss); 12284 rv = ssl3_SendChannelIDEncryptedExtensions(ss);
11944 » if (rv != SECSuccess) 12285 if (rv != SECSuccess)
11945 » » goto xmit_loser; /* err code was set. */ 12286 goto xmit_loser; /* err code was set. */
11946 » } 12287 }
11947 12288
11948 » if (IS_DTLS(ss)) { 12289 if (IS_DTLS(ss)) {
11949 » flags |= ssl_SEND_FLAG_NO_RETRANSMIT; 12290 flags |= ssl_SEND_FLAG_NO_RETRANSMIT;
11950 » } 12291 }
11951 12292
11952 » rv = ssl3_SendFinished(ss, flags); 12293 rv = ssl3_SendFinished(ss, flags);
11953 » if (rv != SECSuccess) { 12294 if (rv != SECSuccess) {
11954 » goto xmit_loser;» /* err is set. */ 12295 goto xmit_loser; /* err is set. */
11955 » } 12296 }
11956 } 12297 }
11957 12298
11958 xmit_loser: 12299 xmit_loser:
11959 ssl_ReleaseXmitBufLock(ss);»/*************************************/ 12300 ssl_ReleaseXmitBufLock(ss); /*************************************/
11960 if (rv != SECSuccess) { 12301 if (rv != SECSuccess) {
11961 return rv; 12302 return rv;
11962 } 12303 }
11963 12304
11964 if (ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa || 12305 if (ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa ||
11965 ss->ssl3.hs.kea_def->kea == kea_dhe_rsa) { 12306 ss->ssl3.hs.kea_def->kea == kea_dhe_rsa) {
11966 » effectiveExchKeyType = kt_rsa; 12307 effectiveExchKeyType = kt_rsa;
11967 } else { 12308 } else {
11968 » effectiveExchKeyType = ss->ssl3.hs.kea_def->exchKeyType; 12309 effectiveExchKeyType = ss->ssl3.hs.kea_def->exchKeyType;
11969 } 12310 }
11970 12311
11971 if (sid->cached == never_cached && !ss->opt.noCache && ss->sec.cache) { 12312 if (sid->cached == never_cached && !ss->opt.noCache && ss->sec.cache) {
11972 » /* fill in the sid */ 12313 /* fill in the sid */
11973 » sid->u.ssl3.cipherSuite = ss->ssl3.hs.cipher_suite; 12314 sid->u.ssl3.cipherSuite = ss->ssl3.hs.cipher_suite;
11974 » sid->u.ssl3.compression = ss->ssl3.hs.compression; 12315 sid->u.ssl3.compression = ss->ssl3.hs.compression;
11975 » sid->u.ssl3.policy = ss->ssl3.policy; 12316 sid->u.ssl3.policy = ss->ssl3.policy;
11976 #ifndef NSS_DISABLE_ECC 12317 #ifndef NSS_DISABLE_ECC
11977 » sid->u.ssl3.negotiatedECCurves = ss->ssl3.hs.negotiatedECCurves; 12318 sid->u.ssl3.negotiatedECCurves = ss->ssl3.hs.negotiatedECCurves;
11978 #endif 12319 #endif
11979 » sid->u.ssl3.exchKeyType = effectiveExchKeyType; 12320 sid->u.ssl3.exchKeyType = effectiveExchKeyType;
11980 » sid->version = ss->version; 12321 sid->version = ss->version;
11981 » sid->authAlgorithm = ss->sec.authAlgorithm; 12322 sid->authAlgorithm = ss->sec.authAlgorithm;
11982 » sid->authKeyBits = ss->sec.authKeyBits; 12323 sid->authKeyBits = ss->sec.authKeyBits;
11983 » sid->keaType = ss->sec.keaType; 12324 sid->keaType = ss->sec.keaType;
11984 » sid->keaKeyBits = ss->sec.keaKeyBits; 12325 sid->keaKeyBits = ss->sec.keaKeyBits;
11985 » sid->lastAccessTime = sid->creationTime = ssl_Time(); 12326 sid->lastAccessTime = sid->creationTime = ssl_Time();
11986 » sid->expirationTime = sid->creationTime + ssl3_sid_timeout; 12327 sid->expirationTime = sid->creationTime + ssl3_sid_timeout;
11987 » sid->localCert = CERT_DupCertificate(ss->sec.localCert); 12328 sid->localCert = CERT_DupCertificate(ss->sec.localCert);
11988 12329
11989 » ssl_GetSpecReadLock(ss);» /*************************************/ 12330 ssl_GetSpecReadLock(ss); /*************************************/
11990 12331
11991 » /* Copy the master secret (wrapped or unwrapped) into the sid */ 12332 /* Copy the master secret (wrapped or unwrapped) into the sid */
11992 » if (ss->ssl3.crSpec->msItem.len && ss->ssl3.crSpec->msItem.data) { 12333 if (ss->ssl3.crSpec->msItem.len && ss->ssl3.crSpec->msItem.data) {
11993 » sid->u.ssl3.keys.wrapped_master_secret_len = 12334 sid->u.ssl3.keys.wrapped_master_secret_len =
11994 » » » ss->ssl3.crSpec->msItem.len; 12335 ss->ssl3.crSpec->msItem.len;
11995 » memcpy(sid->u.ssl3.keys.wrapped_master_secret, 12336 memcpy(sid->u.ssl3.keys.wrapped_master_secret,
11996 » » ss->ssl3.crSpec->msItem.data, ss->ssl3.crSpec->msItem.len); 12337 ss->ssl3.crSpec->msItem.data, ss->ssl3.crSpec->msItem.len);
11997 » sid->u.ssl3.masterValid = PR_TRUE; 12338 sid->u.ssl3.masterValid = PR_TRUE;
11998 » sid->u.ssl3.keys.msIsWrapped = PR_FALSE; 12339 sid->u.ssl3.keys.msIsWrapped = PR_FALSE;
11999 » rv = SECSuccess; 12340 rv = SECSuccess;
12000 » } else { 12341 } else {
12001 » rv = ssl3_CacheWrappedMasterSecret(ss, ss->sec.ci.sid, 12342 rv = ssl3_CacheWrappedMasterSecret(ss, ss->sec.ci.sid,
12002 » » » » » ss->ssl3.crSpec, 12343 ss->ssl3.crSpec,
12003 » » » » » effectiveExchKeyType); 12344 effectiveExchKeyType);
12004 » sid->u.ssl3.keys.msIsWrapped = PR_TRUE; 12345 sid->u.ssl3.keys.msIsWrapped = PR_TRUE;
12005 » } 12346 }
12006 » ssl_ReleaseSpecReadLock(ss); /*************************************/ 12347 ssl_ReleaseSpecReadLock(ss); /*************************************/
12007 12348
12008 » /* If the wrap failed, we don't cache the sid. 12349 /* If the wrap failed, we don't cache the sid.
12009 » * The connection continues normally however. 12350 * The connection continues normally however.
12010 » */ 12351 */
12011 » ss->ssl3.hs.cacheSID = rv == SECSuccess; 12352 ss->ssl3.hs.cacheSID = rv == SECSuccess;
12012 } 12353 }
12013 12354
12014 if (ss->ssl3.hs.authCertificatePending) { 12355 if (ss->ssl3.hs.authCertificatePending) {
12015 » if (ss->ssl3.hs.restartTarget) { 12356 if (ss->ssl3.hs.restartTarget) {
12016 » PR_NOT_REACHED("ssl3_HandleFinished: unexpected restartTarget"); 12357 PR_NOT_REACHED("ssl3_HandleFinished: unexpected restartTarget");
12017 » PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 12358 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
12018 » return SECFailure; 12359 return SECFailure;
12019 » } 12360 }
12020 12361
12021 » ss->ssl3.hs.restartTarget = ssl3_FinishHandshake; 12362 ss->ssl3.hs.restartTarget = ssl3_FinishHandshake;
12022 » return SECWouldBlock; 12363 return SECWouldBlock;
12023 } 12364 }
12024 12365
12025 rv = ssl3_FinishHandshake(ss); 12366 rv = ssl3_FinishHandshake(ss);
12026 return rv; 12367 return rv;
12027 } 12368 }
12028 12369
12029 /* The return type is SECStatus instead of void because this function needs 12370 /* The return type is SECStatus instead of void because this function needs
12030 * to have type sslRestartTarget. 12371 * to have type sslRestartTarget.
12031 */ 12372 */
12032 SECStatus 12373 SECStatus
12033 ssl3_FinishHandshake(sslSocket * ss) 12374 ssl3_FinishHandshake(sslSocket *ss)
12034 { 12375 {
12035 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 12376 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
12036 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 12377 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12037 PORT_Assert( ss->ssl3.hs.restartTarget == NULL ); 12378 PORT_Assert(ss->ssl3.hs.restartTarget == NULL);
12038 12379
12039 /* The first handshake is now completed. */ 12380 /* The first handshake is now completed. */
12040 ss->handshake = NULL; 12381 ss->handshake = NULL;
12041 12382
12042 /* RFC 5077 Section 3.3: "The client MUST NOT treat the ticket as valid 12383 /* RFC 5077 Section 3.3: "The client MUST NOT treat the ticket as valid
12043 * until it has verified the server's Finished message." When the server 12384 * until it has verified the server's Finished message." When the server
12044 * sends a NewSessionTicket in a resumption handshake, we must wait until 12385 * sends a NewSessionTicket in a resumption handshake, we must wait until
12045 * the handshake is finished (we have verified the server's Finished 12386 * the handshake is finished (we have verified the server's Finished
12046 * AND the server's certificate) before we update the ticket in the sid. 12387 * AND the server's certificate) before we update the ticket in the sid.
12047 * 12388 *
12048 * This must be done before we call (*ss->sec.cache)(ss->sec.ci.sid) 12389 * This must be done before we call (*ss->sec.cache)(ss->sec.ci.sid)
12049 * because CacheSID requires the session ticket to already be set, and also 12390 * because CacheSID requires the session ticket to already be set, and also
12050 * because of the lazy lock creation scheme used by CacheSID and 12391 * because of the lazy lock creation scheme used by CacheSID and
12051 * ssl3_SetSIDSessionTicket. 12392 * ssl3_SetSIDSessionTicket.
12052 */ 12393 */
12053 if (ss->ssl3.hs.receivedNewSessionTicket) { 12394 if (ss->ssl3.hs.receivedNewSessionTicket) {
12054 » PORT_Assert(!ss->sec.isServer); 12395 PORT_Assert(!ss->sec.isServer);
12055 » ssl3_SetSIDSessionTicket(ss->sec.ci.sid, &ss->ssl3.hs.newSessionTicket); 12396 ssl3_SetSIDSessionTicket(ss->sec.ci.sid, &ss->ssl3.hs.newSessionTicket);
12056 » /* The sid took over the ticket data */ 12397 /* The sid took over the ticket data */
12057 » PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data); 12398 PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data);
12058 ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE; 12399 ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE;
12059 } 12400 }
12060 12401
12061 if (ss->ssl3.hs.cacheSID && ss->sec.isServer) { 12402 if (ss->ssl3.hs.cacheSID && ss->sec.isServer) {
12062 » PORT_Assert(ss->sec.ci.sid->cached == never_cached); 12403 PORT_Assert(ss->sec.ci.sid->cached == never_cached);
12063 » (*ss->sec.cache)(ss->sec.ci.sid); 12404 (*ss->sec.cache)(ss->sec.ci.sid);
12064 » ss->ssl3.hs.cacheSID = PR_FALSE; 12405 ss->ssl3.hs.cacheSID = PR_FALSE;
12065 } 12406 }
12066 12407
12067 ss->ssl3.hs.canFalseStart = PR_FALSE; /* False Start phase is complete */ 12408 ss->ssl3.hs.canFalseStart = PR_FALSE; /* False Start phase is complete */
12068 ss->ssl3.hs.ws = idle_handshake; 12409 ss->ssl3.hs.ws = idle_handshake;
12069 12410
12070 ssl_FinishHandshake(ss); 12411 ssl_FinishHandshake(ss);
12071 12412
12072 return SECSuccess; 12413 return SECSuccess;
12073 } 12414 }
12074 12415
12075 /* Called from ssl3_HandleHandshake() when it has gathered a complete ssl3 12416 /* Called from ssl3_HandleHandshake() when it has gathered a complete ssl3
12076 * hanshake message. 12417 * hanshake message.
12077 * Caller must hold Handshake and RecvBuf locks. 12418 * Caller must hold Handshake and RecvBuf locks.
12078 */ 12419 */
12079 SECStatus 12420 SECStatus
12080 ssl3_HandleHandshakeMessage(sslSocket *ss, SSL3Opaque *b, PRUint32 length) 12421 ssl3_HandleHandshakeMessage(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
12081 { 12422 {
12082 SECStatus rv » = SECSuccess; 12423 SECStatus rv = SECSuccess;
12083 SSL3HandshakeType type » = ss->ssl3.hs.msg_type; 12424 SSL3HandshakeType type = ss->ssl3.hs.msg_type;
12084 SSL3Hashes hashes;» /* computed hashes are put here. */ 12425 SSL3Hashes hashes; /* computed hashes are put here. */
12085 SSL3Hashes *hashesPtr = NULL; /* Set when hashes are computed */ 12426 SSL3Hashes *hashesPtr = NULL; /* Set when hashes are computed */
12086 PRUint8 hdr[4]; 12427 PRUint8 hdr[4];
12087 PRUint8 dtlsData[8]; 12428 PRUint8 dtlsData[8];
12429 PRBool computeHashes = PR_FALSE;
12088 12430
12089 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 12431 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
12090 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 12432 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12091 /* 12433 /*
12092 * We have to compute the hashes before we update them with the 12434 * We have to compute the hashes before we update them with the
12093 * current message. 12435 * current message.
12094 */ 12436 */
12095 ssl_GetSpecReadLock(ss);» /************************************/ 12437 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
12096 if(((type == finished) && (ss->ssl3.hs.ws == wait_finished)) || 12438 if (((type == finished) && (ss->ssl3.hs.ws == wait_finished)) ||
12097 ((type == certificate_verify) && (ss->ssl3.hs.ws == wait_cert_verify))) { 12439 ((type == certificate_verify) &&
12098 » SSL3Sender sender = (SSL3Sender)0; 12440 (ss->ssl3.hs.ws == wait_cert_verify))) {
12099 » ssl3CipherSpec *rSpec = ss->ssl3.prSpec; 12441 computeHashes = PR_TRUE;
12442 }
12443 } else {
12444 if (type == certificate_verify) {
12445 computeHashes =
12446 TLS13_IN_HS_STATE(ss, wait_cert_verify);
12447 } else if (type == finished) {
12448 computeHashes =
12449 TLS13_IN_HS_STATE(ss, wait_cert_request, wait_finished);
12450 }
12451 }
12100 12452
12101 » if (type == finished) { 12453 ssl_GetSpecReadLock(ss); /************************************/
12102 » sender = ss->sec.isServer ? sender_client : sender_server; 12454 if (computeHashes) {
12103 » rSpec = ss->ssl3.crSpec; 12455 SSL3Sender sender = (SSL3Sender)0;
12104 » } 12456 ssl3CipherSpec *rSpec = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 ? ss- >ssl3.crSpec
12105 » rv = ssl3_ComputeHandshakeHashes(ss, rSpec, &hashes, sender); 12457 : ss- >ssl3.prSpec;
12458
12459 if (type == finished) {
12460 sender = ss->sec.isServer ? sender_client : sender_server;
12461 rSpec = ss->ssl3.crSpec;
12462 }
12463 rv = ssl3_ComputeHandshakeHashes(ss, rSpec, &hashes, sender);
12106 if (rv == SECSuccess) { 12464 if (rv == SECSuccess) {
12107 hashesPtr = &hashes; 12465 hashesPtr = &hashes;
12108 } 12466 }
12109 } 12467 }
12110 ssl_ReleaseSpecReadLock(ss); /************************************/ 12468 ssl_ReleaseSpecReadLock(ss); /************************************/
12111 if (rv != SECSuccess) { 12469 if (rv != SECSuccess) {
12112 » return rv;» /* error code was set by ssl3_ComputeHandshakeHashes*/ 12470 return rv; /* error code was set by ssl3_ComputeHandshakeHashes*/
12113 } 12471 }
12114 SSL_TRC(30,("%d: SSL3[%d]: handle handshake message: %s", SSL_GETPID(), 12472 SSL_TRC(30, ("%d: SSL3[%d]: handle handshake message: %s", SSL_GETPID(),
12115 » » ss->fd, ssl3_DecodeHandshakeType(ss->ssl3.hs.msg_type))); 12473 ss->fd, ssl3_DecodeHandshakeType(ss->ssl3.hs.msg_type)));
12116 12474
12117 hdr[0] = (PRUint8)ss->ssl3.hs.msg_type; 12475 hdr[0] = (PRUint8)ss->ssl3.hs.msg_type;
12118 hdr[1] = (PRUint8)(length >> 16); 12476 hdr[1] = (PRUint8)(length >> 16);
12119 hdr[2] = (PRUint8)(length >> 8); 12477 hdr[2] = (PRUint8)(length >> 8);
12120 hdr[3] = (PRUint8)(length ); 12478 hdr[3] = (PRUint8)(length);
12121 12479
12122 /* Start new handshake hashes when we start a new handshake */ 12480 /* Start new handshake hashes when we start a new handshake */
12123 if (ss->ssl3.hs.msg_type == client_hello) { 12481 if (ss->ssl3.hs.msg_type == client_hello) {
12124 » rv = ssl3_RestartHandshakeHashes(ss); 12482 rv = ssl3_RestartHandshakeHashes(ss);
12125 » if (rv != SECSuccess) { 12483 if (rv != SECSuccess) {
12126 » return rv; 12484 return rv;
12127 » } 12485 }
12128 } 12486 }
12129 /* We should not include hello_request and hello_verify_request messages 12487 /* We should not include hello_request and hello_verify_request messages
12130 * in the handshake hashes */ 12488 * in the handshake hashes */
12131 if ((ss->ssl3.hs.msg_type != hello_request) && 12489 if ((ss->ssl3.hs.msg_type != hello_request) &&
12132 » (ss->ssl3.hs.msg_type != hello_verify_request)) { 12490 (ss->ssl3.hs.msg_type != hello_verify_request)) {
12133 » rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char*) hdr, 4); 12491 rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char *)hdr, 4);
12134 » if (rv != SECSuccess) return rv;» /* err code already set. */ 12492 if (rv != SECSuccess)
12493 return rv; /* err code already set. */
12135 12494
12136 » /* Extra data to simulate a complete DTLS handshake fragment */ 12495 /* Extra data to simulate a complete DTLS handshake fragment */
12137 » if (IS_DTLS(ss)) { 12496 if (IS_DTLS(ss)) {
12138 » /* Sequence number */ 12497 /* Sequence number */
12139 » dtlsData[0] = MSB(ss->ssl3.hs.recvMessageSeq); 12498 dtlsData[0] = MSB(ss->ssl3.hs.recvMessageSeq);
12140 » dtlsData[1] = LSB(ss->ssl3.hs.recvMessageSeq); 12499 dtlsData[1] = LSB(ss->ssl3.hs.recvMessageSeq);
12141 12500
12142 » /* Fragment offset */ 12501 /* Fragment offset */
12143 » dtlsData[2] = 0; 12502 dtlsData[2] = 0;
12144 » dtlsData[3] = 0; 12503 dtlsData[3] = 0;
12145 » dtlsData[4] = 0; 12504 dtlsData[4] = 0;
12146 12505
12147 » /* Fragment length */ 12506 /* Fragment length */
12148 » dtlsData[5] = (PRUint8)(length >> 16); 12507 dtlsData[5] = (PRUint8)(length >> 16);
12149 » dtlsData[6] = (PRUint8)(length >> 8); 12508 dtlsData[6] = (PRUint8)(length >> 8);
12150 » dtlsData[7] = (PRUint8)(length ); 12509 dtlsData[7] = (PRUint8)(length);
12151 12510
12152 » rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char*) dtlsData, 12511 rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char *)dtlsData,
12153 » » » » » sizeof(dtlsData)); 12512 sizeof(dtlsData));
12154 » if (rv != SECSuccess) return rv;» /* err code already set. */ 12513 if (rv != SECSuccess)
12155 » } 12514 return rv; /* err code already set. */
12515 }
12156 12516
12157 » /* The message body */ 12517 /* The message body */
12158 » rv = ssl3_UpdateHandshakeHashes(ss, b, length); 12518 rv = ssl3_UpdateHandshakeHashes(ss, b, length);
12159 » if (rv != SECSuccess) return rv;» /* err code already set. */ 12519 if (rv != SECSuccess)
12520 return rv; /* err code already set. */
12160 } 12521 }
12161 12522
12162 PORT_SetError(0);» /* each message starts with no error. */ 12523 PORT_SetError(0); /* each message starts with no error. */
12163 12524
12164 if (ss->ssl3.hs.ws == wait_certificate_status && 12525 if (ss->ssl3.hs.ws == wait_certificate_status &&
12165 ss->ssl3.hs.msg_type != certificate_status) { 12526 ss->ssl3.hs.msg_type != certificate_status) {
12166 /* If we negotiated the certificate_status extension then we deferred 12527 /* If we negotiated the certificate_status extension then we deferred
12167 * certificate validation until we get the CertificateStatus messsage. 12528 * certificate validation until we get the CertificateStatus messsage.
12168 * But the CertificateStatus message is optional. If the server did 12529 * But the CertificateStatus message is optional. If the server did
12169 * not send it then we need to validate the certificate now. If the 12530 * not send it then we need to validate the certificate now. If the
12170 * server does send the CertificateStatus message then we will 12531 * server does send the CertificateStatus message then we will
12171 * authenticate the certificate in ssl3_HandleCertificateStatus. 12532 * authenticate the certificate in ssl3_HandleCertificateStatus.
12172 */ 12533 */
12173 rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */ 12534 rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
12174 PORT_Assert(rv != SECWouldBlock); 12535 PORT_Assert(rv != SECWouldBlock);
12175 if (rv != SECSuccess) { 12536 if (rv != SECSuccess) {
12176 return rv; 12537 return rv;
12177 } 12538 }
12178 } 12539 }
12179 12540
12180 switch (ss->ssl3.hs.msg_type) { 12541 switch (ss->ssl3.hs.msg_type) {
12181 case hello_request: 12542 case client_hello:
12182 » if (length != 0) { 12543 if (!ss->sec.isServer) {
12183 » (void)ssl3_DecodeError(ss); 12544 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12184 » PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_REQUEST); 12545 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO);
12185 » return SECFailure; 12546 return SECFailure;
12186 » } 12547 }
12187 » if (ss->sec.isServer) { 12548 rv = ssl3_HandleClientHello(ss, b, length);
12188 » (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 12549 break;
12189 » PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST); 12550 case server_hello:
12190 » return SECFailure; 12551 if (ss->sec.isServer) {
12191 » } 12552 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12192 » rv = ssl3_HandleHelloRequest(ss); 12553 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO);
12193 » break; 12554 return SECFailure;
12194 case client_hello: 12555 }
12195 » if (!ss->sec.isServer) { 12556 rv = ssl3_HandleServerHello(ss, b, length);
12196 » (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 12557 break;
12197 » PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO); 12558 default:
12198 » return SECFailure; 12559 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
12199 » } 12560 rv = ssl3_HandlePostHelloHandshakeMessage(ss, b, length, hashesP tr);
12200 » rv = ssl3_HandleClientHello(ss, b, length); 12561 } else {
12201 » break; 12562 rv = tls13_HandlePostHelloHandshakeMessage(ss, b, length,
12202 case server_hello: 12563 hashesPtr);
12203 » if (ss->sec.isServer) { 12564 }
12204 » (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 12565 break;
12205 » PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO);
12206 » return SECFailure;
12207 » }
12208 » rv = ssl3_HandleServerHello(ss, b, length);
12209 » break;
12210 case hello_verify_request:
12211 » if (!IS_DTLS(ss) || ss->sec.isServer) {
12212 » (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12213 » PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_VERIFY_REQUEST);
12214 » return SECFailure;
12215 » }
12216 » rv = dtls_HandleHelloVerifyRequest(ss, b, length);
12217 » break;
12218 case certificate:
12219 » rv = ssl3_HandleCertificate(ss, b, length);
12220 » break;
12221 case certificate_status:
12222 » rv = ssl3_HandleCertificateStatus(ss, b, length);
12223 » break;
12224 case server_key_exchange:
12225 » if (ss->sec.isServer) {
12226 » (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12227 » PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH);
12228 » return SECFailure;
12229 » }
12230 » rv = ssl3_HandleServerKeyExchange(ss, b, length);
12231 » break;
12232 case certificate_request:
12233 » if (ss->sec.isServer) {
12234 » (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12235 » PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST);
12236 » return SECFailure;
12237 » }
12238 » rv = ssl3_HandleCertificateRequest(ss, b, length);
12239 » break;
12240 case server_hello_done:
12241 » if (length != 0) {
12242 » (void)ssl3_DecodeError(ss);
12243 » PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_DONE);
12244 » return SECFailure;
12245 » }
12246 » if (ss->sec.isServer) {
12247 » (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12248 » PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
12249 » return SECFailure;
12250 » }
12251 » rv = ssl3_HandleServerHelloDone(ss);
12252 » break;
12253 case certificate_verify:
12254 » if (!ss->sec.isServer) {
12255 » (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12256 » PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY);
12257 » return SECFailure;
12258 » }
12259 » rv = ssl3_HandleCertificateVerify(ss, b, length, hashesPtr);
12260 » break;
12261 case client_key_exchange:
12262 » if (!ss->sec.isServer) {
12263 » (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12264 » PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
12265 » return SECFailure;
12266 » }
12267 » rv = ssl3_HandleClientKeyExchange(ss, b, length);
12268 » break;
12269 case new_session_ticket:
12270 » if (ss->sec.isServer) {
12271 » (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12272 » PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
12273 » return SECFailure;
12274 » }
12275 » rv = ssl3_HandleNewSessionTicket(ss, b, length);
12276 » break;
12277 case finished:
12278 rv = ssl3_HandleFinished(ss, b, length, hashesPtr);
12279 » break;
12280 default:
12281 » (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12282 » PORT_SetError(SSL_ERROR_RX_UNKNOWN_HANDSHAKE);
12283 » rv = SECFailure;
12284 } 12566 }
12285 12567
12286 if (IS_DTLS(ss) && (rv != SECFailure)) { 12568 if (IS_DTLS(ss) && (rv != SECFailure)) {
12287 » /* Increment the expected sequence number */ 12569 /* Increment the expected sequence number */
12288 » ss->ssl3.hs.recvMessageSeq++; 12570 ss->ssl3.hs.recvMessageSeq++;
12571 }
12572 return rv;
12573 }
12574
12575 static SECStatus
12576 ssl3_HandlePostHelloHandshakeMessage(sslSocket *ss, SSL3Opaque *b,
12577 PRUint32 length, SSL3Hashes *hashesPtr)
12578 {
12579 SECStatus rv;
12580 PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);
12581
12582 switch (ss->ssl3.hs.msg_type) {
12583 case hello_request:
12584 if (length != 0) {
12585 (void)ssl3_DecodeError(ss);
12586 PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_REQUEST);
12587 return SECFailure;
12588 }
12589 if (ss->sec.isServer) {
12590 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12591 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST);
12592 return SECFailure;
12593 }
12594 rv = ssl3_HandleHelloRequest(ss);
12595 break;
12596 case hello_verify_request:
12597 if (!IS_DTLS(ss) || ss->sec.isServer) {
12598 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12599 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_VERIFY_REQUEST);
12600 return SECFailure;
12601 }
12602 rv = dtls_HandleHelloVerifyRequest(ss, b, length);
12603 break;
12604 case certificate:
12605 rv = ssl3_HandleCertificate(ss, b, length);
12606 break;
12607 case certificate_status:
12608 rv = ssl3_HandleCertificateStatus(ss, b, length);
12609 break;
12610 case server_key_exchange:
12611 if (ss->sec.isServer) {
12612 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12613 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH);
12614 return SECFailure;
12615 }
12616 rv = ssl3_HandleServerKeyExchange(ss, b, length);
12617 break;
12618 case certificate_request:
12619 if (ss->sec.isServer) {
12620 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12621 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST);
12622 return SECFailure;
12623 }
12624 rv = ssl3_HandleCertificateRequest(ss, b, length);
12625 break;
12626 case server_hello_done:
12627 if (length != 0) {
12628 (void)ssl3_DecodeError(ss);
12629 PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_DONE);
12630 return SECFailure;
12631 }
12632 if (ss->sec.isServer) {
12633 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12634 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
12635 return SECFailure;
12636 }
12637 rv = ssl3_HandleServerHelloDone(ss);
12638 break;
12639 case certificate_verify:
12640 if (!ss->sec.isServer) {
12641 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12642 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY);
12643 return SECFailure;
12644 }
12645 rv = ssl3_HandleCertificateVerify(ss, b, length, hashesPtr);
12646 break;
12647 case client_key_exchange:
12648 if (!ss->sec.isServer) {
12649 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12650 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
12651 return SECFailure;
12652 }
12653 rv = ssl3_HandleClientKeyExchange(ss, b, length);
12654 break;
12655 case new_session_ticket:
12656 if (ss->sec.isServer) {
12657 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12658 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
12659 return SECFailure;
12660 }
12661 rv = ssl3_HandleNewSessionTicket(ss, b, length);
12662 break;
12663 case finished:
12664 rv = ssl3_HandleFinished(ss, b, length, hashesPtr);
12665 break;
12666 default:
12667 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12668 PORT_SetError(SSL_ERROR_RX_UNKNOWN_HANDSHAKE);
12669 rv = SECFailure;
12289 } 12670 }
12290 12671
12291 return rv; 12672 return rv;
12292 } 12673 }
12293 12674
12294 /* Called only from ssl3_HandleRecord, for each (deciphered) ssl3 record. 12675 /* Called only from ssl3_HandleRecord, for each (deciphered) ssl3 record.
12295 * origBuf is the decrypted ssl record content. 12676 * origBuf is the decrypted ssl record content.
12296 * Caller must hold the handshake and RecvBuf locks. 12677 * Caller must hold the handshake and RecvBuf locks.
12297 */ 12678 */
12298 static SECStatus 12679 static SECStatus
12299 ssl3_HandleHandshake(sslSocket *ss, sslBuffer *origBuf) 12680 ssl3_HandleHandshake(sslSocket *ss, sslBuffer *origBuf)
12300 { 12681 {
12301 /* 12682 /*
12302 * There may be a partial handshake message already in the handshake 12683 * There may be a partial handshake message already in the handshake
12303 * state. The incoming buffer may contain another portion, or a 12684 * state. The incoming buffer may contain another portion, or a
12304 * complete message or several messages followed by another portion. 12685 * complete message or several messages followed by another portion.
12305 * 12686 *
12306 * Each message is made contiguous before being passed to the actual 12687 * Each message is made contiguous before being passed to the actual
12307 * message parser. 12688 * message parser.
12308 */ 12689 */
12309 sslBuffer *buf = &ss->ssl3.hs.msgState; /* do not lose the original buffer p ointer */ 12690 sslBuffer *buf = &ss->ssl3.hs.msgState; /* do not lose the original buffer p ointer */
12310 SECStatus rv; 12691 SECStatus rv;
12311 12692
12312 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 12693 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
12313 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 12694 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
12314 12695
12315 if (buf->buf == NULL) { 12696 if (buf->buf == NULL) {
12316 » *buf = *origBuf; 12697 *buf = *origBuf;
12317 } 12698 }
12318 while (buf->len > 0) { 12699 while (buf->len > 0) {
12319 » if (ss->ssl3.hs.header_bytes < 4) { 12700 if (ss->ssl3.hs.header_bytes < 4) {
12320 » PRUint8 t; 12701 PRUint8 t;
12321 » t = *(buf->buf++); 12702 t = *(buf->buf++);
12322 » buf->len--; 12703 buf->len--;
12323 » if (ss->ssl3.hs.header_bytes++ == 0) 12704 if (ss->ssl3.hs.header_bytes++ == 0)
12324 » » ss->ssl3.hs.msg_type = (SSL3HandshakeType)t; 12705 ss->ssl3.hs.msg_type = (SSL3HandshakeType)t;
12325 » else 12706 else
12326 » » ss->ssl3.hs.msg_len = (ss->ssl3.hs.msg_len << 8) + t; 12707 ss->ssl3.hs.msg_len = (ss->ssl3.hs.msg_len << 8) + t;
12327 » if (ss->ssl3.hs.header_bytes < 4) 12708 if (ss->ssl3.hs.header_bytes < 4)
12328 » » continue; 12709 continue;
12329 12710
12330 #define MAX_HANDSHAKE_MSG_LEN 0x1ffff» /* 128k - 1 */ 12711 #define MAX_HANDSHAKE_MSG_LEN 0x1ffff /* 128k - 1 */
12331 » if (ss->ssl3.hs.msg_len > MAX_HANDSHAKE_MSG_LEN) { 12712 if (ss->ssl3.hs.msg_len > MAX_HANDSHAKE_MSG_LEN) {
12332 » » (void)ssl3_DecodeError(ss); 12713 (void)ssl3_DecodeError(ss);
12333 » » PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE); 12714 PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE);
12334 » » return SECFailure; 12715 return SECFailure;
12335 » } 12716 }
12336 #undef MAX_HANDSHAKE_MSG_LEN 12717 #undef MAX_HANDSHAKE_MSG_LEN
12337 12718
12338 » /* If msg_len is zero, be sure we fall through, 12719 /* If msg_len is zero, be sure we fall through,
12339 » ** even if buf->len is zero. 12720 ** even if buf->len is zero.
12340 » */ 12721 */
12341 » if (ss->ssl3.hs.msg_len > 0) 12722 if (ss->ssl3.hs.msg_len > 0)
12342 » » continue; 12723 continue;
12343 » } 12724 }
12344 12725
12345 » /* 12726 /*
12346 » * Header has been gathered and there is at least one byte of new 12727 * Header has been gathered and there is at least one byte of new
12347 » * data available for this message. If it can be done right out 12728 * data available for this message. If it can be done right out
12348 » * of the original buffer, then use it from there. 12729 * of the original buffer, then use it from there.
12349 » */ 12730 */
12350 » if (ss->ssl3.hs.msg_body.len == 0 && buf->len >= ss->ssl3.hs.msg_len) { 12731 if (ss->ssl3.hs.msg_body.len == 0 && buf->len >= ss->ssl3.hs.msg_len) {
12351 » /* handle it from input buffer */ 12732 /* handle it from input buffer */
12352 » rv = ssl3_HandleHandshakeMessage(ss, buf->buf, ss->ssl3.hs.msg_len); 12733 rv = ssl3_HandleHandshakeMessage(ss, buf->buf, ss->ssl3.hs.msg_len);
12353 » if (rv == SECFailure) { 12734 if (rv == SECFailure) {
12354 » » /* This test wants to fall through on either 12735 /* This test wants to fall through on either
12355 » » * SECSuccess or SECWouldBlock. 12736 * SECSuccess or SECWouldBlock.
12356 » » * ssl3_HandleHandshakeMessage MUST set the error code. 12737 * ssl3_HandleHandshakeMessage MUST set the error code.
12357 » » */ 12738 */
12358 » » return rv; 12739 return rv;
12359 » } 12740 }
12360 » buf->buf += ss->ssl3.hs.msg_len; 12741 buf->buf += ss->ssl3.hs.msg_len;
12361 » buf->len -= ss->ssl3.hs.msg_len; 12742 buf->len -= ss->ssl3.hs.msg_len;
12362 » ss->ssl3.hs.msg_len = 0; 12743 ss->ssl3.hs.msg_len = 0;
12363 » ss->ssl3.hs.header_bytes = 0; 12744 ss->ssl3.hs.header_bytes = 0;
12364 » if (rv != SECSuccess) { /* return if SECWouldBlock. */ 12745 if (rv != SECSuccess) { /* return if SECWouldBlock. */
12365 » » return rv; 12746 return rv;
12366 » } 12747 }
12367 » } else { 12748 } else {
12368 » /* must be copied to msg_body and dealt with from there */ 12749 /* must be copied to msg_body and dealt with from there */
12369 » unsigned int bytes; 12750 unsigned int bytes;
12370 12751
12371 » PORT_Assert(ss->ssl3.hs.msg_body.len < ss->ssl3.hs.msg_len); 12752 PORT_Assert(ss->ssl3.hs.msg_body.len < ss->ssl3.hs.msg_len);
12372 » bytes = PR_MIN(buf->len, ss->ssl3.hs.msg_len - ss->ssl3.hs.msg_body. len); 12753 bytes = PR_MIN(buf->len, ss->ssl3.hs.msg_len - ss->ssl3.hs.msg_body. len);
12373 12754
12374 » /* Grow the buffer if needed */ 12755 /* Grow the buffer if needed */
12375 » rv = sslBuffer_Grow(&ss->ssl3.hs.msg_body, ss->ssl3.hs.msg_len); 12756 rv = sslBuffer_Grow(&ss->ssl3.hs.msg_body, ss->ssl3.hs.msg_len);
12376 » if (rv != SECSuccess) { 12757 if (rv != SECSuccess) {
12377 » » /* sslBuffer_Grow has set a memory error code. */ 12758 /* sslBuffer_Grow has set a memory error code. */
12378 » » return SECFailure; 12759 return SECFailure;
12379 » } 12760 }
12380 12761
12381 » PORT_Memcpy(ss->ssl3.hs.msg_body.buf + ss->ssl3.hs.msg_body.len, 12762 PORT_Memcpy(ss->ssl3.hs.msg_body.buf + ss->ssl3.hs.msg_body.len,
12382 » » buf->buf, bytes); 12763 buf->buf, bytes);
12383 » ss->ssl3.hs.msg_body.len += bytes; 12764 ss->ssl3.hs.msg_body.len += bytes;
12384 » buf->buf += bytes; 12765 buf->buf += bytes;
12385 » buf->len -= bytes; 12766 buf->len -= bytes;
12386 12767
12387 » PORT_Assert(ss->ssl3.hs.msg_body.len <= ss->ssl3.hs.msg_len); 12768 PORT_Assert(ss->ssl3.hs.msg_body.len <= ss->ssl3.hs.msg_len);
12388 12769
12389 » /* if we have a whole message, do it */ 12770 /* if we have a whole message, do it */
12390 » if (ss->ssl3.hs.msg_body.len == ss->ssl3.hs.msg_len) { 12771 if (ss->ssl3.hs.msg_body.len == ss->ssl3.hs.msg_len) {
12391 » » rv = ssl3_HandleHandshakeMessage( 12772 rv = ssl3_HandleHandshakeMessage(
12392 » » ss, ss->ssl3.hs.msg_body.buf, ss->ssl3.hs.msg_len); 12773 ss, ss->ssl3.hs.msg_body.buf, ss->ssl3.hs.msg_len);
12393 » » if (rv == SECFailure) { 12774 if (rv == SECFailure) {
12394 » » /* This test wants to fall through on either 12775 /* This test wants to fall through on either
12395 » » * SECSuccess or SECWouldBlock. 12776 * SECSuccess or SECWouldBlock.
12396 » » * ssl3_HandleHandshakeMessage MUST set error code. 12777 * ssl3_HandleHandshakeMessage MUST set error code.
12397 » » */ 12778 */
12398 » » return rv; 12779 return rv;
12399 » » } 12780 }
12400 » » ss->ssl3.hs.msg_body.len = 0; 12781 ss->ssl3.hs.msg_body.len = 0;
12401 » » ss->ssl3.hs.msg_len = 0; 12782 ss->ssl3.hs.msg_len = 0;
12402 » » ss->ssl3.hs.header_bytes = 0; 12783 ss->ssl3.hs.header_bytes = 0;
12403 » » if (rv != SECSuccess) { /* return if SECWouldBlock. */ 12784 if (rv != SECSuccess) { /* return if SECWouldBlock. */
12404 » » return rv; 12785 return rv;
12405 » » } 12786 }
12406 » } else { 12787 } else {
12407 » » PORT_Assert(buf->len == 0); 12788 PORT_Assert(buf->len == 0);
12408 » » break; 12789 break;
12409 » } 12790 }
12410 » } 12791 }
12411 }» /* end loop */ 12792 } /* end loop */
12412 12793
12413 origBuf->len = 0;» /* So ssl3_GatherAppDataRecord will keep looping. */ 12794 origBuf->len = 0; /* So ssl3_GatherAppDataRecord will keep looping. */
12414 buf->buf = NULL;» /* not a leak. */ 12795 buf->buf = NULL; /* not a leak. */
12415 return SECSuccess; 12796 return SECSuccess;
12416 } 12797 }
12417 12798
12418 /* These macros return the given value with the MSB copied to all the other 12799 /* These macros return the given value with the MSB copied to all the other
12419 * bits. They use the fact that arithmetic shift shifts-in the sign bit. 12800 * bits. They use the fact that arithmetic shift shifts-in the sign bit.
12420 * However, this is not ensured by the C standard so you may need to replace 12801 * However, this is not ensured by the C standard so you may need to replace
12421 * them with something else for odd compilers. */ 12802 * them with something else for odd compilers. */
12422 #define DUPLICATE_MSB_TO_ALL(x) ( (unsigned)( (int)(x) >> (sizeof(int)*8-1) ) ) 12803 #define DUPLICATE_MSB_TO_ALL(x) ((unsigned)((int)(x) >> (sizeof(int) * 8 - 1)))
12423 #define DUPLICATE_MSB_TO_ALL_8(x) ((unsigned char)(DUPLICATE_MSB_TO_ALL(x))) 12804 #define DUPLICATE_MSB_TO_ALL_8(x) ((unsigned char)(DUPLICATE_MSB_TO_ALL(x)))
12424 12805
12425 /* SECStatusToMask returns, in constant time, a mask value of all ones if 12806 /* SECStatusToMask returns, in constant time, a mask value of all ones if
12426 * rv == SECSuccess. Otherwise it returns zero. */ 12807 * rv == SECSuccess. Otherwise it returns zero. */
12427 static unsigned int 12808 static unsigned int
12428 SECStatusToMask(SECStatus rv) 12809 SECStatusToMask(SECStatus rv)
12429 { 12810 {
12430 unsigned int good; 12811 unsigned int good;
12431 /* rv ^ SECSuccess is zero iff rv == SECSuccess. Subtracting one results 12812 /* rv ^ SECSuccess is zero iff rv == SECSuccess. Subtracting one results
12432 * in the MSB being set to one iff it was zero before. */ 12813 * in the MSB being set to one iff it was zero before. */
(...skipping 14 matching lines...) Expand all
12447 static unsigned char 12828 static unsigned char
12448 ssl_ConstantTimeEQ8(unsigned char a, unsigned char b) 12829 ssl_ConstantTimeEQ8(unsigned char a, unsigned char b)
12449 { 12830 {
12450 unsigned int c = a ^ b; 12831 unsigned int c = a ^ b;
12451 c--; 12832 c--;
12452 return DUPLICATE_MSB_TO_ALL_8(c); 12833 return DUPLICATE_MSB_TO_ALL_8(c);
12453 } 12834 }
12454 12835
12455 static SECStatus 12836 static SECStatus
12456 ssl_RemoveSSLv3CBCPadding(sslBuffer *plaintext, 12837 ssl_RemoveSSLv3CBCPadding(sslBuffer *plaintext,
12457 » » » unsigned int blockSize, 12838 unsigned int blockSize,
12458 » » » unsigned int macSize) 12839 unsigned int macSize)
12459 { 12840 {
12460 unsigned int paddingLength, good, t; 12841 unsigned int paddingLength, good, t;
12461 const unsigned int overhead = 1 /* padding length byte */ + macSize; 12842 const unsigned int overhead = 1 /* padding length byte */ + macSize;
12462 12843
12463 /* These lengths are all public so we can test them in non-constant 12844 /* These lengths are all public so we can test them in non-constant
12464 * time. */ 12845 * time. */
12465 if (overhead > plaintext->len) { 12846 if (overhead > plaintext->len) {
12466 » return SECFailure; 12847 return SECFailure;
12467 } 12848 }
12468 12849
12469 paddingLength = plaintext->buf[plaintext->len-1]; 12850 paddingLength = plaintext->buf[plaintext->len - 1];
12470 /* SSLv3 padding bytes are random and cannot be checked. */ 12851 /* SSLv3 padding bytes are random and cannot be checked. */
12471 t = plaintext->len; 12852 t = plaintext->len;
12472 t -= paddingLength+overhead; 12853 t -= paddingLength + overhead;
12473 /* If len >= paddingLength+overhead then the MSB of t is zero. */ 12854 /* If len >= paddingLength+overhead then the MSB of t is zero. */
12474 good = DUPLICATE_MSB_TO_ALL(~t); 12855 good = DUPLICATE_MSB_TO_ALL(~t);
12475 /* SSLv3 requires that the padding is minimal. */ 12856 /* SSLv3 requires that the padding is minimal. */
12476 t = blockSize - (paddingLength+1); 12857 t = blockSize - (paddingLength + 1);
12477 good &= DUPLICATE_MSB_TO_ALL(~t); 12858 good &= DUPLICATE_MSB_TO_ALL(~t);
12478 plaintext->len -= good & (paddingLength+1); 12859 plaintext->len -= good & (paddingLength + 1);
12479 return (good & SECSuccess) | (~good & SECFailure); 12860 return (good & SECSuccess) | (~good & SECFailure);
12480 } 12861 }
12481 12862
12482 static SECStatus 12863 static SECStatus
12483 ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize) 12864 ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize)
12484 { 12865 {
12485 unsigned int paddingLength, good, t, toCheck, i; 12866 unsigned int paddingLength, good, t, toCheck, i;
12486 const unsigned int overhead = 1 /* padding length byte */ + macSize; 12867 const unsigned int overhead = 1 /* padding length byte */ + macSize;
12487 12868
12488 /* These lengths are all public so we can test them in non-constant 12869 /* These lengths are all public so we can test them in non-constant
12489 * time. */ 12870 * time. */
12490 if (overhead > plaintext->len) { 12871 if (overhead > plaintext->len) {
12491 » return SECFailure; 12872 return SECFailure;
12492 } 12873 }
12493 12874
12494 paddingLength = plaintext->buf[plaintext->len-1]; 12875 paddingLength = plaintext->buf[plaintext->len - 1];
12495 t = plaintext->len; 12876 t = plaintext->len;
12496 t -= paddingLength+overhead; 12877 t -= paddingLength + overhead;
12497 /* If len >= paddingLength+overhead then the MSB of t is zero. */ 12878 /* If len >= paddingLength+overhead then the MSB of t is zero. */
12498 good = DUPLICATE_MSB_TO_ALL(~t); 12879 good = DUPLICATE_MSB_TO_ALL(~t);
12499 12880
12500 /* The padding consists of a length byte at the end of the record and then 12881 /* The padding consists of a length byte at the end of the record and then
12501 * that many bytes of padding, all with the same value as the length byte. 12882 * that many bytes of padding, all with the same value as the length byte.
12502 * Thus, with the length byte included, there are paddingLength+1 bytes of 12883 * Thus, with the length byte included, there are paddingLength+1 bytes of
12503 * padding. 12884 * padding.
12504 * 12885 *
12505 * We can't check just |paddingLength+1| bytes because that leaks 12886 * We can't check just |paddingLength+1| bytes because that leaks
12506 * decrypted information. Therefore we always have to check the maximum 12887 * decrypted information. Therefore we always have to check the maximum
12507 * amount of padding possible. (Again, the length of the record is 12888 * amount of padding possible. (Again, the length of the record is
12508 * public information so we can use it.) */ 12889 * public information so we can use it.) */
12509 toCheck = 255; /* maximum amount of padding. */ 12890 toCheck = 255; /* maximum amount of padding. */
12510 if (toCheck > plaintext->len-1) { 12891 if (toCheck > plaintext->len - 1) {
12511 » toCheck = plaintext->len-1; 12892 toCheck = plaintext->len - 1;
12512 } 12893 }
12513 12894
12514 for (i = 0; i < toCheck; i++) { 12895 for (i = 0; i < toCheck; i++) {
12515 » unsigned int t = paddingLength - i; 12896 unsigned int t = paddingLength - i;
12516 » /* If i <= paddingLength then the MSB of t is zero and mask is 12897 /* If i <= paddingLength then the MSB of t is zero and mask is
12517 » * 0xff. Otherwise, mask is 0. */ 12898 * 0xff. Otherwise, mask is 0. */
12518 » unsigned char mask = DUPLICATE_MSB_TO_ALL(~t); 12899 unsigned char mask = DUPLICATE_MSB_TO_ALL(~t);
12519 » unsigned char b = plaintext->buf[plaintext->len-1-i]; 12900 unsigned char b = plaintext->buf[plaintext->len - 1 - i];
12520 » /* The final |paddingLength+1| bytes should all have the value 12901 /* The final |paddingLength+1| bytes should all have the value
12521 » * |paddingLength|. Therefore the XOR should be zero. */ 12902 * |paddingLength|. Therefore the XOR should be zero. */
12522 » good &= ~(mask&(paddingLength ^ b)); 12903 good &= ~(mask & (paddingLength ^ b));
12523 } 12904 }
12524 12905
12525 /* If any of the final |paddingLength+1| bytes had the wrong value, 12906 /* If any of the final |paddingLength+1| bytes had the wrong value,
12526 * one or more of the lower eight bits of |good| will be cleared. We 12907 * one or more of the lower eight bits of |good| will be cleared. We
12527 * AND the bottom 8 bits together and duplicate the result to all the 12908 * AND the bottom 8 bits together and duplicate the result to all the
12528 * bits. */ 12909 * bits. */
12529 good &= good >> 4; 12910 good &= good >> 4;
12530 good &= good >> 2; 12911 good &= good >> 2;
12531 good &= good >> 1; 12912 good &= good >> 1;
12532 good <<= sizeof(good)*8-1; 12913 good <<= sizeof(good) * 8 - 1;
12533 good = DUPLICATE_MSB_TO_ALL(good); 12914 good = DUPLICATE_MSB_TO_ALL(good);
12534 12915
12535 plaintext->len -= good & (paddingLength+1); 12916 plaintext->len -= good & (paddingLength + 1);
12536 return (good & SECSuccess) | (~good & SECFailure); 12917 return (good & SECSuccess) | (~good & SECFailure);
12537 } 12918 }
12538 12919
12539 /* On entry: 12920 /* On entry:
12540 * originalLength >= macSize 12921 * originalLength >= macSize
12541 * macSize <= MAX_MAC_LENGTH 12922 * macSize <= MAX_MAC_LENGTH
12542 * plaintext->len >= macSize 12923 * plaintext->len >= macSize
12543 */ 12924 */
12544 static void 12925 static void
12545 ssl_CBCExtractMAC(sslBuffer *plaintext, 12926 ssl_CBCExtractMAC(sslBuffer *plaintext,
12546 » » unsigned int originalLength, 12927 unsigned int originalLength,
12547 » » SSL3Opaque* out, 12928 SSL3Opaque *out,
12548 » » unsigned int macSize) 12929 unsigned int macSize)
12549 { 12930 {
12550 unsigned char rotatedMac[MAX_MAC_LENGTH]; 12931 unsigned char rotatedMac[MAX_MAC_LENGTH];
12551 /* macEnd is the index of |plaintext->buf| just after the end of the 12932 /* macEnd is the index of |plaintext->buf| just after the end of the
12552 * MAC. */ 12933 * MAC. */
12553 unsigned macEnd = plaintext->len; 12934 unsigned macEnd = plaintext->len;
12554 unsigned macStart = macEnd - macSize; 12935 unsigned macStart = macEnd - macSize;
12555 /* scanStart contains the number of bytes that we can ignore because 12936 /* scanStart contains the number of bytes that we can ignore because
12556 * the MAC's position can only vary by 255 bytes. */ 12937 * the MAC's position can only vary by 255 bytes. */
12557 unsigned scanStart = 0; 12938 unsigned scanStart = 0;
12558 unsigned i, j, divSpoiler; 12939 unsigned i, j, divSpoiler;
12559 unsigned char rotateOffset; 12940 unsigned char rotateOffset;
12560 12941
12561 if (originalLength > macSize + 255 + 1) 12942 if (originalLength > macSize + 255 + 1)
12562 » scanStart = originalLength - (macSize + 255 + 1); 12943 scanStart = originalLength - (macSize + 255 + 1);
12563 12944
12564 /* divSpoiler contains a multiple of macSize that is used to cause the 12945 /* divSpoiler contains a multiple of macSize that is used to cause the
12565 * modulo operation to be constant time. Without this, the time varies 12946 * modulo operation to be constant time. Without this, the time varies
12566 * based on the amount of padding when running on Intel chips at least. 12947 * based on the amount of padding when running on Intel chips at least.
12567 * 12948 *
12568 * The aim of right-shifting macSize is so that the compiler doesn't 12949 * The aim of right-shifting macSize is so that the compiler doesn't
12569 * figure out that it can remove divSpoiler as that would require it 12950 * figure out that it can remove divSpoiler as that would require it
12570 * to prove that macSize is always even, which I hope is beyond it. */ 12951 * to prove that macSize is always even, which I hope is beyond it. */
12571 divSpoiler = macSize >> 1; 12952 divSpoiler = macSize >> 1;
12572 divSpoiler <<= (sizeof(divSpoiler)-1)*8; 12953 divSpoiler <<= (sizeof(divSpoiler) - 1) * 8;
12573 rotateOffset = (divSpoiler + macStart - scanStart) % macSize; 12954 rotateOffset = (divSpoiler + macStart - scanStart) % macSize;
12574 12955
12575 memset(rotatedMac, 0, macSize); 12956 memset(rotatedMac, 0, macSize);
12576 for (i = scanStart; i < originalLength;) { 12957 for (i = scanStart; i < originalLength;) {
12577 » for (j = 0; j < macSize && i < originalLength; i++, j++) { 12958 for (j = 0; j < macSize && i < originalLength; i++, j++) {
12578 » unsigned char macStarted = ssl_ConstantTimeGE(i, macStart); 12959 unsigned char macStarted = ssl_ConstantTimeGE(i, macStart);
12579 » unsigned char macEnded = ssl_ConstantTimeGE(i, macEnd); 12960 unsigned char macEnded = ssl_ConstantTimeGE(i, macEnd);
12580 » unsigned char b = 0; 12961 unsigned char b = 0;
12581 » b = plaintext->buf[i]; 12962 b = plaintext->buf[i];
12582 » rotatedMac[j] |= b & macStarted & ~macEnded; 12963 rotatedMac[j] |= b & macStarted & ~macEnded;
12583 » } 12964 }
12584 } 12965 }
12585 12966
12586 /* Now rotate the MAC. If we knew that the MAC fit into a CPU cache line 12967 /* Now rotate the MAC. If we knew that the MAC fit into a CPU cache line
12587 * we could line-align |rotatedMac| and rotate in place. */ 12968 * we could line-align |rotatedMac| and rotate in place. */
12588 memset(out, 0, macSize); 12969 memset(out, 0, macSize);
12589 for (i = 0; i < macSize; i++) { 12970 for (i = 0; i < macSize; i++) {
12590 » unsigned char offset = 12971 unsigned char offset =
12591 » (divSpoiler + macSize - rotateOffset + i) % macSize; 12972 (divSpoiler + macSize - rotateOffset + i) % macSize;
12592 » for (j = 0; j < macSize; j++) { 12973 for (j = 0; j < macSize; j++) {
12593 » out[j] |= rotatedMac[i] & ssl_ConstantTimeEQ8(j, offset); 12974 out[j] |= rotatedMac[i] & ssl_ConstantTimeEQ8(j, offset);
12594 » } 12975 }
12595 } 12976 }
12596 } 12977 }
12597 12978
12979 /* Unprotect an SSL3 record and leave the result in plaintext.
12980 *
12981 * If SECFailure is returned, we:
12982 * 1. Set |*alert| to the alert to be sent.
12983 * 2. Call PORT_SetError() with an appropriate code.
12984 *
12985 * Called by ssl3_HandleRecord. Caller must hold the spec read lock.
12986 * Therefore, we MUST not call SSL3_SendAlert().
12987 *
12988 */
12989 static SECStatus
12990 ssl3_UnprotectRecord(sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *plaintext,
12991 SSL3AlertDescription *alert)
12992 {
12993 ssl3CipherSpec *crSpec = ss->ssl3.crSpec;
12994 const ssl3BulkCipherDef *cipher_def = crSpec->cipher_def;
12995 PRBool isTLS;
12996 unsigned int good;
12997 unsigned int ivLen = 0;
12998 SSL3ContentType rType;
12999 unsigned int minLength;
13000 unsigned int originalLen = 0;
13001 unsigned char header[13];
13002 unsigned int headerLen;
13003 SSL3Opaque hash[MAX_MAC_LENGTH];
13004 SSL3Opaque givenHashBuf[MAX_MAC_LENGTH];
13005 SSL3Opaque *givenHash;
13006 unsigned int hashBytes = MAX_MAC_LENGTH + 1;
13007 SECStatus rv;
13008
13009 good = ~0U;
13010 minLength = crSpec->mac_size;
13011 if (cipher_def->type == type_block) {
13012 /* CBC records have a padding length byte at the end. */
13013 minLength++;
13014 if (crSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
13015 /* With >= TLS 1.1, CBC records have an explicit IV. */
13016 minLength += cipher_def->iv_size;
13017 }
13018 } else if (cipher_def->type == type_aead) {
13019 minLength = cipher_def->explicit_nonce_size + cipher_def->tag_size;
13020 }
13021
13022 /* We can perform this test in variable time because the record's total
13023 * length and the ciphersuite are both public knowledge. */
13024 if (cText->buf->len < minLength) {
13025 goto decrypt_loser;
13026 }
13027
13028 if (cipher_def->type == type_block &&
13029 crSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
13030 /* Consume the per-record explicit IV. RFC 4346 Section 6.2.3.2 states
13031 * "The receiver decrypts the entire GenericBlockCipher structure and
13032 * then discards the first cipher block corresponding to the IV
13033 * component." Instead, we decrypt the first cipher block and then
13034 * discard it before decrypting the rest.
13035 */
13036 SSL3Opaque iv[MAX_IV_LENGTH];
13037 int decoded;
13038
13039 ivLen = cipher_def->iv_size;
13040 if (ivLen < 8 || ivLen > sizeof(iv)) {
13041 *alert = internal_error;
13042 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
13043 return SECFailure;
13044 }
13045
13046 PRINT_BUF(80, (ss, "IV (ciphertext):", cText->buf->buf, ivLen));
13047
13048 /* The decryption result is garbage, but since we just throw away
13049 * the block it doesn't matter. The decryption of the next block
13050 * depends only on the ciphertext of the IV block.
13051 */
13052 rv = crSpec->decode(crSpec->decodeContext, iv, &decoded,
13053 sizeof(iv), cText->buf->buf, ivLen);
13054
13055 good &= SECStatusToMask(rv);
13056 }
13057
13058 PRINT_BUF(80, (ss, "ciphertext:", cText->buf->buf + ivLen,
13059 cText->buf->len - ivLen));
13060
13061 isTLS = (PRBool)(crSpec->version > SSL_LIBRARY_VERSION_3_0);
13062
13063 if (isTLS && cText->buf->len - ivLen > (MAX_FRAGMENT_LENGTH + 2048)) {
13064 *alert = record_overflow;
13065 PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
13066 return SECFailure;
13067 }
13068
13069 rType = cText->type;
13070 if (cipher_def->type == type_aead) {
13071 /* XXX For many AEAD ciphers, the plaintext is shorter than the
13072 * ciphertext by a fixed byte count, but it is not true in general.
13073 * Each AEAD cipher should provide a function that returns the
13074 * plaintext length for a given ciphertext. */
13075 unsigned int decryptedLen =
13076 cText->buf->len - cipher_def->explicit_nonce_size -
13077 cipher_def->tag_size;
13078 headerLen = ssl3_BuildRecordPseudoHeader(
13079 header, IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num,
13080 rType, isTLS, cText->version, IS_DTLS(ss), decryptedLen);
13081 PORT_Assert(headerLen <= sizeof(header));
13082 rv = crSpec->aead(
13083 ss->sec.isServer ? &crSpec->client : &crSpec->server,
13084 PR_TRUE, /* do decrypt */
13085 plaintext->buf, /* out */
13086 (int *)&plaintext->len, /* outlen */
13087 plaintext->space, /* maxout */
13088 cText->buf->buf, /* in */
13089 cText->buf->len, /* inlen */
13090 header, headerLen);
13091 if (rv != SECSuccess) {
13092 good = 0;
13093 }
13094 } else {
13095 if (cipher_def->type == type_block &&
13096 ((cText->buf->len - ivLen) % cipher_def->block_size) != 0) {
13097 goto decrypt_loser;
13098 }
13099
13100 /* decrypt from cText buf to plaintext. */
13101 rv = crSpec->decode(
13102 crSpec->decodeContext, plaintext->buf, (int *)&plaintext->len,
13103 plaintext->space, cText->buf->buf + ivLen, cText->buf->len - ivLen);
13104 if (rv != SECSuccess) {
13105 goto decrypt_loser;
13106 }
13107
13108 PRINT_BUF(80, (ss, "cleartext:", plaintext->buf, plaintext->len));
13109
13110 originalLen = plaintext->len;
13111
13112 /* If it's a block cipher, check and strip the padding. */
13113 if (cipher_def->type == type_block) {
13114 const unsigned int blockSize = cipher_def->block_size;
13115 const unsigned int macSize = crSpec->mac_size;
13116
13117 if (!isTLS) {
13118 good &= SECStatusToMask(ssl_RemoveSSLv3CBCPadding(
13119 plaintext, blockSize, macSize));
13120 } else {
13121 good &= SECStatusToMask(ssl_RemoveTLSCBCPadding(
13122 plaintext, macSize));
13123 }
13124 }
13125
13126 /* compute the MAC */
13127 headerLen = ssl3_BuildRecordPseudoHeader(
13128 header, IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num,
13129 rType, isTLS, cText->version, IS_DTLS(ss),
13130 plaintext->len - crSpec->mac_size);
13131 PORT_Assert(headerLen <= sizeof(header));
13132 if (cipher_def->type == type_block) {
13133 rv = ssl3_ComputeRecordMACConstantTime(
13134 crSpec, (PRBool)(!ss->sec.isServer), header, headerLen,
13135 plaintext->buf, plaintext->len, originalLen,
13136 hash, &hashBytes);
13137
13138 ssl_CBCExtractMAC(plaintext, originalLen, givenHashBuf,
13139 crSpec->mac_size);
13140 givenHash = givenHashBuf;
13141
13142 /* plaintext->len will always have enough space to remove the MAC
13143 * because in ssl_Remove{SSLv3|TLS}CBCPadding we only adjust
13144 * plaintext->len if the result has enough space for the MAC and we
13145 * tested the unadjusted size against minLength, above. */
13146 plaintext->len -= crSpec->mac_size;
13147 } else {
13148 /* This is safe because we checked the minLength above. */
13149 plaintext->len -= crSpec->mac_size;
13150
13151 rv = ssl3_ComputeRecordMAC(
13152 crSpec, (PRBool)(!ss->sec.isServer), header, headerLen,
13153 plaintext->buf, plaintext->len, hash, &hashBytes);
13154
13155 /* We can read the MAC directly from the record because its location
13156 * is public when a stream cipher is used. */
13157 givenHash = plaintext->buf + plaintext->len;
13158 }
13159
13160 good &= SECStatusToMask(rv);
13161
13162 if (hashBytes != (unsigned)crSpec->mac_size ||
13163 NSS_SecureMemcmp(givenHash, hash, crSpec->mac_size) != 0) {
13164 /* We're allowed to leak whether or not the MAC check was correct */
13165 good = 0;
13166 }
13167 }
13168
13169 if (good == 0) {
13170 decrypt_loser:
13171 /* always log mac error, in case attacker can read server logs. */
13172 PORT_SetError(SSL_ERROR_BAD_MAC_READ);
13173 *alert = bad_record_mac;
13174 return SECFailure;
13175 }
13176 return SECSuccess;
13177 }
13178
12598 /* if cText is non-null, then decipher, check MAC, and decompress the 13179 /* if cText is non-null, then decipher, check MAC, and decompress the
12599 * SSL record from cText->buf (typically gs->inbuf) 13180 * SSL record from cText->buf (typically gs->inbuf)
12600 * into databuf (typically gs->buf), and any previous contents of databuf 13181 * into databuf (typically gs->buf), and any previous contents of databuf
12601 * is lost. Then handle databuf according to its SSL record type, 13182 * is lost. Then handle databuf according to its SSL record type,
12602 * unless it's an application record. 13183 * unless it's an application record.
12603 * 13184 *
12604 * If cText is NULL, then the ciphertext has previously been deciphered and 13185 * If cText is NULL, then the ciphertext has previously been deciphered and
12605 * checked, and is already sitting in databuf. It is processed as an SSL 13186 * checked, and is already sitting in databuf. It is processed as an SSL
12606 * Handshake message. 13187 * Handshake message.
12607 * 13188 *
12608 * DOES NOT process the decrypted/decompressed application data. 13189 * DOES NOT process the decrypted/decompressed application data.
12609 * On return, databuf contains the decrypted/decompressed record. 13190 * On return, databuf contains the decrypted/decompressed record.
12610 * 13191 *
12611 * Called from ssl3_GatherCompleteHandshake 13192 * Called from ssl3_GatherCompleteHandshake
12612 * ssl3_RestartHandshakeAfterCertReq 13193 * ssl3_RestartHandshakeAfterCertReq
12613 * 13194 *
12614 * Caller must hold the RecvBufLock. 13195 * Caller must hold the RecvBufLock.
12615 * 13196 *
12616 * This function aquires and releases the SSL3Handshake Lock, holding the 13197 * This function aquires and releases the SSL3Handshake Lock, holding the
12617 * lock around any calls to functions that handle records other than 13198 * lock around any calls to functions that handle records other than
12618 * Application Data records. 13199 * Application Data records.
12619 */ 13200 */
12620 SECStatus 13201 SECStatus
12621 ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *databuf) 13202 ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *databuf)
12622 { 13203 {
12623 const ssl3BulkCipherDef *cipher_def; 13204 SECStatus rv;
12624 ssl3CipherSpec * crSpec; 13205 PRBool isTLS;
12625 SECStatus rv; 13206 PRUint64 dtls_seq_num = 0;
12626 unsigned int hashBytes = MAX_MAC_LENGTH + 1; 13207 ssl3CipherSpec *crSpec;
12627 PRBool isTLS; 13208 SSL3ContentType rType;
12628 SSL3ContentType rType; 13209 sslBuffer *plaintext;
12629 SSL3Opaque hash[MAX_MAC_LENGTH]; 13210 sslBuffer temp_buf;
12630 SSL3Opaque givenHashBuf[MAX_MAC_LENGTH]; 13211 SSL3AlertDescription alert;
12631 SSL3Opaque *givenHash; 13212 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
12632 sslBuffer *plaintext;
12633 sslBuffer temp_buf;
12634 PRUint64 dtls_seq_num = 0;
12635 unsigned int ivLen = 0;
12636 unsigned int originalLen = 0;
12637 unsigned int good;
12638 unsigned int minLength;
12639 unsigned char header[13];
12640 unsigned int headerLen;
12641
12642 PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
12643 13213
12644 if (!ss->ssl3.initialized) { 13214 if (!ss->ssl3.initialized) {
12645 » ssl_GetSSL3HandshakeLock(ss); 13215 ssl_GetSSL3HandshakeLock(ss);
12646 » rv = ssl3_InitState(ss); 13216 rv = ssl3_InitState(ss);
12647 » ssl_ReleaseSSL3HandshakeLock(ss); 13217 ssl_ReleaseSSL3HandshakeLock(ss);
12648 » if (rv != SECSuccess) { 13218 if (rv != SECSuccess) {
12649 » return rv;» » /* ssl3_InitState has set the error code. */ 13219 return rv; /* ssl3_InitState has set the error code. */
12650 » } 13220 }
12651 } 13221 }
12652 13222
12653 /* check for Token Presence */ 13223 /* check for Token Presence */
12654 if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) { 13224 if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
12655 » PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); 13225 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
12656 » return SECFailure; 13226 return SECFailure;
12657 } 13227 }
12658 13228
12659 /* cText is NULL when we're called from ssl3_RestartHandshakeAfterXXX(). 13229 /* cText is NULL when we're called from ssl3_RestartHandshakeAfterXXX().
12660 * This implies that databuf holds a previously deciphered SSL Handshake 13230 * This implies that databuf holds a previously deciphered SSL Handshake
12661 * message. 13231 * message.
12662 */ 13232 */
12663 if (cText == NULL) { 13233 if (cText == NULL) {
12664 » SSL_DBG(("%d: SSL3[%d]: HandleRecord, resuming handshake", 13234 SSL_DBG(("%d: SSL3[%d]: HandleRecord, resuming handshake",
12665 » » SSL_GETPID(), ss->fd)); 13235 SSL_GETPID(), ss->fd));
12666 » rType = content_handshake; 13236 rType = content_handshake;
12667 » goto process_it; 13237 goto process_it;
12668 } 13238 }
12669 13239
12670 ssl_GetSpecReadLock(ss); /******************************************/ 13240 ssl_GetSpecReadLock(ss); /******************************************/
13241 crSpec = ss->ssl3.crSpec;
13242 isTLS = (PRBool)(crSpec->version > SSL_LIBRARY_VERSION_3_0);
12671 13243
12672 crSpec = ss->ssl3.crSpec;
12673 cipher_def = crSpec->cipher_def;
12674
12675 /*
12676 * DTLS relevance checks:
12677 * Note that this code currently ignores all out-of-epoch packets,
12678 * which means we lose some in the case of rehandshake +
12679 * loss/reordering. Since DTLS is explicitly unreliable, this
12680 * seems like a good tradeoff for implementation effort and is
12681 * consistent with the guidance of RFC 6347 Sections 4.1 and 4.2.4.1
12682 */
12683 if (IS_DTLS(ss)) { 13244 if (IS_DTLS(ss)) {
12684 » DTLSEpoch epoch = (cText->seq_num.high >> 16) & 0xffff; 13245 if (!dtls_IsRelevant(ss, crSpec, cText, &dtls_seq_num)) {
12685 » 13246 ssl_ReleaseSpecReadLock(ss);
12686 » if (crSpec->epoch != epoch) { 13247 /* Silently drop the packet */
12687 » ssl_ReleaseSpecReadLock(ss);
12688 » SSL_DBG(("%d: SSL3[%d]: HandleRecord, received packet "
12689 » » "from irrelevant epoch %d", SSL_GETPID(), ss->fd, epoch));
12690 » /* Silently drop the packet */
12691 databuf->len = 0; /* Needed to ensure data not left around */ 13248 databuf->len = 0; /* Needed to ensure data not left around */
12692 » return SECSuccess; 13249 return SECSuccess;
12693 » } 13250 }
12694
12695 » dtls_seq_num = (((PRUint64)(cText->seq_num.high & 0xffff)) << 32) |
12696 » » » ((PRUint64)cText->seq_num.low);
12697
12698 » if (dtls_RecordGetRecvd(&crSpec->recvdRecords, dtls_seq_num) != 0) {
12699 » ssl_ReleaseSpecReadLock(ss);
12700 » SSL_DBG(("%d: SSL3[%d]: HandleRecord, rejecting "
12701 » » "potentially replayed packet", SSL_GETPID(), ss->fd));
12702 » /* Silently drop the packet */
12703 databuf->len = 0; /* Needed to ensure data not left around */
12704 » return SECSuccess;
12705 » }
12706 }
12707
12708 good = ~0U;
12709 minLength = crSpec->mac_size;
12710 if (cipher_def->type == type_block) {
12711 » /* CBC records have a padding length byte at the end. */
12712 » minLength++;
12713 » if (crSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
12714 » /* With >= TLS 1.1, CBC records have an explicit IV. */
12715 » minLength += cipher_def->iv_size;
12716 » }
12717 } else if (cipher_def->type == type_aead) {
12718 » minLength = cipher_def->explicit_nonce_size + cipher_def->tag_size;
12719 }
12720
12721 /* We can perform this test in variable time because the record's total
12722 * length and the ciphersuite are both public knowledge. */
12723 if (cText->buf->len < minLength) {
12724 » goto decrypt_loser;
12725 }
12726
12727 if (cipher_def->type == type_block &&
12728 » crSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
12729 » /* Consume the per-record explicit IV. RFC 4346 Section 6.2.3.2 states
12730 » * "The receiver decrypts the entire GenericBlockCipher structure and
12731 » * then discards the first cipher block corresponding to the IV
12732 » * component." Instead, we decrypt the first cipher block and then
12733 » * discard it before decrypting the rest.
12734 » */
12735 » SSL3Opaque iv[MAX_IV_LENGTH];
12736 » int decoded;
12737
12738 » ivLen = cipher_def->iv_size;
12739 » if (ivLen < 8 || ivLen > sizeof(iv)) {
12740 » ssl_ReleaseSpecReadLock(ss);
12741 » PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
12742 » return SECFailure;
12743 » }
12744
12745 » PRINT_BUF(80, (ss, "IV (ciphertext):", cText->buf->buf, ivLen));
12746
12747 » /* The decryption result is garbage, but since we just throw away
12748 » * the block it doesn't matter. The decryption of the next block
12749 » * depends only on the ciphertext of the IV block.
12750 » */
12751 » rv = crSpec->decode(crSpec->decodeContext, iv, &decoded,
12752 » » » sizeof(iv), cText->buf->buf, ivLen);
12753
12754 » good &= SECStatusToMask(rv);
12755 } 13251 }
12756 13252
12757 /* If we will be decompressing the buffer we need to decrypt somewhere 13253 /* If we will be decompressing the buffer we need to decrypt somewhere
12758 * other than into databuf */ 13254 * other than into databuf */
12759 if (crSpec->decompressor) { 13255 if (crSpec->decompressor) {
12760 » temp_buf.buf = NULL; 13256 temp_buf.buf = NULL;
12761 » temp_buf.space = 0; 13257 temp_buf.space = 0;
12762 » plaintext = &temp_buf; 13258 plaintext = &temp_buf;
12763 } else { 13259 } else {
12764 » plaintext = databuf; 13260 plaintext = databuf;
12765 } 13261 }
12766 13262
12767 plaintext->len = 0; /* filled in by decode call below. */ 13263 plaintext->len = 0; /* filled in by Unprotect call below. */
12768 if (plaintext->space < MAX_FRAGMENT_LENGTH) { 13264 if (plaintext->space < MAX_FRAGMENT_LENGTH) {
12769 » rv = sslBuffer_Grow(plaintext, MAX_FRAGMENT_LENGTH + 2048); 13265 rv = sslBuffer_Grow(plaintext, MAX_FRAGMENT_LENGTH + 2048);
12770 » if (rv != SECSuccess) { 13266 if (rv != SECSuccess) {
12771 » ssl_ReleaseSpecReadLock(ss); 13267 ssl_ReleaseSpecReadLock(ss);
12772 » SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes", 13268 SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes",
12773 » » SSL_GETPID(), ss->fd, MAX_FRAGMENT_LENGTH + 2048)); 13269 SSL_GETPID(), ss->fd, MAX_FRAGMENT_LENGTH + 2048));
12774 » /* sslBuffer_Grow has set a memory error code. */ 13270 /* sslBuffer_Grow has set a memory error code. */
12775 » /* Perhaps we should send an alert. (but we have no memory!) */ 13271 /* Perhaps we should send an alert. (but we have no memory!) */
12776 » return SECFailure; 13272 return SECFailure;
12777 » } 13273 }
12778 } 13274 }
12779 13275
12780 PRINT_BUF(80, (ss, "ciphertext:", cText->buf->buf + ivLen, 13276 /* IMPORTANT: Unprotect functions MUST NOT send alerts
12781 » » » » cText->buf->len - ivLen)); 13277 * because we still hold the spec read lock. Instead, if they
12782 13278 * return SECFailure, they set *alert to the alert to be sent. */
12783 isTLS = (PRBool)(crSpec->version > SSL_LIBRARY_VERSION_3_0); 13279 if (crSpec->version < SSL_LIBRARY_VERSION_TLS_1_3 ||
12784 13280 crSpec->cipher_def->calg == ssl_calg_null) {
12785 if (isTLS && cText->buf->len - ivLen > (MAX_FRAGMENT_LENGTH + 2048)) { 13281 /* Unencrypted TLS 1.3 records use the pre-TLS 1.3 format. */
12786 » ssl_ReleaseSpecReadLock(ss); 13282 rv = ssl3_UnprotectRecord(ss, cText, plaintext, &alert);
12787 » SSL3_SendAlert(ss, alert_fatal, record_overflow); 13283 } else {
12788 » PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG); 13284 rv = tls13_UnprotectRecord(ss, cText, plaintext, &alert);
12789 » return SECFailure;
12790 } 13285 }
12791 13286
12792 rType = cText->type; 13287 if (rv != SECSuccess) {
12793 if (cipher_def->type == type_aead) { 13288 ssl_ReleaseSpecReadLock(ss);
12794 » /* XXX For many AEAD ciphers, the plaintext is shorter than the
12795 » * ciphertext by a fixed byte count, but it is not true in general.
12796 » * Each AEAD cipher should provide a function that returns the
12797 » * plaintext length for a given ciphertext. */
12798 » unsigned int decryptedLen =
12799 » cText->buf->len - cipher_def->explicit_nonce_size -
12800 » cipher_def->tag_size;
12801 » headerLen = ssl3_BuildRecordPseudoHeader(
12802 » header, IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num,
12803 » rType, isTLS, cText->version, IS_DTLS(ss), decryptedLen);
12804 » PORT_Assert(headerLen <= sizeof(header));
12805 » rv = crSpec->aead(
12806 » » ss->sec.isServer ? &crSpec->client : &crSpec->server,
12807 » » PR_TRUE, /* do decrypt */
12808 » » plaintext->buf, /* out */
12809 » » (int*) &plaintext->len, /* outlen */
12810 » » plaintext->space, /* maxout */
12811 » » cText->buf->buf, /* in */
12812 » » cText->buf->len, /* inlen */
12813 » » header, headerLen);
12814 » if (rv != SECSuccess) {
12815 » good = 0;
12816 » }
12817 } else {
12818 » if (cipher_def->type == type_block &&
12819 » ((cText->buf->len - ivLen) % cipher_def->block_size) != 0) {
12820 » goto decrypt_loser;
12821 » }
12822 13289
12823 » /* decrypt from cText buf to plaintext. */ 13290 SSL_DBG(("%d: SSL3[%d]: decryption failed", SSL_GETPID(), ss->fd));
12824 » rv = crSpec->decode(
12825 » crSpec->decodeContext, plaintext->buf, (int *)&plaintext->len,
12826 » plaintext->space, cText->buf->buf + ivLen, cText->buf->len - ivLen);
12827 » if (rv != SECSuccess) {
12828 » goto decrypt_loser;
12829 » }
12830 13291
12831 » PRINT_BUF(80, (ss, "cleartext:", plaintext->buf, plaintext->len)); 13292 if (!IS_DTLS(ss)) {
12832 13293 int errCode = PORT_GetError();
12833 » originalLen = plaintext->len; 13294 SSL3_SendAlert(ss, alert_fatal, alert);
12834 13295 /* Reset the error code in case SSL3_SendAlert called
12835 » /* If it's a block cipher, check and strip the padding. */ 13296 * PORT_SetError(). */
12836 » if (cipher_def->type == type_block) { 13297 PORT_SetError(errCode);
12837 » const unsigned int blockSize = cipher_def->block_size; 13298 return SECFailure;
12838 » const unsigned int macSize = crSpec->mac_size; 13299 } else {
12839 13300 /* Silently drop the packet */
12840 » if (!isTLS) { 13301 databuf->len = 0; /* Needed to ensure data not left around */
12841 » » good &= SECStatusToMask(ssl_RemoveSSLv3CBCPadding( 13302 return SECSuccess;
12842 » » » plaintext, blockSize, macSize)); 13303 }
12843 » } else {
12844 » » good &= SECStatusToMask(ssl_RemoveTLSCBCPadding(
12845 » » » plaintext, macSize));
12846 » }
12847 » }
12848
12849 » /* compute the MAC */
12850 » headerLen = ssl3_BuildRecordPseudoHeader(
12851 » header, IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num,
12852 » rType, isTLS, cText->version, IS_DTLS(ss),
12853 » plaintext->len - crSpec->mac_size);
12854 » PORT_Assert(headerLen <= sizeof(header));
12855 » if (cipher_def->type == type_block) {
12856 » rv = ssl3_ComputeRecordMACConstantTime(
12857 » » crSpec, (PRBool)(!ss->sec.isServer), header, headerLen,
12858 » » plaintext->buf, plaintext->len, originalLen,
12859 » » hash, &hashBytes);
12860
12861 » ssl_CBCExtractMAC(plaintext, originalLen, givenHashBuf,
12862 » » » crSpec->mac_size);
12863 » givenHash = givenHashBuf;
12864
12865 » /* plaintext->len will always have enough space to remove the MAC
12866 » * because in ssl_Remove{SSLv3|TLS}CBCPadding we only adjust
12867 » * plaintext->len if the result has enough space for the MAC and we
12868 » * tested the unadjusted size against minLength, above. */
12869 » plaintext->len -= crSpec->mac_size;
12870 » } else {
12871 » /* This is safe because we checked the minLength above. */
12872 » plaintext->len -= crSpec->mac_size;
12873
12874 » rv = ssl3_ComputeRecordMAC(
12875 » » crSpec, (PRBool)(!ss->sec.isServer), header, headerLen,
12876 » » plaintext->buf, plaintext->len, hash, &hashBytes);
12877
12878 » /* We can read the MAC directly from the record because its location
12879 » * is public when a stream cipher is used. */
12880 » givenHash = plaintext->buf + plaintext->len;
12881 » }
12882
12883 » good &= SECStatusToMask(rv);
12884
12885 » if (hashBytes != (unsigned)crSpec->mac_size ||
12886 » NSS_SecureMemcmp(givenHash, hash, crSpec->mac_size) != 0) {
12887 » /* We're allowed to leak whether or not the MAC check was correct */
12888 » good = 0;
12889 » }
12890 } 13304 }
12891 13305
12892 if (good == 0) { 13306 /* SECSuccess */
12893 decrypt_loser:
12894 » /* must not hold spec lock when calling SSL3_SendAlert. */
12895 » ssl_ReleaseSpecReadLock(ss);
12896
12897 » SSL_DBG(("%d: SSL3[%d]: decryption failed", SSL_GETPID(), ss->fd));
12898
12899 » if (!IS_DTLS(ss)) {
12900 » SSL3_SendAlert(ss, alert_fatal, bad_record_mac);
12901 » /* always log mac error, in case attacker can read server logs. */
12902 » PORT_SetError(SSL_ERROR_BAD_MAC_READ);
12903 » return SECFailure;
12904 » } else {
12905 » /* Silently drop the packet */
12906 databuf->len = 0; /* Needed to ensure data not left around */
12907 » return SECSuccess;
12908 » }
12909 }
12910
12911 if (!IS_DTLS(ss)) { 13307 if (!IS_DTLS(ss)) {
12912 » ssl3_BumpSequenceNumber(&crSpec->read_seq_num); 13308 ssl3_BumpSequenceNumber(&crSpec->read_seq_num);
12913 } else { 13309 } else {
12914 » dtls_RecordSetRecvd(&crSpec->recvdRecords, dtls_seq_num); 13310 dtls_RecordSetRecvd(&crSpec->recvdRecords, dtls_seq_num);
12915 } 13311 }
12916 13312
12917 ssl_ReleaseSpecReadLock(ss); /*****************************************/ 13313 ssl_ReleaseSpecReadLock(ss); /*****************************************/
12918 13314
12919 /* 13315 /*
12920 * The decrypted data is now in plaintext. 13316 * The decrypted data is now in plaintext.
12921 */ 13317 */
13318 rType = cText->type; /* This must go after decryption because TLS 1.3
13319 * has encrypted content types. */
12922 13320
12923 /* possibly decompress the record. If we aren't using compression then 13321 /* possibly decompress the record. If we aren't using compression then
12924 * plaintext == databuf and so the uncompressed data is already in 13322 * plaintext == databuf and so the uncompressed data is already in
12925 * databuf. */ 13323 * databuf. */
12926 if (crSpec->decompressor) { 13324 if (crSpec->decompressor) {
12927 » if (databuf->space < plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION) { 13325 if (databuf->space < plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION) {
12928 » rv = sslBuffer_Grow( 13326 rv = sslBuffer_Grow(
12929 » databuf, plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION); 13327 databuf, plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION);
12930 » if (rv != SECSuccess) { 13328 if (rv != SECSuccess) {
12931 » » SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes", 13329 SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes",
12932 » » » SSL_GETPID(), ss->fd, 13330 SSL_GETPID(), ss->fd,
12933 » » » plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION)); 13331 plaintext->len +
12934 » » /* sslBuffer_Grow has set a memory error code. */ 13332 SSL3_COMPRESSION_MAX_EXPANSION));
12935 » » /* Perhaps we should send an alert. (but we have no memory!) */ 13333 /* sslBuffer_Grow has set a memory error code. */
12936 » » PORT_Free(plaintext->buf); 13334 /* Perhaps we should send an alert. (but we have no memory!) */
12937 » » return SECFailure; 13335 PORT_Free(plaintext->buf);
12938 » } 13336 return SECFailure;
12939 » } 13337 }
13338 }
12940 13339
12941 » rv = crSpec->decompressor(crSpec->decompressContext, 13340 rv = crSpec->decompressor(crSpec->decompressContext,
12942 » » » » databuf->buf, 13341 databuf->buf,
12943 » » » » (int*) &databuf->len, 13342 (int *)&databuf->len,
12944 » » » » databuf->space, 13343 databuf->space,
12945 » » » » plaintext->buf, 13344 plaintext->buf,
12946 » » » » plaintext->len); 13345 plaintext->len);
12947 13346
12948 » if (rv != SECSuccess) { 13347 if (rv != SECSuccess) {
12949 » int err = ssl_MapLowLevelError(SSL_ERROR_DECOMPRESSION_FAILURE); 13348 int err = ssl_MapLowLevelError(SSL_ERROR_DECOMPRESSION_FAILURE);
12950 » SSL3_SendAlert(ss, alert_fatal, 13349 SSL3_SendAlert(ss, alert_fatal,
12951 » » » isTLS ? decompression_failure : bad_record_mac); 13350 isTLS ? decompression_failure
13351 : bad_record_mac);
12952 13352
12953 » /* There appears to be a bug with (at least) Apache + OpenSSL where 13353 /* There appears to be a bug with (at least) Apache + OpenSSL where
12954 » * resumed SSLv3 connections don't actually use compression. See 13354 * resumed SSLv3 connections don't actually use compression. See
12955 » * comments 93-95 of 13355 * comments 93-95 of
12956 » * https://bugzilla.mozilla.org/show_bug.cgi?id=275744 13356 * https://bugzilla.mozilla.org/show_bug.cgi?id=275744
12957 » * 13357 *
12958 » * So, if we get a decompression error, and the record appears to 13358 * So, if we get a decompression error, and the record appears to
12959 » * be already uncompressed, then we return a more specific error 13359 * be already uncompressed, then we return a more specific error
12960 » * code to hopefully save somebody some debugging time in the 13360 * code to hopefully save somebody some debugging time in the
12961 » * future. 13361 * future.
12962 » */ 13362 */
12963 » if (plaintext->len >= 4) { 13363 if (plaintext->len >= 4) {
12964 » » unsigned int len = ((unsigned int) plaintext->buf[1] << 16) | 13364 unsigned int len = ((unsigned int)plaintext->buf[1] << 16) |
12965 » » ((unsigned int) plaintext->buf[2] << 8) | 13365 ((unsigned int)plaintext->buf[2] << 8) |
12966 » » (unsigned int) plaintext->buf[3]; 13366 (unsigned int)plaintext->buf[3];
12967 » » if (len == plaintext->len - 4) { 13367 if (len == plaintext->len - 4) {
12968 » » /* This appears to be uncompressed already */ 13368 /* This appears to be uncompressed already */
12969 » » err = SSL_ERROR_RX_UNEXPECTED_UNCOMPRESSED_RECORD; 13369 err = SSL_ERROR_RX_UNEXPECTED_UNCOMPRESSED_RECORD;
12970 » » } 13370 }
12971 » } 13371 }
12972 13372
12973 » PORT_Free(plaintext->buf); 13373 PORT_Free(plaintext->buf);
12974 » PORT_SetError(err); 13374 PORT_SetError(err);
12975 » return SECFailure; 13375 return SECFailure;
12976 » } 13376 }
12977 13377
12978 » PORT_Free(plaintext->buf); 13378 PORT_Free(plaintext->buf);
12979 } 13379 }
12980 13380
12981 /* 13381 /*
12982 ** Having completed the decompression, check the length again. 13382 ** Having completed the decompression, check the length again.
12983 */ 13383 */
12984 if (isTLS && databuf->len > (MAX_FRAGMENT_LENGTH + 1024)) { 13384 if (isTLS && databuf->len > (MAX_FRAGMENT_LENGTH + 1024)) {
12985 » SSL3_SendAlert(ss, alert_fatal, record_overflow); 13385 SSL3_SendAlert(ss, alert_fatal, record_overflow);
12986 » PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG); 13386 PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
12987 » return SECFailure; 13387 return SECFailure;
12988 } 13388 }
12989 13389
12990 /* Application data records are processed by the caller of this 13390 /* Application data records are processed by the caller of this
12991 ** function, not by this function. 13391 ** function, not by this function.
12992 */ 13392 */
12993 if (rType == content_application_data) { 13393 if (rType == content_application_data) {
12994 » if (ss->firstHsDone) 13394 if (ss->firstHsDone)
12995 » return SECSuccess; 13395 return SECSuccess;
12996 » (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 13396 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12997 » PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA); 13397 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA);
12998 » return SECFailure; 13398 return SECFailure;
12999 } 13399 }
13000 13400
13001 /* It's a record that must be handled by ssl itself, not the application. 13401 /* It's a record that must be handled by ssl itself, not the application.
13002 */ 13402 */
13003 process_it: 13403 process_it:
13004 /* XXX Get the xmit lock here. Odds are very high that we'll be xmiting 13404 /* XXX Get the xmit lock here. Odds are very high that we'll be xmiting
13005 * data ang getting the xmit lock here prevents deadlocks. 13405 * data ang getting the xmit lock here prevents deadlocks.
13006 */ 13406 */
13007 ssl_GetSSL3HandshakeLock(ss); 13407 ssl_GetSSL3HandshakeLock(ss);
13008 13408
13009 /* All the functions called in this switch MUST set error code if 13409 /* All the functions called in this switch MUST set error code if
13010 ** they return SECFailure or SECWouldBlock. 13410 ** they return SECFailure or SECWouldBlock.
13011 */ 13411 */
13012 switch (rType) { 13412 switch (rType) {
13013 case content_change_cipher_spec: 13413 case content_change_cipher_spec:
13014 » rv = ssl3_HandleChangeCipherSpecs(ss, databuf); 13414 rv = ssl3_HandleChangeCipherSpecs(ss, databuf);
13015 » break; 13415 break;
13016 case content_alert: 13416 case content_alert:
13017 » rv = ssl3_HandleAlert(ss, databuf); 13417 rv = ssl3_HandleAlert(ss, databuf);
13018 » break; 13418 break;
13019 case content_handshake: 13419 case content_handshake:
13020 » if (!IS_DTLS(ss)) { 13420 if (!IS_DTLS(ss)) {
13021 » rv = ssl3_HandleHandshake(ss, databuf); 13421 rv = ssl3_HandleHandshake(ss, databuf);
13022 » } else { 13422 } else {
13023 » rv = dtls_HandleHandshake(ss, databuf); 13423 rv = dtls_HandleHandshake(ss, databuf);
13024 » } 13424 }
13025 » break; 13425 break;
13026 /* 13426 /*
13027 case content_application_data is handled before this switch 13427 case content_application_data is handled before this switch
13028 */ 13428 */
13029 default: 13429 default:
13030 » SSL_DBG(("%d: SSL3[%d]: bogus content type=%d", 13430 SSL_DBG(("%d: SSL3[%d]: bogus content type=%d",
13031 » » SSL_GETPID(), ss->fd, cText->type)); 13431 SSL_GETPID(), ss->fd, cText->type));
13032 » /* XXX Send an alert ??? */ 13432 /* XXX Send an alert ??? */
13033 » PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE); 13433 PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE);
13034 » rv = SECFailure; 13434 rv = SECFailure;
13035 » break; 13435 break;
13036 } 13436 }
13037 13437
13038 ssl_ReleaseSSL3HandshakeLock(ss); 13438 ssl_ReleaseSSL3HandshakeLock(ss);
13039 return rv; 13439 return rv;
13040 } 13440 }
13041 13441
13042 /* 13442 /*
13043 * Initialization functions 13443 * Initialization functions
13044 */ 13444 */
13045 13445
13046 /* Called from ssl3_InitState, immediately below. */ 13446 /* Called from ssl3_InitState, immediately below. */
13047 /* Caller must hold the SpecWriteLock. */ 13447 /* Caller must hold the SpecWriteLock. */
13048 static void 13448 static void
13049 ssl3_InitCipherSpec(sslSocket *ss, ssl3CipherSpec *spec) 13449 ssl3_InitCipherSpec(sslSocket *ss, ssl3CipherSpec *spec)
13050 { 13450 {
13051 spec->cipher_def = &bulk_cipher_defs[cipher_null]; 13451 spec->cipher_def = &bulk_cipher_defs[cipher_null];
13052 PORT_Assert(spec->cipher_def->cipher == cipher_null); 13452 PORT_Assert(spec->cipher_def->cipher == cipher_null);
13053 spec->mac_def = &mac_defs[mac_null]; 13453 spec->mac_def = &mac_defs[mac_null];
13054 PORT_Assert(spec->mac_def->mac == mac_null); 13454 PORT_Assert(spec->mac_def->mac == mac_null);
13055 spec->encode = Null_Cipher; 13455 spec->encode = Null_Cipher;
13056 spec->decode = Null_Cipher; 13456 spec->decode = Null_Cipher;
13057 spec->destroy = NULL; 13457 spec->destroy = NULL;
13058 spec->compressor = NULL; 13458 spec->compressor = NULL;
13059 spec->decompressor = NULL; 13459 spec->decompressor = NULL;
13060 spec->destroyCompressContext = NULL; 13460 spec->destroyCompressContext = NULL;
13061 spec->destroyDecompressContext = NULL; 13461 spec->destroyDecompressContext = NULL;
13062 spec->mac_size = 0; 13462 spec->mac_size = 0;
13063 spec->master_secret = NULL; 13463 spec->master_secret = NULL;
13064 spec->bypassCiphers = PR_FALSE; 13464 spec->bypassCiphers = PR_FALSE;
13065 13465
13066 spec->msItem.data = NULL; 13466 spec->msItem.data = NULL;
13067 spec->msItem.len = 0; 13467 spec->msItem.len = 0;
13068 13468
13069 spec->client.write_key = NULL; 13469 spec->client.write_key = NULL;
13070 spec->client.write_mac_key = NULL; 13470 spec->client.write_mac_key = NULL;
13071 spec->client.write_mac_context = NULL; 13471 spec->client.write_mac_context = NULL;
13072 13472
13073 spec->server.write_key = NULL; 13473 spec->server.write_key = NULL;
13074 spec->server.write_mac_key = NULL; 13474 spec->server.write_mac_key = NULL;
13075 spec->server.write_mac_context = NULL; 13475 spec->server.write_mac_context = NULL;
13076 13476
13077 spec->write_seq_num.high = 0; 13477 spec->write_seq_num.high = 0;
13078 spec->write_seq_num.low = 0; 13478 spec->write_seq_num.low = 0;
13079 13479
13080 spec->read_seq_num.high = 0; 13480 spec->read_seq_num.high = 0;
13081 spec->read_seq_num.low = 0; 13481 spec->read_seq_num.low = 0;
13082 13482
13083 spec->epoch = 0; 13483 spec->epoch = 0;
13084 dtls_InitRecvdRecords(&spec->recvdRecords); 13484 dtls_InitRecvdRecords(&spec->recvdRecords);
13085 13485
13086 spec->version = ss->vrange.max; 13486 spec->version = ss->vrange.max;
13087 } 13487 }
13088 13488
13089 /* Called from:»ssl3_SendRecord 13489 /* Called from: ssl3_SendRecord
13090 **» » ssl3_StartHandshakeHash() <- ssl2_BeginClientHandshake() 13490 ** ssl3_StartHandshakeHash() <- ssl2_BeginClientHandshake()
13091 **» » ssl3_SendClientHello() 13491 ** ssl3_SendClientHello()
13092 **» » ssl3_HandleV2ClientHello() 13492 ** ssl3_HandleV2ClientHello()
13093 **» » ssl3_HandleRecord() 13493 ** ssl3_HandleRecord()
13094 ** 13494 **
13095 ** This function should perhaps acquire and release the SpecWriteLock. 13495 ** This function should perhaps acquire and release the SpecWriteLock.
13096 ** 13496 **
13097 ** 13497 **
13098 */ 13498 */
13099 static SECStatus 13499 static SECStatus
13100 ssl3_InitState(sslSocket *ss) 13500 ssl3_InitState(sslSocket *ss)
13101 { 13501 {
13102 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 13502 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
13103 13503
13104 if (ss->ssl3.initialized) 13504 if (ss->ssl3.initialized)
13105 » return SECSuccess;» /* Function should be idempotent */ 13505 return SECSuccess; /* Function should be idempotent */
13106 13506
13107 ss->ssl3.policy = SSL_ALLOWED; 13507 ss->ssl3.policy = SSL_ALLOWED;
13108 13508
13109 ssl_GetSpecWriteLock(ss); 13509 ssl_GetSpecWriteLock(ss);
13110 ss->ssl3.crSpec = ss->ssl3.cwSpec = &ss->ssl3.specs[0]; 13510 ss->ssl3.crSpec = ss->ssl3.cwSpec = &ss->ssl3.specs[0];
13111 ss->ssl3.prSpec = ss->ssl3.pwSpec = &ss->ssl3.specs[1]; 13511 ss->ssl3.prSpec = ss->ssl3.pwSpec = &ss->ssl3.specs[1];
13112 ss->ssl3.hs.sendingSCSV = PR_FALSE; 13512 ss->ssl3.hs.sendingSCSV = PR_FALSE;
13113 ssl3_InitCipherSpec(ss, ss->ssl3.crSpec); 13513 ssl3_InitCipherSpec(ss, ss->ssl3.crSpec);
13114 ssl3_InitCipherSpec(ss, ss->ssl3.prSpec); 13514 ssl3_InitCipherSpec(ss, ss->ssl3.prSpec);
13115 ss->ssl3.hs.preliminaryInfo = 0; 13515 ss->ssl3.hs.preliminaryInfo = 0;
13116 13516
13117 ss->ssl3.hs.ws = (ss->sec.isServer) ? wait_client_hello : wait_server_hello; 13517 ss->ssl3.hs.ws = (ss->sec.isServer) ? wait_client_hello : wait_server_hello;
13118 #ifndef NSS_DISABLE_ECC 13518 #ifndef NSS_DISABLE_ECC
13119 ss->ssl3.hs.negotiatedECCurves = ssl3_GetSupportedECCurveMask(ss); 13519 ss->ssl3.hs.negotiatedECCurves = ssl3_GetSupportedECCurveMask(ss);
13120 #endif 13520 #endif
13121 ssl_ReleaseSpecWriteLock(ss); 13521 ssl_ReleaseSpecWriteLock(ss);
13122 13522
13123 PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData)); 13523 PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
13124 13524
13125 if (IS_DTLS(ss)) { 13525 if (IS_DTLS(ss)) {
13126 » ss->ssl3.hs.sendMessageSeq = 0; 13526 ss->ssl3.hs.sendMessageSeq = 0;
13127 » ss->ssl3.hs.recvMessageSeq = 0; 13527 ss->ssl3.hs.recvMessageSeq = 0;
13128 » ss->ssl3.hs.rtTimeoutMs = INITIAL_DTLS_TIMEOUT_MS; 13528 ss->ssl3.hs.rtTimeoutMs = INITIAL_DTLS_TIMEOUT_MS;
13129 » ss->ssl3.hs.rtRetries = 0; 13529 ss->ssl3.hs.rtRetries = 0;
13130 » ss->ssl3.hs.recvdHighWater = -1; 13530 ss->ssl3.hs.recvdHighWater = -1;
13131 » PR_INIT_CLIST(&ss->ssl3.hs.lastMessageFlight); 13531 PR_INIT_CLIST(&ss->ssl3.hs.lastMessageFlight);
13132 » dtls_SetMTU(ss, 0); /* Set the MTU to the highest plateau */ 13532 dtls_SetMTU(ss, 0); /* Set the MTU to the highest plateau */
13133 } 13533 }
13134 13534
13535 PR_INIT_CLIST(&ss->ssl3.hs.remoteKeyShares);
13536 ss->ssl3.hs.xSS = NULL;
13537 ss->ssl3.hs.xES = NULL;
13538 ss->ssl3.hs.trafficSecret = NULL;
13539 ss->ssl3.hs.clientFinishedSecret = NULL;
13540 ss->ssl3.hs.serverFinishedSecret = NULL;
13541 ss->ssl3.hs.certReqContextLen = 0;
13542
13135 PORT_Assert(!ss->ssl3.hs.messages.buf && !ss->ssl3.hs.messages.space); 13543 PORT_Assert(!ss->ssl3.hs.messages.buf && !ss->ssl3.hs.messages.space);
13136 ss->ssl3.hs.messages.buf = NULL; 13544 ss->ssl3.hs.messages.buf = NULL;
13137 ss->ssl3.hs.messages.space = 0; 13545 ss->ssl3.hs.messages.space = 0;
13138 13546
13139 ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE; 13547 ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE;
13140 PORT_Memset(&ss->ssl3.hs.newSessionTicket, 0, 13548 PORT_Memset(&ss->ssl3.hs.newSessionTicket, 0,
13141 » » sizeof(ss->ssl3.hs.newSessionTicket)); 13549 sizeof(ss->ssl3.hs.newSessionTicket));
13142 13550
13143 ss->ssl3.initialized = PR_TRUE; 13551 ss->ssl3.initialized = PR_TRUE;
13144 return SECSuccess; 13552 return SECSuccess;
13145 } 13553 }
13146 13554
13147 /* Returns a reference counted object that contains a key pair. 13555 /* Returns a reference counted object that contains a key pair.
13148 * Or NULL on failure. Initial ref count is 1. 13556 * Or NULL on failure. Initial ref count is 1.
13149 * Uses the keys in the pair as input. 13557 * Uses the keys in the pair as input.
13150 */ 13558 */
13151 ssl3KeyPair * 13559 ssl3KeyPair *
13152 ssl3_NewKeyPair( SECKEYPrivateKey * privKey, SECKEYPublicKey * pubKey) 13560 ssl3_NewKeyPair(SECKEYPrivateKey *privKey, SECKEYPublicKey *pubKey)
13153 { 13561 {
13154 ssl3KeyPair * pair; 13562 ssl3KeyPair *pair;
13155 13563
13156 if (!privKey || !pubKey) { 13564 if (!privKey || !pubKey) {
13157 » PORT_SetError(PR_INVALID_ARGUMENT_ERROR); 13565 PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
13158 » return NULL; 13566 return NULL;
13159 } 13567 }
13160 pair = PORT_ZNew(ssl3KeyPair); 13568 pair = PORT_ZNew(ssl3KeyPair);
13161 if (!pair) 13569 if (!pair)
13162 » return NULL;» » » /* error code is set. */ 13570 return NULL; /* error code is set. */
13163 pair->refCount = 1; 13571 pair->refCount = 1;
13164 pair->privKey = privKey; 13572 pair->privKey = privKey;
13165 pair->pubKey = pubKey; 13573 pair->pubKey = pubKey;
13166 return pair;» » » /* success */ 13574 return pair; /* success */
13167 } 13575 }
13168 13576
13169 ssl3KeyPair * 13577 ssl3KeyPair *
13170 ssl3_GetKeyPairRef(ssl3KeyPair * keyPair) 13578 ssl3_GetKeyPairRef(ssl3KeyPair *keyPair)
13171 { 13579 {
13172 PR_ATOMIC_INCREMENT(&keyPair->refCount); 13580 PR_ATOMIC_INCREMENT(&keyPair->refCount);
13173 return keyPair; 13581 return keyPair;
13174 } 13582 }
13175 13583
13176 void 13584 void
13177 ssl3_FreeKeyPair(ssl3KeyPair * keyPair) 13585 ssl3_FreeKeyPair(ssl3KeyPair *keyPair)
13178 { 13586 {
13179 PRInt32 newCount = PR_ATOMIC_DECREMENT(&keyPair->refCount); 13587 PRInt32 newCount = PR_ATOMIC_DECREMENT(&keyPair->refCount);
13180 if (!newCount) { 13588 if (!newCount) {
13181 » if (keyPair->privKey) 13589 if (keyPair->privKey)
13182 » SECKEY_DestroyPrivateKey(keyPair->privKey); 13590 SECKEY_DestroyPrivateKey(keyPair->privKey);
13183 » if (keyPair->pubKey) 13591 if (keyPair->pubKey)
13184 » SECKEY_DestroyPublicKey( keyPair->pubKey); 13592 SECKEY_DestroyPublicKey(keyPair->pubKey);
13185 » PORT_Free(keyPair); 13593 PORT_Free(keyPair);
13186 } 13594 }
13187 } 13595 }
13188 13596
13189 /* 13597 /*
13190 * Creates the public and private RSA keys for SSL Step down. 13598 * Creates the public and private RSA keys for SSL Step down.
13191 * Called from SSL_ConfigSecureServer in sslsecur.c 13599 * Called from SSL_ConfigSecureServer in sslsecur.c
13192 */ 13600 */
13193 SECStatus 13601 SECStatus
13194 ssl3_CreateRSAStepDownKeys(sslSocket *ss) 13602 ssl3_CreateRSAStepDownKeys(sslSocket *ss)
13195 { 13603 {
13196 SECStatus rv » = SECSuccess; 13604 SECStatus rv = SECSuccess;
13197 SECKEYPrivateKey * privKey;» » /* RSA step down key */ 13605 SECKEYPrivateKey *privKey; /* RSA step down key */
13198 SECKEYPublicKey * pubKey;» » /* RSA step down key */ 13606 SECKEYPublicKey *pubKey; /* RSA step down key */
13199 13607
13200 if (ss->stepDownKeyPair) 13608 if (ss->stepDownKeyPair)
13201 » ssl3_FreeKeyPair(ss->stepDownKeyPair); 13609 ssl3_FreeKeyPair(ss->stepDownKeyPair);
13202 ss->stepDownKeyPair = NULL; 13610 ss->stepDownKeyPair = NULL;
13203 #ifndef HACKED_EXPORT_SERVER 13611 #ifndef HACKED_EXPORT_SERVER
13204 /* Sigh, should have a get key strength call for private keys */ 13612 /* Sigh, should have a get key strength call for private keys */
13205 if (PK11_GetPrivateModulusLen(ss->serverCerts[kt_rsa].SERVERKEY) > 13613 if (PK11_GetPrivateModulusLen(ss->serverCerts[kt_rsa].SERVERKEY) >
13206 EXPORT_RSA_KEY_LENGTH) { 13614 EXPORT_RSA_KEY_LENGTH) {
13207 » /* need to ask for the key size in bits */ 13615 /* need to ask for the key size in bits */
13208 » privKey = SECKEY_CreateRSAPrivateKey(EXPORT_RSA_KEY_LENGTH * BPB, 13616 privKey = SECKEY_CreateRSAPrivateKey(EXPORT_RSA_KEY_LENGTH * BPB,
13209 » » » » » &pubKey, NULL); 13617 &pubKey, NULL);
13210 » if (!privKey || !pubKey || 13618 if (!privKey || !pubKey ||
13211 » !(ss->stepDownKeyPair = ssl3_NewKeyPair(privKey, pubKey))) { 13619 !(ss->stepDownKeyPair = ssl3_NewKeyPair(privKey, pubKey))) {
13212 » ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL); 13620 ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
13213 » rv = SECFailure; 13621 rv = SECFailure;
13214 » } 13622 }
13215 } 13623 }
13216 #endif 13624 #endif
13217 return rv; 13625 return rv;
13218 } 13626 }
13219 13627
13220 /* record the export policy for this cipher suite */ 13628 /* record the export policy for this cipher suite */
13221 SECStatus 13629 SECStatus
13222 ssl3_SetPolicy(ssl3CipherSuite which, int policy) 13630 ssl3_SetPolicy(ssl3CipherSuite which, int policy)
13223 { 13631 {
13224 ssl3CipherSuiteCfg *suite; 13632 ssl3CipherSuiteCfg *suite;
13225 13633
13226 suite = ssl_LookupCipherSuiteCfg(which, cipherSuites); 13634 suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
13227 if (suite == NULL) { 13635 if (suite == NULL) {
13228 » return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */ 13636 return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
13229 } 13637 }
13230 suite->policy = policy; 13638 suite->policy = policy;
13231 13639
13232 return SECSuccess; 13640 return SECSuccess;
13233 } 13641 }
13234 13642
13235 SECStatus 13643 SECStatus
13236 ssl3_GetPolicy(ssl3CipherSuite which, PRInt32 *oPolicy) 13644 ssl3_GetPolicy(ssl3CipherSuite which, PRInt32 *oPolicy)
13237 { 13645 {
13238 ssl3CipherSuiteCfg *suite; 13646 ssl3CipherSuiteCfg *suite;
13239 PRInt32 policy; 13647 PRInt32 policy;
13240 SECStatus rv; 13648 SECStatus rv;
13241 13649
13242 suite = ssl_LookupCipherSuiteCfg(which, cipherSuites); 13650 suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
13243 if (suite) { 13651 if (suite) {
13244 » policy = suite->policy; 13652 policy = suite->policy;
13245 » rv = SECSuccess; 13653 rv = SECSuccess;
13246 } else { 13654 } else {
13247 » policy = SSL_NOT_ALLOWED; 13655 policy = SSL_NOT_ALLOWED;
13248 » rv = SECFailure;» /* err code was set by Lookup. */ 13656 rv = SECFailure; /* err code was set by Lookup. */
13249 } 13657 }
13250 *oPolicy = policy; 13658 *oPolicy = policy;
13251 return rv; 13659 return rv;
13252 } 13660 }
13253 13661
13254 /* record the user preference for this suite */ 13662 /* record the user preference for this suite */
13255 SECStatus 13663 SECStatus
13256 ssl3_CipherPrefSetDefault(ssl3CipherSuite which, PRBool enabled) 13664 ssl3_CipherPrefSetDefault(ssl3CipherSuite which, PRBool enabled)
13257 { 13665 {
13258 ssl3CipherSuiteCfg *suite; 13666 ssl3CipherSuiteCfg *suite;
13259 13667
13260 suite = ssl_LookupCipherSuiteCfg(which, cipherSuites); 13668 suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
13261 if (suite == NULL) { 13669 if (suite == NULL) {
13262 » return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */ 13670 return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
13263 } 13671 }
13264 suite->enabled = enabled; 13672 suite->enabled = enabled;
13265 return SECSuccess; 13673 return SECSuccess;
13266 } 13674 }
13267 13675
13268 /* return the user preference for this suite */ 13676 /* return the user preference for this suite */
13269 SECStatus 13677 SECStatus
13270 ssl3_CipherPrefGetDefault(ssl3CipherSuite which, PRBool *enabled) 13678 ssl3_CipherPrefGetDefault(ssl3CipherSuite which, PRBool *enabled)
13271 { 13679 {
13272 ssl3CipherSuiteCfg *suite; 13680 ssl3CipherSuiteCfg *suite;
13273 PRBool pref; 13681 PRBool pref;
13274 SECStatus rv; 13682 SECStatus rv;
13275 13683
13276 suite = ssl_LookupCipherSuiteCfg(which, cipherSuites); 13684 suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
13277 if (suite) { 13685 if (suite) {
13278 » pref = suite->enabled; 13686 pref = suite->enabled;
13279 » rv = SECSuccess; 13687 rv = SECSuccess;
13280 } else { 13688 } else {
13281 » pref = SSL_NOT_ALLOWED; 13689 pref = SSL_NOT_ALLOWED;
13282 » rv = SECFailure;» /* err code was set by Lookup. */ 13690 rv = SECFailure; /* err code was set by Lookup. */
13283 } 13691 }
13284 *enabled = pref; 13692 *enabled = pref;
13285 return rv; 13693 return rv;
13286 } 13694 }
13287 13695
13288 SECStatus 13696 SECStatus
13289 ssl3_CipherPrefSet(sslSocket *ss, ssl3CipherSuite which, PRBool enabled) 13697 ssl3_CipherPrefSet(sslSocket *ss, ssl3CipherSuite which, PRBool enabled)
13290 { 13698 {
13291 ssl3CipherSuiteCfg *suite; 13699 ssl3CipherSuiteCfg *suite;
13292 13700
13293 suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites); 13701 suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites);
13294 if (suite == NULL) { 13702 if (suite == NULL) {
13295 » return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */ 13703 return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
13296 } 13704 }
13297 suite->enabled = enabled; 13705 suite->enabled = enabled;
13298 return SECSuccess; 13706 return SECSuccess;
13299 } 13707 }
13300 13708
13301 SECStatus 13709 SECStatus
13302 ssl3_CipherPrefGet(sslSocket *ss, ssl3CipherSuite which, PRBool *enabled) 13710 ssl3_CipherPrefGet(sslSocket *ss, ssl3CipherSuite which, PRBool *enabled)
13303 { 13711 {
13304 ssl3CipherSuiteCfg *suite; 13712 ssl3CipherSuiteCfg *suite;
13305 PRBool pref; 13713 PRBool pref;
13306 SECStatus rv; 13714 SECStatus rv;
13307 13715
13308 suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites); 13716 suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites);
13309 if (suite) { 13717 if (suite) {
13310 » pref = suite->enabled; 13718 pref = suite->enabled;
13311 » rv = SECSuccess; 13719 rv = SECSuccess;
13312 } else { 13720 } else {
13313 » pref = SSL_NOT_ALLOWED; 13721 pref = SSL_NOT_ALLOWED;
13314 » rv = SECFailure;» /* err code was set by Lookup. */ 13722 rv = SECFailure; /* err code was set by Lookup. */
13315 } 13723 }
13316 *enabled = pref; 13724 *enabled = pref;
13317 return rv; 13725 return rv;
13318 } 13726 }
13319 13727
13320 SECStatus 13728 SECStatus
13321 SSL_SignaturePrefSet(PRFileDesc *fd, const SSLSignatureAndHashAlg *algorithms, 13729 SSL_SignaturePrefSet(PRFileDesc *fd, const SSLSignatureAndHashAlg *algorithms,
13322 unsigned int count) 13730 unsigned int count)
13323 { 13731 {
13324 sslSocket *ss; 13732 sslSocket *ss;
(...skipping 15 matching lines...) Expand all
13340 ss->ssl3.signatureAlgorithmCount = 0; 13748 ss->ssl3.signatureAlgorithmCount = 0;
13341 for (i = 0; i < count; ++i) { 13749 for (i = 0; i < count; ++i) {
13342 if (!ssl3_IsSupportedSignatureAlgorithm(&algorithms[i])) { 13750 if (!ssl3_IsSupportedSignatureAlgorithm(&algorithms[i])) {
13343 SSL_DBG(("%d: SSL[%d]: invalid signature algorithm set %d/%d", 13751 SSL_DBG(("%d: SSL[%d]: invalid signature algorithm set %d/%d",
13344 SSL_GETPID(), fd, algorithms[i].sigAlg, 13752 SSL_GETPID(), fd, algorithms[i].sigAlg,
13345 algorithms[i].hashAlg)); 13753 algorithms[i].hashAlg));
13346 continue; 13754 continue;
13347 } 13755 }
13348 13756
13349 ss->ssl3.signatureAlgorithms[ss->ssl3.signatureAlgorithmCount++] = 13757 ss->ssl3.signatureAlgorithms[ss->ssl3.signatureAlgorithmCount++] =
13350 algorithms[i]; 13758 algorithms[i];
13351 } 13759 }
13352 13760
13353 if (ss->ssl3.signatureAlgorithmCount == 0) { 13761 if (ss->ssl3.signatureAlgorithmCount == 0) {
13354 PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM); 13762 PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM);
13355 return SECFailure; 13763 return SECFailure;
13356 } 13764 }
13357 return SECSuccess; 13765 return SECSuccess;
13358 } 13766 }
13359 13767
13360 SECStatus 13768 SECStatus
(...skipping 11 matching lines...) Expand all
13372 return SECFailure; 13780 return SECFailure;
13373 } 13781 }
13374 13782
13375 if (!algorithms || !count || 13783 if (!algorithms || !count ||
13376 maxCount < ss->ssl3.signatureAlgorithmCount) { 13784 maxCount < ss->ssl3.signatureAlgorithmCount) {
13377 PORT_SetError(SEC_ERROR_INVALID_ARGS); 13785 PORT_SetError(SEC_ERROR_INVALID_ARGS);
13378 return SECFailure; 13786 return SECFailure;
13379 } 13787 }
13380 13788
13381 requiredSpace = 13789 requiredSpace =
13382 ss->ssl3.signatureAlgorithmCount * sizeof(SSLSignatureAndHashAlg); 13790 ss->ssl3.signatureAlgorithmCount * sizeof(SSLSignatureAndHashAlg);
13383 PORT_Memcpy(algorithms, ss->ssl3.signatureAlgorithms, requiredSpace); 13791 PORT_Memcpy(algorithms, ss->ssl3.signatureAlgorithms, requiredSpace);
13384 *count = ss->ssl3.signatureAlgorithmCount; 13792 *count = ss->ssl3.signatureAlgorithmCount;
13385 return SECSuccess; 13793 return SECSuccess;
13386 } 13794 }
13387 13795
13388 unsigned int 13796 unsigned int
13389 SSL_SignatureMaxCount() { 13797 SSL_SignatureMaxCount()
13798 {
13390 return MAX_SIGNATURE_ALGORITHMS; 13799 return MAX_SIGNATURE_ALGORITHMS;
13391 } 13800 }
13392 13801
13393 SECStatus 13802 SECStatus
13394 ssl3_CipherOrderSet(sslSocket *ss, const ssl3CipherSuite *ciphers, unsigned int len) 13803 ssl3_CipherOrderSet(sslSocket *ss, const ssl3CipherSuite *ciphers, unsigned int len)
13395 { 13804 {
13396 /* |i| iterates over |ciphers| while |done| and |j| iterate over 13805 /* |i| iterates over |ciphers| while |done| and |j| iterate over
13397 * |ss->cipherSuites|. */ 13806 * |ss->cipherSuites|. */
13398 unsigned int i, done; 13807 unsigned int i, done;
13399 13808
13400 for (i = done = 0; i < len; i++) { 13809 for (i = done = 0; i < len; i++) {
13401 » PRUint16 id = ciphers[i]; 13810 PRUint16 id = ciphers[i];
13402 » unsigned int existingIndex, j; 13811 unsigned int existingIndex, j;
13403 » PRBool found = PR_FALSE; 13812 PRBool found = PR_FALSE;
13404 13813
13405 » for (j = done; j < ssl_V3_SUITES_IMPLEMENTED; j++) { 13814 for (j = done; j < ssl_V3_SUITES_IMPLEMENTED; j++) {
13406 » if (ss->cipherSuites[j].cipher_suite == id) { 13815 if (ss->cipherSuites[j].cipher_suite == id) {
13407 » » existingIndex = j; 13816 existingIndex = j;
13408 » » found = PR_TRUE; 13817 found = PR_TRUE;
13409 » » break; 13818 break;
13410 » } 13819 }
13411 » } 13820 }
13412 13821
13413 » if (!found) { 13822 if (!found) {
13414 » continue; 13823 continue;
13415 » } 13824 }
13416 13825
13417 » if (existingIndex != done) { 13826 if (existingIndex != done) {
13418 » const ssl3CipherSuiteCfg temp = ss->cipherSuites[done]; 13827 const ssl3CipherSuiteCfg temp = ss->cipherSuites[done];
13419 » ss->cipherSuites[done] = ss->cipherSuites[existingIndex]; 13828 ss->cipherSuites[done] = ss->cipherSuites[existingIndex];
13420 » ss->cipherSuites[existingIndex] = temp; 13829 ss->cipherSuites[existingIndex] = temp;
13421 » } 13830 }
13422 » done++; 13831 done++;
13423 } 13832 }
13424 13833
13425 /* Disable all cipher suites that weren't included. */ 13834 /* Disable all cipher suites that weren't included. */
13426 for (; done < ssl_V3_SUITES_IMPLEMENTED; done++) { 13835 for (; done < ssl_V3_SUITES_IMPLEMENTED; done++) {
13427 » ss->cipherSuites[done].enabled = 0; 13836 ss->cipherSuites[done].enabled = 0;
13428 } 13837 }
13429 13838
13430 return SECSuccess; 13839 return SECSuccess;
13431 } 13840 }
13432 13841
13433 /* copy global default policy into socket. */ 13842 /* copy global default policy into socket. */
13434 void 13843 void
13435 ssl3_InitSocketPolicy(sslSocket *ss) 13844 ssl3_InitSocketPolicy(sslSocket *ss)
13436 { 13845 {
13437 PORT_Memcpy(ss->cipherSuites, cipherSuites, sizeof cipherSuites); 13846 PORT_Memcpy(ss->cipherSuites, cipherSuites, sizeof cipherSuites);
13438 PORT_Memcpy(ss->ssl3.signatureAlgorithms, defaultSignatureAlgorithms, 13847 PORT_Memcpy(ss->ssl3.signatureAlgorithms, defaultSignatureAlgorithms,
13439 sizeof(defaultSignatureAlgorithms)); 13848 sizeof(defaultSignatureAlgorithms));
13440 ss->ssl3.signatureAlgorithmCount = PR_ARRAY_SIZE(defaultSignatureAlgorithms) ; 13849 ss->ssl3.signatureAlgorithmCount = PR_ARRAY_SIZE(defaultSignatureAlgorithms) ;
13441 } 13850 }
13442 13851
13443 SECStatus 13852 SECStatus
13444 ssl3_GetTLSUniqueChannelBinding(sslSocket *ss, 13853 ssl3_GetTLSUniqueChannelBinding(sslSocket *ss,
13445 » » » » unsigned char *out, 13854 unsigned char *out,
13446 » » » » unsigned int *outLen, 13855 unsigned int *outLen,
13447 » » » » unsigned int outLenMax) { 13856 unsigned int outLenMax)
13448 PRBool isTLS; 13857 {
13449 int index = 0; 13858 PRBool isTLS;
13859 int index = 0;
13450 unsigned int len; 13860 unsigned int len;
13451 SECStatus rv = SECFailure; 13861 SECStatus rv = SECFailure;
13452 13862
13453 *outLen = 0; 13863 *outLen = 0;
13454 13864
13455 ssl_GetSSL3HandshakeLock(ss); 13865 ssl_GetSSL3HandshakeLock(ss);
13456 13866
13457 ssl_GetSpecReadLock(ss); 13867 ssl_GetSpecReadLock(ss);
13458 isTLS = (PRBool)(ss->ssl3.cwSpec->version > SSL_LIBRARY_VERSION_3_0); 13868 isTLS = (PRBool)(ss->ssl3.cwSpec->version > SSL_LIBRARY_VERSION_3_0);
13459 ssl_ReleaseSpecReadLock(ss); 13869 ssl_ReleaseSpecReadLock(ss);
13460 13870
13461 /* The tls-unique channel binding is the first Finished structure in the 13871 /* The tls-unique channel binding is the first Finished structure in the
13462 * handshake. In the case of a resumption, that's the server's Finished. 13872 * handshake. In the case of a resumption, that's the server's Finished.
13463 * Otherwise, it's the client's Finished. */ 13873 * Otherwise, it's the client's Finished. */
13464 len = ss->ssl3.hs.finishedBytes; 13874 len = ss->ssl3.hs.finishedBytes;
13465 13875
13466 /* Sending or receiving a Finished message will set finishedBytes to a 13876 /* Sending or receiving a Finished message will set finishedBytes to a
13467 * non-zero value. */ 13877 * non-zero value. */
13468 if (len == 0) { 13878 if (len == 0) {
13469 » PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED); 13879 PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED);
13470 » goto loser; 13880 goto loser;
13471 } 13881 }
13472 13882
13473 /* If we are in the middle of a renegotiation then the channel binding 13883 /* If we are in the middle of a renegotiation then the channel binding
13474 * value is poorly defined and depends on the direction that it will be 13884 * value is poorly defined and depends on the direction that it will be
13475 * used on. Therefore we simply return an error in this case. */ 13885 * used on. Therefore we simply return an error in this case. */
13476 if (ss->firstHsDone && ss->ssl3.hs.ws != idle_handshake) { 13886 if (ss->firstHsDone && ss->ssl3.hs.ws != idle_handshake) {
13477 » PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED); 13887 PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
13478 » goto loser; 13888 goto loser;
13479 } 13889 }
13480 13890
13481 /* If resuming, then we want the second Finished value in the array, which 13891 /* If resuming, then we want the second Finished value in the array, which
13482 * is the server's */ 13892 * is the server's */
13483 if (ss->ssl3.hs.isResuming) 13893 if (ss->ssl3.hs.isResuming)
13484 » index = 1; 13894 index = 1;
13485 13895
13486 *outLen = len; 13896 *outLen = len;
13487 if (outLenMax < len) { 13897 if (outLenMax < len) {
13488 » PORT_SetError(SEC_ERROR_OUTPUT_LEN); 13898 PORT_SetError(SEC_ERROR_OUTPUT_LEN);
13489 » goto loser; 13899 goto loser;
13490 } 13900 }
13491 13901
13492 if (isTLS) { 13902 if (isTLS) {
13493 » memcpy(out, &ss->ssl3.hs.finishedMsgs.tFinished[index], len); 13903 memcpy(out, &ss->ssl3.hs.finishedMsgs.tFinished[index], len);
13494 } else { 13904 } else {
13495 » memcpy(out, &ss->ssl3.hs.finishedMsgs.sFinished[index], len); 13905 memcpy(out, &ss->ssl3.hs.finishedMsgs.sFinished[index], len);
13496 } 13906 }
13497 13907
13498 rv = SECSuccess; 13908 rv = SECSuccess;
13499 13909
13500 loser: 13910 loser:
13501 ssl_ReleaseSSL3HandshakeLock(ss); 13911 ssl_ReleaseSSL3HandshakeLock(ss);
13502 return rv; 13912 return rv;
13503 } 13913 }
13504 13914
13505 /* ssl3_config_match_init must have already been called by 13915 /* ssl3_config_match_init must have already been called by
13506 * the caller of this function. 13916 * the caller of this function.
13507 */ 13917 */
13508 SECStatus 13918 SECStatus
13509 ssl3_ConstructV2CipherSpecsHack(sslSocket *ss, unsigned char *cs, int *size) 13919 ssl3_ConstructV2CipherSpecsHack(sslSocket *ss, unsigned char *cs, int *size)
13510 { 13920 {
13511 int i, count = 0; 13921 int i, count = 0;
13512 13922
13513 PORT_Assert(ss != 0); 13923 PORT_Assert(ss != 0);
13514 if (!ss) { 13924 if (!ss) {
13515 » PORT_SetError(PR_INVALID_ARGUMENT_ERROR); 13925 PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
13516 » return SECFailure; 13926 return SECFailure;
13517 } 13927 }
13518 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { 13928 if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
13519 » *size = 0; 13929 *size = 0;
13520 » return SECSuccess; 13930 return SECSuccess;
13521 } 13931 }
13522 if (cs == NULL) { 13932 if (cs == NULL) {
13523 » *size = count_cipher_suites(ss, SSL_ALLOWED, PR_TRUE); 13933 *size = count_cipher_suites(ss, SSL_ALLOWED, PR_TRUE);
13524 » return SECSuccess; 13934 return SECSuccess;
13525 } 13935 }
13526 13936
13527 /* ssl3_config_match_init was called by the caller of this function. */ 13937 /* ssl3_config_match_init was called by the caller of this function. */
13528 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { 13938 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
13529 » ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i]; 13939 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
13530 » if (config_match(suite, SSL_ALLOWED, PR_TRUE, &ss->vrange, ss)) { 13940 if (config_match(suite, SSL_ALLOWED, PR_TRUE, &ss->vrange, ss)) {
13531 » if (cs != NULL) { 13941 if (cs != NULL) {
13532 » » *cs++ = 0x00; 13942 *cs++ = 0x00;
13533 » » *cs++ = (suite->cipher_suite >> 8) & 0xFF; 13943 *cs++ = (suite->cipher_suite >> 8) & 0xFF;
13534 » » *cs++ = suite->cipher_suite & 0xFF; 13944 *cs++ = suite->cipher_suite & 0xFF;
13535 » } 13945 }
13536 » count++; 13946 count++;
13537 » } 13947 }
13538 } 13948 }
13539 *size = count; 13949 *size = count;
13540 return SECSuccess; 13950 return SECSuccess;
13541 } 13951 }
13542 13952
13543 /* 13953 /*
13544 ** If ssl3 socket has completed the first handshake, and is in idle state, 13954 ** If ssl3 socket has completed the first handshake, and is in idle state,
13545 ** then start a new handshake. 13955 ** then start a new handshake.
13546 ** If flushCache is true, the SID cache will be flushed first, forcing a 13956 ** If flushCache is true, the SID cache will be flushed first, forcing a
13547 ** "Full" handshake (not a session restart handshake), to be done. 13957 ** "Full" handshake (not a session restart handshake), to be done.
13548 ** 13958 **
13549 ** called from SSL_RedoHandshake(), which already holds the handshake locks. 13959 ** called from SSL_RedoHandshake(), which already holds the handshake locks.
13550 */ 13960 */
13551 SECStatus 13961 SECStatus
13552 ssl3_RedoHandshake(sslSocket *ss, PRBool flushCache) 13962 ssl3_RedoHandshake(sslSocket *ss, PRBool flushCache)
13553 { 13963 {
13554 sslSessionID * sid = ss->sec.ci.sid; 13964 sslSessionID *sid = ss->sec.ci.sid;
13555 SECStatus rv; 13965 SECStatus rv;
13556 13966
13557 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 13967 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
13558 13968
13559 if (!ss->firstHsDone || 13969 if (!ss->firstHsDone ||
13560 ((ss->version >= SSL_LIBRARY_VERSION_3_0) && 13970 ((ss->version >= SSL_LIBRARY_VERSION_3_0) &&
13561 » ss->ssl3.initialized && 13971 ss->ssl3.initialized &&
13562 » (ss->ssl3.hs.ws != idle_handshake))) { 13972 (ss->ssl3.hs.ws != idle_handshake))) {
13563 » PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED); 13973 PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED);
13564 » return SECFailure; 13974 return SECFailure;
13565 } 13975 }
13566 13976
13567 if (IS_DTLS(ss)) { 13977 if (IS_DTLS(ss)) {
13568 » dtls_RehandshakeCleanup(ss); 13978 dtls_RehandshakeCleanup(ss);
13569 } 13979 }
13570 13980
13571 if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) { 13981 if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
13572 » PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED); 13982 PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
13573 » return SECFailure; 13983 return SECFailure;
13574 } 13984 }
13575 if (sid && flushCache) { 13985 if (sid && flushCache) {
13576 if (ss->sec.uncache) 13986 if (ss->sec.uncache)
13577 ss->sec.uncache(sid); /* remove it from whichever cache it's in. */ 13987 ss->sec.uncache(sid); /* remove it from whichever cache it's in. */
13578 » ssl_FreeSID(sid);» /* dec ref count and free if zero. */ 13988 ssl_FreeSID(sid); /* dec ref count and free if zero. */
13579 » ss->sec.ci.sid = NULL; 13989 ss->sec.ci.sid = NULL;
13580 } 13990 }
13581 13991
13582 ssl_GetXmitBufLock(ss);» /**************************************/ 13992 ssl_GetXmitBufLock(ss); /**************************************/
13583 13993
13584 /* start off a new handshake. */ 13994 /* start off a new handshake. */
13585 rv = (ss->sec.isServer) ? ssl3_SendHelloRequest(ss) 13995 rv = (ss->sec.isServer) ? ssl3_SendHelloRequest(ss)
13586 : ssl3_SendClientHello(ss, PR_FALSE); 13996 : ssl3_SendClientHello(ss, PR_FALSE);
13587 13997
13588 ssl_ReleaseXmitBufLock(ss);»/**************************************/ 13998 ssl_ReleaseXmitBufLock(ss); /**************************************/
13589 return rv; 13999 return rv;
13590 } 14000 }
13591 14001
13592 /* Called from ssl_DestroySocketContents() in sslsock.c */ 14002 /* Called from ssl_DestroySocketContents() in sslsock.c */
13593 void 14003 void
13594 ssl3_DestroySSL3Info(sslSocket *ss) 14004 ssl3_DestroySSL3Info(sslSocket *ss)
13595 { 14005 {
13596 14006
13597 if (ss->ssl3.clientCertificate != NULL) 14007 if (ss->ssl3.clientCertificate != NULL)
13598 » CERT_DestroyCertificate(ss->ssl3.clientCertificate); 14008 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
13599 14009
13600 if (ss->ssl3.clientPrivateKey != NULL) 14010 if (ss->ssl3.clientPrivateKey != NULL)
13601 » SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); 14011 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
13602 #ifdef NSS_PLATFORM_CLIENT_AUTH
13603 if (ss->ssl3.platformClientKey)
13604 » ssl_FreePlatformKey(ss->ssl3.platformClientKey);
13605 #endif /* NSS_PLATFORM_CLIENT_AUTH */
13606 14012
13607 if (ss->ssl3.channelID) 14013 if (ss->ssl3.channelID)
13608 » SECKEY_DestroyPrivateKey(ss->ssl3.channelID); 14014 SECKEY_DestroyPrivateKey(ss->ssl3.channelID);
13609 if (ss->ssl3.channelIDPub) 14015 if (ss->ssl3.channelIDPub)
13610 » SECKEY_DestroyPublicKey(ss->ssl3.channelIDPub); 14016 SECKEY_DestroyPublicKey(ss->ssl3.channelIDPub);
13611 14017
13612 if (ss->ssl3.peerCertArena != NULL) 14018 if (ss->ssl3.peerCertArena != NULL)
13613 » ssl3_CleanupPeerCerts(ss); 14019 ssl3_CleanupPeerCerts(ss);
13614 14020
13615 if (ss->ssl3.clientCertChain != NULL) { 14021 if (ss->ssl3.clientCertChain != NULL) {
13616 CERT_DestroyCertificateList(ss->ssl3.clientCertChain); 14022 CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
13617 ss->ssl3.clientCertChain = NULL; 14023 ss->ssl3.clientCertChain = NULL;
13618 } 14024 }
13619 14025
13620 /* clean up handshake */ 14026 /* clean up handshake */
13621 #ifndef NO_PKCS11_BYPASS 14027 #ifndef NO_PKCS11_BYPASS
13622 if (ss->opt.bypassPKCS11) { 14028 if (ss->opt.bypassPKCS11) {
13623 » if (ss->ssl3.hs.hashType == handshake_hash_combo) { 14029 if (ss->ssl3.hs.hashType == handshake_hash_combo) {
13624 » SHA1_DestroyContext((SHA1Context *)ss->ssl3.hs.sha_cx, PR_FALSE); 14030 SHA1_DestroyContext((SHA1Context *)ss->ssl3.hs.sha_cx, PR_FALSE);
13625 » MD5_DestroyContext((MD5Context *)ss->ssl3.hs.md5_cx, PR_FALSE); 14031 MD5_DestroyContext((MD5Context *)ss->ssl3.hs.md5_cx, PR_FALSE);
13626 » } else if (ss->ssl3.hs.hashType == handshake_hash_single) { 14032 } else if (ss->ssl3.hs.hashType == handshake_hash_single) {
13627 » ss->ssl3.hs.sha_obj->destroy(ss->ssl3.hs.sha_cx, PR_FALSE); 14033 ss->ssl3.hs.sha_obj->destroy(ss->ssl3.hs.sha_cx, PR_FALSE);
13628 » } 14034 }
13629 } 14035 }
13630 #endif 14036 #endif
13631 if (ss->ssl3.hs.md5) { 14037 if (ss->ssl3.hs.md5) {
13632 » PK11_DestroyContext(ss->ssl3.hs.md5,PR_TRUE); 14038 PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE);
13633 } 14039 }
13634 if (ss->ssl3.hs.sha) { 14040 if (ss->ssl3.hs.sha) {
13635 » PK11_DestroyContext(ss->ssl3.hs.sha,PR_TRUE); 14041 PK11_DestroyContext(ss->ssl3.hs.sha, PR_TRUE);
13636 } 14042 }
13637 if (ss->ssl3.hs.clientSigAndHash) { 14043 if (ss->ssl3.hs.clientSigAndHash) {
13638 » PORT_Free(ss->ssl3.hs.clientSigAndHash); 14044 PORT_Free(ss->ssl3.hs.clientSigAndHash);
13639 } 14045 }
13640 if (ss->ssl3.hs.messages.buf) { 14046 if (ss->ssl3.hs.messages.buf) {
13641 » PORT_Free(ss->ssl3.hs.messages.buf); 14047 PORT_Free(ss->ssl3.hs.messages.buf);
13642 » ss->ssl3.hs.messages.buf = NULL; 14048 ss->ssl3.hs.messages.buf = NULL;
13643 » ss->ssl3.hs.messages.len = 0; 14049 ss->ssl3.hs.messages.len = 0;
13644 » ss->ssl3.hs.messages.space = 0; 14050 ss->ssl3.hs.messages.space = 0;
13645 } 14051 }
13646 14052
13647 /* free the SSL3Buffer (msg_body) */ 14053 /* free the SSL3Buffer (msg_body) */
13648 PORT_Free(ss->ssl3.hs.msg_body.buf); 14054 PORT_Free(ss->ssl3.hs.msg_body.buf);
13649 14055
13650 SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket, PR_FALSE); 14056 SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket, PR_FALSE);
13651 14057
13652 /* free up the CipherSpecs */ 14058 /* free up the CipherSpecs */
13653 ssl3_DestroyCipherSpec(&ss->ssl3.specs[0], PR_TRUE/*freeSrvName*/); 14059 ssl3_DestroyCipherSpec(&ss->ssl3.specs[0], PR_TRUE /*freeSrvName*/);
13654 ssl3_DestroyCipherSpec(&ss->ssl3.specs[1], PR_TRUE/*freeSrvName*/); 14060 ssl3_DestroyCipherSpec(&ss->ssl3.specs[1], PR_TRUE /*freeSrvName*/);
13655 14061
13656 /* Destroy the DTLS data */ 14062 /* Destroy the DTLS data */
13657 if (IS_DTLS(ss)) { 14063 if (IS_DTLS(ss)) {
13658 » dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight); 14064 dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight);
13659 » if (ss->ssl3.hs.recvdFragments.buf) { 14065 if (ss->ssl3.hs.recvdFragments.buf) {
13660 » PORT_Free(ss->ssl3.hs.recvdFragments.buf); 14066 PORT_Free(ss->ssl3.hs.recvdFragments.buf);
13661 » } 14067 }
13662 } 14068 }
13663 14069
14070 /* Destroy TLS 1.3 handshake shares */
14071 tls13_DestroyKeyShares(&ss->ssl3.hs.remoteKeyShares);
14072
14073 /* Destroy TLS 1.3 keys */
14074 if (ss->ssl3.hs.xSS)
14075 PK11_FreeSymKey(ss->ssl3.hs.xSS);
14076 if (ss->ssl3.hs.xES)
14077 PK11_FreeSymKey(ss->ssl3.hs.xES);
14078 if (ss->ssl3.hs.trafficSecret)
14079 PK11_FreeSymKey(ss->ssl3.hs.trafficSecret);
14080 if (ss->ssl3.hs.clientFinishedSecret)
14081 PK11_FreeSymKey(ss->ssl3.hs.clientFinishedSecret);
14082 if (ss->ssl3.hs.serverFinishedSecret)
14083 PK11_FreeSymKey(ss->ssl3.hs.serverFinishedSecret);
14084
13664 if (ss->ssl3.dheGroups) { 14085 if (ss->ssl3.dheGroups) {
13665 » PORT_Free(ss->ssl3.dheGroups); 14086 PORT_Free(ss->ssl3.dheGroups);
13666 } 14087 }
13667 14088
13668 ss->ssl3.initialized = PR_FALSE; 14089 ss->ssl3.initialized = PR_FALSE;
13669 14090
13670 SECITEM_FreeItem(&ss->ssl3.nextProto, PR_FALSE); 14091 SECITEM_FreeItem(&ss->ssl3.nextProto, PR_FALSE);
13671 } 14092 }
13672 14093
14094 #define MAP_NULL(x) (((x) != 0) ? (x) : SEC_OID_NULL_CIPHER)
14095
14096 SECStatus
14097 ssl3_ApplyNSSPolicy(void)
14098 {
14099 unsigned i;
14100 SECStatus rv;
14101 PRUint32 policy = 0;
14102
14103 rv = NSS_GetAlgorithmPolicy(SEC_OID_APPLY_SSL_POLICY, &policy);
14104 if (rv != SECSuccess || !(policy & NSS_USE_POLICY_IN_SSL)) {
14105 return SECSuccess; /* do nothing */
14106 }
14107
14108 /* disable every ciphersuite */
14109 for (i = 1; i < PR_ARRAY_SIZE(cipher_suite_defs); ++i) {
14110 const ssl3CipherSuiteDef *suite = &cipher_suite_defs[i];
14111 SECOidTag policyOid;
14112
14113 policyOid = MAP_NULL(kea_defs[suite->key_exchange_alg].oid);
14114 rv = NSS_GetAlgorithmPolicy(policyOid, &policy);
14115 if (rv == SECSuccess && !(policy & NSS_USE_ALG_IN_SSL_KX)) {
14116 ssl_CipherPrefSetDefault(suite->cipher_suite, PR_FALSE);
14117 ssl_CipherPolicySet(suite->cipher_suite, SSL_NOT_ALLOWED);
14118 continue;
14119 }
14120
14121 policyOid = MAP_NULL(bulk_cipher_defs[suite->bulk_cipher_alg].oid);
14122 rv = NSS_GetAlgorithmPolicy(policyOid, &policy);
14123 if (rv == SECSuccess && !(policy & NSS_USE_ALG_IN_SSL)) {
14124 ssl_CipherPrefSetDefault(suite->cipher_suite, PR_FALSE);
14125 ssl_CipherPolicySet(suite->cipher_suite, SSL_NOT_ALLOWED);
14126 continue;
14127 }
14128
14129 if (bulk_cipher_defs[suite->bulk_cipher_alg].type != type_aead) {
14130 policyOid = MAP_NULL(mac_defs[suite->mac_alg].oid);
14131 rv = NSS_GetAlgorithmPolicy(policyOid, &policy);
14132 if (rv == SECSuccess && !(policy & NSS_USE_ALG_IN_SSL)) {
14133 ssl_CipherPrefSetDefault(suite->cipher_suite, PR_FALSE);
14134 ssl_CipherPolicySet(suite->cipher_suite,
14135 SSL_NOT_ALLOWED);
14136 continue;
14137 }
14138 }
14139 }
14140
14141 rv = ssl3_ConstrainRangeByPolicy();
14142
14143 return rv;
14144 }
14145
13673 /* End of ssl3con.c */ 14146 /* End of ssl3con.c */
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698