4 * ***** BEGIN LICENSE BLOCK *****
5 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
7 * The contents of this file are subject to the Mozilla Public License Version
8 * 1.1 (the "License"); you may not use this file except in compliance with
9 * the License. You may obtain a copy of the License at
10 * http://www.mozilla.org/MPL/
12 * Software distributed under the License is distributed on an "AS IS" basis,
13 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
14 * for the specific language governing rights and limitations under the
17 * The Original Code is the Netscape security libraries.
19 * The Initial Developer of the Original Code is
20 * Netscape Communications Corporation.
21 * Portions created by the Initial Developer are Copyright (C) 1994-2000
22 * the Initial Developer. All Rights Reserved.
25 * Dr Stephen Henson <stephen.henson@gemplus.com>
26 * Dr Vipul Gupta <vipul.gupta@sun.com> and
27 * Douglas Stebila <douglas@stebila.ca>, Sun Microsystems Laboratories
29 * Alternatively, the contents of this file may be used under the terms of
30 * either the GNU General Public License Version 2 or later (the "GPL"), or
31 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
32 * in which case the provisions of the GPL or the LGPL are applicable instead
33 * of those above. If you wish to allow use of your version of this file only
34 * under the terms of either the GPL or the LGPL, and not to allow others to
35 * use your version of this file under the terms of the MPL, indicate your
36 * decision by deleting the provisions above and replace them with the notice
37 * and other provisions required by the GPL or the LGPL. If you do not delete
38 * the provisions above, a recipient may use your version of this file under
39 * the terms of any one of the MPL, the GPL or the LGPL.
41 * ***** END LICENSE BLOCK ***** */
42 /* $Id: ssl3con.c,v 1.113 2008/09/22 23:47:00 wtc%google.com Exp $ */
46 #include "cryptohi.h" /* for DSAU_ stuff */
67 #define PK11_SETATTRS(x,id,v,l) (x)->type = (id); \
68 (x)->pValue=(v); (x)->ulValueLen = (l);
71 static void ssl3_CleanupPeerCerts(sslSocket
*ss
);
72 static PK11SymKey
*ssl3_GenerateRSAPMS(sslSocket
*ss
, ssl3CipherSpec
*spec
,
73 PK11SlotInfo
* serverKeySlot
);
74 static SECStatus
ssl3_DeriveMasterSecret(sslSocket
*ss
, PK11SymKey
*pms
);
75 static SECStatus
ssl3_DeriveConnectionKeysPKCS11(sslSocket
*ss
);
76 static SECStatus
ssl3_HandshakeFailure( sslSocket
*ss
);
77 static SECStatus
ssl3_InitState( sslSocket
*ss
);
78 static SECStatus
ssl3_SendCertificate( sslSocket
*ss
);
79 static SECStatus
ssl3_SendEmptyCertificate( sslSocket
*ss
);
80 static SECStatus
ssl3_SendCertificateRequest(sslSocket
*ss
);
81 static SECStatus
ssl3_SendFinished( sslSocket
*ss
, PRInt32 flags
);
82 static SECStatus
ssl3_SendServerHello( sslSocket
*ss
);
83 static SECStatus
ssl3_SendServerHelloDone( sslSocket
*ss
);
84 static SECStatus
ssl3_SendServerKeyExchange( sslSocket
*ss
);
85 static SECStatus
ssl3_NewHandshakeHashes( sslSocket
*ss
);
86 static SECStatus
ssl3_UpdateHandshakeHashes( sslSocket
*ss
, unsigned char *b
,
89 static SECStatus
Null_Cipher(void *ctx
, unsigned char *output
, int *outputLen
,
90 int maxOutputLen
, const unsigned char *input
,
93 #define MAX_SEND_BUF_LENGTH 32000 /* watch for 16-bit integer overflow */
94 #define MIN_SEND_BUF_LENGTH 4000
96 #define MAX_CIPHER_SUITES 20
98 /* This list of SSL3 cipher suites is sorted in descending order of
99 * precedence (desirability). It only includes cipher suites we implement.
100 * This table is modified by SSL3_SetPolicy(). The ordering of cipher suites
101 * in this table must match the ordering in SSL_ImplementedCiphers (sslenum.c)
103 static ssl3CipherSuiteCfg cipherSuites
[ssl_V3_SUITES_IMPLEMENTED
] = {
104 /* cipher_suite policy enabled is_present*/
105 #ifdef NSS_ENABLE_ECC
106 { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
107 { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
108 #endif /* NSS_ENABLE_ECC */
109 { TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
110 { TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
111 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
112 { TLS_DHE_DSS_WITH_AES_256_CBC_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
113 #ifdef NSS_ENABLE_ECC
114 { TLS_ECDH_RSA_WITH_AES_256_CBC_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
115 { TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
116 #endif /* NSS_ENABLE_ECC */
117 { TLS_RSA_WITH_CAMELLIA_256_CBC_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
118 { TLS_RSA_WITH_AES_256_CBC_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
120 #ifdef NSS_ENABLE_ECC
121 { TLS_ECDHE_ECDSA_WITH_RC4_128_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
122 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
123 { TLS_ECDHE_RSA_WITH_RC4_128_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
124 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
125 #endif /* NSS_ENABLE_ECC */
126 { TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
127 { TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
128 { TLS_DHE_DSS_WITH_RC4_128_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
129 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
130 { TLS_DHE_DSS_WITH_AES_128_CBC_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
131 #ifdef NSS_ENABLE_ECC
132 { TLS_ECDH_RSA_WITH_RC4_128_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
133 { TLS_ECDH_RSA_WITH_AES_128_CBC_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
134 { TLS_ECDH_ECDSA_WITH_RC4_128_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
135 { TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
136 #endif /* NSS_ENABLE_ECC */
137 { TLS_RSA_WITH_CAMELLIA_128_CBC_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
138 { SSL_RSA_WITH_RC4_128_MD5
, SSL_NOT_ALLOWED
, PR_TRUE
, PR_FALSE
},
139 { SSL_RSA_WITH_RC4_128_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
140 { TLS_RSA_WITH_AES_128_CBC_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
142 #ifdef NSS_ENABLE_ECC
143 { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
144 { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
145 #endif /* NSS_ENABLE_ECC */
146 { SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
147 { SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
148 #ifdef NSS_ENABLE_ECC
149 { TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
150 { TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
151 #endif /* NSS_ENABLE_ECC */
152 { SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA
, SSL_NOT_ALLOWED
, PR_TRUE
, PR_FALSE
},
153 { SSL_RSA_WITH_3DES_EDE_CBC_SHA
, SSL_NOT_ALLOWED
, PR_TRUE
, PR_FALSE
},
156 { SSL_DHE_RSA_WITH_DES_CBC_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
157 { SSL_DHE_DSS_WITH_DES_CBC_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
158 { SSL_RSA_FIPS_WITH_DES_CBC_SHA
, SSL_NOT_ALLOWED
, PR_TRUE
, PR_FALSE
},
159 { SSL_RSA_WITH_DES_CBC_SHA
, SSL_NOT_ALLOWED
, PR_TRUE
, PR_FALSE
},
160 { TLS_RSA_EXPORT1024_WITH_RC4_56_SHA
, SSL_NOT_ALLOWED
, PR_TRUE
, PR_FALSE
},
161 { TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA
, SSL_NOT_ALLOWED
, PR_TRUE
, PR_FALSE
},
163 { SSL_RSA_EXPORT_WITH_RC4_40_MD5
, SSL_NOT_ALLOWED
, PR_TRUE
, PR_FALSE
},
164 { SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5
, SSL_NOT_ALLOWED
, PR_TRUE
, PR_FALSE
},
166 #ifdef NSS_ENABLE_ECC
167 { TLS_ECDHE_ECDSA_WITH_NULL_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
, PR_FALSE
},
168 { TLS_ECDHE_RSA_WITH_NULL_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
, PR_FALSE
},
169 { TLS_ECDH_RSA_WITH_NULL_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
, PR_FALSE
},
170 { TLS_ECDH_ECDSA_WITH_NULL_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
, PR_FALSE
},
171 #endif /* NSS_ENABLE_ECC */
172 { SSL_RSA_WITH_NULL_SHA
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
173 { SSL_RSA_WITH_NULL_MD5
, SSL_NOT_ALLOWED
, PR_FALSE
,PR_FALSE
},
177 static const /*SSL3CompressionMethod*/ uint8 compressions
[] = {
181 static const int compressionMethodsCount
=
182 sizeof(compressions
) / sizeof(compressions
[0]);
184 static const /*SSL3ClientCertificateType */ uint8 certificate_types
[] = {
187 #ifdef NSS_ENABLE_ECC
189 #endif /* NSS_ENABLE_ECC */
194 * make sure there is room in the write buffer for padding and
195 * other compression and cryptographic expansions
197 #define SSL3_BUFFER_FUDGE 100
199 #define EXPORT_RSA_KEY_LENGTH 64 /* bytes */
202 /* This is a hack to make sure we don't do double handshakes for US policy */
203 PRBool ssl3_global_policy_some_restricted
= PR_FALSE
;
205 /* This global item is used only in servers. It is is initialized by
206 ** SSL_ConfigSecureServer(), and is used in ssl3_SendCertificateRequest().
208 CERTDistNames
*ssl3_server_ca_list
= NULL
;
209 static SSL3Statistics ssl3stats
;
211 /* indexed by SSL3BulkCipher */
212 static const ssl3BulkCipherDef bulk_cipher_defs
[] = {
213 /* cipher calg keySz secretSz type ivSz BlkSz keygen */
214 {cipher_null
, calg_null
, 0, 0, type_stream
, 0, 0, kg_null
},
215 {cipher_rc4
, calg_rc4
, 16, 16, type_stream
, 0, 0, kg_strong
},
216 {cipher_rc4_40
, calg_rc4
, 16, 5, type_stream
, 0, 0, kg_export
},
217 {cipher_rc4_56
, calg_rc4
, 16, 7, type_stream
, 0, 0, kg_export
},
218 {cipher_rc2
, calg_rc2
, 16, 16, type_block
, 8, 8, kg_strong
},
219 {cipher_rc2_40
, calg_rc2
, 16, 5, type_block
, 8, 8, kg_export
},
220 {cipher_des
, calg_des
, 8, 8, type_block
, 8, 8, kg_strong
},
221 {cipher_3des
, calg_3des
, 24, 24, type_block
, 8, 8, kg_strong
},
222 {cipher_des40
, calg_des
, 8, 5, type_block
, 8, 8, kg_export
},
223 {cipher_idea
, calg_idea
, 16, 16, type_block
, 8, 8, kg_strong
},
224 {cipher_aes_128
, calg_aes
, 16, 16, type_block
, 16,16, kg_strong
},
225 {cipher_aes_256
, calg_aes
, 32, 32, type_block
, 16,16, kg_strong
},
226 {cipher_camellia_128
, calg_camellia
,16, 16, type_block
, 16,16, kg_strong
},
227 {cipher_camellia_256
, calg_camellia
,32, 32, type_block
, 16,16, kg_strong
},
228 {cipher_missing
, calg_null
, 0, 0, type_stream
, 0, 0, kg_null
},
231 static const ssl3KEADef kea_defs
[] =
232 { /* indexed by SSL3KeyExchangeAlgorithm */
233 /* kea exchKeyType signKeyType is_limited limit tls_keygen */
234 {kea_null
, kt_null
, sign_null
, PR_FALSE
, 0, PR_FALSE
},
235 {kea_rsa
, kt_rsa
, sign_rsa
, PR_FALSE
, 0, PR_FALSE
},
236 {kea_rsa_export
, kt_rsa
, sign_rsa
, PR_TRUE
, 512, PR_FALSE
},
237 {kea_rsa_export_1024
,kt_rsa
, sign_rsa
, PR_TRUE
, 1024, PR_FALSE
},
238 {kea_dh_dss
, kt_dh
, sign_dsa
, PR_FALSE
, 0, PR_FALSE
},
239 {kea_dh_dss_export
, kt_dh
, sign_dsa
, PR_TRUE
, 512, PR_FALSE
},
240 {kea_dh_rsa
, kt_dh
, sign_rsa
, PR_FALSE
, 0, PR_FALSE
},
241 {kea_dh_rsa_export
, kt_dh
, sign_rsa
, PR_TRUE
, 512, PR_FALSE
},
242 {kea_dhe_dss
, kt_dh
, sign_dsa
, PR_FALSE
, 0, PR_FALSE
},
243 {kea_dhe_dss_export
, kt_dh
, sign_dsa
, PR_TRUE
, 512, PR_FALSE
},
244 {kea_dhe_rsa
, kt_dh
, sign_rsa
, PR_FALSE
, 0, PR_FALSE
},
245 {kea_dhe_rsa_export
, kt_dh
, sign_rsa
, PR_TRUE
, 512, PR_FALSE
},
246 {kea_dh_anon
, kt_dh
, sign_null
, PR_FALSE
, 0, PR_FALSE
},
247 {kea_dh_anon_export
, kt_dh
, sign_null
, PR_TRUE
, 512, PR_FALSE
},
248 {kea_rsa_fips
, kt_rsa
, sign_rsa
, PR_FALSE
, 0, PR_TRUE
},
249 #ifdef NSS_ENABLE_ECC
250 {kea_ecdh_ecdsa
, kt_ecdh
, sign_ecdsa
, PR_FALSE
, 0, PR_FALSE
},
251 {kea_ecdhe_ecdsa
, kt_ecdh
, sign_ecdsa
, PR_FALSE
, 0, PR_FALSE
},
252 {kea_ecdh_rsa
, kt_ecdh
, sign_rsa
, PR_FALSE
, 0, PR_FALSE
},
253 {kea_ecdhe_rsa
, kt_ecdh
, sign_rsa
, PR_FALSE
, 0, PR_FALSE
},
254 {kea_ecdh_anon
, kt_ecdh
, sign_null
, PR_FALSE
, 0, PR_FALSE
},
255 #endif /* NSS_ENABLE_ECC */
258 /* must use ssl_LookupCipherSuiteDef to access */
259 static const ssl3CipherSuiteDef cipher_suite_defs
[] =
261 /* cipher_suite bulk_cipher_alg mac_alg key_exchange_alg */
263 {SSL_NULL_WITH_NULL_NULL
, cipher_null
, mac_null
, kea_null
},
264 {SSL_RSA_WITH_NULL_MD5
, cipher_null
, mac_md5
, kea_rsa
},
265 {SSL_RSA_WITH_NULL_SHA
, cipher_null
, mac_sha
, kea_rsa
},
266 {SSL_RSA_EXPORT_WITH_RC4_40_MD5
,cipher_rc4_40
, mac_md5
, kea_rsa_export
},
267 {SSL_RSA_WITH_RC4_128_MD5
, cipher_rc4
, mac_md5
, kea_rsa
},
268 {SSL_RSA_WITH_RC4_128_SHA
, cipher_rc4
, mac_sha
, kea_rsa
},
269 {SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5
,
270 cipher_rc2_40
, mac_md5
, kea_rsa_export
},
271 #if 0 /* not implemented */
272 {SSL_RSA_WITH_IDEA_CBC_SHA
, cipher_idea
, mac_sha
, kea_rsa
},
273 {SSL_RSA_EXPORT_WITH_DES40_CBC_SHA
,
274 cipher_des40
, mac_sha
, kea_rsa_export
},
276 {SSL_RSA_WITH_DES_CBC_SHA
, cipher_des
, mac_sha
, kea_rsa
},
277 {SSL_RSA_WITH_3DES_EDE_CBC_SHA
, cipher_3des
, mac_sha
, kea_rsa
},
278 {SSL_DHE_DSS_WITH_DES_CBC_SHA
, cipher_des
, mac_sha
, kea_dhe_dss
},
279 {SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA
,
280 cipher_3des
, mac_sha
, kea_dhe_dss
},
281 {TLS_DHE_DSS_WITH_RC4_128_SHA
, cipher_rc4
, mac_sha
, kea_dhe_dss
},
282 #if 0 /* not implemented */
283 {SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA
,
284 cipher_des40
, mac_sha
, kea_dh_dss_export
},
285 {SSL_DH_DSS_DES_CBC_SHA
, cipher_des
, mac_sha
, kea_dh_dss
},
286 {SSL_DH_DSS_3DES_CBC_SHA
, cipher_3des
, mac_sha
, kea_dh_dss
},
287 {SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA
,
288 cipher_des40
, mac_sha
, kea_dh_rsa_export
},
289 {SSL_DH_RSA_DES_CBC_SHA
, cipher_des
, mac_sha
, kea_dh_rsa
},
290 {SSL_DH_RSA_3DES_CBC_SHA
, cipher_3des
, mac_sha
, kea_dh_rsa
},
291 {SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA
,
292 cipher_des40
, mac_sha
, kea_dh_dss_export
},
293 {SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA
,
294 cipher_des40
, mac_sha
, kea_dh_rsa_export
},
296 {SSL_DHE_RSA_WITH_DES_CBC_SHA
, cipher_des
, mac_sha
, kea_dhe_rsa
},
297 {SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA
,
298 cipher_3des
, mac_sha
, kea_dhe_rsa
},
300 {SSL_DH_ANON_EXPORT_RC4_40_MD5
, cipher_rc4_40
, mac_md5
, kea_dh_anon_export
},
301 {SSL_DH_ANON_EXPORT_RC4_40_MD5
, cipher_rc4
, mac_md5
, kea_dh_anon_export
},
302 {SSL_DH_ANON_EXPORT_WITH_DES40_CBC_SHA
,
303 cipher_des40
, mac_sha
, kea_dh_anon_export
},
304 {SSL_DH_ANON_DES_CBC_SHA
, cipher_des
, mac_sha
, kea_dh_anon
},
305 {SSL_DH_ANON_3DES_CBC_SHA
, cipher_3des
, mac_sha
, kea_dh_anon
},
309 /* New TLS cipher suites */
310 {TLS_RSA_WITH_AES_128_CBC_SHA
, cipher_aes_128
, mac_sha
, kea_rsa
},
311 {TLS_DHE_DSS_WITH_AES_128_CBC_SHA
, cipher_aes_128
, mac_sha
, kea_dhe_dss
},
312 {TLS_DHE_RSA_WITH_AES_128_CBC_SHA
, cipher_aes_128
, mac_sha
, kea_dhe_rsa
},
313 {TLS_RSA_WITH_AES_256_CBC_SHA
, cipher_aes_256
, mac_sha
, kea_rsa
},
314 {TLS_DHE_DSS_WITH_AES_256_CBC_SHA
, cipher_aes_256
, mac_sha
, kea_dhe_dss
},
315 {TLS_DHE_RSA_WITH_AES_256_CBC_SHA
, cipher_aes_256
, mac_sha
, kea_dhe_rsa
},
317 {TLS_DH_DSS_WITH_AES_128_CBC_SHA
, cipher_aes_128
, mac_sha
, kea_dh_dss
},
318 {TLS_DH_RSA_WITH_AES_128_CBC_SHA
, cipher_aes_128
, mac_sha
, kea_dh_rsa
},
319 {TLS_DH_ANON_WITH_AES_128_CBC_SHA
, cipher_aes_128
, mac_sha
, kea_dh_anon
},
320 {TLS_DH_DSS_WITH_AES_256_CBC_SHA
, cipher_aes_256
, mac_sha
, kea_dh_dss
},
321 {TLS_DH_RSA_WITH_AES_256_CBC_SHA
, cipher_aes_256
, mac_sha
, kea_dh_rsa
},
322 {TLS_DH_ANON_WITH_AES_256_CBC_SHA
, cipher_aes_256
, mac_sha
, kea_dh_anon
},
325 {TLS_RSA_WITH_CAMELLIA_128_CBC_SHA
, cipher_camellia_128
, mac_sha
, kea_rsa
},
326 {TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA
,
327 cipher_camellia_128
, mac_sha
, kea_dhe_dss
},
328 {TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA
,
329 cipher_camellia_128
, mac_sha
, kea_dhe_rsa
},
330 {TLS_RSA_WITH_CAMELLIA_256_CBC_SHA
, cipher_camellia_256
, mac_sha
, kea_rsa
},
331 {TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA
,
332 cipher_camellia_256
, mac_sha
, kea_dhe_dss
},
333 {TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA
,
334 cipher_camellia_256
, mac_sha
, kea_dhe_rsa
},
336 {TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA
,
337 cipher_des
, mac_sha
,kea_rsa_export_1024
},
338 {TLS_RSA_EXPORT1024_WITH_RC4_56_SHA
,
339 cipher_rc4_56
, mac_sha
,kea_rsa_export_1024
},
341 {SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA
, cipher_3des
, mac_sha
, kea_rsa_fips
},
342 {SSL_RSA_FIPS_WITH_DES_CBC_SHA
, cipher_des
, mac_sha
, kea_rsa_fips
},
344 #ifdef NSS_ENABLE_ECC
345 {TLS_ECDH_ECDSA_WITH_NULL_SHA
, cipher_null
, mac_sha
, kea_ecdh_ecdsa
},
346 {TLS_ECDH_ECDSA_WITH_RC4_128_SHA
, cipher_rc4
, mac_sha
, kea_ecdh_ecdsa
},
347 {TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA
, cipher_3des
, mac_sha
, kea_ecdh_ecdsa
},
348 {TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA
, cipher_aes_128
, mac_sha
, kea_ecdh_ecdsa
},
349 {TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA
, cipher_aes_256
, mac_sha
, kea_ecdh_ecdsa
},
351 {TLS_ECDHE_ECDSA_WITH_NULL_SHA
, cipher_null
, mac_sha
, kea_ecdhe_ecdsa
},
352 {TLS_ECDHE_ECDSA_WITH_RC4_128_SHA
, cipher_rc4
, mac_sha
, kea_ecdhe_ecdsa
},
353 {TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA
, cipher_3des
, mac_sha
, kea_ecdhe_ecdsa
},
354 {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
, cipher_aes_128
, mac_sha
, kea_ecdhe_ecdsa
},
355 {TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
, cipher_aes_256
, mac_sha
, kea_ecdhe_ecdsa
},
357 {TLS_ECDH_RSA_WITH_NULL_SHA
, cipher_null
, mac_sha
, kea_ecdh_rsa
},
358 {TLS_ECDH_RSA_WITH_RC4_128_SHA
, cipher_rc4
, mac_sha
, kea_ecdh_rsa
},
359 {TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA
, cipher_3des
, mac_sha
, kea_ecdh_rsa
},
360 {TLS_ECDH_RSA_WITH_AES_128_CBC_SHA
, cipher_aes_128
, mac_sha
, kea_ecdh_rsa
},
361 {TLS_ECDH_RSA_WITH_AES_256_CBC_SHA
, cipher_aes_256
, mac_sha
, kea_ecdh_rsa
},
363 {TLS_ECDHE_RSA_WITH_NULL_SHA
, cipher_null
, mac_sha
, kea_ecdhe_rsa
},
364 {TLS_ECDHE_RSA_WITH_RC4_128_SHA
, cipher_rc4
, mac_sha
, kea_ecdhe_rsa
},
365 {TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
, cipher_3des
, mac_sha
, kea_ecdhe_rsa
},
366 {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
, cipher_aes_128
, mac_sha
, kea_ecdhe_rsa
},
367 {TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
, cipher_aes_256
, mac_sha
, kea_ecdhe_rsa
},
370 {TLS_ECDH_anon_WITH_NULL_SHA
, cipher_null
, mac_sha
, kea_ecdh_anon
},
371 {TLS_ECDH_anon_WITH_RC4_128_SHA
, cipher_rc4
, mac_sha
, kea_ecdh_anon
},
372 {TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA
, cipher_3des
, mac_sha
, kea_ecdh_anon
},
373 {TLS_ECDH_anon_WITH_AES_128_CBC_SHA
, cipher_aes_128
, mac_sha
, kea_ecdh_anon
},
374 {TLS_ECDH_anon_WITH_AES_256_CBC_SHA
, cipher_aes_256
, mac_sha
, kea_ecdh_anon
},
376 #endif /* NSS_ENABLE_ECC */
379 static const CK_MECHANISM_TYPE kea_alg_defs
[] = {
387 typedef struct SSLCipher2MechStr
{
388 SSLCipherAlgorithm calg
;
389 CK_MECHANISM_TYPE cmech
;
392 /* indexed by type SSLCipherAlgorithm */
393 static const SSLCipher2Mech alg2Mech
[] = {
395 { calg_null
, (CK_MECHANISM_TYPE
)0x80000000L
},
396 { calg_rc4
, CKM_RC4
},
397 { calg_rc2
, CKM_RC2_CBC
},
398 { calg_des
, CKM_DES_CBC
},
399 { calg_3des
, CKM_DES3_CBC
},
400 { calg_idea
, CKM_IDEA_CBC
},
401 { calg_fortezza
, CKM_SKIPJACK_CBC64
},
402 { calg_aes
, CKM_AES_CBC
},
403 { calg_camellia
, CKM_CAMELLIA_CBC
},
404 /* { calg_init , (CK_MECHANISM_TYPE)0x7fffffffL } */
407 #define mmech_null (CK_MECHANISM_TYPE)0x80000000L
408 #define mmech_md5 CKM_SSL3_MD5_MAC
409 #define mmech_sha CKM_SSL3_SHA1_MAC
410 #define mmech_md5_hmac CKM_MD5_HMAC
411 #define mmech_sha_hmac CKM_SHA_1_HMAC
413 static const ssl3MACDef mac_defs
[] = { /* indexed by SSL3MACAlgorithm */
414 /* mac mmech pad_size mac_size */
415 { mac_null
, mmech_null
, 0, 0 },
416 { mac_md5
, mmech_md5
, 48, MD5_LENGTH
},
417 { mac_sha
, mmech_sha
, 40, SHA1_LENGTH
},
418 {hmac_md5
, mmech_md5_hmac
, 48, MD5_LENGTH
},
419 {hmac_sha
, mmech_sha_hmac
, 40, SHA1_LENGTH
},
422 /* indexed by SSL3BulkCipher */
423 const char * const ssl3_cipherName
[] = {
441 #ifdef NSS_ENABLE_ECC
442 /* The ECCWrappedKeyInfo structure defines how various pieces of
443 * information are laid out within wrappedSymmetricWrappingkey
444 * for ECDH key exchange. Since wrappedSymmetricWrappingkey is
445 * a 512-byte buffer (see sslimpl.h), the variable length field
446 * in ECCWrappedKeyInfo can be at most (512 - 8) = 504 bytes.
448 * XXX For now, NSS only supports named elliptic curves of size 571 bits
449 * or smaller. The public value will fit within 145 bytes and EC params
450 * will fit within 12 bytes. We'll need to revisit this when NSS
451 * supports arbitrary curves.
453 #define MAX_EC_WRAPPED_KEY_BUFLEN 504
455 typedef struct ECCWrappedKeyInfoStr
{
456 PRUint16 size
; /* EC public key size in bits */
457 PRUint16 encodedParamLen
; /* length (in bytes) of DER encoded EC params */
458 PRUint16 pubValueLen
; /* length (in bytes) of EC public value */
459 PRUint16 wrappedKeyLen
; /* length (in bytes) of the wrapped key */
460 PRUint8 var
[MAX_EC_WRAPPED_KEY_BUFLEN
]; /* this buffer contains the */
461 /* EC public-key params, the EC public value and the wrapped key */
463 #endif /* NSS_ENABLE_ECC */
468 ssl3_DecodeHandshakeType(int msgType
)
471 static char line
[40];
474 case hello_request
: rv
= "hello_request (0)"; break;
475 case client_hello
: rv
= "client_hello (1)"; break;
476 case server_hello
: rv
= "server_hello (2)"; break;
477 case certificate
: rv
= "certificate (11)"; break;
478 case server_key_exchange
: rv
= "server_key_exchange (12)"; break;
479 case certificate_request
: rv
= "certificate_request (13)"; break;
480 case server_hello_done
: rv
= "server_hello_done (14)"; break;
481 case certificate_verify
: rv
= "certificate_verify (15)"; break;
482 case client_key_exchange
: rv
= "client_key_exchange (16)"; break;
483 case finished
: rv
= "finished (20)"; break;
485 sprintf(line
, "*UNKNOWN* handshake type! (%d)", msgType
);
492 ssl3_DecodeContentType(int msgType
)
495 static char line
[40];
498 case content_change_cipher_spec
:
499 rv
= "change_cipher_spec (20)"; break;
500 case content_alert
: rv
= "alert (21)"; break;
501 case content_handshake
: rv
= "handshake (22)"; break;
502 case content_application_data
:
503 rv
= "application_data (23)"; break;
505 sprintf(line
, "*UNKNOWN* record type! (%d)", msgType
);
514 SSL_GetStatistics(void)
519 typedef struct tooLongStr
{
520 #if defined(IS_LITTLE_ENDIAN)
529 void SSL_AtomicIncrementLong(long * x
)
531 if ((sizeof *x
) == sizeof(PRInt32
)) {
532 PR_AtomicIncrement((PRInt32
*)x
);
534 tooLong
* tl
= (tooLong
*)x
;
535 if (PR_AtomicIncrement(&tl
->low
) == 0)
536 PR_AtomicIncrement(&tl
->high
);
540 /* return pointer to ssl3CipherSuiteDef for suite, or NULL */
541 /* XXX This does a linear search. A binary search would be better. */
542 static const ssl3CipherSuiteDef
*
543 ssl_LookupCipherSuiteDef(ssl3CipherSuite suite
)
545 int cipher_suite_def_len
=
546 sizeof(cipher_suite_defs
) / sizeof(cipher_suite_defs
[0]);
549 for (i
= 0; i
< cipher_suite_def_len
; i
++) {
550 if (cipher_suite_defs
[i
].cipher_suite
== suite
)
551 return &cipher_suite_defs
[i
];
553 PORT_Assert(PR_FALSE
); /* We should never get here. */
554 PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE
);
558 /* Find the cipher configuration struct associate with suite */
559 /* XXX This does a linear search. A binary search would be better. */
560 static ssl3CipherSuiteCfg
*
561 ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite
, ssl3CipherSuiteCfg
*suites
)
565 for (i
= 0; i
< ssl_V3_SUITES_IMPLEMENTED
; i
++) {
566 if (suites
[i
].cipher_suite
== suite
)
569 /* return NULL and let the caller handle it. */
570 PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE
);
575 /* Initialize the suite->isPresent value for config_match
576 * Returns count of enabled ciphers supported by extant tokens,
577 * regardless of policy or user preference.
578 * If this returns zero, the user cannot do SSL v3.
581 ssl3_config_match_init(sslSocket
*ss
)
583 ssl3CipherSuiteCfg
* suite
;
584 const ssl3CipherSuiteDef
*cipher_def
;
585 SSLCipherAlgorithm cipher_alg
;
586 CK_MECHANISM_TYPE cipher_mech
;
587 SSL3KEAType exchKeyType
;
592 sslServerCerts
*svrAuth
;
596 PORT_SetError(SEC_ERROR_INVALID_ARGS
);
599 if (!ss
->opt
.enableSSL3
&& !ss
->opt
.enableTLS
) {
602 isServer
= (PRBool
)(ss
->sec
.isServer
!= 0);
604 for (i
= 0; i
< ssl_V3_SUITES_IMPLEMENTED
; i
++) {
605 suite
= &ss
->cipherSuites
[i
];
606 if (suite
->enabled
) {
608 /* We need the cipher defs to see if we have a token that can handle
609 * this cipher. It isn't part of the static definition.
611 cipher_def
= ssl_LookupCipherSuiteDef(suite
->cipher_suite
);
613 suite
->isPresent
= PR_FALSE
;
616 cipher_alg
=bulk_cipher_defs
[cipher_def
->bulk_cipher_alg
].calg
;
617 PORT_Assert( alg2Mech
[cipher_alg
].calg
== cipher_alg
);
618 cipher_mech
= alg2Mech
[cipher_alg
].cmech
;
620 kea_defs
[cipher_def
->key_exchange_alg
].exchKeyType
;
621 #ifndef NSS_ENABLE_ECC
622 svrAuth
= ss
->serverCerts
+ exchKeyType
;
624 /* XXX SSLKEAType isn't really a good choice for
625 * indexing certificates. It doesn't work for
626 * (EC)DHE-* ciphers. Here we use a hack to ensure
627 * that the server uses an RSA cert for (EC)DHE-RSA.
629 switch (cipher_def
->key_exchange_alg
) {
631 #if NSS_SERVER_DHE_IMPLEMENTED
632 /* XXX NSS does not yet implement the server side of _DHE_
633 * cipher suites. Correcting the computation for svrAuth,
634 * as the case below does, causes NSS SSL servers to begin to
635 * negotiate cipher suites they do not implement. So, until
636 * server side _DHE_ is implemented, keep this disabled.
640 svrAuth
= ss
->serverCerts
+ kt_rsa
;
645 * XXX We ought to have different indices for
646 * ECDSA- and RSA-signed EC certificates so
647 * we could support both key exchange mechanisms
648 * simultaneously. For now, both of them use
649 * whatever is in the certificate slot for kt_ecdh
652 svrAuth
= ss
->serverCerts
+ exchKeyType
;
655 #endif /* NSS_ENABLE_ECC */
657 /* Mark the suites that are backed by real tokens, certs and keys */
658 suite
->isPresent
= (PRBool
)
659 (((exchKeyType
== kt_null
) ||
660 ((!isServer
|| (svrAuth
->serverKeyPair
&&
661 svrAuth
->SERVERKEY
&&
662 svrAuth
->serverCertChain
)) &&
663 PK11_TokenExists(kea_alg_defs
[exchKeyType
]))) &&
664 ((cipher_alg
== calg_null
) || PK11_TokenExists(cipher_mech
)));
665 if (suite
->isPresent
)
669 PORT_Assert(numPresent
> 0 || numEnabled
== 0);
670 if (numPresent
<= 0) {
671 PORT_SetError(SSL_ERROR_NO_CIPHERS_SUPPORTED
);
677 /* return PR_TRUE if suite matches policy and enabled state */
678 /* It would be a REALLY BAD THING (tm) if we ever permitted the use
679 ** of a cipher that was NOT_ALLOWED. So, if this is ever called with
680 ** policy == SSL_NOT_ALLOWED, report no match.
682 /* adjust suite enabled to the availability of a token that can do the
685 config_match(ssl3CipherSuiteCfg
*suite
, int policy
, PRBool enabled
)
687 PORT_Assert(policy
!= SSL_NOT_ALLOWED
&& enabled
!= PR_FALSE
);
688 if (policy
== SSL_NOT_ALLOWED
|| !enabled
)
690 return (PRBool
)(suite
->enabled
&&
692 suite
->policy
!= SSL_NOT_ALLOWED
&&
693 suite
->policy
<= policy
);
696 /* return number of cipher suites that match policy and enabled state */
697 /* called from ssl3_SendClientHello and ssl3_ConstructV2CipherSpecsHack */
699 count_cipher_suites(sslSocket
*ss
, int policy
, PRBool enabled
)
703 if (!ss
->opt
.enableSSL3
&& !ss
->opt
.enableTLS
) {
706 for (i
= 0; i
< ssl_V3_SUITES_IMPLEMENTED
; i
++) {
707 if (config_match(&ss
->cipherSuites
[i
], policy
, enabled
))
711 PORT_SetError(SSL_ERROR_SSL_DISABLED
);
717 anyRestrictedEnabled(sslSocket
*ss
)
721 if (!ss
->opt
.enableSSL3
&& !ss
->opt
.enableTLS
) {
724 for (i
= 0; i
< ssl_V3_SUITES_IMPLEMENTED
; i
++) {
725 ssl3CipherSuiteCfg
*suite
= &ss
->cipherSuites
[i
];
726 if (suite
->policy
== SSL_RESTRICTED
&&
735 * Null compression, mac and encryption functions
739 Null_Cipher(void *ctx
, unsigned char *output
, int *outputLen
, int maxOutputLen
,
740 const unsigned char *input
, int inputLen
)
742 *outputLen
= inputLen
;
744 PORT_Memcpy(output
, input
, inputLen
);
749 * SSL3 Utility functions
753 ssl3_NegotiateVersion(sslSocket
*ss
, SSL3ProtocolVersion peerVersion
)
755 SSL3ProtocolVersion version
;
756 SSL3ProtocolVersion maxVersion
;
758 if (ss
->opt
.enableTLS
) {
759 maxVersion
= SSL_LIBRARY_VERSION_3_1_TLS
;
760 } else if (ss
->opt
.enableSSL3
) {
761 maxVersion
= SSL_LIBRARY_VERSION_3_0
;
763 /* what are we doing here? */
764 PORT_Assert(ss
->opt
.enableSSL3
|| ss
->opt
.enableTLS
);
765 PORT_SetError(SSL_ERROR_SSL_DISABLED
);
769 ss
->version
= version
= PR_MIN(maxVersion
, peerVersion
);
771 if ((version
== SSL_LIBRARY_VERSION_3_1_TLS
&& ss
->opt
.enableTLS
) ||
772 (version
== SSL_LIBRARY_VERSION_3_0
&& ss
->opt
.enableSSL3
)) {
776 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP
);
782 ssl3_GetNewRandom(SSL3Random
*random
)
784 PRUint32 gmt
= ssl_Time();
787 random
->rand
[0] = (unsigned char)(gmt
>> 24);
788 random
->rand
[1] = (unsigned char)(gmt
>> 16);
789 random
->rand
[2] = (unsigned char)(gmt
>> 8);
790 random
->rand
[3] = (unsigned char)(gmt
);
792 /* first 4 bytes are reserverd for time */
793 rv
= PK11_GenerateRandom(&random
->rand
[4], SSL3_RANDOM_LENGTH
- 4);
794 if (rv
!= SECSuccess
) {
795 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE
);
800 /* Called by ssl3_SendServerKeyExchange and ssl3_SendCertificateVerify */
802 ssl3_SignHashes(SSL3Hashes
*hash
, SECKEYPrivateKey
*key
, SECItem
*buf
,
805 SECStatus rv
= SECFailure
;
806 PRBool doDerEncode
= PR_FALSE
;
811 signatureLen
= PK11_SignatureLen(key
);
812 if (signatureLen
<= 0) {
813 PORT_SetError(SEC_ERROR_INVALID_KEY
);
817 buf
->len
= (unsigned)signatureLen
;
818 buf
->data
= (unsigned char *)PORT_Alloc(signatureLen
);
820 goto done
; /* error code was set. */
822 switch (key
->keyType
) {
824 hashItem
.data
= hash
->md5
;
825 hashItem
.len
= sizeof(SSL3Hashes
);
829 hashItem
.data
= hash
->sha
;
830 hashItem
.len
= sizeof(hash
->sha
);
832 #ifdef NSS_ENABLE_ECC
834 doDerEncode
= PR_TRUE
;
835 hashItem
.data
= hash
->sha
;
836 hashItem
.len
= sizeof(hash
->sha
);
838 #endif /* NSS_ENABLE_ECC */
840 PORT_SetError(SEC_ERROR_INVALID_KEY
);
843 PRINT_BUF(60, (NULL
, "hash(es) to be signed", hashItem
.data
, hashItem
.len
));
845 rv
= PK11_Sign(key
, buf
, &hashItem
);
846 if (rv
!= SECSuccess
) {
847 ssl_MapLowLevelError(SSL_ERROR_SIGN_HASHES_FAILURE
);
848 } else if (doDerEncode
) {
849 SECItem derSig
= {siBuffer
, NULL
, 0};
851 /* This also works for an ECDSA signature */
852 rv
= DSAU_EncodeDerSigWithLen(&derSig
, buf
, buf
->len
);
853 if (rv
== SECSuccess
) {
854 PORT_Free(buf
->data
); /* discard unencoded signature. */
855 *buf
= derSig
; /* give caller encoded signature. */
856 } else if (derSig
.data
) {
857 PORT_Free(derSig
.data
);
861 PRINT_BUF(60, (NULL
, "signed hashes", (unsigned char*)buf
->data
, buf
->len
));
863 if (rv
!= SECSuccess
&& buf
->data
) {
864 PORT_Free(buf
->data
);
870 /* Called from ssl3_HandleServerKeyExchange, ssl3_HandleCertificateVerify */
872 ssl3_VerifySignedHashes(SSL3Hashes
*hash
, CERTCertificate
*cert
,
873 SECItem
*buf
, PRBool isTLS
, void *pwArg
)
875 SECKEYPublicKey
* key
;
876 SECItem
* signature
= NULL
;
879 #ifdef NSS_ENABLE_ECC
881 #endif /* NSS_ENABLE_ECC */
884 PRINT_BUF(60, (NULL
, "check signed hashes",
885 buf
->data
, buf
->len
));
887 key
= CERT_ExtractPublicKey(cert
);
889 /* CERT_ExtractPublicKey doesn't set error code */
890 PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE
);
894 switch (key
->keyType
) {
896 hashItem
.data
= hash
->md5
;
897 hashItem
.len
= sizeof(SSL3Hashes
);
900 hashItem
.data
= hash
->sha
;
901 hashItem
.len
= sizeof(hash
->sha
);
903 signature
= DSAU_DecodeDerSig(buf
);
905 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE
);
912 #ifdef NSS_ENABLE_ECC
914 hashItem
.data
= hash
->sha
;
915 hashItem
.len
= sizeof(hash
->sha
);
917 * ECDSA signatures always encode the integers r and s
918 * using ASN (unlike DSA where ASN encoding is used
919 * with TLS but not with SSL3)
921 len
= SECKEY_SignatureLen(key
);
923 SECKEY_DestroyPublicKey(key
);
924 PORT_SetError(SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE
);
927 signature
= DSAU_DecodeDerSigToLen(buf
, len
);
929 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE
);
934 #endif /* NSS_ENABLE_ECC */
937 SECKEY_DestroyPublicKey(key
);
938 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG
);
942 PRINT_BUF(60, (NULL
, "hash(es) to be verified",
943 hashItem
.data
, hashItem
.len
));
945 rv
= PK11_Verify(key
, buf
, &hashItem
, pwArg
);
946 SECKEY_DestroyPublicKey(key
);
948 SECITEM_FreeItem(signature
, PR_TRUE
);
950 if (rv
!= SECSuccess
) {
951 ssl_MapLowLevelError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE
);
957 /* Caller must set hiLevel error code. */
958 /* Called from ssl3_ComputeExportRSAKeyHash
959 * ssl3_ComputeDHKeyHash
960 * which are called from ssl3_HandleServerKeyExchange.
963 ssl3_ComputeCommonKeyHash(PRUint8
* hashBuf
, unsigned int bufLen
,
964 SSL3Hashes
*hashes
, PRBool bypassPKCS11
)
966 SECStatus rv
= SECSuccess
;
969 MD5_HashBuf (hashes
->md5
, hashBuf
, bufLen
);
970 SHA1_HashBuf(hashes
->sha
, hashBuf
, bufLen
);
972 rv
= PK11_HashBuf(SEC_OID_MD5
, hashes
->md5
, hashBuf
, bufLen
);
973 if (rv
!= SECSuccess
) {
974 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE
);
979 rv
= PK11_HashBuf(SEC_OID_SHA1
, hashes
->sha
, hashBuf
, bufLen
);
980 if (rv
!= SECSuccess
) {
981 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE
);
989 /* Caller must set hiLevel error code.
990 ** Called from ssl3_SendServerKeyExchange and
991 ** ssl3_HandleServerKeyExchange.
994 ssl3_ComputeExportRSAKeyHash(SECItem modulus
, SECItem publicExponent
,
995 SSL3Random
*client_rand
, SSL3Random
*server_rand
,
996 SSL3Hashes
*hashes
, PRBool bypassPKCS11
)
1000 SECStatus rv
= SECSuccess
;
1001 unsigned int bufLen
;
1002 PRUint8 buf
[2*SSL3_RANDOM_LENGTH
+ 2 + 4096/8 + 2 + 4096/8];
1004 bufLen
= 2*SSL3_RANDOM_LENGTH
+ 2 + modulus
.len
+ 2 + publicExponent
.len
;
1005 if (bufLen
<= sizeof buf
) {
1008 hashBuf
= PORT_Alloc(bufLen
);
1014 memcpy(hashBuf
, client_rand
, SSL3_RANDOM_LENGTH
);
1015 pBuf
= hashBuf
+ SSL3_RANDOM_LENGTH
;
1016 memcpy(pBuf
, server_rand
, SSL3_RANDOM_LENGTH
);
1017 pBuf
+= SSL3_RANDOM_LENGTH
;
1018 pBuf
[0] = (PRUint8
)(modulus
.len
>> 8);
1019 pBuf
[1] = (PRUint8
)(modulus
.len
);
1021 memcpy(pBuf
, modulus
.data
, modulus
.len
);
1022 pBuf
+= modulus
.len
;
1023 pBuf
[0] = (PRUint8
)(publicExponent
.len
>> 8);
1024 pBuf
[1] = (PRUint8
)(publicExponent
.len
);
1026 memcpy(pBuf
, publicExponent
.data
, publicExponent
.len
);
1027 pBuf
+= publicExponent
.len
;
1028 PORT_Assert((unsigned int)(pBuf
- hashBuf
) == bufLen
);
1030 rv
= ssl3_ComputeCommonKeyHash(hashBuf
, bufLen
, hashes
, bypassPKCS11
);
1032 PRINT_BUF(95, (NULL
, "RSAkey hash: ", hashBuf
, bufLen
));
1033 PRINT_BUF(95, (NULL
, "RSAkey hash: MD5 result", hashes
->md5
, MD5_LENGTH
));
1034 PRINT_BUF(95, (NULL
, "RSAkey hash: SHA1 result", hashes
->sha
, SHA1_LENGTH
));
1036 if (hashBuf
!= buf
&& hashBuf
!= NULL
)
1041 /* Caller must set hiLevel error code. */
1042 /* Called from ssl3_HandleServerKeyExchange. */
1044 ssl3_ComputeDHKeyHash(SECItem dh_p
, SECItem dh_g
, SECItem dh_Ys
,
1045 SSL3Random
*client_rand
, SSL3Random
*server_rand
,
1046 SSL3Hashes
*hashes
, PRBool bypassPKCS11
)
1050 SECStatus rv
= SECSuccess
;
1051 unsigned int bufLen
;
1052 PRUint8 buf
[2*SSL3_RANDOM_LENGTH
+ 2 + 4096/8 + 2 + 4096/8];
1054 bufLen
= 2*SSL3_RANDOM_LENGTH
+ 2 + dh_p
.len
+ 2 + dh_g
.len
+ 2 + dh_Ys
.len
;
1055 if (bufLen
<= sizeof buf
) {
1058 hashBuf
= PORT_Alloc(bufLen
);
1064 memcpy(hashBuf
, client_rand
, SSL3_RANDOM_LENGTH
);
1065 pBuf
= hashBuf
+ SSL3_RANDOM_LENGTH
;
1066 memcpy(pBuf
, server_rand
, SSL3_RANDOM_LENGTH
);
1067 pBuf
+= SSL3_RANDOM_LENGTH
;
1068 pBuf
[0] = (PRUint8
)(dh_p
.len
>> 8);
1069 pBuf
[1] = (PRUint8
)(dh_p
.len
);
1071 memcpy(pBuf
, dh_p
.data
, dh_p
.len
);
1073 pBuf
[0] = (PRUint8
)(dh_g
.len
>> 8);
1074 pBuf
[1] = (PRUint8
)(dh_g
.len
);
1076 memcpy(pBuf
, dh_g
.data
, dh_g
.len
);
1078 pBuf
[0] = (PRUint8
)(dh_Ys
.len
>> 8);
1079 pBuf
[1] = (PRUint8
)(dh_Ys
.len
);
1081 memcpy(pBuf
, dh_Ys
.data
, dh_Ys
.len
);
1083 PORT_Assert((unsigned int)(pBuf
- hashBuf
) == bufLen
);
1085 rv
= ssl3_ComputeCommonKeyHash(hashBuf
, bufLen
, hashes
, bypassPKCS11
);
1087 PRINT_BUF(95, (NULL
, "DHkey hash: ", hashBuf
, bufLen
));
1088 PRINT_BUF(95, (NULL
, "DHkey hash: MD5 result", hashes
->md5
, MD5_LENGTH
));
1089 PRINT_BUF(95, (NULL
, "DHkey hash: SHA1 result", hashes
->sha
, SHA1_LENGTH
));
1091 if (hashBuf
!= buf
&& hashBuf
!= NULL
)
1097 ssl3_BumpSequenceNumber(SSL3SequenceNumber
*num
)
1104 /* Called twice, only from ssl3_DestroyCipherSpec (immediately below). */
1106 ssl3_CleanupKeyMaterial(ssl3KeyMaterial
*mat
)
1108 if (mat
->write_key
!= NULL
) {
1109 PK11_FreeSymKey(mat
->write_key
);
1110 mat
->write_key
= NULL
;
1112 if (mat
->write_mac_key
!= NULL
) {
1113 PK11_FreeSymKey(mat
->write_mac_key
);
1114 mat
->write_mac_key
= NULL
;
1116 if (mat
->write_mac_context
!= NULL
) {
1117 PK11_DestroyContext(mat
->write_mac_context
, PR_TRUE
);
1118 mat
->write_mac_context
= NULL
;
1122 /* Called from ssl3_SendChangeCipherSpecs() and
1123 ** ssl3_HandleChangeCipherSpecs()
1124 ** ssl3_DestroySSL3Info
1125 ** Caller must hold SpecWriteLock.
1128 ssl3_DestroyCipherSpec(ssl3CipherSpec
*spec
)
1130 PRBool freeit
= (PRBool
)(!spec
->bypassCiphers
);
1131 /* PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); Don't have ss! */
1132 if (spec
->destroy
) {
1133 spec
->destroy(spec
->encodeContext
, freeit
);
1134 spec
->destroy(spec
->decodeContext
, freeit
);
1135 spec
->encodeContext
= NULL
; /* paranoia */
1136 spec
->decodeContext
= NULL
;
1138 if (spec
->master_secret
!= NULL
) {
1139 PK11_FreeSymKey(spec
->master_secret
);
1140 spec
->master_secret
= NULL
;
1142 spec
->msItem
.data
= NULL
;
1143 spec
->msItem
.len
= 0;
1144 ssl3_CleanupKeyMaterial(&spec
->client
);
1145 ssl3_CleanupKeyMaterial(&spec
->server
);
1146 spec
->bypassCiphers
= PR_FALSE
;
1150 /* Fill in the pending cipher spec with info from the selected ciphersuite.
1151 ** This is as much initialization as we can do without having key material.
1152 ** Called from ssl3_HandleServerHello(), ssl3_SendServerHello()
1153 ** Caller must hold the ssl3 handshake lock.
1154 ** Acquires & releases SpecWriteLock.
1157 ssl3_SetupPendingCipherSpec(sslSocket
*ss
)
1159 ssl3CipherSpec
* pwSpec
;
1160 ssl3CipherSpec
* cwSpec
;
1161 ssl3CipherSuite suite
= ss
->ssl3
.hs
.cipher_suite
;
1162 SSL3MACAlgorithm mac
;
1163 SSL3BulkCipher cipher
;
1164 SSL3KeyExchangeAlgorithm kea
;
1165 const ssl3CipherSuiteDef
*suite_def
;
1168 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
1170 ssl_GetSpecWriteLock(ss
); /*******************************/
1172 pwSpec
= ss
->ssl3
.pwSpec
;
1173 PORT_Assert(pwSpec
== ss
->ssl3
.prSpec
);
1175 /* This hack provides maximal interoperability with SSL 3 servers. */
1176 cwSpec
= ss
->ssl3
.cwSpec
;
1177 if (cwSpec
->mac_def
->mac
== mac_null
) {
1178 /* SSL records are not being MACed. */
1179 cwSpec
->version
= ss
->version
;
1182 pwSpec
->version
= ss
->version
;
1183 isTLS
= (PRBool
)(pwSpec
->version
> SSL_LIBRARY_VERSION_3_0
);
1185 SSL_TRC(3, ("%d: SSL3[%d]: Set XXX Pending Cipher Suite to 0x%04x",
1186 SSL_GETPID(), ss
->fd
, suite
));
1188 suite_def
= ssl_LookupCipherSuiteDef(suite
);
1189 if (suite_def
== NULL
) {
1190 ssl_ReleaseSpecWriteLock(ss
);
1191 return SECFailure
; /* error code set by ssl_LookupCipherSuiteDef */
1195 cipher
= suite_def
->bulk_cipher_alg
;
1196 kea
= suite_def
->key_exchange_alg
;
1197 mac
= suite_def
->mac_alg
;
1201 ss
->ssl3
.hs
.suite_def
= suite_def
;
1202 ss
->ssl3
.hs
.kea_def
= &kea_defs
[kea
];
1203 PORT_Assert(ss
->ssl3
.hs
.kea_def
->kea
== kea
);
1205 pwSpec
->cipher_def
= &bulk_cipher_defs
[cipher
];
1206 PORT_Assert(pwSpec
->cipher_def
->cipher
== cipher
);
1208 pwSpec
->mac_def
= &mac_defs
[mac
];
1209 PORT_Assert(pwSpec
->mac_def
->mac
== mac
);
1211 ss
->sec
.keyBits
= pwSpec
->cipher_def
->key_size
* BPB
;
1212 ss
->sec
.secretKeyBits
= pwSpec
->cipher_def
->secret_key_size
* BPB
;
1213 ss
->sec
.cipherType
= cipher
;
1215 pwSpec
->encodeContext
= NULL
;
1216 pwSpec
->decodeContext
= NULL
;
1218 pwSpec
->mac_size
= pwSpec
->mac_def
->mac_size
;
1220 ssl_ReleaseSpecWriteLock(ss
); /*******************************/
1224 /* Initialize encryption and MAC contexts for pending spec.
1225 * Master Secret already is derived in spec->msItem
1226 * Caller holds Spec write lock.
1229 ssl3_InitPendingContextsBypass(sslSocket
*ss
)
1231 ssl3CipherSpec
* pwSpec
;
1232 const ssl3BulkCipherDef
*cipher_def
;
1233 void * serverContext
= NULL
;
1234 void * clientContext
= NULL
;
1235 BLapiInitContextFunc initFn
= (BLapiInitContextFunc
)NULL
;
1237 unsigned int optArg1
= 0;
1238 unsigned int optArg2
= 0;
1239 PRBool server_encrypts
= ss
->sec
.isServer
;
1241 SSLCipherAlgorithm calg
;
1244 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
1246 PORT_Assert(ss
->ssl3
.prSpec
== ss
->ssl3
.pwSpec
);
1248 pwSpec
= ss
->ssl3
.pwSpec
;
1249 cipher_def
= pwSpec
->cipher_def
;
1250 macLength
= pwSpec
->mac_size
;
1252 /* MAC setup is done when computing the mac, not here.
1253 * Now setup the crypto contexts.
1256 calg
= cipher_def
->calg
;
1258 serverContext
= pwSpec
->server
.cipher_context
;
1259 clientContext
= pwSpec
->client
.cipher_context
;
1263 pwSpec
->encode
= Null_Cipher
;
1264 pwSpec
->decode
= Null_Cipher
;
1265 pwSpec
->destroy
= NULL
;
1269 initFn
= (BLapiInitContextFunc
)RC4_InitContext
;
1270 pwSpec
->encode
= (SSLCipher
) RC4_Encrypt
;
1271 pwSpec
->decode
= (SSLCipher
) RC4_Decrypt
;
1272 pwSpec
->destroy
= (SSLDestroy
) RC4_DestroyContext
;
1275 initFn
= (BLapiInitContextFunc
)RC2_InitContext
;
1277 optArg1
= cipher_def
->key_size
;
1278 pwSpec
->encode
= (SSLCipher
) RC2_Encrypt
;
1279 pwSpec
->decode
= (SSLCipher
) RC2_Decrypt
;
1280 pwSpec
->destroy
= (SSLDestroy
) RC2_DestroyContext
;
1283 initFn
= (BLapiInitContextFunc
)DES_InitContext
;
1285 optArg1
= server_encrypts
;
1286 pwSpec
->encode
= (SSLCipher
) DES_Encrypt
;
1287 pwSpec
->decode
= (SSLCipher
) DES_Decrypt
;
1288 pwSpec
->destroy
= (SSLDestroy
) DES_DestroyContext
;
1291 initFn
= (BLapiInitContextFunc
)DES_InitContext
;
1292 mode
= NSS_DES_EDE3_CBC
;
1293 optArg1
= server_encrypts
;
1294 pwSpec
->encode
= (SSLCipher
) DES_Encrypt
;
1295 pwSpec
->decode
= (SSLCipher
) DES_Decrypt
;
1296 pwSpec
->destroy
= (SSLDestroy
) DES_DestroyContext
;
1299 initFn
= (BLapiInitContextFunc
)AES_InitContext
;
1301 optArg1
= server_encrypts
;
1302 optArg2
= AES_BLOCK_SIZE
;
1303 pwSpec
->encode
= (SSLCipher
) AES_Encrypt
;
1304 pwSpec
->decode
= (SSLCipher
) AES_Decrypt
;
1305 pwSpec
->destroy
= (SSLDestroy
) AES_DestroyContext
;
1308 case ssl_calg_camellia
:
1309 initFn
= (BLapiInitContextFunc
)Camellia_InitContext
;
1310 mode
= NSS_CAMELLIA_CBC
;
1311 optArg1
= server_encrypts
;
1312 optArg2
= CAMELLIA_BLOCK_SIZE
;
1313 pwSpec
->encode
= (SSLCipher
) Camellia_Encrypt
;
1314 pwSpec
->decode
= (SSLCipher
) Camellia_Decrypt
;
1315 pwSpec
->destroy
= (SSLDestroy
) Camellia_DestroyContext
;
1319 case ssl_calg_fortezza
:
1322 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
1325 rv
= (*initFn
)(serverContext
,
1326 pwSpec
->server
.write_key_item
.data
,
1327 pwSpec
->server
.write_key_item
.len
,
1328 pwSpec
->server
.write_iv_item
.data
,
1329 mode
, optArg1
, optArg2
);
1330 if (rv
!= SECSuccess
) {
1332 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
1336 if (calg
== ssl_calg_des
|| calg
== ssl_calg_3des
|| calg
== ssl_calg_aes
1337 || calg
== ssl_calg_camellia
) {
1338 /* For block ciphers, if the server is encrypting, then the client
1339 * is decrypting, and vice versa.
1344 rv
= (*initFn
)(clientContext
,
1345 pwSpec
->client
.write_key_item
.data
,
1346 pwSpec
->client
.write_key_item
.len
,
1347 pwSpec
->client
.write_iv_item
.data
,
1348 mode
, optArg1
, optArg2
);
1349 if (rv
!= SECSuccess
) {
1351 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
1355 pwSpec
->encodeContext
= (ss
->sec
.isServer
) ? serverContext
: clientContext
;
1356 pwSpec
->decodeContext
= (ss
->sec
.isServer
) ? clientContext
: serverContext
;
1365 /* This function should probably be moved to pk11wrap and be named
1366 * PK11_ParamFromIVAndEffectiveKeyBits
1369 ssl3_ParamFromIV(CK_MECHANISM_TYPE mtype
, SECItem
*iv
, CK_ULONG ulEffectiveBits
)
1371 SECItem
* param
= PK11_ParamFromIV(mtype
, iv
);
1372 if (param
&& param
->data
&& param
->len
>= sizeof(CK_RC2_PARAMS
)) {
1374 case CKM_RC2_KEY_GEN
:
1378 case CKM_RC2_MAC_GENERAL
:
1379 case CKM_RC2_CBC_PAD
:
1380 *(CK_RC2_PARAMS
*)param
->data
= ulEffectiveBits
;
1387 /* Initialize encryption and MAC contexts for pending spec.
1388 * Master Secret already is derived.
1389 * Caller holds Spec write lock.
1392 ssl3_InitPendingContextsPKCS11(sslSocket
*ss
)
1394 ssl3CipherSpec
* pwSpec
;
1395 const ssl3BulkCipherDef
*cipher_def
;
1396 PK11Context
* serverContext
= NULL
;
1397 PK11Context
* clientContext
= NULL
;
1399 CK_MECHANISM_TYPE mechanism
;
1400 CK_MECHANISM_TYPE mac_mech
;
1402 CK_ULONG effKeyBits
;
1405 SSLCipherAlgorithm calg
;
1407 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
1409 PORT_Assert(ss
->ssl3
.prSpec
== ss
->ssl3
.pwSpec
);
1411 pwSpec
= ss
->ssl3
.pwSpec
;
1412 cipher_def
= pwSpec
->cipher_def
;
1413 macLength
= pwSpec
->mac_size
;
1416 ** Now setup the MAC contexts,
1417 ** crypto contexts are setup below.
1420 pwSpec
->client
.write_mac_context
= NULL
;
1421 pwSpec
->server
.write_mac_context
= NULL
;
1422 mac_mech
= pwSpec
->mac_def
->mmech
;
1423 mac_param
.data
= (unsigned char *)&macLength
;
1424 mac_param
.len
= sizeof(macLength
);
1427 pwSpec
->client
.write_mac_context
= PK11_CreateContextBySymKey(
1428 mac_mech
, CKA_SIGN
, pwSpec
->client
.write_mac_key
, &mac_param
);
1429 if (pwSpec
->client
.write_mac_context
== NULL
) {
1430 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE
);
1433 pwSpec
->server
.write_mac_context
= PK11_CreateContextBySymKey(
1434 mac_mech
, CKA_SIGN
, pwSpec
->server
.write_mac_key
, &mac_param
);
1435 if (pwSpec
->server
.write_mac_context
== NULL
) {
1436 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE
);
1441 ** Now setup the crypto contexts.
1444 calg
= cipher_def
->calg
;
1445 PORT_Assert(alg2Mech
[calg
].calg
== calg
);
1447 if (calg
== calg_null
) {
1448 pwSpec
->encode
= Null_Cipher
;
1449 pwSpec
->decode
= Null_Cipher
;
1450 pwSpec
->destroy
= NULL
;
1453 mechanism
= alg2Mech
[calg
].cmech
;
1454 effKeyBits
= cipher_def
->key_size
* BPB
;
1457 * build the server context
1459 iv
.data
= pwSpec
->server
.write_iv
;
1460 iv
.len
= cipher_def
->iv_size
;
1461 param
= ssl3_ParamFromIV(mechanism
, &iv
, effKeyBits
);
1462 if (param
== NULL
) {
1463 ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE
);
1466 serverContext
= PK11_CreateContextBySymKey(mechanism
,
1467 (ss
->sec
.isServer
? CKA_ENCRYPT
: CKA_DECRYPT
),
1468 pwSpec
->server
.write_key
, param
);
1469 iv
.data
= PK11_IVFromParam(mechanism
, param
, (int *)&iv
.len
);
1471 PORT_Memcpy(pwSpec
->server
.write_iv
, iv
.data
, iv
.len
);
1472 SECITEM_FreeItem(param
, PR_TRUE
);
1473 if (serverContext
== NULL
) {
1474 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE
);
1479 * build the client context
1481 iv
.data
= pwSpec
->client
.write_iv
;
1482 iv
.len
= cipher_def
->iv_size
;
1484 param
= ssl3_ParamFromIV(mechanism
, &iv
, effKeyBits
);
1485 if (param
== NULL
) {
1486 ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE
);
1489 clientContext
= PK11_CreateContextBySymKey(mechanism
,
1490 (ss
->sec
.isServer
? CKA_DECRYPT
: CKA_ENCRYPT
),
1491 pwSpec
->client
.write_key
, param
);
1492 iv
.data
= PK11_IVFromParam(mechanism
, param
, (int *)&iv
.len
);
1494 PORT_Memcpy(pwSpec
->client
.write_iv
, iv
.data
, iv
.len
);
1495 SECITEM_FreeItem(param
,PR_TRUE
);
1496 if (clientContext
== NULL
) {
1497 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE
);
1500 pwSpec
->encode
= (SSLCipher
) PK11_CipherOp
;
1501 pwSpec
->decode
= (SSLCipher
) PK11_CipherOp
;
1502 pwSpec
->destroy
= (SSLDestroy
) PK11_DestroyContext
;
1504 pwSpec
->encodeContext
= (ss
->sec
.isServer
) ? serverContext
: clientContext
;
1505 pwSpec
->decodeContext
= (ss
->sec
.isServer
) ? clientContext
: serverContext
;
1507 serverContext
= NULL
;
1508 clientContext
= NULL
;
1513 if (serverContext
!= NULL
) PK11_DestroyContext(serverContext
, PR_TRUE
);
1514 if (clientContext
!= NULL
) PK11_DestroyContext(clientContext
, PR_TRUE
);
1515 if (pwSpec
->client
.write_mac_context
!= NULL
) {
1516 PK11_DestroyContext(pwSpec
->client
.write_mac_context
,PR_TRUE
);
1517 pwSpec
->client
.write_mac_context
= NULL
;
1519 if (pwSpec
->server
.write_mac_context
!= NULL
) {
1520 PK11_DestroyContext(pwSpec
->server
.write_mac_context
,PR_TRUE
);
1521 pwSpec
->server
.write_mac_context
= NULL
;
1527 /* Complete the initialization of all keys, ciphers, MACs and their contexts
1528 * for the pending Cipher Spec.
1529 * Called from: ssl3_SendClientKeyExchange (for Full handshake)
1530 * ssl3_HandleRSAClientKeyExchange (for Full handshake)
1531 * ssl3_HandleServerHello (for session restart)
1532 * ssl3_HandleClientHello (for session restart)
1533 * Sets error code, but caller probably should override to disambiguate.
1534 * NULL pms means re-use old master_secret.
1536 * This code is common to the bypass and PKCS11 execution paths.
1537 * For the bypass case, pms is NULL.
1540 ssl3_InitPendingCipherSpec(sslSocket
*ss
, PK11SymKey
*pms
)
1542 ssl3CipherSpec
* pwSpec
;
1545 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
1547 ssl_GetSpecWriteLock(ss
); /**************************************/
1549 PORT_Assert(ss
->ssl3
.prSpec
== ss
->ssl3
.pwSpec
);
1551 pwSpec
= ss
->ssl3
.pwSpec
;
1553 if (pms
|| (!pwSpec
->msItem
.len
&& !pwSpec
->master_secret
)) {
1554 rv
= ssl3_DeriveMasterSecret(ss
, pms
);
1555 if (rv
!= SECSuccess
) {
1556 goto done
; /* err code set by ssl3_DeriveMasterSecret */
1559 if (ss
->opt
.bypassPKCS11
&& pwSpec
->msItem
.len
&& pwSpec
->msItem
.data
) {
1560 /* Double Bypass succeeded in extracting the master_secret */
1561 const ssl3KEADef
* kea_def
= ss
->ssl3
.hs
.kea_def
;
1562 PRBool isTLS
= (PRBool
)(kea_def
->tls_keygen
||
1563 (pwSpec
->version
> SSL_LIBRARY_VERSION_3_0
));
1564 pwSpec
->bypassCiphers
= PR_TRUE
;
1565 rv
= ssl3_KeyAndMacDeriveBypass( pwSpec
,
1566 (const unsigned char *)&ss
->ssl3
.hs
.client_random
,
1567 (const unsigned char *)&ss
->ssl3
.hs
.server_random
,
1569 (PRBool
)(kea_def
->is_limited
));
1570 if (rv
== SECSuccess
) {
1571 rv
= ssl3_InitPendingContextsBypass(ss
);
1573 } else if (pwSpec
->master_secret
) {
1574 rv
= ssl3_DeriveConnectionKeysPKCS11(ss
);
1575 if (rv
== SECSuccess
) {
1576 rv
= ssl3_InitPendingContextsPKCS11(ss
);
1579 PORT_Assert(pwSpec
->master_secret
);
1580 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
1585 ssl_ReleaseSpecWriteLock(ss
); /******************************/
1586 if (rv
!= SECSuccess
)
1587 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE
);
1592 * 60 bytes is 3 times the maximum length MAC size that is supported.
1594 static const unsigned char mac_pad_1
[60] = {
1595 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1596 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1597 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1598 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1599 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1600 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1601 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1602 0x36, 0x36, 0x36, 0x36
1604 static const unsigned char mac_pad_2
[60] = {
1605 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1606 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1607 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1608 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1609 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1610 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1611 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1612 0x5c, 0x5c, 0x5c, 0x5c
1615 /* Called from: ssl3_SendRecord()
1616 ** ssl3_HandleRecord()
1617 ** Caller must already hold the SpecReadLock. (wish we could assert that!)
1620 ssl3_ComputeRecordMAC(
1621 ssl3CipherSpec
* spec
,
1622 PRBool useServerMacKey
,
1623 SSL3ContentType type
,
1624 SSL3ProtocolVersion version
,
1625 SSL3SequenceNumber seq_num
,
1626 const SSL3Opaque
* input
,
1628 unsigned char * outbuf
,
1629 unsigned int * outLength
)
1631 const ssl3MACDef
* mac_def
;
1634 unsigned int tempLen
;
1635 unsigned char temp
[MAX_MAC_LENGTH
];
1637 temp
[0] = (unsigned char)(seq_num
.high
>> 24);
1638 temp
[1] = (unsigned char)(seq_num
.high
>> 16);
1639 temp
[2] = (unsigned char)(seq_num
.high
>> 8);
1640 temp
[3] = (unsigned char)(seq_num
.high
>> 0);
1641 temp
[4] = (unsigned char)(seq_num
.low
>> 24);
1642 temp
[5] = (unsigned char)(seq_num
.low
>> 16);
1643 temp
[6] = (unsigned char)(seq_num
.low
>> 8);
1644 temp
[7] = (unsigned char)(seq_num
.low
>> 0);
1647 /* TLS MAC includes the record's version field, SSL's doesn't.
1648 ** We decide which MAC defintiion to use based on the version of
1649 ** the protocol that was negotiated when the spec became current,
1650 ** NOT based on the version value in the record itself.
1651 ** But, we use the record'v version value in the computation.
1653 if (spec
->version
<= SSL_LIBRARY_VERSION_3_0
) {
1654 temp
[9] = MSB(inputLength
);
1655 temp
[10] = LSB(inputLength
);
1659 /* New TLS hash includes version. */
1660 temp
[9] = MSB(version
);
1661 temp
[10] = LSB(version
);
1662 temp
[11] = MSB(inputLength
);
1663 temp
[12] = LSB(inputLength
);
1668 PRINT_BUF(95, (NULL
, "frag hash1: temp", temp
, tempLen
));
1669 PRINT_BUF(95, (NULL
, "frag hash1: input", input
, inputLength
));
1671 mac_def
= spec
->mac_def
;
1672 if (mac_def
->mac
== mac_null
) {
1676 if (! spec
->bypassCiphers
) {
1677 PK11Context
*mac_context
=
1678 (useServerMacKey
? spec
->server
.write_mac_context
1679 : spec
->client
.write_mac_context
);
1680 rv
= PK11_DigestBegin(mac_context
);
1681 rv
|= PK11_DigestOp(mac_context
, temp
, tempLen
);
1682 rv
|= PK11_DigestOp(mac_context
, input
, inputLength
);
1683 rv
|= PK11_DigestFinal(mac_context
, outbuf
, outLength
, spec
->mac_size
);
1685 /* bypass version */
1686 const SECHashObject
*hashObj
= NULL
;
1687 unsigned int pad_bytes
= 0;
1688 PRUint64 write_mac_context
[MAX_MAC_CONTEXT_LLONGS
];
1690 switch (mac_def
->mac
) {
1696 hashObj
= HASH_GetRawHashObject(HASH_AlgMD5
);
1700 hashObj
= HASH_GetRawHashObject(HASH_AlgSHA1
);
1702 case ssl_hmac_md5
: /* used with TLS */
1703 hashObj
= HASH_GetRawHashObject(HASH_AlgMD5
);
1705 case ssl_hmac_sha
: /* used with TLS */
1706 hashObj
= HASH_GetRawHashObject(HASH_AlgSHA1
);
1713 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
1718 /* compute "inner" part of SSL3 MAC */
1719 hashObj
->begin(write_mac_context
);
1720 if (useServerMacKey
)
1721 hashObj
->update(write_mac_context
,
1722 spec
->server
.write_mac_key_item
.data
,
1723 spec
->server
.write_mac_key_item
.len
);
1725 hashObj
->update(write_mac_context
,
1726 spec
->client
.write_mac_key_item
.data
,
1727 spec
->client
.write_mac_key_item
.len
);
1728 hashObj
->update(write_mac_context
, mac_pad_1
, pad_bytes
);
1729 hashObj
->update(write_mac_context
, temp
, tempLen
);
1730 hashObj
->update(write_mac_context
, input
, inputLength
);
1731 hashObj
->end(write_mac_context
, temp
, &tempLen
, sizeof temp
);
1733 /* compute "outer" part of SSL3 MAC */
1734 hashObj
->begin(write_mac_context
);
1735 if (useServerMacKey
)
1736 hashObj
->update(write_mac_context
,
1737 spec
->server
.write_mac_key_item
.data
,
1738 spec
->server
.write_mac_key_item
.len
);
1740 hashObj
->update(write_mac_context
,
1741 spec
->client
.write_mac_key_item
.data
,
1742 spec
->client
.write_mac_key_item
.len
);
1743 hashObj
->update(write_mac_context
, mac_pad_2
, pad_bytes
);
1744 hashObj
->update(write_mac_context
, temp
, tempLen
);
1745 hashObj
->end(write_mac_context
, outbuf
, outLength
, spec
->mac_size
);
1747 } else { /* is TLS */
1748 #define cx ((HMACContext *)write_mac_context)
1749 if (useServerMacKey
) {
1750 rv
= HMAC_Init(cx
, hashObj
,
1751 spec
->server
.write_mac_key_item
.data
,
1752 spec
->server
.write_mac_key_item
.len
, PR_FALSE
);
1754 rv
= HMAC_Init(cx
, hashObj
,
1755 spec
->client
.write_mac_key_item
.data
,
1756 spec
->client
.write_mac_key_item
.len
, PR_FALSE
);
1758 if (rv
== SECSuccess
) {
1760 HMAC_Update(cx
, temp
, tempLen
);
1761 HMAC_Update(cx
, input
, inputLength
);
1762 rv
= HMAC_Finish(cx
, outbuf
, outLength
, spec
->mac_size
);
1763 HMAC_Destroy(cx
, PR_FALSE
);
1769 PORT_Assert(rv
!= SECSuccess
|| *outLength
== (unsigned)spec
->mac_size
);
1771 PRINT_BUF(95, (NULL
, "frag hash2: result", outbuf
, *outLength
));
1773 if (rv
!= SECSuccess
) {
1775 ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE
);
1781 ssl3_ClientAuthTokenPresent(sslSessionID
*sid
) {
1782 PK11SlotInfo
*slot
= NULL
;
1783 PRBool isPresent
= PR_TRUE
;
1785 /* we only care if we are doing client auth */
1786 if (!sid
|| !sid
->u
.ssl3
.clAuthValid
) {
1791 slot
= SECMOD_LookupSlot(sid
->u
.ssl3
.clAuthModuleID
,
1792 sid
->u
.ssl3
.clAuthSlotID
);
1794 !PK11_IsPresent(slot
) ||
1795 sid
->u
.ssl3
.clAuthSeries
!= PK11_GetSlotSeries(slot
) ||
1796 sid
->u
.ssl3
.clAuthSlotID
!= PK11_GetSlotID(slot
) ||
1797 sid
->u
.ssl3
.clAuthModuleID
!= PK11_GetModuleID(slot
) ||
1798 (PK11_NeedLogin(slot
) && !PK11_IsLoggedIn(slot
, NULL
))) {
1799 isPresent
= PR_FALSE
;
1802 PK11_FreeSlot(slot
);
1808 ssl3_CompressMACEncryptRecord(sslSocket
* ss
,
1809 SSL3ContentType type
,
1810 const SSL3Opaque
* pIn
,
1811 PRUint32 contentLen
)
1813 ssl3CipherSpec
* cwSpec
;
1814 const ssl3BulkCipherDef
* cipher_def
;
1815 sslBuffer
* wrBuf
= &ss
->sec
.writeBuf
;
1817 PRUint32 macLen
= 0;
1819 PRUint32 p1Len
, p2Len
, oddLen
= 0;
1820 PRInt32 cipherBytes
= 0;
1823 * null compression is easy to do
1824 PORT_Memcpy(wrBuf->buf + SSL3_RECORD_HEADER_LENGTH, pIn, contentLen);
1827 ssl_GetSpecReadLock(ss
); /********************************/
1829 cwSpec
= ss
->ssl3
.cwSpec
;
1830 cipher_def
= cwSpec
->cipher_def
;
1834 rv
= ssl3_ComputeRecordMAC( cwSpec
, (PRBool
)(ss
->sec
.isServer
),
1835 type
, cwSpec
->version
, cwSpec
->write_seq_num
, pIn
, contentLen
,
1836 wrBuf
->buf
+ contentLen
+ SSL3_RECORD_HEADER_LENGTH
, &macLen
);
1837 if (rv
!= SECSuccess
) {
1838 ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE
);
1839 goto spec_locked_loser
;
1843 fragLen
= contentLen
+ macLen
; /* needs to be encrypted */
1844 PORT_Assert(fragLen
<= MAX_FRAGMENT_LENGTH
+ 1024);
1847 * Pad the text (if we're doing a block cipher)
1850 if (cipher_def
->type
== type_block
) {
1851 unsigned char * pBuf
;
1855 oddLen
= contentLen
% cipher_def
->block_size
;
1856 /* Assume blockSize is a power of two */
1857 padding_length
= cipher_def
->block_size
- 1 -
1858 ((fragLen
) & (cipher_def
->block_size
- 1));
1859 fragLen
+= padding_length
+ 1;
1860 PORT_Assert((fragLen
% cipher_def
->block_size
) == 0);
1862 /* Pad according to TLS rules (also acceptable to SSL3). */
1863 pBuf
= &wrBuf
->buf
[fragLen
+ SSL3_RECORD_HEADER_LENGTH
- 1];
1864 for (i
= padding_length
+ 1; i
> 0; --i
) {
1865 *pBuf
-- = padding_length
;
1867 /* now, if contentLen is not a multiple of block size, fix it */
1868 p2Len
= fragLen
- p1Len
;
1878 PORT_Assert( (cipher_def
->block_size
< 2) || \
1879 (p2Len
% cipher_def
->block_size
) == 0);
1880 memcpy(wrBuf
->buf
+ SSL3_RECORD_HEADER_LENGTH
+ p1Len
,
1881 pIn
+ p1Len
, oddLen
);
1884 rv
= cwSpec
->encode( cwSpec
->encodeContext
,
1885 wrBuf
->buf
+ SSL3_RECORD_HEADER_LENGTH
, /* output */
1886 &cipherBytes
, /* actual outlen */
1887 p1Len
, /* max outlen */
1888 pIn
, p1Len
); /* input, and inputlen */
1889 PORT_Assert(rv
== SECSuccess
&& cipherBytes
== p1Len
);
1890 if (rv
!= SECSuccess
|| cipherBytes
!= p1Len
) {
1891 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE
);
1892 goto spec_locked_loser
;
1896 PRInt32 cipherBytesPart2
= -1;
1897 rv
= cwSpec
->encode( cwSpec
->encodeContext
,
1898 wrBuf
->buf
+ SSL3_RECORD_HEADER_LENGTH
+ p1Len
,
1899 &cipherBytesPart2
, /* output and actual outLen */
1900 p2Len
, /* max outlen */
1901 wrBuf
->buf
+ SSL3_RECORD_HEADER_LENGTH
+ p1Len
,
1902 p2Len
); /* input and inputLen*/
1903 PORT_Assert(rv
== SECSuccess
&& cipherBytesPart2
== p2Len
);
1904 if (rv
!= SECSuccess
|| cipherBytesPart2
!= p2Len
) {
1905 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE
);
1906 goto spec_locked_loser
;
1908 cipherBytes
+= cipherBytesPart2
;
1910 PORT_Assert(cipherBytes
<= MAX_FRAGMENT_LENGTH
+ 1024);
1912 ssl3_BumpSequenceNumber(&cwSpec
->write_seq_num
);
1914 wrBuf
->len
= cipherBytes
+ SSL3_RECORD_HEADER_LENGTH
;
1915 wrBuf
->buf
[0] = type
;
1916 wrBuf
->buf
[1] = MSB(cwSpec
->version
);
1917 wrBuf
->buf
[2] = LSB(cwSpec
->version
);
1918 wrBuf
->buf
[3] = MSB(cipherBytes
);
1919 wrBuf
->buf
[4] = LSB(cipherBytes
);
1921 ssl_ReleaseSpecReadLock(ss
); /************************************/
1926 ssl_ReleaseSpecReadLock(ss
);
1930 /* Process the plain text before sending it.
1931 * Returns the number of bytes of plaintext that were succesfully sent
1932 * plus the number of bytes of plaintext that were copied into the
1933 * output (write) buffer.
1934 * Returns SECFailure on a hard IO error, memory error, or crypto error.
1935 * Does NOT return SECWouldBlock.
1937 * Notes on the use of the private ssl flags:
1938 * (no private SSL flags)
1939 * Attempt to make and send SSL records for all plaintext
1940 * If non-blocking and a send gets WOULD_BLOCK,
1941 * or if the pending (ciphertext) buffer is not empty,
1942 * then buffer remaining bytes of ciphertext into pending buf,
1943 * and continue to do that for all succssive records until all
1945 * ssl_SEND_FLAG_FORCE_INTO_BUFFER
1946 * As above, except this suppresses all write attempts, and forces
1947 * all ciphertext into the pending ciphertext buffer.
1951 ssl3_SendRecord( sslSocket
* ss
,
1952 SSL3ContentType type
,
1953 const SSL3Opaque
* pIn
, /* input buffer */
1954 PRInt32 nIn
, /* bytes of input */
1957 sslBuffer
* wrBuf
= &ss
->sec
.writeBuf
;
1959 PRInt32 totalSent
= 0;
1961 SSL_TRC(3, ("%d: SSL3[%d] SendRecord type: %s nIn=%d",
1962 SSL_GETPID(), ss
->fd
, ssl3_DecodeContentType(type
),
1964 PRINT_BUF(3, (ss
, "Send record (plain text)", pIn
, nIn
));
1966 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
) );
1968 if (ss
->ssl3
.initialized
== PR_FALSE
) {
1969 /* This can happen on a server if the very first incoming record
1970 ** looks like a defective ssl3 record (e.g. too long), and we're
1971 ** trying to send an alert.
1973 PR_ASSERT(type
== content_alert
);
1974 rv
= ssl3_InitState(ss
);
1975 if (rv
!= SECSuccess
) {
1976 return SECFailure
; /* ssl3_InitState has set the error code. */
1980 /* check for Token Presence */
1981 if (!ssl3_ClientAuthTokenPresent(ss
->sec
.ci
.sid
)) {
1982 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL
);
1987 PRUint32 contentLen
= PR_MIN(nIn
, MAX_FRAGMENT_LENGTH
);
1989 if (wrBuf
->space
< contentLen
+ SSL3_BUFFER_FUDGE
) {
1990 PRInt32 newSpace
= PR_MAX(wrBuf
->space
* 2, contentLen
);
1991 newSpace
= PR_MIN(newSpace
, MAX_FRAGMENT_LENGTH
);
1992 newSpace
+= SSL3_BUFFER_FUDGE
;
1993 rv
= sslBuffer_Grow(wrBuf
, newSpace
);
1994 if (rv
!= SECSuccess
) {
1995 SSL_DBG(("%d: SSL3[%d]: SendRecord, tried to get %d bytes",
1996 SSL_GETPID(), ss
->fd
, newSpace
));
1997 return SECFailure
; /* sslBuffer_Grow set a memory error code. */
2001 rv
= ssl3_CompressMACEncryptRecord( ss
, type
, pIn
, contentLen
);
2002 if (rv
!= SECSuccess
)
2007 PORT_Assert( nIn
>= 0 );
2009 PRINT_BUF(50, (ss
, "send (encrypted) record data:", wrBuf
->buf
, wrBuf
->len
));
2011 /* If there's still some previously saved ciphertext,
2012 * or the caller doesn't want us to send the data yet,
2013 * then add all our new ciphertext to the amount previously saved.
2015 if ((ss
->pendingBuf
.len
> 0) ||
2016 (flags
& ssl_SEND_FLAG_FORCE_INTO_BUFFER
)) {
2018 rv
= ssl_SaveWriteData(ss
, wrBuf
->buf
, wrBuf
->len
);
2019 if (rv
!= SECSuccess
) {
2020 /* presumably a memory error, SEC_ERROR_NO_MEMORY */
2023 wrBuf
->len
= 0; /* All cipher text is saved away. */
2025 if (!(flags
& ssl_SEND_FLAG_FORCE_INTO_BUFFER
)) {
2027 ss
->handshakeBegun
= 1;
2028 sent
= ssl_SendSavedWriteData(ss
);
2029 if (sent
< 0 && PR_GetError() != PR_WOULD_BLOCK_ERROR
) {
2030 ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE
);
2033 if (ss
->pendingBuf
.len
) {
2034 flags
|= ssl_SEND_FLAG_FORCE_INTO_BUFFER
;
2037 } else if (wrBuf
->len
> 0) {
2039 ss
->handshakeBegun
= 1;
2040 sent
= ssl_DefSend(ss
, wrBuf
->buf
, wrBuf
->len
,
2041 flags
& ~ssl_SEND_FLAG_MASK
);
2043 if (PR_GetError() != PR_WOULD_BLOCK_ERROR
) {
2044 ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE
);
2047 /* we got PR_WOULD_BLOCK_ERROR, which means none was sent. */
2052 /* now take all the remaining unsent new ciphertext and
2053 * append it to the buffer of previously unsent ciphertext.
2055 rv
= ssl_SaveWriteData(ss
, wrBuf
->buf
+ sent
, wrBuf
->len
);
2056 if (rv
!= SECSuccess
) {
2057 /* presumably a memory error, SEC_ERROR_NO_MEMORY */
2062 totalSent
+= contentLen
;
2067 #define SSL3_PENDING_HIGH_WATER 1024
2069 /* Attempt to send the content of "in" in an SSL application_data record.
2070 * Returns "len" or SECFailure, never SECWouldBlock, nor SECSuccess.
2073 ssl3_SendApplicationData(sslSocket
*ss
, const unsigned char *in
,
2074 PRInt32 len
, PRInt32 flags
)
2076 PRInt32 totalSent
= 0;
2077 PRInt32 discarded
= 0;
2079 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
) );
2080 if (len
< 0 || !in
) {
2081 PORT_SetError(PR_INVALID_ARGUMENT_ERROR
);
2085 if (ss
->pendingBuf
.len
> SSL3_PENDING_HIGH_WATER
&&
2086 !ssl_SocketIsBlocking(ss
)) {
2087 PORT_Assert(!ssl_SocketIsBlocking(ss
));
2088 PORT_SetError(PR_WOULD_BLOCK_ERROR
);
2092 if (ss
->appDataBuffered
&& len
) {
2093 PORT_Assert (in
[0] == (unsigned char)(ss
->appDataBuffered
));
2094 if (in
[0] != (unsigned char)(ss
->appDataBuffered
)) {
2095 PORT_SetError(PR_INVALID_ARGUMENT_ERROR
);
2102 while (len
> totalSent
) {
2103 PRInt32 sent
, toSend
;
2105 if (totalSent
> 0) {
2107 * The thread yield is intended to give the reader thread a
2108 * chance to get some cycles while the writer thread is in
2109 * the middle of a large application data write. (See
2110 * Bugzilla bug 127740, comment #1.)
2112 ssl_ReleaseXmitBufLock(ss
);
2113 PR_Sleep(PR_INTERVAL_NO_WAIT
); /* PR_Yield(); */
2114 ssl_GetXmitBufLock(ss
);
2116 toSend
= PR_MIN(len
- totalSent
, MAX_FRAGMENT_LENGTH
);
2117 sent
= ssl3_SendRecord(ss
, content_application_data
,
2118 in
+ totalSent
, toSend
, flags
);
2120 if (totalSent
> 0 && PR_GetError() == PR_WOULD_BLOCK_ERROR
) {
2121 PORT_Assert(ss
->lastWriteBlocked
);
2124 return SECFailure
; /* error code set by ssl3_SendRecord */
2127 if (ss
->pendingBuf
.len
) {
2128 /* must be a non-blocking socket */
2129 PORT_Assert(!ssl_SocketIsBlocking(ss
));
2130 PORT_Assert(ss
->lastWriteBlocked
);
2134 if (ss
->pendingBuf
.len
) {
2135 /* Must be non-blocking. */
2136 PORT_Assert(!ssl_SocketIsBlocking(ss
));
2137 if (totalSent
> 0) {
2138 ss
->appDataBuffered
= 0x100 | in
[totalSent
- 1];
2141 totalSent
= totalSent
+ discarded
- 1;
2142 if (totalSent
<= 0) {
2143 PORT_SetError(PR_WOULD_BLOCK_ERROR
);
2144 totalSent
= SECFailure
;
2148 ss
->appDataBuffered
= 0;
2149 return totalSent
+ discarded
;
2152 /* Attempt to send the content of sendBuf buffer in an SSL handshake record.
2153 * This function returns SECSuccess or SECFailure, never SECWouldBlock.
2154 * Always set sendBuf.len to 0, even when returning SECFailure.
2156 * Called from SSL3_SendAlert(), ssl3_SendChangeCipherSpecs(),
2157 * ssl3_AppendHandshake(), ssl3_SendClientHello(),
2158 * ssl3_SendHelloRequest(), ssl3_SendServerHelloDone(),
2159 * ssl3_SendFinished(),
2162 ssl3_FlushHandshake(sslSocket
*ss
, PRInt32 flags
)
2164 PRInt32 rv
= SECSuccess
;
2166 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
2167 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
) );
2169 if (!ss
->sec
.ci
.sendBuf
.buf
|| !ss
->sec
.ci
.sendBuf
.len
)
2172 /* only this flag is allowed */
2173 PORT_Assert(!(flags
& ~ssl_SEND_FLAG_FORCE_INTO_BUFFER
));
2174 if ((flags
& ~ssl_SEND_FLAG_FORCE_INTO_BUFFER
) != 0) {
2175 PORT_SetError(SEC_ERROR_INVALID_ARGS
);
2178 rv
= ssl3_SendRecord(ss
, content_handshake
, ss
->sec
.ci
.sendBuf
.buf
,
2179 ss
->sec
.ci
.sendBuf
.len
, flags
);
2182 int err
= PORT_GetError();
2183 PORT_Assert(err
!= PR_WOULD_BLOCK_ERROR
);
2184 if (err
== PR_WOULD_BLOCK_ERROR
) {
2185 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
2187 } else if (rv
< ss
->sec
.ci
.sendBuf
.len
) {
2188 /* short write should never happen */
2189 PORT_Assert(rv
>= ss
->sec
.ci
.sendBuf
.len
);
2190 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
2196 /* Whether we succeeded or failed, toss the old handshake data. */
2197 ss
->sec
.ci
.sendBuf
.len
= 0;
2202 * Called from ssl3_HandleAlert and from ssl3_HandleCertificate when
2203 * the remote client sends a negative response to our certificate request.
2204 * Returns SECFailure if the application has required client auth.
2205 * SECSuccess otherwise.
2208 ssl3_HandleNoCertificate(sslSocket
*ss
)
2210 if (ss
->sec
.peerCert
!= NULL
) {
2211 if (ss
->sec
.peerKey
!= NULL
) {
2212 SECKEY_DestroyPublicKey(ss
->sec
.peerKey
);
2213 ss
->sec
.peerKey
= NULL
;
2215 CERT_DestroyCertificate(ss
->sec
.peerCert
);
2216 ss
->sec
.peerCert
= NULL
;
2218 ssl3_CleanupPeerCerts(ss
);
2220 /* If the server has required client-auth blindly but doesn't
2221 * actually look at the certificate it won't know that no
2222 * certificate was presented so we shutdown the socket to ensure
2223 * an error. We only do this if we haven't already completed the
2224 * first handshake because if we're redoing the handshake we
2225 * know the server is paying attention to the certificate.
2227 if ((ss
->opt
.requireCertificate
== SSL_REQUIRE_ALWAYS
) ||
2228 (!ss
->firstHsDone
&&
2229 (ss
->opt
.requireCertificate
== SSL_REQUIRE_FIRST_HANDSHAKE
))) {
2232 ss
->sec
.uncache(ss
->sec
.ci
.sid
);
2233 SSL3_SendAlert(ss
, alert_fatal
, bad_certificate
);
2235 lower
= ss
->fd
->lower
;
2237 lower
->methods
->shutdown(lower
, PR_SHUTDOWN_SEND
);
2239 lower
->methods
->shutdown(lower
, PR_SHUTDOWN_BOTH
);
2241 PORT_SetError(SSL_ERROR_NO_CERTIFICATE
);
2247 /************************************************************************
2252 ** Acquires both handshake and XmitBuf locks.
2253 ** Called from: ssl3_IllegalParameter <-
2254 ** ssl3_HandshakeFailure <-
2255 ** ssl3_HandleAlert <- ssl3_HandleRecord.
2256 ** ssl3_HandleChangeCipherSpecs <- ssl3_HandleRecord
2257 ** ssl3_ConsumeHandshakeVariable <-
2258 ** ssl3_HandleHelloRequest <-
2259 ** ssl3_HandleServerHello <-
2260 ** ssl3_HandleServerKeyExchange <-
2261 ** ssl3_HandleCertificateRequest <-
2262 ** ssl3_HandleServerHelloDone <-
2263 ** ssl3_HandleClientHello <-
2264 ** ssl3_HandleV2ClientHello <-
2265 ** ssl3_HandleCertificateVerify <-
2266 ** ssl3_HandleClientKeyExchange <-
2267 ** ssl3_HandleCertificate <-
2268 ** ssl3_HandleFinished <-
2269 ** ssl3_HandleHandshakeMessage <-
2270 ** ssl3_HandleRecord <-
2274 SSL3_SendAlert(sslSocket
*ss
, SSL3AlertLevel level
, SSL3AlertDescription desc
)
2279 SSL_TRC(3, ("%d: SSL3[%d]: send alert record, level=%d desc=%d",
2280 SSL_GETPID(), ss
->fd
, level
, desc
));
2285 ssl_GetSSL3HandshakeLock(ss
);
2286 if (level
== alert_fatal
) {
2287 if (ss
->sec
.ci
.sid
) {
2288 ss
->sec
.uncache(ss
->sec
.ci
.sid
);
2291 ssl_GetXmitBufLock(ss
);
2292 rv
= ssl3_FlushHandshake(ss
, ssl_SEND_FLAG_FORCE_INTO_BUFFER
);
2293 if (rv
== SECSuccess
) {
2295 sent
= ssl3_SendRecord(ss
, content_alert
, bytes
, 2,
2296 desc
== no_certificate
2297 ? ssl_SEND_FLAG_FORCE_INTO_BUFFER
: 0);
2298 rv
= (sent
>= 0) ? SECSuccess
: (SECStatus
)sent
;
2300 ssl_ReleaseXmitBufLock(ss
);
2301 ssl_ReleaseSSL3HandshakeLock(ss
);
2302 return rv
; /* error set by ssl3_FlushHandshake or ssl3_SendRecord */
2306 * Send illegal_parameter alert. Set generic error number.
2309 ssl3_IllegalParameter(sslSocket
*ss
)
2313 isTLS
= (PRBool
)(ss
->ssl3
.pwSpec
->version
> SSL_LIBRARY_VERSION_3_0
);
2314 (void)SSL3_SendAlert(ss
, alert_fatal
, illegal_parameter
);
2315 PORT_SetError(ss
->sec
.isServer
? SSL_ERROR_BAD_CLIENT
2316 : SSL_ERROR_BAD_SERVER
);
2321 * Send handshake_Failure alert. Set generic error number.
2324 ssl3_HandshakeFailure(sslSocket
*ss
)
2326 (void)SSL3_SendAlert(ss
, alert_fatal
, handshake_failure
);
2327 PORT_SetError( ss
->sec
.isServer
? SSL_ERROR_BAD_CLIENT
2328 : SSL_ERROR_BAD_SERVER
);
2333 * Send handshake_Failure alert. Set generic error number.
2336 ssl3_DecodeError(sslSocket
*ss
)
2338 (void)SSL3_SendAlert(ss
, alert_fatal
,
2339 ss
->version
> SSL_LIBRARY_VERSION_3_0
? decode_error
2340 : illegal_parameter
);
2341 PORT_SetError( ss
->sec
.isServer
? SSL_ERROR_BAD_CLIENT
2342 : SSL_ERROR_BAD_SERVER
);
2346 /* Called from ssl3_HandleRecord.
2347 ** Caller must hold both RecvBuf and Handshake locks.
2350 ssl3_HandleAlert(sslSocket
*ss
, sslBuffer
*buf
)
2352 SSL3AlertLevel level
;
2353 SSL3AlertDescription desc
;
2356 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
2357 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
2359 SSL_TRC(3, ("%d: SSL3[%d]: handle alert record", SSL_GETPID(), ss
->fd
));
2361 if (buf
->len
!= 2) {
2362 (void)ssl3_DecodeError(ss
);
2363 PORT_SetError(SSL_ERROR_RX_MALFORMED_ALERT
);
2366 level
= (SSL3AlertLevel
)buf
->buf
[0];
2367 desc
= (SSL3AlertDescription
)buf
->buf
[1];
2369 SSL_TRC(5, ("%d: SSL3[%d] received alert, level = %d, description = %d",
2370 SSL_GETPID(), ss
->fd
, level
, desc
));
2373 case close_notify
: ss
->recvdCloseNotify
= 1;
2374 error
= SSL_ERROR_CLOSE_NOTIFY_ALERT
; break;
2375 case unexpected_message
: error
= SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT
;
2377 case bad_record_mac
: error
= SSL_ERROR_BAD_MAC_ALERT
; break;
2378 case decryption_failed
: error
= SSL_ERROR_DECRYPTION_FAILED_ALERT
;
2380 case record_overflow
: error
= SSL_ERROR_RECORD_OVERFLOW_ALERT
; break;
2381 case decompression_failure
: error
= SSL_ERROR_DECOMPRESSION_FAILURE_ALERT
;
2383 case handshake_failure
: error
= SSL_ERROR_HANDSHAKE_FAILURE_ALERT
;
2385 case no_certificate
: error
= SSL_ERROR_NO_CERTIFICATE
; break;
2386 case bad_certificate
: error
= SSL_ERROR_BAD_CERT_ALERT
; break;
2387 case unsupported_certificate
:error
= SSL_ERROR_UNSUPPORTED_CERT_ALERT
;break;
2388 case certificate_revoked
: error
= SSL_ERROR_REVOKED_CERT_ALERT
; break;
2389 case certificate_expired
: error
= SSL_ERROR_EXPIRED_CERT_ALERT
; break;
2390 case certificate_unknown
: error
= SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT
;
2392 case illegal_parameter
: error
= SSL_ERROR_ILLEGAL_PARAMETER_ALERT
;break;
2394 /* All alerts below are TLS only. */
2395 case unknown_ca
: error
= SSL_ERROR_UNKNOWN_CA_ALERT
; break;
2396 case access_denied
: error
= SSL_ERROR_ACCESS_DENIED_ALERT
; break;
2397 case decode_error
: error
= SSL_ERROR_DECODE_ERROR_ALERT
; break;
2398 case decrypt_error
: error
= SSL_ERROR_DECRYPT_ERROR_ALERT
; break;
2399 case export_restriction
: error
= SSL_ERROR_EXPORT_RESTRICTION_ALERT
;
2401 case protocol_version
: error
= SSL_ERROR_PROTOCOL_VERSION_ALERT
; break;
2402 case insufficient_security
: error
= SSL_ERROR_INSUFFICIENT_SECURITY_ALERT
;
2404 case internal_error
: error
= SSL_ERROR_INTERNAL_ERROR_ALERT
; break;
2405 case user_canceled
: error
= SSL_ERROR_USER_CANCELED_ALERT
; break;
2406 case no_renegotiation
: error
= SSL_ERROR_NO_RENEGOTIATION_ALERT
; break;
2408 /* Alerts for TLS client hello extensions */
2409 case unsupported_extension
:
2410 error
= SSL_ERROR_UNSUPPORTED_EXTENSION_ALERT
; break;
2411 case certificate_unobtainable
:
2412 error
= SSL_ERROR_CERTIFICATE_UNOBTAINABLE_ALERT
; break;
2413 case unrecognized_name
:
2414 error
= SSL_ERROR_UNRECOGNIZED_NAME_ALERT
; break;
2415 case bad_certificate_status_response
:
2416 error
= SSL_ERROR_BAD_CERT_STATUS_RESPONSE_ALERT
; break;
2417 case bad_certificate_hash_value
:
2418 error
= SSL_ERROR_BAD_CERT_HASH_VALUE_ALERT
; break;
2419 default: error
= SSL_ERROR_RX_UNKNOWN_ALERT
; break;
2421 if (level
== alert_fatal
) {
2422 ss
->sec
.uncache(ss
->sec
.ci
.sid
);
2423 if ((ss
->ssl3
.hs
.ws
== wait_server_hello
) &&
2424 (desc
== handshake_failure
)) {
2425 /* XXX This is a hack. We're assuming that any handshake failure
2426 * XXX on the client hello is a failure to match ciphers.
2428 error
= SSL_ERROR_NO_CYPHER_OVERLAP
;
2430 PORT_SetError(error
);
2433 if ((desc
== no_certificate
) && (ss
->ssl3
.hs
.ws
== wait_client_cert
)) {
2434 /* I'm a server. I've requested a client cert. He hasn't got one. */
2437 PORT_Assert(ss
->sec
.isServer
);
2438 ss
->ssl3
.hs
.ws
= wait_client_key
;
2439 rv
= ssl3_HandleNoCertificate(ss
);
2446 * Change Cipher Specs
2447 * Called from ssl3_HandleServerHelloDone,
2448 * ssl3_HandleClientHello,
2449 * and ssl3_HandleFinished
2451 * Acquires and releases spec write lock, to protect switching the current
2452 * and pending write spec pointers.
2456 ssl3_SendChangeCipherSpecs(sslSocket
*ss
)
2458 uint8 change
= change_cipher_spec_choice
;
2459 ssl3CipherSpec
* pwSpec
;
2463 SSL_TRC(3, ("%d: SSL3[%d]: send change_cipher_spec record",
2464 SSL_GETPID(), ss
->fd
));
2466 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
) );
2467 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
2469 rv
= ssl3_FlushHandshake(ss
, ssl_SEND_FLAG_FORCE_INTO_BUFFER
);
2470 if (rv
!= SECSuccess
) {
2471 return rv
; /* error code set by ssl3_FlushHandshake */
2473 sent
= ssl3_SendRecord(ss
, content_change_cipher_spec
, &change
, 1,
2474 ssl_SEND_FLAG_FORCE_INTO_BUFFER
);
2476 return (SECStatus
)sent
; /* error code set by ssl3_SendRecord */
2479 /* swap the pending and current write specs. */
2480 ssl_GetSpecWriteLock(ss
); /**************************************/
2481 pwSpec
= ss
->ssl3
.pwSpec
;
2482 pwSpec
->write_seq_num
.high
= 0;
2483 pwSpec
->write_seq_num
.low
= 0;
2485 ss
->ssl3
.pwSpec
= ss
->ssl3
.cwSpec
;
2486 ss
->ssl3
.cwSpec
= pwSpec
;
2488 SSL_TRC(3, ("%d: SSL3[%d] Set Current Write Cipher Suite to Pending",
2489 SSL_GETPID(), ss
->fd
));
2491 /* We need to free up the contexts, keys and certs ! */
2492 /* If we are really through with the old cipher spec
2493 * (Both the read and write sides have changed) destroy it.
2495 if (ss
->ssl3
.prSpec
== ss
->ssl3
.pwSpec
) {
2496 ssl3_DestroyCipherSpec(ss
->ssl3
.pwSpec
);
2498 ssl_ReleaseSpecWriteLock(ss
); /**************************************/
2503 /* Called from ssl3_HandleRecord.
2504 ** Caller must hold both RecvBuf and Handshake locks.
2506 * Acquires and releases spec write lock, to protect switching the current
2507 * and pending write spec pointers.
2510 ssl3_HandleChangeCipherSpecs(sslSocket
*ss
, sslBuffer
*buf
)
2512 ssl3CipherSpec
* prSpec
;
2513 SSL3WaitState ws
= ss
->ssl3
.hs
.ws
;
2514 SSL3ChangeCipherSpecChoice change
;
2516 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
2517 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
2519 SSL_TRC(3, ("%d: SSL3[%d]: handle change_cipher_spec record",
2520 SSL_GETPID(), ss
->fd
));
2522 if (ws
!= wait_change_cipher
) {
2523 (void)SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
2524 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER
);
2529 (void)ssl3_DecodeError(ss
);
2530 PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER
);
2533 change
= (SSL3ChangeCipherSpecChoice
)buf
->buf
[0];
2534 if (change
!= change_cipher_spec_choice
) {
2535 /* illegal_parameter is correct here for both SSL3 and TLS. */
2536 (void)ssl3_IllegalParameter(ss
);
2537 PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER
);
2542 /* Swap the pending and current read specs. */
2543 ssl_GetSpecWriteLock(ss
); /*************************************/
2544 prSpec
= ss
->ssl3
.prSpec
;
2545 prSpec
->read_seq_num
.high
= prSpec
->read_seq_num
.low
= 0;
2547 ss
->ssl3
.prSpec
= ss
->ssl3
.crSpec
;
2548 ss
->ssl3
.crSpec
= prSpec
;
2549 ss
->ssl3
.hs
.ws
= wait_finished
;
2551 SSL_TRC(3, ("%d: SSL3[%d] Set Current Read Cipher Suite to Pending",
2552 SSL_GETPID(), ss
->fd
));
2554 /* If we are really through with the old cipher prSpec
2555 * (Both the read and write sides have changed) destroy it.
2557 if (ss
->ssl3
.prSpec
== ss
->ssl3
.pwSpec
) {
2558 ssl3_DestroyCipherSpec(ss
->ssl3
.prSpec
);
2560 ssl_ReleaseSpecWriteLock(ss
); /*************************************/
2564 /* This method uses PKCS11 to derive the MS from the PMS, where PMS
2565 ** is a PKCS11 symkey. This is used in all cases except the
2566 ** "triple bypass" with RSA key exchange.
2567 ** Called from ssl3_InitPendingCipherSpec. prSpec is pwSpec.
2570 ssl3_DeriveMasterSecret(sslSocket
*ss
, PK11SymKey
*pms
)
2572 ssl3CipherSpec
* pwSpec
= ss
->ssl3
.pwSpec
;
2573 const ssl3KEADef
*kea_def
= ss
->ssl3
.hs
.kea_def
;
2574 unsigned char * cr
= (unsigned char *)&ss
->ssl3
.hs
.client_random
;
2575 unsigned char * sr
= (unsigned char *)&ss
->ssl3
.hs
.server_random
;
2576 PRBool isTLS
= (PRBool
)(kea_def
->tls_keygen
||
2577 (pwSpec
->version
> SSL_LIBRARY_VERSION_3_0
));
2579 * Whenever isDH is true, we need to use CKM_TLS_MASTER_KEY_DERIVE_DH
2580 * which, unlike CKM_TLS_MASTER_KEY_DERIVE, converts arbitrary size
2581 * data into a 48-byte value.
2583 PRBool isDH
= (PRBool
) ((ss
->ssl3
.hs
.kea_def
->exchKeyType
== kt_dh
) ||
2584 (ss
->ssl3
.hs
.kea_def
->exchKeyType
== kt_ecdh
));
2585 SECStatus rv
= SECFailure
;
2586 CK_MECHANISM_TYPE master_derive
;
2587 CK_MECHANISM_TYPE key_derive
;
2590 CK_VERSION pms_version
;
2591 CK_SSL3_MASTER_KEY_DERIVE_PARAMS master_params
;
2593 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
2594 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSpecWriteLock(ss
));
2595 PORT_Assert(ss
->ssl3
.prSpec
== ss
->ssl3
.pwSpec
);
2597 if(isDH
) master_derive
= CKM_TLS_MASTER_KEY_DERIVE_DH
;
2598 else master_derive
= CKM_TLS_MASTER_KEY_DERIVE
;
2599 key_derive
= CKM_TLS_KEY_AND_MAC_DERIVE
;
2600 keyFlags
= CKF_SIGN
| CKF_VERIFY
;
2602 if (isDH
) master_derive
= CKM_SSL3_MASTER_KEY_DERIVE_DH
;
2603 else master_derive
= CKM_SSL3_MASTER_KEY_DERIVE
;
2604 key_derive
= CKM_SSL3_KEY_AND_MAC_DERIVE
;
2608 if (pms
|| !pwSpec
->master_secret
) {
2609 master_params
.pVersion
= &pms_version
;
2610 master_params
.RandomInfo
.pClientRandom
= cr
;
2611 master_params
.RandomInfo
.ulClientRandomLen
= SSL3_RANDOM_LENGTH
;
2612 master_params
.RandomInfo
.pServerRandom
= sr
;
2613 master_params
.RandomInfo
.ulServerRandomLen
= SSL3_RANDOM_LENGTH
;
2615 params
.data
= (unsigned char *) &master_params
;
2616 params
.len
= sizeof master_params
;
2621 if (ssl_trace
>= 100) {
2622 SECStatus extractRV
= PK11_ExtractKeyValue(pms
);
2623 if (extractRV
== SECSuccess
) {
2624 SECItem
* keyData
= PK11_GetKeyData(pms
);
2625 if (keyData
&& keyData
->data
&& keyData
->len
) {
2626 ssl_PrintBuf(ss
, "Pre-Master Secret",
2627 keyData
->data
, keyData
->len
);
2632 pwSpec
->master_secret
= PK11_DeriveWithFlags(pms
, master_derive
,
2633 ¶ms
, key_derive
, CKA_DERIVE
, 0, keyFlags
);
2634 if (!isDH
&& pwSpec
->master_secret
&& ss
->opt
.detectRollBack
) {
2635 SSL3ProtocolVersion client_version
;
2636 client_version
= pms_version
.major
<< 8 | pms_version
.minor
;
2637 if (client_version
!= ss
->clientHelloVersion
) {
2638 /* Destroy it. Version roll-back detected. */
2639 PK11_FreeSymKey(pwSpec
->master_secret
);
2640 pwSpec
->master_secret
= NULL
;
2643 if (pwSpec
->master_secret
== NULL
) {
2644 /* Generate a faux master secret in the same slot as the old one. */
2645 PK11SlotInfo
* slot
= PK11_GetSlotFromKey((PK11SymKey
*)pms
);
2646 PK11SymKey
* fpms
= ssl3_GenerateRSAPMS(ss
, pwSpec
, slot
);
2648 PK11_FreeSlot(slot
);
2650 pwSpec
->master_secret
= PK11_DeriveWithFlags(fpms
,
2651 master_derive
, ¶ms
, key_derive
,
2652 CKA_DERIVE
, 0, keyFlags
);
2653 PK11_FreeSymKey(fpms
);
2657 if (pwSpec
->master_secret
== NULL
) {
2658 /* Generate a faux master secret from the internal slot. */
2659 PK11SlotInfo
* slot
= PK11_GetInternalSlot();
2660 PK11SymKey
* fpms
= ssl3_GenerateRSAPMS(ss
, pwSpec
, slot
);
2662 PK11_FreeSlot(slot
);
2664 pwSpec
->master_secret
= PK11_DeriveWithFlags(fpms
,
2665 master_derive
, ¶ms
, key_derive
,
2666 CKA_DERIVE
, 0, keyFlags
);
2667 if (pwSpec
->master_secret
== NULL
) {
2668 pwSpec
->master_secret
= fpms
; /* use the fpms as the master. */
2673 PK11_FreeSymKey(fpms
);
2676 if (pwSpec
->master_secret
== NULL
) {
2677 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE
);
2680 if (ss
->opt
.bypassPKCS11
) {
2682 /* In hope of doing a "double bypass",
2683 * need to extract the master secret's value from the key object
2684 * and store it raw in the sslSocket struct.
2686 rv
= PK11_ExtractKeyValue(pwSpec
->master_secret
);
2687 if (rv
!= SECSuccess
) {
2688 #if defined(NSS_SURVIVE_DOUBLE_BYPASS_FAILURE)
2689 /* The double bypass failed.
2690 * Attempt to revert to an all PKCS#11, non-bypass method.
2691 * Do we need any unacquired locks here?
2693 ss
->opt
.bypassPKCS11
= 0;
2694 rv
= ssl3_NewHandshakeHashes(ss
);
2695 if (rv
== SECSuccess
) {
2696 rv
= ssl3_UpdateHandshakeHashes(ss
, ss
->ssl3
.hs
.messages
.buf
,
2697 ss
->ssl3
.hs
.messages
.len
);
2702 /* This returns the address of the secItem inside the key struct,
2703 * not a copy or a reference. So, there's no need to free it.
2705 keydata
= PK11_GetKeyData(pwSpec
->master_secret
);
2706 if (keydata
&& keydata
->len
<= sizeof pwSpec
->raw_master_secret
) {
2707 memcpy(pwSpec
->raw_master_secret
, keydata
->data
, keydata
->len
);
2708 pwSpec
->msItem
.data
= pwSpec
->raw_master_secret
;
2709 pwSpec
->msItem
.len
= keydata
->len
;
2711 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
2720 * Derive encryption and MAC Keys (and IVs) from master secret
2721 * Sets a useful error code when returning SECFailure.
2723 * Called only from ssl3_InitPendingCipherSpec(),
2724 * which in turn is called from
2725 * sendRSAClientKeyExchange (for Full handshake)
2726 * sendDHClientKeyExchange (for Full handshake)
2727 * ssl3_HandleClientKeyExchange (for Full handshake)
2728 * ssl3_HandleServerHello (for session restart)
2729 * ssl3_HandleClientHello (for session restart)
2730 * Caller MUST hold the specWriteLock, and SSL3HandshakeLock.
2731 * ssl3_InitPendingCipherSpec does that.
2735 ssl3_DeriveConnectionKeysPKCS11(sslSocket
*ss
)
2737 ssl3CipherSpec
* pwSpec
= ss
->ssl3
.pwSpec
;
2738 const ssl3KEADef
* kea_def
= ss
->ssl3
.hs
.kea_def
;
2739 unsigned char * cr
= (unsigned char *)&ss
->ssl3
.hs
.client_random
;
2740 unsigned char * sr
= (unsigned char *)&ss
->ssl3
.hs
.server_random
;
2741 PRBool isTLS
= (PRBool
)(kea_def
->tls_keygen
||
2742 (pwSpec
->version
> SSL_LIBRARY_VERSION_3_0
));
2743 /* following variables used in PKCS11 path */
2744 const ssl3BulkCipherDef
*cipher_def
= pwSpec
->cipher_def
;
2745 PK11SlotInfo
* slot
= NULL
;
2746 PK11SymKey
* symKey
= NULL
;
2747 void * pwArg
= ss
->pkcs11PinArg
;
2749 CK_SSL3_KEY_MAT_PARAMS key_material_params
;
2750 CK_SSL3_KEY_MAT_OUT returnedKeys
;
2751 CK_MECHANISM_TYPE key_derive
;
2752 CK_MECHANISM_TYPE bulk_mechanism
;
2753 SSLCipherAlgorithm calg
;
2755 PRBool skipKeysAndIVs
= (PRBool
)(cipher_def
->calg
== calg_null
);
2757 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
2758 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSpecWriteLock(ss
));
2759 PORT_Assert(ss
->ssl3
.prSpec
== ss
->ssl3
.pwSpec
);
2761 if (!pwSpec
->master_secret
) {
2762 PORT_SetError(SSL_ERROR_SESSION_KEY_GEN_FAILURE
);
2766 * generate the key material
2768 key_material_params
.ulMacSizeInBits
= pwSpec
->mac_size
* BPB
;
2769 key_material_params
.ulKeySizeInBits
= cipher_def
->secret_key_size
* BPB
;
2770 key_material_params
.ulIVSizeInBits
= cipher_def
->iv_size
* BPB
;
2772 key_material_params
.bIsExport
= (CK_BBOOL
)(kea_def
->is_limited
);
2773 /* was: (CK_BBOOL)(cipher_def->keygen_mode != kg_strong); */
2775 key_material_params
.RandomInfo
.pClientRandom
= cr
;
2776 key_material_params
.RandomInfo
.ulClientRandomLen
= SSL3_RANDOM_LENGTH
;
2777 key_material_params
.RandomInfo
.pServerRandom
= sr
;
2778 key_material_params
.RandomInfo
.ulServerRandomLen
= SSL3_RANDOM_LENGTH
;
2779 key_material_params
.pReturnedKeyMaterial
= &returnedKeys
;
2781 returnedKeys
.pIVClient
= pwSpec
->client
.write_iv
;
2782 returnedKeys
.pIVServer
= pwSpec
->server
.write_iv
;
2783 keySize
= cipher_def
->key_size
;
2785 if (skipKeysAndIVs
) {
2787 key_material_params
.ulKeySizeInBits
= 0;
2788 key_material_params
.ulIVSizeInBits
= 0;
2789 returnedKeys
.pIVClient
= NULL
;
2790 returnedKeys
.pIVServer
= NULL
;
2793 calg
= cipher_def
->calg
;
2794 PORT_Assert( alg2Mech
[calg
].calg
== calg
);
2795 bulk_mechanism
= alg2Mech
[calg
].cmech
;
2797 params
.data
= (unsigned char *)&key_material_params
;
2798 params
.len
= sizeof(key_material_params
);
2801 key_derive
= CKM_TLS_KEY_AND_MAC_DERIVE
;
2803 key_derive
= CKM_SSL3_KEY_AND_MAC_DERIVE
;
2806 /* CKM_SSL3_KEY_AND_MAC_DERIVE is defined to set ENCRYPT, DECRYPT, and
2807 * DERIVE by DEFAULT */
2808 symKey
= PK11_Derive(pwSpec
->master_secret
, key_derive
, ¶ms
,
2809 bulk_mechanism
, CKA_ENCRYPT
, keySize
);
2811 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE
);
2814 /* we really should use the actual mac'ing mechanism here, but we
2815 * don't because these types are used to map keytype anyway and both
2816 * mac's map to the same keytype.
2818 slot
= PK11_GetSlotFromKey(symKey
);
2820 PK11_FreeSlot(slot
); /* slot is held until the key is freed */
2821 pwSpec
->client
.write_mac_key
=
2822 PK11_SymKeyFromHandle(slot
, symKey
, PK11_OriginDerive
,
2823 CKM_SSL3_SHA1_MAC
, returnedKeys
.hClientMacSecret
, PR_TRUE
, pwArg
);
2824 if (pwSpec
->client
.write_mac_key
== NULL
) {
2825 goto loser
; /* loser sets err */
2827 pwSpec
->server
.write_mac_key
=
2828 PK11_SymKeyFromHandle(slot
, symKey
, PK11_OriginDerive
,
2829 CKM_SSL3_SHA1_MAC
, returnedKeys
.hServerMacSecret
, PR_TRUE
, pwArg
);
2830 if (pwSpec
->server
.write_mac_key
== NULL
) {
2831 goto loser
; /* loser sets err */
2833 if (!skipKeysAndIVs
) {
2834 pwSpec
->client
.write_key
=
2835 PK11_SymKeyFromHandle(slot
, symKey
, PK11_OriginDerive
,
2836 bulk_mechanism
, returnedKeys
.hClientKey
, PR_TRUE
, pwArg
);
2837 if (pwSpec
->client
.write_key
== NULL
) {
2838 goto loser
; /* loser sets err */
2840 pwSpec
->server
.write_key
=
2841 PK11_SymKeyFromHandle(slot
, symKey
, PK11_OriginDerive
,
2842 bulk_mechanism
, returnedKeys
.hServerKey
, PR_TRUE
, pwArg
);
2843 if (pwSpec
->server
.write_key
== NULL
) {
2844 goto loser
; /* loser sets err */
2847 PK11_FreeSymKey(symKey
);
2852 if (symKey
) PK11_FreeSymKey(symKey
);
2853 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE
);
2858 ssl3_RestartHandshakeHashes(sslSocket
*ss
)
2860 SECStatus rv
= SECSuccess
;
2862 if (ss
->opt
.bypassPKCS11
) {
2863 ss
->ssl3
.hs
.messages
.len
= 0;
2864 MD5_Begin((MD5Context
*)ss
->ssl3
.hs
.md5_cx
);
2865 SHA1_Begin((SHA1Context
*)ss
->ssl3
.hs
.sha_cx
);
2867 rv
= PK11_DigestBegin(ss
->ssl3
.hs
.md5
);
2868 if (rv
!= SECSuccess
) {
2869 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE
);
2872 rv
= PK11_DigestBegin(ss
->ssl3
.hs
.sha
);
2873 if (rv
!= SECSuccess
) {
2874 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE
);
2882 ssl3_NewHandshakeHashes(sslSocket
*ss
)
2884 PK11Context
*md5
= NULL
;
2885 PK11Context
*sha
= NULL
;
2888 * note: We should probably lookup an SSL3 slot for these
2889 * handshake hashes in hopes that we wind up with the same slots
2890 * that the master secret will wind up in ...
2892 SSL_TRC(30,("%d: SSL3[%d]: start handshake hashes", SSL_GETPID(), ss
->fd
));
2893 if (ss
->opt
.bypassPKCS11
) {
2894 PORT_Assert(!ss
->ssl3
.hs
.messages
.buf
&& !ss
->ssl3
.hs
.messages
.space
);
2895 ss
->ssl3
.hs
.messages
.buf
= NULL
;
2896 ss
->ssl3
.hs
.messages
.space
= 0;
2898 ss
->ssl3
.hs
.md5
= md5
= PK11_CreateDigestContext(SEC_OID_MD5
);
2899 ss
->ssl3
.hs
.sha
= sha
= PK11_CreateDigestContext(SEC_OID_SHA1
);
2901 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE
);
2905 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE
);
2909 if (SECSuccess
== ssl3_RestartHandshakeHashes(ss
)) {
2915 PK11_DestroyContext(md5
, PR_TRUE
);
2916 ss
->ssl3
.hs
.md5
= NULL
;
2919 PK11_DestroyContext(sha
, PR_TRUE
);
2920 ss
->ssl3
.hs
.sha
= NULL
;
2927 * Handshake messages
2929 /* Called from ssl3_AppendHandshake()
2930 ** ssl3_StartHandshakeHash()
2931 ** ssl3_HandleV2ClientHello()
2932 ** ssl3_HandleHandshakeMessage()
2933 ** Caller must hold the ssl3Handshake lock.
2936 ssl3_UpdateHandshakeHashes(sslSocket
*ss
, unsigned char *b
, unsigned int l
)
2938 SECStatus rv
= SECSuccess
;
2940 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
2942 PRINT_BUF(90, (NULL
, "MD5 & SHA handshake hash input:", b
, l
));
2944 if (ss
->opt
.bypassPKCS11
) {
2945 MD5_Update((MD5Context
*)ss
->ssl3
.hs
.md5_cx
, b
, l
);
2946 SHA1_Update((SHA1Context
*)ss
->ssl3
.hs
.sha_cx
, b
, l
);
2947 #if defined(NSS_SURVIVE_DOUBLE_BYPASS_FAILURE)
2948 rv
= sslBuffer_Append(&ss
->ssl3
.hs
.messages
, b
, l
);
2952 rv
= PK11_DigestOp(ss
->ssl3
.hs
.md5
, b
, l
);
2953 if (rv
!= SECSuccess
) {
2954 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE
);
2957 rv
= PK11_DigestOp(ss
->ssl3
.hs
.sha
, b
, l
);
2958 if (rv
!= SECSuccess
) {
2959 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE
);
2965 /**************************************************************************
2966 * Append Handshake functions.
2967 * All these functions set appropriate error codes.
2968 * Most rely on ssl3_AppendHandshake to set the error code.
2969 **************************************************************************/
2971 ssl3_AppendHandshake(sslSocket
*ss
, const void *void_src
, PRInt32 bytes
)
2973 unsigned char * src
= (unsigned char *)void_src
;
2974 int room
= ss
->sec
.ci
.sendBuf
.space
- ss
->sec
.ci
.sendBuf
.len
;
2977 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) ); /* protects sendBuf. */
2979 if (ss
->sec
.ci
.sendBuf
.space
< MAX_SEND_BUF_LENGTH
&& room
< bytes
) {
2980 rv
= sslBuffer_Grow(&ss
->sec
.ci
.sendBuf
, PR_MAX(MIN_SEND_BUF_LENGTH
,
2981 PR_MIN(MAX_SEND_BUF_LENGTH
, ss
->sec
.ci
.sendBuf
.len
+ bytes
)));
2982 if (rv
!= SECSuccess
)
2983 return rv
; /* sslBuffer_Grow has set a memory error code. */
2984 room
= ss
->sec
.ci
.sendBuf
.space
- ss
->sec
.ci
.sendBuf
.len
;
2987 PRINT_BUF(60, (ss
, "Append to Handshake", (unsigned char*)void_src
, bytes
));
2988 rv
= ssl3_UpdateHandshakeHashes(ss
, src
, bytes
);
2989 if (rv
!= SECSuccess
)
2990 return rv
; /* error code set by ssl3_UpdateHandshakeHashes */
2992 while (bytes
> room
) {
2994 PORT_Memcpy(ss
->sec
.ci
.sendBuf
.buf
+ ss
->sec
.ci
.sendBuf
.len
, src
,
2996 ss
->sec
.ci
.sendBuf
.len
+= room
;
2997 rv
= ssl3_FlushHandshake(ss
, ssl_SEND_FLAG_FORCE_INTO_BUFFER
);
2998 if (rv
!= SECSuccess
) {
2999 return rv
; /* error code set by ssl3_FlushHandshake */
3003 room
= ss
->sec
.ci
.sendBuf
.space
;
3004 PORT_Assert(ss
->sec
.ci
.sendBuf
.len
== 0);
3006 PORT_Memcpy(ss
->sec
.ci
.sendBuf
.buf
+ ss
->sec
.ci
.sendBuf
.len
, src
, bytes
);
3007 ss
->sec
.ci
.sendBuf
.len
+= bytes
;
3012 ssl3_AppendHandshakeNumber(sslSocket
*ss
, PRInt32 num
, PRInt32 lenSize
)
3020 *p
++ = (num
>> 24) & 0xff;
3022 *p
++ = (num
>> 16) & 0xff;
3024 *p
++ = (num
>> 8) & 0xff;
3028 SSL_TRC(60, ("%d: number:", SSL_GETPID()));
3029 rv
= ssl3_AppendHandshake(ss
, &b
[0], lenSize
);
3030 return rv
; /* error code set by AppendHandshake, if applicable. */
3034 ssl3_AppendHandshakeVariable(
3035 sslSocket
*ss
, const SSL3Opaque
*src
, PRInt32 bytes
, PRInt32 lenSize
)
3039 PORT_Assert((bytes
< (1<<8) && lenSize
== 1) ||
3040 (bytes
< (1L<<16) && lenSize
== 2) ||
3041 (bytes
< (1L<<24) && lenSize
== 3));
3043 SSL_TRC(60,("%d: append variable:", SSL_GETPID()));
3044 rv
= ssl3_AppendHandshakeNumber(ss
, bytes
, lenSize
);
3045 if (rv
!= SECSuccess
) {
3046 return rv
; /* error code set by AppendHandshake, if applicable. */
3048 SSL_TRC(60, ("data:"));
3049 rv
= ssl3_AppendHandshake(ss
, src
, bytes
);
3050 return rv
; /* error code set by AppendHandshake, if applicable. */
3054 ssl3_AppendHandshakeHeader(sslSocket
*ss
, SSL3HandshakeType t
, PRUint32 length
)
3058 SSL_TRC(30,("%d: SSL3[%d]: append handshake header: type %s",
3059 SSL_GETPID(), ss
->fd
, ssl3_DecodeHandshakeType(t
)));
3060 PRINT_BUF(60, (ss
, "MD5 handshake hash:",
3061 (unsigned char*)ss
->ssl3
.hs
.md5_cx
, MD5_LENGTH
));
3062 PRINT_BUF(95, (ss
, "SHA handshake hash:",
3063 (unsigned char*)ss
->ssl3
.hs
.sha_cx
, SHA1_LENGTH
));
3065 rv
= ssl3_AppendHandshakeNumber(ss
, t
, 1);
3066 if (rv
!= SECSuccess
) {
3067 return rv
; /* error code set by AppendHandshake, if applicable. */
3069 rv
= ssl3_AppendHandshakeNumber(ss
, length
, 3);
3070 return rv
; /* error code set by AppendHandshake, if applicable. */
3073 /**************************************************************************
3074 * Consume Handshake functions.
3076 * All data used in these functions is protected by two locks,
3077 * the RecvBufLock and the SSL3HandshakeLock
3078 **************************************************************************/
3080 /* Read up the next "bytes" number of bytes from the (decrypted) input
3081 * stream "b" (which is *length bytes long). Copy them into buffer "v".
3082 * Reduces *length by bytes. Advances *b by bytes.
3084 * If this function returns SECFailure, it has already sent an alert,
3085 * and has set a generic error code. The caller should probably
3086 * override the generic error code by setting another.
3089 ssl3_ConsumeHandshake(sslSocket
*ss
, void *v
, PRInt32 bytes
, SSL3Opaque
**b
,
3092 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
3093 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
3095 if ((PRUint32
)bytes
> *length
) {
3096 return ssl3_DecodeError(ss
);
3098 PORT_Memcpy(v
, *b
, bytes
);
3099 PRINT_BUF(60, (ss
, "consume bytes:", *b
, bytes
));
3105 /* Read up the next "bytes" number of bytes from the (decrypted) input
3106 * stream "b" (which is *length bytes long), and interpret them as an
3107 * integer in network byte order. Returns the received value.
3108 * Reduces *length by bytes. Advances *b by bytes.
3110 * Returns SECFailure (-1) on failure.
3111 * This value is indistinguishable from the equivalent received value.
3112 * Only positive numbers are to be received this way.
3113 * Thus, the largest value that may be sent this way is 0x7fffffff.
3114 * On error, an alert has been sent, and a generic error code has been set.
3117 ssl3_ConsumeHandshakeNumber(sslSocket
*ss
, PRInt32 bytes
, SSL3Opaque
**b
,
3124 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
3125 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
3126 PORT_Assert( bytes
<= sizeof num
);
3128 if ((PRUint32
)bytes
> *length
) {
3129 return ssl3_DecodeError(ss
);
3131 PRINT_BUF(60, (ss
, "consume bytes:", *b
, bytes
));
3133 for (i
= 0; i
< bytes
; i
++)
3134 num
= (num
<< 8) + buf
[i
];
3140 /* Read in two values from the incoming decrypted byte stream "b", which is
3141 * *length bytes long. The first value is a number whose size is "bytes"
3142 * bytes long. The second value is a byte-string whose size is the value
3143 * of the first number received. The latter byte-string, and its length,
3144 * is returned in the SECItem i.
3146 * Returns SECFailure (-1) on failure.
3147 * On error, an alert has been sent, and a generic error code has been set.
3149 * RADICAL CHANGE for NSS 3.11. All callers of this function make copies
3150 * of the data returned in the SECItem *i, so making a copy of it here
3151 * is simply wasteful. So, This function now just sets SECItem *i to
3152 * point to the values in the buffer **b.
3155 ssl3_ConsumeHandshakeVariable(sslSocket
*ss
, SECItem
*i
, PRInt32 bytes
,
3156 SSL3Opaque
**b
, PRUint32
*length
)
3160 PORT_Assert(bytes
<= 3);
3163 count
= ssl3_ConsumeHandshakeNumber(ss
, bytes
, b
, length
);
3164 if (count
< 0) { /* Can't test for SECSuccess here. */
3168 if ((PRUint32
)count
> *length
) {
3169 return ssl3_DecodeError(ss
);
3179 /**************************************************************************
3180 * end of Consume Handshake functions.
3181 **************************************************************************/
3183 /* Extract the hashes of handshake messages to this point.
3184 * Called from ssl3_SendCertificateVerify
3186 * ssl3_HandleHandshakeMessage
3188 * Caller must hold the SSL3HandshakeLock.
3189 * Caller must hold a read or write lock on the Spec R/W lock.
3190 * (There is presently no way to assert on a Read lock.)
3193 ssl3_ComputeHandshakeHashes(sslSocket
* ss
,
3194 ssl3CipherSpec
*spec
, /* uses ->master_secret */
3195 SSL3Hashes
* hashes
, /* output goes here. */
3198 SECStatus rv
= SECSuccess
;
3199 PRBool isTLS
= (PRBool
)(spec
->version
> SSL_LIBRARY_VERSION_3_0
);
3200 unsigned int outLength
;
3201 SSL3Opaque md5_inner
[MAX_MAC_LENGTH
];
3202 SSL3Opaque sha_inner
[MAX_MAC_LENGTH
];
3204 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
3206 if (ss
->opt
.bypassPKCS11
) {
3207 /* compute them without PKCS11 */
3208 PRUint64 md5_cx
[MAX_MAC_CONTEXT_LLONGS
];
3209 PRUint64 sha_cx
[MAX_MAC_CONTEXT_LLONGS
];
3211 #define md5cx ((MD5Context *)md5_cx)
3212 #define shacx ((SHA1Context *)sha_cx)
3214 if (!spec
->msItem
.data
) {
3215 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE
);
3219 MD5_Clone (md5cx
, (MD5Context
*)ss
->ssl3
.hs
.md5_cx
);
3220 SHA1_Clone(shacx
, (SHA1Context
*)ss
->ssl3
.hs
.sha_cx
);
3223 /* compute hashes for SSL3. */
3226 s
[0] = (unsigned char)(sender
>> 24);
3227 s
[1] = (unsigned char)(sender
>> 16);
3228 s
[2] = (unsigned char)(sender
>> 8);
3229 s
[3] = (unsigned char)sender
;
3232 MD5_Update(md5cx
, s
, 4);
3233 PRINT_BUF(95, (NULL
, "MD5 inner: sender", s
, 4));
3236 PRINT_BUF(95, (NULL
, "MD5 inner: MAC Pad 1", mac_pad_1
,
3237 mac_defs
[mac_md5
].pad_size
));
3239 MD5_Update(md5cx
, spec
->msItem
.data
, spec
->msItem
.len
);
3240 MD5_Update(md5cx
, mac_pad_1
, mac_defs
[mac_md5
].pad_size
);
3241 MD5_End(md5cx
, md5_inner
, &outLength
, MD5_LENGTH
);
3243 PRINT_BUF(95, (NULL
, "MD5 inner: result", md5_inner
, outLength
));
3246 SHA1_Update(shacx
, s
, 4);
3247 PRINT_BUF(95, (NULL
, "SHA inner: sender", s
, 4));
3250 PRINT_BUF(95, (NULL
, "SHA inner: MAC Pad 1", mac_pad_1
,
3251 mac_defs
[mac_sha
].pad_size
));
3253 SHA1_Update(shacx
, spec
->msItem
.data
, spec
->msItem
.len
);
3254 SHA1_Update(shacx
, mac_pad_1
, mac_defs
[mac_sha
].pad_size
);
3255 SHA1_End(shacx
, sha_inner
, &outLength
, SHA1_LENGTH
);
3257 PRINT_BUF(95, (NULL
, "SHA inner: result", sha_inner
, outLength
));
3258 PRINT_BUF(95, (NULL
, "MD5 outer: MAC Pad 2", mac_pad_2
,
3259 mac_defs
[mac_md5
].pad_size
));
3260 PRINT_BUF(95, (NULL
, "MD5 outer: MD5 inner", md5_inner
, MD5_LENGTH
));
3263 MD5_Update(md5cx
, spec
->msItem
.data
, spec
->msItem
.len
);
3264 MD5_Update(md5cx
, mac_pad_2
, mac_defs
[mac_md5
].pad_size
);
3265 MD5_Update(md5cx
, md5_inner
, MD5_LENGTH
);
3267 MD5_End(md5cx
, hashes
->md5
, &outLength
, MD5_LENGTH
);
3269 PRINT_BUF(60, (NULL
, "MD5 outer: result", hashes
->md5
, MD5_LENGTH
));
3272 PRINT_BUF(95, (NULL
, "SHA outer: MAC Pad 2", mac_pad_2
,
3273 mac_defs
[mac_sha
].pad_size
));
3274 PRINT_BUF(95, (NULL
, "SHA outer: SHA inner", sha_inner
, SHA1_LENGTH
));
3277 SHA1_Update(shacx
, spec
->msItem
.data
, spec
->msItem
.len
);
3278 SHA1_Update(shacx
, mac_pad_2
, mac_defs
[mac_sha
].pad_size
);
3279 SHA1_Update(shacx
, sha_inner
, SHA1_LENGTH
);
3281 SHA1_End(shacx
, hashes
->sha
, &outLength
, SHA1_LENGTH
);
3283 PRINT_BUF(60, (NULL
, "SHA outer: result", hashes
->sha
, SHA1_LENGTH
));
3289 /* compute hases with PKCS11 */
3291 PK11Context
* sha
= NULL
;
3292 unsigned char *md5StateBuf
= NULL
;
3293 unsigned char *shaStateBuf
= NULL
;
3294 unsigned int md5StateLen
, shaStateLen
;
3295 unsigned char md5StackBuf
[256];
3296 unsigned char shaStackBuf
[512];
3298 if (!spec
->master_secret
) {
3299 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE
);
3303 md5StateBuf
= PK11_SaveContextAlloc(ss
->ssl3
.hs
.md5
, md5StackBuf
,
3304 sizeof md5StackBuf
, &md5StateLen
);
3305 if (md5StateBuf
== NULL
) {
3306 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE
);
3309 md5
= ss
->ssl3
.hs
.md5
;
3311 shaStateBuf
= PK11_SaveContextAlloc(ss
->ssl3
.hs
.sha
, shaStackBuf
,
3312 sizeof shaStackBuf
, &shaStateLen
);
3313 if (shaStateBuf
== NULL
) {
3314 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE
);
3317 sha
= ss
->ssl3
.hs
.sha
;
3320 /* compute hashes for SSL3. */
3323 s
[0] = (unsigned char)(sender
>> 24);
3324 s
[1] = (unsigned char)(sender
>> 16);
3325 s
[2] = (unsigned char)(sender
>> 8);
3326 s
[3] = (unsigned char)sender
;
3329 rv
|= PK11_DigestOp(md5
, s
, 4);
3330 PRINT_BUF(95, (NULL
, "MD5 inner: sender", s
, 4));
3333 PRINT_BUF(95, (NULL
, "MD5 inner: MAC Pad 1", mac_pad_1
,
3334 mac_defs
[mac_md5
].pad_size
));
3336 rv
|= PK11_DigestKey(md5
,spec
->master_secret
);
3337 rv
|= PK11_DigestOp(md5
, mac_pad_1
, mac_defs
[mac_md5
].pad_size
);
3338 rv
|= PK11_DigestFinal(md5
, md5_inner
, &outLength
, MD5_LENGTH
);
3339 PORT_Assert(rv
!= SECSuccess
|| outLength
== MD5_LENGTH
);
3340 if (rv
!= SECSuccess
) {
3341 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE
);
3346 PRINT_BUF(95, (NULL
, "MD5 inner: result", md5_inner
, outLength
));
3349 rv
|= PK11_DigestOp(sha
, s
, 4);
3350 PRINT_BUF(95, (NULL
, "SHA inner: sender", s
, 4));
3353 PRINT_BUF(95, (NULL
, "SHA inner: MAC Pad 1", mac_pad_1
,
3354 mac_defs
[mac_sha
].pad_size
));
3356 rv
|= PK11_DigestKey(sha
, spec
->master_secret
);
3357 rv
|= PK11_DigestOp(sha
, mac_pad_1
, mac_defs
[mac_sha
].pad_size
);
3358 rv
|= PK11_DigestFinal(sha
, sha_inner
, &outLength
, SHA1_LENGTH
);
3359 PORT_Assert(rv
!= SECSuccess
|| outLength
== SHA1_LENGTH
);
3360 if (rv
!= SECSuccess
) {
3361 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE
);
3366 PRINT_BUF(95, (NULL
, "SHA inner: result", sha_inner
, outLength
));
3368 PRINT_BUF(95, (NULL
, "MD5 outer: MAC Pad 2", mac_pad_2
,
3369 mac_defs
[mac_md5
].pad_size
));
3370 PRINT_BUF(95, (NULL
, "MD5 outer: MD5 inner", md5_inner
, MD5_LENGTH
));
3372 rv
|= PK11_DigestBegin(md5
);
3373 rv
|= PK11_DigestKey(md5
, spec
->master_secret
);
3374 rv
|= PK11_DigestOp(md5
, mac_pad_2
, mac_defs
[mac_md5
].pad_size
);
3375 rv
|= PK11_DigestOp(md5
, md5_inner
, MD5_LENGTH
);
3377 rv
|= PK11_DigestFinal(md5
, hashes
->md5
, &outLength
, MD5_LENGTH
);
3378 PORT_Assert(rv
!= SECSuccess
|| outLength
== MD5_LENGTH
);
3379 if (rv
!= SECSuccess
) {
3380 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE
);
3385 PRINT_BUF(60, (NULL
, "MD5 outer: result", hashes
->md5
, MD5_LENGTH
));
3388 PRINT_BUF(95, (NULL
, "SHA outer: MAC Pad 2", mac_pad_2
,
3389 mac_defs
[mac_sha
].pad_size
));
3390 PRINT_BUF(95, (NULL
, "SHA outer: SHA inner", sha_inner
, SHA1_LENGTH
));
3392 rv
|= PK11_DigestBegin(sha
);
3393 rv
|= PK11_DigestKey(sha
,spec
->master_secret
);
3394 rv
|= PK11_DigestOp(sha
, mac_pad_2
, mac_defs
[mac_sha
].pad_size
);
3395 rv
|= PK11_DigestOp(sha
, sha_inner
, SHA1_LENGTH
);
3397 rv
|= PK11_DigestFinal(sha
, hashes
->sha
, &outLength
, SHA1_LENGTH
);
3398 PORT_Assert(rv
!= SECSuccess
|| outLength
== SHA1_LENGTH
);
3399 if (rv
!= SECSuccess
) {
3400 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE
);
3405 PRINT_BUF(60, (NULL
, "SHA outer: result", hashes
->sha
, SHA1_LENGTH
));
3411 if (PK11_RestoreContext(ss
->ssl3
.hs
.md5
, md5StateBuf
, md5StateLen
)
3414 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE
);
3417 if (md5StateBuf
!= md5StackBuf
) {
3418 PORT_ZFree(md5StateBuf
, md5StateLen
);
3422 if (PK11_RestoreContext(ss
->ssl3
.hs
.sha
, shaStateBuf
, shaStateLen
)
3425 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE
);
3428 if (shaStateBuf
!= shaStackBuf
) {
3429 PORT_ZFree(shaStateBuf
, shaStateLen
);
3437 * SSL 2 based implementations pass in the initial outbound buffer
3438 * so that the handshake hash can contain the included information.
3440 * Called from ssl2_BeginClientHandshake() in sslcon.c
3443 ssl3_StartHandshakeHash(sslSocket
*ss
, unsigned char * buf
, int length
)
3447 ssl_GetSSL3HandshakeLock(ss
); /**************************************/
3449 rv
= ssl3_InitState(ss
);
3450 if (rv
!= SECSuccess
) {
3451 goto done
; /* ssl3_InitState has set the error code. */
3454 PORT_Memset(&ss
->ssl3
.hs
.client_random
, 0, SSL3_RANDOM_LENGTH
);
3456 &ss
->ssl3
.hs
.client_random
.rand
[SSL3_RANDOM_LENGTH
- SSL_CHALLENGE_BYTES
],
3457 &ss
->sec
.ci
.clientChallenge
,
3458 SSL_CHALLENGE_BYTES
);
3460 rv
= ssl3_UpdateHandshakeHashes(ss
, buf
, length
);
3461 /* if it failed, ssl3_UpdateHandshakeHashes has set the error code. */
3464 ssl_ReleaseSSL3HandshakeLock(ss
); /**************************************/
3468 /**************************************************************************
3469 * end of Handshake Hash functions.
3470 * Begin Send and Handle functions for handshakes.
3471 **************************************************************************/
3473 /* Called from ssl3_HandleHelloRequest(),
3474 * ssl3_HandleFinished() (for step-up)
3475 * ssl3_RedoHandshake()
3476 * ssl2_BeginClientHandshake (when resuming ssl3 session)
3479 ssl3_SendClientHello(sslSocket
*ss
)
3482 ssl3CipherSpec
* cwSpec
;
3487 int actual_count
= 0;
3488 PRInt32 total_exten_len
= 0;
3490 SSL_TRC(3, ("%d: SSL3[%d]: send client_hello handshake", SSL_GETPID(),
3493 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
3494 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
) );
3496 rv
= ssl3_InitState(ss
);
3497 if (rv
!= SECSuccess
) {
3498 return rv
; /* ssl3_InitState has set the error code. */
3501 /* We might be starting a session renegotiation in which case we should
3502 * clear previous state.
3504 PORT_Memset(&ss
->xtnData
, 0, sizeof(TLSExtensionData
));
3506 SSL_TRC(30,("%d: SSL3[%d]: reset handshake hashes",
3507 SSL_GETPID(), ss
->fd
));
3508 rv
= ssl3_RestartHandshakeHashes(ss
);
3509 if (rv
!= SECSuccess
) {
3513 /* We ignore ss->sec.ci.sid here, and use ssl_Lookup because Lookup
3514 * handles expired entries and other details.
3515 * XXX If we've been called from ssl2_BeginClientHandshake, then
3516 * this lookup is duplicative and wasteful.
3518 sid
= (ss
->opt
.noCache
) ? NULL
3519 : ssl_LookupSID(&ss
->sec
.ci
.peer
, ss
->sec
.ci
.port
, ss
->peerID
, ss
->url
);
3521 /* We can't resume based on a different token. If the sid exists,
3522 * make sure the token that holds the master secret still exists ...
3523 * If we previously did client-auth, make sure that the token that holds
3524 * the private key still exists, is logged in, hasn't been removed, etc.
3527 PRBool sidOK
= PR_TRUE
;
3528 if (sid
->u
.ssl3
.keys
.msIsWrapped
) {
3529 /* Session key was wrapped, which means it was using PKCS11, */
3530 PK11SlotInfo
*slot
= NULL
;
3531 if (sid
->u
.ssl3
.masterValid
&& !ss
->opt
.bypassPKCS11
) {
3532 slot
= SECMOD_LookupSlot(sid
->u
.ssl3
.masterModuleID
,
3533 sid
->u
.ssl3
.masterSlotID
);
3538 PK11SymKey
*wrapKey
= NULL
;
3539 if (!PK11_IsPresent(slot
) ||
3540 ((wrapKey
= PK11_GetWrapKey(slot
,
3541 sid
->u
.ssl3
.masterWrapIndex
,
3542 sid
->u
.ssl3
.masterWrapMech
,
3543 sid
->u
.ssl3
.masterWrapSeries
,
3544 ss
->pkcs11PinArg
)) == NULL
) ) {
3547 if (wrapKey
) PK11_FreeSymKey(wrapKey
);
3548 PK11_FreeSlot(slot
);
3552 /* If we previously did client-auth, make sure that the token that
3553 ** holds the private key still exists, is logged in, hasn't been
3556 if (sidOK
&& !ssl3_ClientAuthTokenPresent(sid
)) {
3561 SSL_AtomicIncrementLong(& ssl3stats
.sch_sid_cache_not_ok
);
3562 (*ss
->sec
.uncache
)(sid
);
3569 SSL_AtomicIncrementLong(& ssl3stats
.sch_sid_cache_hits
);
3571 /* Are we attempting a stateless session resume? */
3572 if (sid
->version
> SSL_LIBRARY_VERSION_3_0
&&
3573 sid
->u
.ssl3
.sessionTicket
.ticket
.data
)
3574 SSL_AtomicIncrementLong(& ssl3stats
.sch_sid_stateless_resumes
);
3576 rv
= ssl3_NegotiateVersion(ss
, sid
->version
);
3577 if (rv
!= SECSuccess
)
3578 return rv
; /* error code was set */
3580 PRINT_BUF(4, (ss
, "client, found session-id:", sid
->u
.ssl3
.sessionID
,
3581 sid
->u
.ssl3
.sessionIDLength
));
3583 ss
->ssl3
.policy
= sid
->u
.ssl3
.policy
;
3585 SSL_AtomicIncrementLong(& ssl3stats
.sch_sid_cache_misses
);
3587 rv
= ssl3_NegotiateVersion(ss
, SSL_LIBRARY_VERSION_3_1_TLS
);
3588 if (rv
!= SECSuccess
)
3589 return rv
; /* error code was set */
3591 sid
= ssl3_NewSessionID(ss
, PR_FALSE
);
3593 return SECFailure
; /* memory error is set */
3597 ssl_GetSpecWriteLock(ss
);
3598 cwSpec
= ss
->ssl3
.cwSpec
;
3599 if (cwSpec
->mac_def
->mac
== mac_null
) {
3600 /* SSL records are not being MACed. */
3601 cwSpec
->version
= ss
->version
;
3603 ssl_ReleaseSpecWriteLock(ss
);
3605 if (ss
->sec
.ci
.sid
!= NULL
) {
3606 ssl_FreeSID(ss
->sec
.ci
.sid
); /* decrement ref count, free if zero */
3608 ss
->sec
.ci
.sid
= sid
;
3610 ss
->sec
.send
= ssl3_SendApplicationData
;
3612 /* shouldn't get here if SSL3 is disabled, but ... */
3613 PORT_Assert(ss
->opt
.enableSSL3
|| ss
->opt
.enableTLS
);
3614 if (!ss
->opt
.enableSSL3
&& !ss
->opt
.enableTLS
) {
3615 PORT_SetError(SSL_ERROR_SSL_DISABLED
);
3619 /* how many suites does our PKCS11 support (regardless of policy)? */
3620 num_suites
= ssl3_config_match_init(ss
);
3622 return SECFailure
; /* ssl3_config_match_init has set error code. */
3624 if (ss
->opt
.enableTLS
&& ss
->version
> SSL_LIBRARY_VERSION_3_0
) {
3625 PRUint32 maxBytes
= 65535; /* 2^16 - 1 */
3628 extLen
= ssl3_CallHelloExtensionSenders(ss
, PR_FALSE
, maxBytes
, NULL
);
3633 total_exten_len
+= extLen
;
3635 if (total_exten_len
> 0)
3636 total_exten_len
+= 2;
3638 #if defined(NSS_ENABLE_ECC) && !defined(NSS_ECC_MORE_THAN_SUITE_B)
3639 else { /* SSL3 only */
3640 ssl3_DisableECCSuites(ss
, NULL
); /* disable all ECC suites */
3644 /* how many suites are permitted by policy and user preference? */
3645 num_suites
= count_cipher_suites(ss
, ss
->ssl3
.policy
, PR_TRUE
);
3647 return SECFailure
; /* count_cipher_suites has set error code. */
3649 length
= sizeof(SSL3ProtocolVersion
) + SSL3_RANDOM_LENGTH
+
3650 1 + ((sid
== NULL
) ? 0 : sid
->u
.ssl3
.sessionIDLength
) +
3651 2 + num_suites
*sizeof(ssl3CipherSuite
) +
3652 1 + compressionMethodsCount
+ total_exten_len
;
3654 rv
= ssl3_AppendHandshakeHeader(ss
, client_hello
, length
);
3655 if (rv
!= SECSuccess
) {
3656 return rv
; /* err set by ssl3_AppendHandshake* */
3659 ss
->clientHelloVersion
= ss
->version
;
3660 rv
= ssl3_AppendHandshakeNumber(ss
, ss
->clientHelloVersion
, 2);
3661 if (rv
!= SECSuccess
) {
3662 return rv
; /* err set by ssl3_AppendHandshake* */
3664 rv
= ssl3_GetNewRandom(&ss
->ssl3
.hs
.client_random
);
3665 if (rv
!= SECSuccess
) {
3666 return rv
; /* err set by GetNewRandom. */
3668 rv
= ssl3_AppendHandshake(ss
, &ss
->ssl3
.hs
.client_random
,
3669 SSL3_RANDOM_LENGTH
);
3670 if (rv
!= SECSuccess
) {
3671 return rv
; /* err set by ssl3_AppendHandshake* */
3675 rv
= ssl3_AppendHandshakeVariable(
3676 ss
, sid
->u
.ssl3
.sessionID
, sid
->u
.ssl3
.sessionIDLength
, 1);
3678 rv
= ssl3_AppendHandshakeVariable(ss
, NULL
, 0, 1);
3679 if (rv
!= SECSuccess
) {
3680 return rv
; /* err set by ssl3_AppendHandshake* */
3683 rv
= ssl3_AppendHandshakeNumber(ss
, num_suites
*sizeof(ssl3CipherSuite
), 2);
3684 if (rv
!= SECSuccess
) {
3685 return rv
; /* err set by ssl3_AppendHandshake* */
3689 for (i
= 0; i
< ssl_V3_SUITES_IMPLEMENTED
; i
++) {
3690 ssl3CipherSuiteCfg
*suite
= &ss
->cipherSuites
[i
];
3691 if (config_match(suite
, ss
->ssl3
.policy
, PR_TRUE
)) {
3693 if (actual_count
> num_suites
) {
3694 /* set error card removal/insertion error */
3695 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL
);
3698 rv
= ssl3_AppendHandshakeNumber(ss
, suite
->cipher_suite
,
3699 sizeof(ssl3CipherSuite
));
3700 if (rv
!= SECSuccess
) {
3701 return rv
; /* err set by ssl3_AppendHandshake* */
3706 /* if cards were removed or inserted between count_cipher_suites and
3707 * generating our list, detect the error here rather than send it off to
3709 if (actual_count
!= num_suites
) {
3710 /* Card removal/insertion error */
3711 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL
);
3715 rv
= ssl3_AppendHandshakeNumber(ss
, compressionMethodsCount
, 1);
3716 if (rv
!= SECSuccess
) {
3717 return rv
; /* err set by ssl3_AppendHandshake* */
3719 for (i
= 0; i
< compressionMethodsCount
; i
++) {
3720 rv
= ssl3_AppendHandshakeNumber(ss
, compressions
[i
], 1);
3721 if (rv
!= SECSuccess
) {
3722 return rv
; /* err set by ssl3_AppendHandshake* */
3726 if (total_exten_len
) {
3727 PRUint32 maxBytes
= total_exten_len
- 2;
3730 rv
= ssl3_AppendHandshakeNumber(ss
, maxBytes
, 2);
3731 if (rv
!= SECSuccess
) {
3732 return rv
; /* err set by AppendHandshake. */
3735 extLen
= ssl3_CallHelloExtensionSenders(ss
, PR_TRUE
, maxBytes
, NULL
);
3740 PORT_Assert(!maxBytes
);
3744 rv
= ssl3_FlushHandshake(ss
, 0);
3745 if (rv
!= SECSuccess
) {
3746 return rv
; /* error code set by ssl3_FlushHandshake */
3749 ss
->ssl3
.hs
.ws
= wait_server_hello
;
3754 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
3755 * ssl3 Hello Request.
3756 * Caller must hold Handshake and RecvBuf locks.
3759 ssl3_HandleHelloRequest(sslSocket
*ss
)
3761 sslSessionID
*sid
= ss
->sec
.ci
.sid
;
3764 SSL_TRC(3, ("%d: SSL3[%d]: handle hello_request handshake",
3765 SSL_GETPID(), ss
->fd
));
3767 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
3768 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
3770 if (ss
->ssl3
.hs
.ws
== wait_server_hello
)
3772 if (ss
->ssl3
.hs
.ws
!= idle_handshake
|| ss
->sec
.isServer
) {
3773 (void)SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
3774 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST
);
3778 ss
->sec
.uncache(sid
);
3780 ss
->sec
.ci
.sid
= NULL
;
3783 ssl_GetXmitBufLock(ss
);
3784 rv
= ssl3_SendClientHello(ss
);
3785 ssl_ReleaseXmitBufLock(ss
);
3790 #define UNKNOWN_WRAP_MECHANISM 0x7fffffff
3792 static const CK_MECHANISM_TYPE wrapMechanismList
[SSL_NUM_WRAP_MECHS
] = {
3807 UNKNOWN_WRAP_MECHANISM
3811 ssl_FindIndexByWrapMechanism(CK_MECHANISM_TYPE mech
)
3813 const CK_MECHANISM_TYPE
*pMech
= wrapMechanismList
;
3815 while (mech
!= *pMech
&& *pMech
!= UNKNOWN_WRAP_MECHANISM
) {
3818 return (*pMech
== UNKNOWN_WRAP_MECHANISM
) ? -1
3819 : (pMech
- wrapMechanismList
);
3823 ssl_UnwrapSymWrappingKey(
3824 SSLWrappedSymWrappingKey
*pWswk
,
3825 SECKEYPrivateKey
* svrPrivKey
,
3826 SSL3KEAType exchKeyType
,
3827 CK_MECHANISM_TYPE masterWrapMech
,
3830 PK11SymKey
* unwrappedWrappingKey
= NULL
;
3832 #ifdef NSS_ENABLE_ECC
3834 SECKEYPublicKey pubWrapKey
;
3835 ECCWrappedKeyInfo
*ecWrapped
;
3836 #endif /* NSS_ENABLE_ECC */
3838 /* found the wrapping key on disk. */
3839 PORT_Assert(pWswk
->symWrapMechanism
== masterWrapMech
);
3840 PORT_Assert(pWswk
->exchKeyType
== exchKeyType
);
3841 if (pWswk
->symWrapMechanism
!= masterWrapMech
||
3842 pWswk
->exchKeyType
!= exchKeyType
) {
3845 wrappedKey
.type
= siBuffer
;
3846 wrappedKey
.data
= pWswk
->wrappedSymmetricWrappingkey
;
3847 wrappedKey
.len
= pWswk
->wrappedSymKeyLen
;
3848 PORT_Assert(wrappedKey
.len
<= sizeof pWswk
->wrappedSymmetricWrappingkey
);
3850 switch (exchKeyType
) {
3853 unwrappedWrappingKey
=
3854 PK11_PubUnwrapSymKey(svrPrivKey
, &wrappedKey
,
3855 masterWrapMech
, CKA_UNWRAP
, 0);
3858 #ifdef NSS_ENABLE_ECC
3861 * For kt_ecdh, we first create an EC public key based on
3862 * data stored with the wrappedSymmetricWrappingkey. Next,
3863 * we do an ECDH computation involving this public key and
3864 * the SSL server's (long-term) EC private key. The resulting
3865 * shared secret is treated the same way as Fortezza's Ks, i.e.,
3866 * it is used to recover the symmetric wrapping key.
3868 * The data in wrappedSymmetricWrappingkey is laid out as defined
3869 * in the ECCWrappedKeyInfo structure.
3871 ecWrapped
= (ECCWrappedKeyInfo
*) pWswk
->wrappedSymmetricWrappingkey
;
3873 PORT_Assert(ecWrapped
->encodedParamLen
+ ecWrapped
->pubValueLen
+
3874 ecWrapped
->wrappedKeyLen
<= MAX_EC_WRAPPED_KEY_BUFLEN
);
3876 if (ecWrapped
->encodedParamLen
+ ecWrapped
->pubValueLen
+
3877 ecWrapped
->wrappedKeyLen
> MAX_EC_WRAPPED_KEY_BUFLEN
) {
3878 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
3882 pubWrapKey
.keyType
= ecKey
;
3883 pubWrapKey
.u
.ec
.size
= ecWrapped
->size
;
3884 pubWrapKey
.u
.ec
.DEREncodedParams
.len
= ecWrapped
->encodedParamLen
;
3885 pubWrapKey
.u
.ec
.DEREncodedParams
.data
= ecWrapped
->var
;
3886 pubWrapKey
.u
.ec
.publicValue
.len
= ecWrapped
->pubValueLen
;
3887 pubWrapKey
.u
.ec
.publicValue
.data
= ecWrapped
->var
+
3888 ecWrapped
->encodedParamLen
;
3890 wrappedKey
.len
= ecWrapped
->wrappedKeyLen
;
3891 wrappedKey
.data
= ecWrapped
->var
+ ecWrapped
->encodedParamLen
+
3892 ecWrapped
->pubValueLen
;
3894 /* Derive Ks using ECDH */
3895 Ks
= PK11_PubDeriveWithKDF(svrPrivKey
, &pubWrapKey
, PR_FALSE
, NULL
,
3896 NULL
, CKM_ECDH1_DERIVE
, masterWrapMech
,
3897 CKA_DERIVE
, 0, CKD_NULL
, NULL
, NULL
);
3902 /* Use Ks to unwrap the wrapping key */
3903 unwrappedWrappingKey
= PK11_UnwrapSymKey(Ks
, masterWrapMech
, NULL
,
3904 &wrappedKey
, masterWrapMech
,
3906 PK11_FreeSymKey(Ks
);
3917 return unwrappedWrappingKey
;
3920 /* Each process sharing the server session ID cache has its own array of
3921 * SymKey pointers for the symmetric wrapping keys that are used to wrap
3922 * the master secrets. There is one key for each KEA type. These Symkeys
3923 * correspond to the wrapped SymKeys kept in the server session cache.
3927 PK11SymKey
* symWrapKey
[kt_kea_size
];
3930 static PZLock
* symWrapKeysLock
= NULL
;
3931 static ssl3SymWrapKey symWrapKeys
[SSL_NUM_WRAP_MECHS
];
3933 SECStatus
ssl_FreeSymWrapKeysLock(void)
3935 if (symWrapKeysLock
) {
3936 PZ_DestroyLock(symWrapKeysLock
);
3937 symWrapKeysLock
= NULL
;
3940 PORT_SetError(SEC_ERROR_NOT_INITIALIZED
);
3945 SSL3_ShutdownServerCache(void)
3949 if (!symWrapKeysLock
)
3950 return SECSuccess
; /* lock was never initialized */
3951 PZ_Lock(symWrapKeysLock
);
3952 /* get rid of all symWrapKeys */
3953 for (i
= 0; i
< SSL_NUM_WRAP_MECHS
; ++i
) {
3954 for (j
= 0; j
< kt_kea_size
; ++j
) {
3955 PK11SymKey
** pSymWrapKey
;
3956 pSymWrapKey
= &symWrapKeys
[i
].symWrapKey
[j
];
3958 PK11_FreeSymKey(*pSymWrapKey
);
3959 *pSymWrapKey
= NULL
;
3964 PZ_Unlock(symWrapKeysLock
);
3965 ssl_FreeSessionCacheLocks();
3969 SECStatus
ssl_InitSymWrapKeysLock(void)
3971 symWrapKeysLock
= PZ_NewLock(nssILockOther
);
3972 return symWrapKeysLock
? SECSuccess
: SECFailure
;
3975 /* Try to get wrapping key for mechanism from in-memory array.
3976 * If that fails, look for one on disk.
3977 * If that fails, generate a new one, put the new one on disk,
3978 * Put the new key in the in-memory array.
3981 getWrappingKey( sslSocket
* ss
,
3982 PK11SlotInfo
* masterSecretSlot
,
3983 SSL3KEAType exchKeyType
,
3984 CK_MECHANISM_TYPE masterWrapMech
,
3987 SECKEYPrivateKey
* svrPrivKey
;
3988 SECKEYPublicKey
* svrPubKey
= NULL
;
3989 PK11SymKey
* unwrappedWrappingKey
= NULL
;
3990 PK11SymKey
** pSymWrapKey
;
3991 CK_MECHANISM_TYPE asymWrapMechanism
= CKM_INVALID_MECHANISM
;
3993 int symWrapMechIndex
;
3996 SSLWrappedSymWrappingKey wswk
;
3998 svrPrivKey
= ss
->serverCerts
[exchKeyType
].SERVERKEY
;
3999 PORT_Assert(svrPrivKey
!= NULL
);
4001 return NULL
; /* why are we here?!? */
4004 symWrapMechIndex
= ssl_FindIndexByWrapMechanism(masterWrapMech
);
4005 PORT_Assert(symWrapMechIndex
>= 0);
4006 if (symWrapMechIndex
< 0)
4007 return NULL
; /* invalid masterWrapMech. */
4009 pSymWrapKey
= &symWrapKeys
[symWrapMechIndex
].symWrapKey
[exchKeyType
];
4011 ssl_InitSessionCacheLocks(PR_TRUE
);
4013 PZ_Lock(symWrapKeysLock
);
4015 unwrappedWrappingKey
= *pSymWrapKey
;
4016 if (unwrappedWrappingKey
!= NULL
) {
4017 if (PK11_VerifyKeyOK(unwrappedWrappingKey
)) {
4018 unwrappedWrappingKey
= PK11_ReferenceSymKey(unwrappedWrappingKey
);
4021 /* slot series has changed, so this key is no good any more. */
4022 PK11_FreeSymKey(unwrappedWrappingKey
);
4023 *pSymWrapKey
= unwrappedWrappingKey
= NULL
;
4026 /* Try to get wrapped SymWrapping key out of the (disk) cache. */
4027 /* Following call fills in wswk on success. */
4028 if (ssl_GetWrappingKey(symWrapMechIndex
, exchKeyType
, &wswk
)) {
4029 /* found the wrapped sym wrapping key on disk. */
4030 unwrappedWrappingKey
=
4031 ssl_UnwrapSymWrappingKey(&wswk
, svrPrivKey
, exchKeyType
,
4032 masterWrapMech
, pwArg
);
4033 if (unwrappedWrappingKey
) {
4038 if (!masterSecretSlot
) /* caller doesn't want to create a new one. */
4041 length
= PK11_GetBestKeyLength(masterSecretSlot
, masterWrapMech
);
4042 /* Zero length means fixed key length algorithm, or error.
4045 unwrappedWrappingKey
= PK11_KeyGen(masterSecretSlot
, masterWrapMech
, NULL
,
4047 if (!unwrappedWrappingKey
) {
4051 /* Prepare the buffer to receive the wrappedWrappingKey,
4052 * the symmetric wrapping key wrapped using the server's pub key.
4054 PORT_Memset(&wswk
, 0, sizeof wswk
); /* eliminate UMRs. */
4056 if (ss
->serverCerts
[exchKeyType
].serverKeyPair
) {
4057 svrPubKey
= ss
->serverCerts
[exchKeyType
].serverKeyPair
->pubKey
;
4059 if (svrPubKey
== NULL
) {
4060 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
4063 wrappedKey
.type
= siBuffer
;
4064 wrappedKey
.len
= SECKEY_PublicKeyStrength(svrPubKey
);
4065 wrappedKey
.data
= wswk
.wrappedSymmetricWrappingkey
;
4067 PORT_Assert(wrappedKey
.len
<= sizeof wswk
.wrappedSymmetricWrappingkey
);
4068 if (wrappedKey
.len
> sizeof wswk
.wrappedSymmetricWrappingkey
)
4071 /* wrap symmetric wrapping key in server's public key. */
4072 switch (exchKeyType
) {
4073 #ifdef NSS_ENABLE_ECC
4074 PK11SymKey
* Ks
= NULL
;
4075 SECKEYPublicKey
*pubWrapKey
= NULL
;
4076 SECKEYPrivateKey
*privWrapKey
= NULL
;
4077 ECCWrappedKeyInfo
*ecWrapped
;
4078 #endif /* NSS_ENABLE_ECC */
4081 asymWrapMechanism
= CKM_RSA_PKCS
;
4082 rv
= PK11_PubWrapSymKey(asymWrapMechanism
, svrPubKey
,
4083 unwrappedWrappingKey
, &wrappedKey
);
4086 #ifdef NSS_ENABLE_ECC
4089 * We generate an ephemeral EC key pair. Perform an ECDH
4090 * computation involving this ephemeral EC public key and
4091 * the SSL server's (long-term) EC private key. The resulting
4092 * shared secret is treated in the same way as Fortezza's Ks,
4093 * i.e., it is used to wrap the wrapping key. To facilitate
4094 * unwrapping in ssl_UnwrapWrappingKey, we also store all
4095 * relevant info about the ephemeral EC public key in
4096 * wswk.wrappedSymmetricWrappingkey and lay it out as
4097 * described in the ECCWrappedKeyInfo structure.
4099 PORT_Assert(svrPubKey
->keyType
== ecKey
);
4100 if (svrPubKey
->keyType
!= ecKey
) {
4101 /* something is wrong in sslsecur.c if this isn't an ecKey */
4102 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
4107 privWrapKey
= SECKEY_CreateECPrivateKey(
4108 &svrPubKey
->u
.ec
.DEREncodedParams
, &pubWrapKey
, NULL
);
4109 if ((privWrapKey
== NULL
) || (pubWrapKey
== NULL
)) {
4114 /* Set the key size in bits */
4115 if (pubWrapKey
->u
.ec
.size
== 0) {
4116 pubWrapKey
->u
.ec
.size
= SECKEY_PublicKeyStrengthInBits(svrPubKey
);
4119 PORT_Assert(pubWrapKey
->u
.ec
.DEREncodedParams
.len
+
4120 pubWrapKey
->u
.ec
.publicValue
.len
< MAX_EC_WRAPPED_KEY_BUFLEN
);
4121 if (pubWrapKey
->u
.ec
.DEREncodedParams
.len
+
4122 pubWrapKey
->u
.ec
.publicValue
.len
>= MAX_EC_WRAPPED_KEY_BUFLEN
) {
4123 PORT_SetError(SEC_ERROR_INVALID_KEY
);
4128 /* Derive Ks using ECDH */
4129 Ks
= PK11_PubDeriveWithKDF(svrPrivKey
, pubWrapKey
, PR_FALSE
, NULL
,
4130 NULL
, CKM_ECDH1_DERIVE
, masterWrapMech
,
4131 CKA_DERIVE
, 0, CKD_NULL
, NULL
, NULL
);
4137 ecWrapped
= (ECCWrappedKeyInfo
*) (wswk
.wrappedSymmetricWrappingkey
);
4138 ecWrapped
->size
= pubWrapKey
->u
.ec
.size
;
4139 ecWrapped
->encodedParamLen
= pubWrapKey
->u
.ec
.DEREncodedParams
.len
;
4140 PORT_Memcpy(ecWrapped
->var
, pubWrapKey
->u
.ec
.DEREncodedParams
.data
,
4141 pubWrapKey
->u
.ec
.DEREncodedParams
.len
);
4143 ecWrapped
->pubValueLen
= pubWrapKey
->u
.ec
.publicValue
.len
;
4144 PORT_Memcpy(ecWrapped
->var
+ ecWrapped
->encodedParamLen
,
4145 pubWrapKey
->u
.ec
.publicValue
.data
,
4146 pubWrapKey
->u
.ec
.publicValue
.len
);
4148 wrappedKey
.len
= MAX_EC_WRAPPED_KEY_BUFLEN
-
4149 (ecWrapped
->encodedParamLen
+ ecWrapped
->pubValueLen
);
4150 wrappedKey
.data
= ecWrapped
->var
+ ecWrapped
->encodedParamLen
+
4151 ecWrapped
->pubValueLen
;
4153 /* wrap symmetricWrapping key with the local Ks */
4154 rv
= PK11_WrapSymKey(masterWrapMech
, NULL
, Ks
,
4155 unwrappedWrappingKey
, &wrappedKey
);
4157 if (rv
!= SECSuccess
) {
4161 /* Write down the length of wrapped key in the buffer
4162 * wswk.wrappedSymmetricWrappingkey at the appropriate offset
4164 ecWrapped
->wrappedKeyLen
= wrappedKey
.len
;
4167 if (privWrapKey
) SECKEY_DestroyPrivateKey(privWrapKey
);
4168 if (pubWrapKey
) SECKEY_DestroyPublicKey(pubWrapKey
);
4169 if (Ks
) PK11_FreeSymKey(Ks
);
4170 asymWrapMechanism
= masterWrapMech
;
4172 #endif /* NSS_ENABLE_ECC */
4179 if (rv
!= SECSuccess
) {
4180 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE
);
4184 PORT_Assert(asymWrapMechanism
!= CKM_INVALID_MECHANISM
);
4186 wswk
.symWrapMechanism
= masterWrapMech
;
4187 wswk
.symWrapMechIndex
= symWrapMechIndex
;
4188 wswk
.asymWrapMechanism
= asymWrapMechanism
;
4189 wswk
.exchKeyType
= exchKeyType
;
4190 wswk
.wrappedSymKeyLen
= wrappedKey
.len
;
4192 /* put it on disk. */
4193 /* If the wrapping key for this KEA type has already been set,
4194 * then abandon the value we just computed and
4195 * use the one we got from the disk.
4197 if (ssl_SetWrappingKey(&wswk
)) {
4198 /* somebody beat us to it. The original contents of our wswk
4199 * has been replaced with the content on disk. Now, discard
4200 * the key we just created and unwrap this new one.
4202 PK11_FreeSymKey(unwrappedWrappingKey
);
4204 unwrappedWrappingKey
=
4205 ssl_UnwrapSymWrappingKey(&wswk
, svrPrivKey
, exchKeyType
,
4206 masterWrapMech
, pwArg
);
4210 if (unwrappedWrappingKey
) {
4211 *pSymWrapKey
= PK11_ReferenceSymKey(unwrappedWrappingKey
);
4216 PZ_Unlock(symWrapKeysLock
);
4217 return unwrappedWrappingKey
;
4221 /* Called from ssl3_SendClientKeyExchange(). */
4222 /* Presently, this always uses PKCS11. There is no bypass for this. */
4224 sendRSAClientKeyExchange(sslSocket
* ss
, SECKEYPublicKey
* svrPubKey
)
4226 PK11SymKey
* pms
= NULL
;
4227 SECStatus rv
= SECFailure
;
4228 SECItem enc_pms
= {siBuffer
, NULL
, 0};
4231 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
4232 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
));
4234 /* Generate the pre-master secret ... */
4235 ssl_GetSpecWriteLock(ss
);
4236 isTLS
= (PRBool
)(ss
->ssl3
.pwSpec
->version
> SSL_LIBRARY_VERSION_3_0
);
4238 pms
= ssl3_GenerateRSAPMS(ss
, ss
->ssl3
.pwSpec
, NULL
);
4239 ssl_ReleaseSpecWriteLock(ss
);
4241 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE
);
4246 if (ssl_trace
>= 100) {
4247 SECStatus extractRV
= PK11_ExtractKeyValue(pms
);
4248 if (extractRV
== SECSuccess
) {
4249 SECItem
* keyData
= PK11_GetKeyData(pms
);
4250 if (keyData
&& keyData
->data
&& keyData
->len
) {
4251 ssl_PrintBuf(ss
, "Pre-Master Secret",
4252 keyData
->data
, keyData
->len
);
4258 /* Get the wrapped (encrypted) pre-master secret, enc_pms */
4259 enc_pms
.len
= SECKEY_PublicKeyStrength(svrPubKey
);
4260 enc_pms
.data
= (unsigned char*)PORT_Alloc(enc_pms
.len
);
4261 if (enc_pms
.data
== NULL
) {
4262 goto loser
; /* err set by PORT_Alloc */
4265 /* wrap pre-master secret in server's public key. */
4266 rv
= PK11_PubWrapSymKey(CKM_RSA_PKCS
, svrPubKey
, pms
, &enc_pms
);
4267 if (rv
!= SECSuccess
) {
4268 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE
);
4272 rv
= ssl3_InitPendingCipherSpec(ss
, pms
);
4273 PK11_FreeSymKey(pms
); pms
= NULL
;
4275 if (rv
!= SECSuccess
) {
4276 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE
);
4280 rv
= ssl3_AppendHandshakeHeader(ss
, client_key_exchange
,
4281 isTLS
? enc_pms
.len
+ 2 : enc_pms
.len
);
4282 if (rv
!= SECSuccess
) {
4283 goto loser
; /* err set by ssl3_AppendHandshake* */
4286 rv
= ssl3_AppendHandshakeVariable(ss
, enc_pms
.data
, enc_pms
.len
, 2);
4288 rv
= ssl3_AppendHandshake(ss
, enc_pms
.data
, enc_pms
.len
);
4290 if (rv
!= SECSuccess
) {
4291 goto loser
; /* err set by ssl3_AppendHandshake* */
4297 if (enc_pms
.data
!= NULL
) {
4298 PORT_Free(enc_pms
.data
);
4301 PK11_FreeSymKey(pms
);
4306 /* Called from ssl3_SendClientKeyExchange(). */
4307 /* Presently, this always uses PKCS11. There is no bypass for this. */
4309 sendDHClientKeyExchange(sslSocket
* ss
, SECKEYPublicKey
* svrPubKey
)
4311 PK11SymKey
* pms
= NULL
;
4312 SECStatus rv
= SECFailure
;
4314 CK_MECHANISM_TYPE target
;
4316 SECKEYDHParams dhParam
; /* DH parameters */
4317 SECKEYPublicKey
*pubKey
= NULL
; /* Ephemeral DH key */
4318 SECKEYPrivateKey
*privKey
= NULL
; /* Ephemeral DH key */
4320 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
4321 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
));
4323 isTLS
= (PRBool
)(ss
->ssl3
.pwSpec
->version
> SSL_LIBRARY_VERSION_3_0
);
4325 /* Copy DH parameters from server key */
4327 if (svrPubKey
->keyType
!= dhKey
) {
4328 PORT_SetError(SEC_ERROR_BAD_KEY
);
4331 dhParam
.prime
.data
= svrPubKey
->u
.dh
.prime
.data
;
4332 dhParam
.prime
.len
= svrPubKey
->u
.dh
.prime
.len
;
4333 dhParam
.base
.data
= svrPubKey
->u
.dh
.base
.data
;
4334 dhParam
.base
.len
= svrPubKey
->u
.dh
.base
.len
;
4336 /* Generate ephemeral DH keypair */
4337 privKey
= SECKEY_CreateDHPrivateKey(&dhParam
, &pubKey
, NULL
);
4338 if (!privKey
|| !pubKey
) {
4339 ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL
);
4343 PRINT_BUF(50, (ss
, "DH public value:",
4344 pubKey
->u
.dh
.publicValue
.data
,
4345 pubKey
->u
.dh
.publicValue
.len
));
4347 if (isTLS
) target
= CKM_TLS_MASTER_KEY_DERIVE_DH
;
4348 else target
= CKM_SSL3_MASTER_KEY_DERIVE_DH
;
4350 /* Determine the PMS */
4352 pms
= PK11_PubDerive(privKey
, svrPubKey
, PR_FALSE
, NULL
, NULL
,
4353 CKM_DH_PKCS_DERIVE
, target
, CKA_DERIVE
, 0, NULL
);
4356 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE
);
4360 SECKEY_DestroyPrivateKey(privKey
);
4363 rv
= ssl3_InitPendingCipherSpec(ss
, pms
);
4364 PK11_FreeSymKey(pms
); pms
= NULL
;
4366 if (rv
!= SECSuccess
) {
4367 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE
);
4371 rv
= ssl3_AppendHandshakeHeader(ss
, client_key_exchange
,
4372 pubKey
->u
.dh
.publicValue
.len
+ 2);
4373 if (rv
!= SECSuccess
) {
4374 goto loser
; /* err set by ssl3_AppendHandshake* */
4376 rv
= ssl3_AppendHandshakeVariable(ss
,
4377 pubKey
->u
.dh
.publicValue
.data
,
4378 pubKey
->u
.dh
.publicValue
.len
, 2);
4379 SECKEY_DestroyPublicKey(pubKey
);
4382 if (rv
!= SECSuccess
) {
4383 goto loser
; /* err set by ssl3_AppendHandshake* */
4391 if(pms
) PK11_FreeSymKey(pms
);
4392 if(privKey
) SECKEY_DestroyPrivateKey(privKey
);
4393 if(pubKey
) SECKEY_DestroyPublicKey(pubKey
);
4401 /* Called from ssl3_HandleServerHelloDone(). */
4403 ssl3_SendClientKeyExchange(sslSocket
*ss
)
4405 SECKEYPublicKey
* serverKey
= NULL
;
4406 SECStatus rv
= SECFailure
;
4409 SSL_TRC(3, ("%d: SSL3[%d]: send client_key_exchange handshake",
4410 SSL_GETPID(), ss
->fd
));
4412 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
));
4413 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
4415 if (ss
->sec
.peerKey
== NULL
) {
4416 serverKey
= CERT_ExtractPublicKey(ss
->sec
.peerCert
);
4417 if (serverKey
== NULL
) {
4418 PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE
);
4422 serverKey
= ss
->sec
.peerKey
;
4423 ss
->sec
.peerKey
= NULL
; /* we're done with it now */
4426 isTLS
= (PRBool
)(ss
->ssl3
.pwSpec
->version
> SSL_LIBRARY_VERSION_3_0
);
4427 /* enforce limits on kea key sizes. */
4428 if (ss
->ssl3
.hs
.kea_def
->is_limited
) {
4429 int keyLen
= SECKEY_PublicKeyStrength(serverKey
); /* bytes */
4431 if (keyLen
* BPB
> ss
->ssl3
.hs
.kea_def
->key_size_limit
) {
4433 (void)SSL3_SendAlert(ss
, alert_fatal
, export_restriction
);
4435 (void)ssl3_HandshakeFailure(ss
);
4436 PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED
);
4441 ss
->sec
.keaType
= ss
->ssl3
.hs
.kea_def
->exchKeyType
;
4442 ss
->sec
.keaKeyBits
= SECKEY_PublicKeyStrengthInBits(serverKey
);
4444 switch (ss
->ssl3
.hs
.kea_def
->exchKeyType
) {
4446 rv
= sendRSAClientKeyExchange(ss
, serverKey
);
4450 rv
= sendDHClientKeyExchange(ss
, serverKey
);
4453 #ifdef NSS_ENABLE_ECC
4455 rv
= ssl3_SendECDHClientKeyExchange(ss
, serverKey
);
4457 #endif /* NSS_ENABLE_ECC */
4460 /* got an unknown or unsupported Key Exchange Algorithm. */
4462 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG
);
4466 SSL_TRC(3, ("%d: SSL3[%d]: DONE sending client_key_exchange",
4467 SSL_GETPID(), ss
->fd
));
4471 SECKEY_DestroyPublicKey(serverKey
);
4472 return rv
; /* err code already set. */
4475 /* Called from ssl3_HandleServerHelloDone(). */
4477 ssl3_SendCertificateVerify(sslSocket
*ss
)
4479 SECStatus rv
= SECFailure
;
4481 SECItem buf
= {siBuffer
, NULL
, 0};
4484 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
));
4485 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
4487 SSL_TRC(3, ("%d: SSL3[%d]: send certificate_verify handshake",
4488 SSL_GETPID(), ss
->fd
));
4490 ssl_GetSpecReadLock(ss
);
4491 rv
= ssl3_ComputeHandshakeHashes(ss
, ss
->ssl3
.pwSpec
, &hashes
, 0);
4492 ssl_ReleaseSpecReadLock(ss
);
4493 if (rv
!= SECSuccess
) {
4494 goto done
; /* err code was set by ssl3_ComputeHandshakeHashes */
4497 isTLS
= (PRBool
)(ss
->ssl3
.pwSpec
->version
> SSL_LIBRARY_VERSION_3_0
);
4498 rv
= ssl3_SignHashes(&hashes
, ss
->ssl3
.clientPrivateKey
, &buf
, isTLS
);
4499 if (rv
== SECSuccess
) {
4500 PK11SlotInfo
* slot
;
4501 sslSessionID
* sid
= ss
->sec
.ci
.sid
;
4503 /* Remember the info about the slot that did the signing.
4504 ** Later, when doing an SSL restart handshake, verify this.
4505 ** These calls are mere accessors, and can't fail.
4507 slot
= PK11_GetSlotFromPrivateKey(ss
->ssl3
.clientPrivateKey
);
4508 sid
->u
.ssl3
.clAuthSeries
= PK11_GetSlotSeries(slot
);
4509 sid
->u
.ssl3
.clAuthSlotID
= PK11_GetSlotID(slot
);
4510 sid
->u
.ssl3
.clAuthModuleID
= PK11_GetModuleID(slot
);
4511 sid
->u
.ssl3
.clAuthValid
= PR_TRUE
;
4512 PK11_FreeSlot(slot
);
4514 /* If we're doing RSA key exchange, we're all done with the private key
4515 * here. Diffie-Hellman key exchanges need the client's
4516 * private key for the key exchange.
4518 if (ss
->ssl3
.hs
.kea_def
->exchKeyType
== kt_rsa
) {
4519 SECKEY_DestroyPrivateKey(ss
->ssl3
.clientPrivateKey
);
4520 ss
->ssl3
.clientPrivateKey
= NULL
;
4522 if (rv
!= SECSuccess
) {
4523 goto done
; /* err code was set by ssl3_SignHashes */
4526 rv
= ssl3_AppendHandshakeHeader(ss
, certificate_verify
, buf
.len
+ 2);
4527 if (rv
!= SECSuccess
) {
4528 goto done
; /* error code set by AppendHandshake */
4530 rv
= ssl3_AppendHandshakeVariable(ss
, buf
.data
, buf
.len
, 2);
4531 if (rv
!= SECSuccess
) {
4532 goto done
; /* error code set by AppendHandshake */
4537 PORT_Free(buf
.data
);
4541 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
4542 * ssl3 ServerHello message.
4543 * Caller must hold Handshake and RecvBuf locks.
4546 ssl3_HandleServerHello(sslSocket
*ss
, SSL3Opaque
*b
, PRUint32 length
)
4548 sslSessionID
*sid
= ss
->sec
.ci
.sid
;
4549 PRInt32 temp
; /* allow for consume number failure */
4550 PRBool suite_found
= PR_FALSE
;
4552 int errCode
= SSL_ERROR_RX_MALFORMED_SERVER_HELLO
;
4554 SECItem sidBytes
= {siBuffer
, NULL
, 0};
4556 PRBool isTLS
= PR_FALSE
;
4557 SSL3AlertDescription desc
= illegal_parameter
;
4558 SSL3ProtocolVersion version
;
4560 SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello handshake",
4561 SSL_GETPID(), ss
->fd
));
4562 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
4563 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
4565 rv
= ssl3_InitState(ss
);
4566 if (rv
!= SECSuccess
) {
4567 errCode
= PORT_GetError(); /* ssl3_InitState has set the error code. */
4570 if (ss
->ssl3
.hs
.ws
!= wait_server_hello
) {
4571 errCode
= SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO
;
4572 desc
= unexpected_message
;
4576 temp
= ssl3_ConsumeHandshakeNumber(ss
, 2, &b
, &length
);
4578 goto loser
; /* alert has been sent */
4580 version
= (SSL3ProtocolVersion
)temp
;
4582 /* this is appropriate since the negotiation is complete, and we only
4585 if (MSB(version
) != MSB(SSL_LIBRARY_VERSION_3_0
)) {
4586 desc
= (version
> SSL_LIBRARY_VERSION_3_0
) ? protocol_version
4587 : handshake_failure
;
4591 rv
= ssl3_NegotiateVersion(ss
, version
);
4592 if (rv
!= SECSuccess
) {
4593 desc
= (version
> SSL_LIBRARY_VERSION_3_0
) ? protocol_version
4594 : handshake_failure
;
4595 errCode
= SSL_ERROR_NO_CYPHER_OVERLAP
;
4598 isTLS
= (ss
->version
> SSL_LIBRARY_VERSION_3_0
);
4600 rv
= ssl3_ConsumeHandshake(
4601 ss
, &ss
->ssl3
.hs
.server_random
, SSL3_RANDOM_LENGTH
, &b
, &length
);
4602 if (rv
!= SECSuccess
) {
4603 goto loser
; /* alert has been sent */
4606 rv
= ssl3_ConsumeHandshakeVariable(ss
, &sidBytes
, 1, &b
, &length
);
4607 if (rv
!= SECSuccess
) {
4608 goto loser
; /* alert has been sent */
4610 if (sidBytes
.len
> SSL3_SESSIONID_BYTES
) {
4612 desc
= decode_error
;
4613 goto alert_loser
; /* malformed. */
4616 /* find selected cipher suite in our list. */
4617 temp
= ssl3_ConsumeHandshakeNumber(ss
, 2, &b
, &length
);
4619 goto loser
; /* alert has been sent */
4621 ssl3_config_match_init(ss
);
4622 for (i
= 0; i
< ssl_V3_SUITES_IMPLEMENTED
; i
++) {
4623 ssl3CipherSuiteCfg
*suite
= &ss
->cipherSuites
[i
];
4624 if ((temp
== suite
->cipher_suite
) &&
4625 (config_match(suite
, ss
->ssl3
.policy
, PR_TRUE
))) {
4626 suite_found
= PR_TRUE
;
4627 break; /* success */
4631 desc
= handshake_failure
;
4632 errCode
= SSL_ERROR_NO_CYPHER_OVERLAP
;
4635 ss
->ssl3
.hs
.cipher_suite
= (ssl3CipherSuite
)temp
;
4636 ss
->ssl3
.hs
.suite_def
= ssl_LookupCipherSuiteDef((ssl3CipherSuite
)temp
);
4637 PORT_Assert(ss
->ssl3
.hs
.suite_def
);
4638 if (!ss
->ssl3
.hs
.suite_def
) {
4639 PORT_SetError(errCode
= SEC_ERROR_LIBRARY_FAILURE
);
4640 goto loser
; /* we don't send alerts for our screw-ups. */
4643 /* find selected compression method in our list. */
4644 temp
= ssl3_ConsumeHandshakeNumber(ss
, 1, &b
, &length
);
4646 goto loser
; /* alert has been sent */
4648 suite_found
= PR_FALSE
;
4649 for (i
= 0; i
< compressionMethodsCount
; i
++) {
4650 if (temp
== compressions
[i
]) {
4651 suite_found
= PR_TRUE
;
4652 break; /* success */
4656 desc
= handshake_failure
;
4657 errCode
= SSL_ERROR_NO_COMPRESSION_OVERLAP
;
4660 ss
->ssl3
.hs
.compression
= (SSL3CompressionMethod
)temp
;
4662 /* Note that if !isTLS && length != 0, we do NOT goto alert_loser.
4663 * There are some old SSL 3.0 implementations that do send stuff
4664 * after the end of the server hello, and we deliberately ignore
4665 * such stuff in the interest of maximal interoperability (being
4666 * "generous in what you accept").
4668 if (isTLS
&& length
!= 0) {
4670 rv
= ssl3_ConsumeHandshakeVariable(ss
, &extensions
, 2, &b
, &length
);
4671 if (rv
!= SECSuccess
|| length
!= 0)
4673 rv
= ssl3_HandleHelloExtensions(ss
, &extensions
.data
, &extensions
.len
);
4674 if (rv
!= SECSuccess
)
4678 /* Any errors after this point are not "malformed" errors. */
4679 desc
= handshake_failure
;
4681 /* we need to call ssl3_SetupPendingCipherSpec here so we can check the
4682 * key exchange algorithm. */
4683 rv
= ssl3_SetupPendingCipherSpec(ss
);
4684 if (rv
!= SECSuccess
) {
4685 goto alert_loser
; /* error code is set. */
4688 /* We may or may not have sent a session id, we may get one back or
4689 * not and if so it may match the one we sent.
4690 * Attempt to restore the master secret to see if this is so...
4691 * Don't consider failure to find a matching SID an error.
4693 sid_match
= (PRBool
)(sidBytes
.len
> 0 &&
4694 sidBytes
.len
== sid
->u
.ssl3
.sessionIDLength
&&
4695 !PORT_Memcmp(sid
->u
.ssl3
.sessionID
, sidBytes
.data
, sidBytes
.len
));
4698 sid
->version
== ss
->version
&&
4699 sid
->u
.ssl3
.cipherSuite
== ss
->ssl3
.hs
.cipher_suite
) do {
4700 ssl3CipherSpec
*pwSpec
= ss
->ssl3
.pwSpec
;
4702 SECItem wrappedMS
; /* wrapped master secret. */
4704 ss
->sec
.authAlgorithm
= sid
->authAlgorithm
;
4705 ss
->sec
.authKeyBits
= sid
->authKeyBits
;
4706 ss
->sec
.keaType
= sid
->keaType
;
4707 ss
->sec
.keaKeyBits
= sid
->keaKeyBits
;
4710 * a) key is wrapped (implies using PKCS11)
4711 * b) key is unwrapped, but we're still using PKCS11
4712 * c) key is unwrapped, and we're bypassing PKCS11.
4714 if (sid
->u
.ssl3
.keys
.msIsWrapped
) {
4716 PK11SymKey
* wrapKey
; /* wrapping key */
4717 CK_FLAGS keyFlags
= 0;
4719 if (ss
->opt
.bypassPKCS11
) {
4720 /* we cannot restart a non-bypass session in a
4725 /* unwrap master secret with PKCS11 */
4726 slot
= SECMOD_LookupSlot(sid
->u
.ssl3
.masterModuleID
,
4727 sid
->u
.ssl3
.masterSlotID
);
4729 break; /* not considered an error. */
4731 if (!PK11_IsPresent(slot
)) {
4732 PK11_FreeSlot(slot
);
4733 break; /* not considered an error. */
4735 wrapKey
= PK11_GetWrapKey(slot
, sid
->u
.ssl3
.masterWrapIndex
,
4736 sid
->u
.ssl3
.masterWrapMech
,
4737 sid
->u
.ssl3
.masterWrapSeries
,
4739 PK11_FreeSlot(slot
);
4740 if (wrapKey
== NULL
) {
4741 break; /* not considered an error. */
4744 if (ss
->version
> SSL_LIBRARY_VERSION_3_0
) { /* isTLS */
4745 keyFlags
= CKF_SIGN
| CKF_VERIFY
;
4748 wrappedMS
.data
= sid
->u
.ssl3
.keys
.wrapped_master_secret
;
4749 wrappedMS
.len
= sid
->u
.ssl3
.keys
.wrapped_master_secret_len
;
4750 pwSpec
->master_secret
=
4751 PK11_UnwrapSymKeyWithFlags(wrapKey
, sid
->u
.ssl3
.masterWrapMech
,
4752 NULL
, &wrappedMS
, CKM_SSL3_MASTER_KEY_DERIVE
,
4753 CKA_DERIVE
, sizeof(SSL3MasterSecret
), keyFlags
);
4754 errCode
= PORT_GetError();
4755 PK11_FreeSymKey(wrapKey
);
4756 if (pwSpec
->master_secret
== NULL
) {
4757 break; /* errorCode set just after call to UnwrapSymKey. */
4759 } else if (ss
->opt
.bypassPKCS11
) {
4760 /* MS is not wrapped */
4761 wrappedMS
.data
= sid
->u
.ssl3
.keys
.wrapped_master_secret
;
4762 wrappedMS
.len
= sid
->u
.ssl3
.keys
.wrapped_master_secret_len
;
4763 memcpy(pwSpec
->raw_master_secret
, wrappedMS
.data
, wrappedMS
.len
);
4764 pwSpec
->msItem
.data
= pwSpec
->raw_master_secret
;
4765 pwSpec
->msItem
.len
= wrappedMS
.len
;
4767 /* We CAN restart a bypass session in a non-bypass socket. */
4768 /* need to import the raw master secret to session object */
4769 PK11SlotInfo
*slot
= PK11_GetInternalSlot();
4770 wrappedMS
.data
= sid
->u
.ssl3
.keys
.wrapped_master_secret
;
4771 wrappedMS
.len
= sid
->u
.ssl3
.keys
.wrapped_master_secret_len
;
4772 pwSpec
->master_secret
=
4773 PK11_ImportSymKey(slot
, CKM_SSL3_MASTER_KEY_DERIVE
,
4774 PK11_OriginUnwrap
, CKA_ENCRYPT
,
4776 PK11_FreeSlot(slot
);
4777 if (pwSpec
->master_secret
== NULL
) {
4783 SSL_AtomicIncrementLong(& ssl3stats
.hsh_sid_cache_hits
);
4785 /* If we sent a session ticket, then this is a stateless resume. */
4786 if (sid
->version
> SSL_LIBRARY_VERSION_3_0
&&
4787 sid
->u
.ssl3
.sessionTicket
.ticket
.data
!= NULL
)
4788 SSL_AtomicIncrementLong(& ssl3stats
.hsh_sid_stateless_resumes
);
4790 if (ssl3_ExtensionNegotiated(ss
, session_ticket_xtn
))
4791 ss
->ssl3
.hs
.ws
= wait_new_session_ticket
;
4793 ss
->ssl3
.hs
.ws
= wait_change_cipher
;
4795 ss
->ssl3
.hs
.isResuming
= PR_TRUE
;
4797 /* copy the peer cert from the SID */
4798 if (sid
->peerCert
!= NULL
) {
4799 ss
->sec
.peerCert
= CERT_DupCertificate(sid
->peerCert
);
4803 /* NULL value for PMS signifies re-use of the old MS */
4804 rv
= ssl3_InitPendingCipherSpec(ss
, NULL
);
4805 if (rv
!= SECSuccess
) {
4806 goto alert_loser
; /* err code was set */
4812 SSL_AtomicIncrementLong(& ssl3stats
.hsh_sid_cache_not_ok
);
4814 SSL_AtomicIncrementLong(& ssl3stats
.hsh_sid_cache_misses
);
4816 /* throw the old one away */
4817 sid
->u
.ssl3
.keys
.resumable
= PR_FALSE
;
4818 (*ss
->sec
.uncache
)(sid
);
4822 ss
->sec
.ci
.sid
= sid
= ssl3_NewSessionID(ss
, PR_FALSE
);
4824 goto alert_loser
; /* memory error is set. */
4827 sid
->version
= ss
->version
;
4828 sid
->u
.ssl3
.sessionIDLength
= sidBytes
.len
;
4829 PORT_Memcpy(sid
->u
.ssl3
.sessionID
, sidBytes
.data
, sidBytes
.len
);
4831 ss
->ssl3
.hs
.isResuming
= PR_FALSE
;
4832 ss
->ssl3
.hs
.ws
= wait_server_cert
;
4836 (void)SSL3_SendAlert(ss
, alert_fatal
, desc
);
4839 errCode
= ssl_MapLowLevelError(errCode
);
4843 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
4844 * ssl3 ServerKeyExchange message.
4845 * Caller must hold Handshake and RecvBuf locks.
4848 ssl3_HandleServerKeyExchange(sslSocket
*ss
, SSL3Opaque
*b
, PRUint32 length
)
4850 PRArenaPool
* arena
= NULL
;
4851 SECKEYPublicKey
*peerKey
= NULL
;
4854 int errCode
= SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH
;
4855 SSL3AlertDescription desc
= illegal_parameter
;
4857 SECItem signature
= {siBuffer
, NULL
, 0};
4859 SSL_TRC(3, ("%d: SSL3[%d]: handle server_key_exchange handshake",
4860 SSL_GETPID(), ss
->fd
));
4861 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
4862 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
4864 if (ss
->ssl3
.hs
.ws
!= wait_server_key
&&
4865 ss
->ssl3
.hs
.ws
!= wait_server_cert
) {
4866 errCode
= SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH
;
4867 desc
= unexpected_message
;
4870 if (ss
->sec
.peerCert
== NULL
) {
4871 errCode
= SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH
;
4872 desc
= unexpected_message
;
4876 isTLS
= (PRBool
)(ss
->ssl3
.prSpec
->version
> SSL_LIBRARY_VERSION_3_0
);
4878 switch (ss
->ssl3
.hs
.kea_def
->exchKeyType
) {
4881 SECItem modulus
= {siBuffer
, NULL
, 0};
4882 SECItem exponent
= {siBuffer
, NULL
, 0};
4884 rv
= ssl3_ConsumeHandshakeVariable(ss
, &modulus
, 2, &b
, &length
);
4885 if (rv
!= SECSuccess
) {
4886 goto loser
; /* malformed. */
4888 rv
= ssl3_ConsumeHandshakeVariable(ss
, &exponent
, 2, &b
, &length
);
4889 if (rv
!= SECSuccess
) {
4890 goto loser
; /* malformed. */
4892 rv
= ssl3_ConsumeHandshakeVariable(ss
, &signature
, 2, &b
, &length
);
4893 if (rv
!= SECSuccess
) {
4894 goto loser
; /* malformed. */
4898 desc
= decode_error
;
4899 goto alert_loser
; /* malformed. */
4902 /* failures after this point are not malformed handshakes. */
4903 /* TLS: send decrypt_error if signature failed. */
4904 desc
= isTLS
? decrypt_error
: handshake_failure
;
4907 * check to make sure the hash is signed by right guy
4909 rv
= ssl3_ComputeExportRSAKeyHash(modulus
, exponent
,
4910 &ss
->ssl3
.hs
.client_random
,
4911 &ss
->ssl3
.hs
.server_random
,
4912 &hashes
, ss
->opt
.bypassPKCS11
);
4913 if (rv
!= SECSuccess
) {
4915 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE
);
4918 rv
= ssl3_VerifySignedHashes(&hashes
, ss
->sec
.peerCert
, &signature
,
4919 isTLS
, ss
->pkcs11PinArg
);
4920 if (rv
!= SECSuccess
) {
4922 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE
);
4927 * we really need to build a new key here because we can no longer
4928 * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate
4929 * pkcs11 slots and ID's.
4931 arena
= PORT_NewArena(DER_DEFAULT_CHUNKSIZE
);
4932 if (arena
== NULL
) {
4936 peerKey
= PORT_ArenaZNew(arena
, SECKEYPublicKey
);
4937 if (peerKey
== NULL
) {
4938 PORT_FreeArena(arena
, PR_FALSE
);
4942 peerKey
->arena
= arena
;
4943 peerKey
->keyType
= rsaKey
;
4944 peerKey
->pkcs11Slot
= NULL
;
4945 peerKey
->pkcs11ID
= CK_INVALID_HANDLE
;
4946 if (SECITEM_CopyItem(arena
, &peerKey
->u
.rsa
.modulus
, &modulus
) ||
4947 SECITEM_CopyItem(arena
, &peerKey
->u
.rsa
.publicExponent
, &exponent
))
4949 PORT_FreeArena(arena
, PR_FALSE
);
4952 ss
->sec
.peerKey
= peerKey
;
4953 ss
->ssl3
.hs
.ws
= wait_cert_request
;
4958 SECItem dh_p
= {siBuffer
, NULL
, 0};
4959 SECItem dh_g
= {siBuffer
, NULL
, 0};
4960 SECItem dh_Ys
= {siBuffer
, NULL
, 0};
4962 rv
= ssl3_ConsumeHandshakeVariable(ss
, &dh_p
, 2, &b
, &length
);
4963 if (rv
!= SECSuccess
) {
4964 goto loser
; /* malformed. */
4966 rv
= ssl3_ConsumeHandshakeVariable(ss
, &dh_g
, 2, &b
, &length
);
4967 if (rv
!= SECSuccess
) {
4968 goto loser
; /* malformed. */
4970 rv
= ssl3_ConsumeHandshakeVariable(ss
, &dh_Ys
, 2, &b
, &length
);
4971 if (rv
!= SECSuccess
) {
4972 goto loser
; /* malformed. */
4974 rv
= ssl3_ConsumeHandshakeVariable(ss
, &signature
, 2, &b
, &length
);
4975 if (rv
!= SECSuccess
) {
4976 goto loser
; /* malformed. */
4980 desc
= decode_error
;
4981 goto alert_loser
; /* malformed. */
4984 PRINT_BUF(60, (NULL
, "Server DH p", dh_p
.data
, dh_p
.len
));
4985 PRINT_BUF(60, (NULL
, "Server DH g", dh_g
.data
, dh_g
.len
));
4986 PRINT_BUF(60, (NULL
, "Server DH Ys", dh_Ys
.data
, dh_Ys
.len
));
4988 /* failures after this point are not malformed handshakes. */
4989 /* TLS: send decrypt_error if signature failed. */
4990 desc
= isTLS
? decrypt_error
: handshake_failure
;
4993 * check to make sure the hash is signed by right guy
4995 rv
= ssl3_ComputeDHKeyHash(dh_p
, dh_g
, dh_Ys
,
4996 &ss
->ssl3
.hs
.client_random
,
4997 &ss
->ssl3
.hs
.server_random
,
4998 &hashes
, ss
->opt
.bypassPKCS11
);
4999 if (rv
!= SECSuccess
) {
5001 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE
);
5004 rv
= ssl3_VerifySignedHashes(&hashes
, ss
->sec
.peerCert
, &signature
,
5005 isTLS
, ss
->pkcs11PinArg
);
5006 if (rv
!= SECSuccess
) {
5008 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE
);
5013 * we really need to build a new key here because we can no longer
5014 * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate
5015 * pkcs11 slots and ID's.
5017 arena
= PORT_NewArena(DER_DEFAULT_CHUNKSIZE
);
5018 if (arena
== NULL
) {
5022 ss
->sec
.peerKey
= peerKey
= PORT_ArenaZNew(arena
, SECKEYPublicKey
);
5023 if (peerKey
== NULL
) {
5027 peerKey
->arena
= arena
;
5028 peerKey
->keyType
= dhKey
;
5029 peerKey
->pkcs11Slot
= NULL
;
5030 peerKey
->pkcs11ID
= CK_INVALID_HANDLE
;
5032 if (SECITEM_CopyItem(arena
, &peerKey
->u
.dh
.prime
, &dh_p
) ||
5033 SECITEM_CopyItem(arena
, &peerKey
->u
.dh
.base
, &dh_g
) ||
5034 SECITEM_CopyItem(arena
, &peerKey
->u
.dh
.publicValue
, &dh_Ys
))
5036 PORT_FreeArena(arena
, PR_FALSE
);
5039 ss
->sec
.peerKey
= peerKey
;
5040 ss
->ssl3
.hs
.ws
= wait_cert_request
;
5044 #ifdef NSS_ENABLE_ECC
5046 rv
= ssl3_HandleECDHServerKeyExchange(ss
, b
, length
);
5048 #endif /* NSS_ENABLE_ECC */
5051 desc
= handshake_failure
;
5052 errCode
= SEC_ERROR_UNSUPPORTED_KEYALG
;
5053 break; /* goto alert_loser; */
5057 (void)SSL3_SendAlert(ss
, alert_fatal
, desc
);
5059 PORT_SetError( errCode
);
5062 no_memory
: /* no-memory error has already been set. */
5063 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE
);
5068 typedef struct dnameNode
{
5069 struct dnameNode
*next
;
5073 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
5074 * ssl3 Certificate Request message.
5075 * Caller must hold Handshake and RecvBuf locks.
5078 ssl3_HandleCertificateRequest(sslSocket
*ss
, SSL3Opaque
*b
, PRUint32 length
)
5080 PRArenaPool
* arena
= NULL
;
5083 PRBool isTLS
= PR_FALSE
;
5085 int errCode
= SSL_ERROR_RX_MALFORMED_CERT_REQUEST
;
5088 SSL3AlertDescription desc
= illegal_parameter
;
5089 SECItem cert_types
= {siBuffer
, NULL
, 0};
5090 CERTDistNames ca_list
;
5092 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_request handshake",
5093 SSL_GETPID(), ss
->fd
));
5094 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
5095 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
5097 if (ss
->ssl3
.hs
.ws
!= wait_cert_request
&&
5098 ss
->ssl3
.hs
.ws
!= wait_server_key
) {
5099 desc
= unexpected_message
;
5100 errCode
= SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST
;
5104 /* clean up anything left from previous handshake. */
5105 if (ss
->ssl3
.clientCertChain
!= NULL
) {
5106 CERT_DestroyCertificateList(ss
->ssl3
.clientCertChain
);
5107 ss
->ssl3
.clientCertChain
= NULL
;
5109 if (ss
->ssl3
.clientCertificate
!= NULL
) {
5110 CERT_DestroyCertificate(ss
->ssl3
.clientCertificate
);
5111 ss
->ssl3
.clientCertificate
= NULL
;
5113 if (ss
->ssl3
.clientPrivateKey
!= NULL
) {
5114 SECKEY_DestroyPrivateKey(ss
->ssl3
.clientPrivateKey
);
5115 ss
->ssl3
.clientPrivateKey
= NULL
;
5118 isTLS
= (PRBool
)(ss
->ssl3
.prSpec
->version
> SSL_LIBRARY_VERSION_3_0
);
5119 rv
= ssl3_ConsumeHandshakeVariable(ss
, &cert_types
, 1, &b
, &length
);
5120 if (rv
!= SECSuccess
)
5121 goto loser
; /* malformed, alert has been sent */
5123 arena
= ca_list
.arena
= PORT_NewArena(DER_DEFAULT_CHUNKSIZE
);
5127 remaining
= ssl3_ConsumeHandshakeNumber(ss
, 2, &b
, &length
);
5129 goto loser
; /* malformed, alert has been sent */
5131 if ((PRUint32
)remaining
> length
)
5134 ca_list
.head
= node
= PORT_ArenaZNew(arena
, dnameNode
);
5138 while (remaining
> 0) {
5142 goto alert_loser
; /* malformed */
5144 node
->name
.len
= len
= ssl3_ConsumeHandshakeNumber(ss
, 2, &b
, &length
);
5146 goto loser
; /* malformed, alert has been sent */
5149 if (remaining
< len
)
5150 goto alert_loser
; /* malformed */
5152 node
->name
.data
= b
;
5158 break; /* success */
5160 node
->next
= PORT_ArenaZNew(arena
, dnameNode
);
5166 ca_list
.nnames
= nnames
;
5167 ca_list
.names
= PORT_ArenaNewArray(arena
, SECItem
, nnames
);
5168 if (nnames
> 0 && ca_list
.names
== NULL
)
5171 for(i
= 0, node
= (dnameNode
*)ca_list
.head
;
5173 i
++, node
= node
->next
) {
5174 ca_list
.names
[i
] = node
->name
;
5178 goto alert_loser
; /* malformed */
5180 desc
= no_certificate
;
5181 ss
->ssl3
.hs
.ws
= wait_hello_done
;
5183 if (ss
->getClientAuthData
== NULL
) {
5184 rv
= SECFailure
; /* force it to send a no_certificate alert */
5186 /* XXX Should pass cert_types in this call!! */
5187 rv
= (SECStatus
)(*ss
->getClientAuthData
)(ss
->getClientAuthDataArg
,
5189 &ss
->ssl3
.clientCertificate
,
5190 &ss
->ssl3
.clientPrivateKey
);
5193 case SECWouldBlock
: /* getClientAuthData has put up a dialog box. */
5194 ssl_SetAlwaysBlock(ss
);
5195 break; /* not an error */
5198 /* check what the callback function returned */
5199 if ((!ss
->ssl3
.clientCertificate
) || (!ss
->ssl3
.clientPrivateKey
)) {
5200 /* we are missing either the key or cert */
5201 if (ss
->ssl3
.clientCertificate
) {
5202 /* got a cert, but no key - free it */
5203 CERT_DestroyCertificate(ss
->ssl3
.clientCertificate
);
5204 ss
->ssl3
.clientCertificate
= NULL
;
5206 if (ss
->ssl3
.clientPrivateKey
) {
5207 /* got a key, but no cert - free it */
5208 SECKEY_DestroyPrivateKey(ss
->ssl3
.clientPrivateKey
);
5209 ss
->ssl3
.clientPrivateKey
= NULL
;
5211 goto send_no_certificate
;
5213 /* Setting ssl3.clientCertChain non-NULL will cause
5214 * ssl3_HandleServerHelloDone to call SendCertificate.
5216 ss
->ssl3
.clientCertChain
= CERT_CertChainFromCert(
5217 ss
->ssl3
.clientCertificate
,
5218 certUsageSSLClient
, PR_FALSE
);
5219 if (ss
->ssl3
.clientCertChain
== NULL
) {
5220 if (ss
->ssl3
.clientCertificate
!= NULL
) {
5221 CERT_DestroyCertificate(ss
->ssl3
.clientCertificate
);
5222 ss
->ssl3
.clientCertificate
= NULL
;
5224 if (ss
->ssl3
.clientPrivateKey
!= NULL
) {
5225 SECKEY_DestroyPrivateKey(ss
->ssl3
.clientPrivateKey
);
5226 ss
->ssl3
.clientPrivateKey
= NULL
;
5228 goto send_no_certificate
;
5230 break; /* not an error */
5234 send_no_certificate
:
5236 ss
->ssl3
.sendEmptyCert
= PR_TRUE
;
5238 (void)SSL3_SendAlert(ss
, alert_warning
, no_certificate
);
5247 PORT_SetError(SEC_ERROR_NO_MEMORY
);
5251 if (isTLS
&& desc
== illegal_parameter
)
5252 desc
= decode_error
;
5253 (void)SSL3_SendAlert(ss
, alert_fatal
, desc
);
5255 PORT_SetError(errCode
);
5259 PORT_FreeArena(arena
, PR_FALSE
);
5264 * attempt to restart the handshake after asynchronously handling
5265 * a request for the client's certificate.
5268 * cert Client cert chosen by application.
5269 * Note: ssl takes this reference, and does not bump the
5270 * reference count. The caller should drop its reference
5271 * without calling CERT_DestroyCert after calling this function.
5273 * key Private key associated with cert. This function makes a
5274 * copy of the private key, so the caller remains responsible
5275 * for destroying its copy after this function returns.
5277 * certChain DER-encoded certs, client cert and its signers.
5278 * Note: ssl takes this reference, and does not copy the chain.
5279 * The caller should drop its reference without destroying the
5280 * chain. SSL will free the chain when it is done with it.
5284 * XXX This code only works on the initial handshake on a connection, XXX
5285 * It does not work on a subsequent handshake (redo).
5287 * Caller holds 1stHandshakeLock.
5290 ssl3_RestartHandshakeAfterCertReq(sslSocket
* ss
,
5291 CERTCertificate
* cert
,
5292 SECKEYPrivateKey
* key
,
5293 CERTCertificateList
*certChain
)
5295 SECStatus rv
= SECSuccess
;
5297 if (MSB(ss
->version
) == MSB(SSL_LIBRARY_VERSION_3_0
)) {
5298 /* XXX This code only works on the initial handshake on a connection,
5299 ** XXX It does not work on a subsequent handshake (redo).
5301 if (ss
->handshake
!= 0) {
5302 ss
->handshake
= ssl_GatherRecord1stHandshake
;
5303 ss
->ssl3
.clientCertificate
= cert
;
5304 ss
->ssl3
.clientCertChain
= certChain
;
5306 (void)SSL3_SendAlert(ss
, alert_warning
, no_certificate
);
5307 ss
->ssl3
.clientPrivateKey
= NULL
;
5309 ss
->ssl3
.clientPrivateKey
= SECKEY_CopyPrivateKey(key
);
5311 ssl_GetRecvBufLock(ss
);
5312 if (ss
->ssl3
.hs
.msgState
.buf
!= NULL
) {
5313 rv
= ssl3_HandleRecord(ss
, NULL
, &ss
->gs
.buf
);
5315 ssl_ReleaseRecvBufLock(ss
);
5323 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
5324 * ssl3 Server Hello Done message.
5325 * Caller must hold Handshake and RecvBuf locks.
5328 ssl3_HandleServerHelloDone(sslSocket
*ss
)
5331 SSL3WaitState ws
= ss
->ssl3
.hs
.ws
;
5332 PRBool send_verify
= PR_FALSE
;
5334 SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello_done handshake",
5335 SSL_GETPID(), ss
->fd
));
5336 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
5337 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
5339 if (ws
!= wait_hello_done
&&
5340 ws
!= wait_server_cert
&&
5341 ws
!= wait_server_key
&&
5342 ws
!= wait_cert_request
) {
5343 SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
5344 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE
);
5348 ssl_GetXmitBufLock(ss
); /*******************************/
5350 if (ss
->ssl3
.sendEmptyCert
) {
5351 ss
->ssl3
.sendEmptyCert
= PR_FALSE
;
5352 rv
= ssl3_SendEmptyCertificate(ss
);
5353 /* Don't send verify */
5354 if (rv
!= SECSuccess
) {
5355 goto loser
; /* error code is set. */
5358 if (ss
->ssl3
.clientCertChain
!= NULL
&&
5359 ss
->ssl3
.clientPrivateKey
!= NULL
) {
5360 send_verify
= PR_TRUE
;
5361 rv
= ssl3_SendCertificate(ss
);
5362 if (rv
!= SECSuccess
) {
5363 goto loser
; /* error code is set. */
5367 rv
= ssl3_SendClientKeyExchange(ss
);
5368 if (rv
!= SECSuccess
) {
5369 goto loser
; /* err is set. */
5373 rv
= ssl3_SendCertificateVerify(ss
);
5374 if (rv
!= SECSuccess
) {
5375 goto loser
; /* err is set. */
5378 rv
= ssl3_SendChangeCipherSpecs(ss
);
5379 if (rv
!= SECSuccess
) {
5380 goto loser
; /* err code was set. */
5382 rv
= ssl3_SendFinished(ss
, 0);
5383 if (rv
!= SECSuccess
) {
5384 goto loser
; /* err code was set. */
5387 ssl_ReleaseXmitBufLock(ss
); /*******************************/
5389 if (ssl3_ExtensionNegotiated(ss
, session_ticket_xtn
))
5390 ss
->ssl3
.hs
.ws
= wait_new_session_ticket
;
5392 ss
->ssl3
.hs
.ws
= wait_change_cipher
;
5396 ssl_ReleaseXmitBufLock(ss
);
5401 * Routines used by servers
5404 ssl3_SendHelloRequest(sslSocket
*ss
)
5408 SSL_TRC(3, ("%d: SSL3[%d]: send hello_request handshake", SSL_GETPID(),
5411 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
5412 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
) );
5414 rv
= ssl3_AppendHandshakeHeader(ss
, hello_request
, 0);
5415 if (rv
!= SECSuccess
) {
5416 return rv
; /* err set by AppendHandshake */
5418 rv
= ssl3_FlushHandshake(ss
, 0);
5419 if (rv
!= SECSuccess
) {
5420 return rv
; /* error code set by ssl3_FlushHandshake */
5422 ss
->ssl3
.hs
.ws
= wait_client_hello
;
5426 /* Sets memory error when returning NULL.
5428 * ssl3_SendClientHello()
5429 * ssl3_HandleServerHello()
5430 * ssl3_HandleClientHello()
5431 * ssl3_HandleV2ClientHello()
5434 ssl3_NewSessionID(sslSocket
*ss
, PRBool is_server
)
5438 sid
= PORT_ZNew(sslSessionID
);
5442 sid
->peerID
= (ss
->peerID
== NULL
) ? NULL
: PORT_Strdup(ss
->peerID
);
5443 sid
->urlSvrName
= (ss
->url
== NULL
) ? NULL
: PORT_Strdup(ss
->url
);
5444 sid
->addr
= ss
->sec
.ci
.peer
;
5445 sid
->port
= ss
->sec
.ci
.port
;
5446 sid
->references
= 1;
5447 sid
->cached
= never_cached
;
5448 sid
->version
= ss
->version
;
5450 sid
->u
.ssl3
.keys
.resumable
= PR_TRUE
;
5451 sid
->u
.ssl3
.policy
= SSL_ALLOWED
;
5452 sid
->u
.ssl3
.clientWriteKey
= NULL
;
5453 sid
->u
.ssl3
.serverWriteKey
= NULL
;
5457 int pid
= SSL_GETPID();
5459 sid
->u
.ssl3
.sessionIDLength
= SSL3_SESSIONID_BYTES
;
5460 sid
->u
.ssl3
.sessionID
[0] = (pid
>> 8) & 0xff;
5461 sid
->u
.ssl3
.sessionID
[1] = pid
& 0xff;
5462 rv
= PK11_GenerateRandom(sid
->u
.ssl3
.sessionID
+ 2,
5463 SSL3_SESSIONID_BYTES
-2);
5464 if (rv
!= SECSuccess
) {
5466 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE
);
5473 /* Called from: ssl3_HandleClientHello, ssl3_HandleV2ClientHello */
5475 ssl3_SendServerHelloSequence(sslSocket
*ss
)
5477 const ssl3KEADef
*kea_def
;
5480 SSL_TRC(3, ("%d: SSL3[%d]: begin send server_hello sequence",
5481 SSL_GETPID(), ss
->fd
));
5483 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
5484 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
) );
5486 rv
= ssl3_SendServerHello(ss
);
5487 if (rv
!= SECSuccess
) {
5488 return rv
; /* err code is set. */
5490 rv
= ssl3_SendCertificate(ss
);
5491 if (rv
!= SECSuccess
) {
5492 return rv
; /* error code is set. */
5494 /* We have to do this after the call to ssl3_SendServerHello,
5495 * because kea_def is set up by ssl3_SendServerHello().
5497 kea_def
= ss
->ssl3
.hs
.kea_def
;
5498 ss
->ssl3
.hs
.usedStepDownKey
= PR_FALSE
;
5500 if (kea_def
->is_limited
&& kea_def
->exchKeyType
== kt_rsa
) {
5501 /* see if we can legally use the key in the cert. */
5502 int keyLen
; /* bytes */
5504 keyLen
= PK11_GetPrivateModulusLen(
5505 ss
->serverCerts
[kea_def
->exchKeyType
].SERVERKEY
);
5508 keyLen
* BPB
<= kea_def
->key_size_limit
) {
5509 /* XXX AND cert is not signing only!! */
5510 /* just fall through and use it. */
5511 } else if (ss
->stepDownKeyPair
!= NULL
) {
5512 ss
->ssl3
.hs
.usedStepDownKey
= PR_TRUE
;
5513 rv
= ssl3_SendServerKeyExchange(ss
);
5514 if (rv
!= SECSuccess
) {
5515 return rv
; /* err code was set. */
5518 #ifndef HACKED_EXPORT_SERVER
5519 PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED
);
5523 #ifdef NSS_ENABLE_ECC
5524 } else if ((kea_def
->kea
== kea_ecdhe_rsa
) ||
5525 (kea_def
->kea
== kea_ecdhe_ecdsa
)) {
5526 rv
= ssl3_SendServerKeyExchange(ss
);
5527 if (rv
!= SECSuccess
) {
5528 return rv
; /* err code was set. */
5530 #endif /* NSS_ENABLE_ECC */
5533 if (ss
->opt
.requestCertificate
) {
5534 rv
= ssl3_SendCertificateRequest(ss
);
5535 if (rv
!= SECSuccess
) {
5536 return rv
; /* err code is set. */
5539 rv
= ssl3_SendServerHelloDone(ss
);
5540 if (rv
!= SECSuccess
) {
5541 return rv
; /* err code is set. */
5544 ss
->ssl3
.hs
.ws
= (ss
->opt
.requestCertificate
) ? wait_client_cert
5549 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
5550 * ssl3 Client Hello message.
5551 * Caller must hold Handshake and RecvBuf locks.
5554 ssl3_HandleClientHello(sslSocket
*ss
, SSL3Opaque
*b
, PRUint32 length
)
5556 sslSessionID
* sid
= NULL
;
5561 int errCode
= SSL_ERROR_RX_MALFORMED_CLIENT_HELLO
;
5562 SSL3AlertDescription desc
= illegal_parameter
;
5563 SSL3ProtocolVersion version
;
5564 SECItem sidBytes
= {siBuffer
, NULL
, 0};
5565 SECItem suites
= {siBuffer
, NULL
, 0};
5566 SECItem comps
= {siBuffer
, NULL
, 0};
5567 PRBool haveSpecWriteLock
= PR_FALSE
;
5568 PRBool haveXmitBufLock
= PR_FALSE
;
5570 SSL_TRC(3, ("%d: SSL3[%d]: handle client_hello handshake",
5571 SSL_GETPID(), ss
->fd
));
5573 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
5574 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
5576 /* Get peer name of client */
5577 rv
= ssl_GetPeerInfo(ss
);
5578 if (rv
!= SECSuccess
) {
5579 return rv
; /* error code is set. */
5582 /* We might be starting session renegotiation in which case we should
5583 * clear previous state.
5585 PORT_Memset(&ss
->xtnData
, 0, sizeof(TLSExtensionData
));
5586 ss
->statelessResume
= PR_FALSE
;
5588 rv
= ssl3_InitState(ss
);
5589 if (rv
!= SECSuccess
) {
5590 return rv
; /* ssl3_InitState has set the error code. */
5593 if ((ss
->ssl3
.hs
.ws
!= wait_client_hello
) &&
5594 (ss
->ssl3
.hs
.ws
!= idle_handshake
)) {
5595 desc
= unexpected_message
;
5596 errCode
= SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO
;
5600 tmp
= ssl3_ConsumeHandshakeNumber(ss
, 2, &b
, &length
);
5602 goto loser
; /* malformed, alert already sent */
5603 ss
->clientHelloVersion
= version
= (SSL3ProtocolVersion
)tmp
;
5604 rv
= ssl3_NegotiateVersion(ss
, version
);
5605 if (rv
!= SECSuccess
) {
5606 desc
= (version
> SSL_LIBRARY_VERSION_3_0
) ? protocol_version
: handshake_failure
;
5607 errCode
= SSL_ERROR_NO_CYPHER_OVERLAP
;
5611 /* grab the client random data. */
5612 rv
= ssl3_ConsumeHandshake(
5613 ss
, &ss
->ssl3
.hs
.client_random
, SSL3_RANDOM_LENGTH
, &b
, &length
);
5614 if (rv
!= SECSuccess
) {
5615 goto loser
; /* malformed */
5618 /* grab the client's SID, if present. */
5619 rv
= ssl3_ConsumeHandshakeVariable(ss
, &sidBytes
, 1, &b
, &length
);
5620 if (rv
!= SECSuccess
) {
5621 goto loser
; /* malformed */
5624 /* grab the list of cipher suites. */
5625 rv
= ssl3_ConsumeHandshakeVariable(ss
, &suites
, 2, &b
, &length
);
5626 if (rv
!= SECSuccess
) {
5627 goto loser
; /* malformed */
5630 /* grab the list of compression methods. */
5631 rv
= ssl3_ConsumeHandshakeVariable(ss
, &comps
, 1, &b
, &length
);
5632 if (rv
!= SECSuccess
) {
5633 goto loser
; /* malformed */
5636 desc
= handshake_failure
;
5638 /* Handle TLS hello extensions for SSL3 & TLS. We do not know if
5639 * we are restarting a previous session until extensions have been
5640 * parsed, since we might have received a SessionTicket extension.
5641 * Note: we allow extensions even when negotiating SSL3 for the sake
5642 * of interoperability (and backwards compatibility).
5646 /* Get length of hello extensions */
5647 PRInt32 extension_length
;
5648 extension_length
= ssl3_ConsumeHandshakeNumber(ss
, 2, &b
, &length
);
5649 if (extension_length
< 0) {
5650 goto loser
; /* alert already sent */
5652 if (extension_length
!= length
) {
5653 ssl3_DecodeError(ss
); /* send alert */
5656 rv
= ssl3_HandleHelloExtensions(ss
, &b
, &length
);
5657 if (rv
!= SECSuccess
) {
5658 goto loser
; /* malformed */
5662 /* We do stateful resumes only if either of the following
5663 * conditions are satisfied: (1) the client does not support the
5664 * session ticket extension, or (2) the client support the session
5665 * ticket extension, but sent an empty ticket.
5667 if (!ssl3_ExtensionNegotiated(ss
, session_ticket_xtn
) ||
5668 ss
->xtnData
.emptySessionTicket
) {
5669 if (sidBytes
.len
> 0 && !ss
->opt
.noCache
) {
5670 SSL_TRC(7, ("%d: SSL3[%d]: server, lookup client session-id for 0x%08x%08x%08x%08x",
5671 SSL_GETPID(), ss
->fd
, ss
->sec
.ci
.peer
.pr_s6_addr32
[0],
5672 ss
->sec
.ci
.peer
.pr_s6_addr32
[1],
5673 ss
->sec
.ci
.peer
.pr_s6_addr32
[2],
5674 ss
->sec
.ci
.peer
.pr_s6_addr32
[3]));
5675 if (ssl_sid_lookup
) {
5676 sid
= (*ssl_sid_lookup
)(&ss
->sec
.ci
.peer
, sidBytes
.data
,
5677 sidBytes
.len
, ss
->dbHandle
);
5679 errCode
= SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED
;
5683 } else if (ss
->statelessResume
) {
5684 /* Fill in the client's session ID if doing a stateless resume.
5685 * (When doing stateless resumes, server echos client's SessionID.)
5687 sid
= ss
->sec
.ci
.sid
;
5688 PORT_Assert(sid
!= NULL
); /* Should have already been filled in.*/
5690 if (sidBytes
.len
> 0 && sidBytes
.len
<= SSL3_SESSIONID_BYTES
) {
5691 sid
->u
.ssl3
.sessionIDLength
= sidBytes
.len
;
5692 PORT_Memcpy(sid
->u
.ssl3
.sessionID
, sidBytes
.data
,
5694 sid
->u
.ssl3
.sessionIDLength
= sidBytes
.len
;
5696 sid
->u
.ssl3
.sessionIDLength
= 0;
5698 ss
->sec
.ci
.sid
= NULL
;
5701 /* We only send a session ticket extension if the client supports
5702 * the extension and we are unable to do either a stateful or
5705 * TODO: send a session ticket if performing a stateful
5706 * resumption. (As per RFC4507, a server may issue a session
5707 * ticket while doing a (stateless or stateful) session resume,
5708 * but OpenSSL-0.9.8g does not accept session tickets while
5711 if (ssl3_ExtensionNegotiated(ss
, session_ticket_xtn
) && sid
== NULL
) {
5712 ssl3_RegisterServerHelloExtensionSender(ss
,
5713 session_ticket_xtn
, ssl3_SendSessionTicketXtn
);
5717 /* We've found a session cache entry for this client.
5718 * Now, if we're going to require a client-auth cert,
5719 * and we don't already have this client's cert in the session cache,
5720 * and this is the first handshake on this connection (not a redo),
5721 * then drop this old cache entry and start a new session.
5723 if ((sid
->peerCert
== NULL
) && ss
->opt
.requestCertificate
&&
5724 ((ss
->opt
.requireCertificate
== SSL_REQUIRE_ALWAYS
) ||
5725 (ss
->opt
.requireCertificate
== SSL_REQUIRE_NO_ERROR
) ||
5726 ((ss
->opt
.requireCertificate
== SSL_REQUIRE_FIRST_HANDSHAKE
)
5727 && !ss
->firstHsDone
))) {
5729 SSL_AtomicIncrementLong(& ssl3stats
.hch_sid_cache_not_ok
);
5730 ss
->sec
.uncache(sid
);
5736 #ifdef NSS_ENABLE_ECC
5737 /* Disable any ECC cipher suites for which we have no cert. */
5738 ssl3_FilterECCipherSuitesByServerCerts(ss
);
5742 /* Look for a matching cipher suite. */
5743 j
= ssl3_config_match_init(ss
);
5744 if (j
<= 0) { /* no ciphers are working/supported by PK11 */
5745 errCode
= PORT_GetError(); /* error code is already set. */
5750 /* If we already have a session for this client, be sure to pick the
5751 ** same cipher suite we picked before.
5752 ** This is not a loop, despite appearances.
5755 ssl3CipherSuiteCfg
*suite
= ss
->cipherSuites
;
5756 /* Find the entry for the cipher suite used in the cached session. */
5757 for (j
= ssl_V3_SUITES_IMPLEMENTED
; j
> 0; --j
, ++suite
) {
5758 if (suite
->cipher_suite
== sid
->u
.ssl3
.cipherSuite
)
5765 /* Double check that the cached cipher suite is still enabled,
5766 * implemented, and allowed by policy. Might have been disabled.
5767 * The product policy won't change during the process lifetime.
5768 * Implemented ("isPresent") shouldn't change for servers.
5770 if (!config_match(suite
, ss
->ssl3
.policy
, PR_TRUE
))
5773 if (!suite
->enabled
)
5776 /* Double check that the cached cipher suite is in the client's list */
5777 for (i
= 0; i
< suites
.len
; i
+= 2) {
5778 if ((suites
.data
[i
] == MSB(suite
->cipher_suite
)) &&
5779 (suites
.data
[i
+ 1] == LSB(suite
->cipher_suite
))) {
5781 ss
->ssl3
.hs
.cipher_suite
= suite
->cipher_suite
;
5782 ss
->ssl3
.hs
.suite_def
=
5783 ssl_LookupCipherSuiteDef(ss
->ssl3
.hs
.cipher_suite
);
5789 /* START A NEW SESSION */
5792 /* Look for a matching cipher suite. */
5793 j
= ssl3_config_match_init(ss
);
5794 if (j
<= 0) { /* no ciphers are working/supported by PK11 */
5795 errCode
= PORT_GetError(); /* error code is already set. */
5800 /* Select a cipher suite.
5801 ** NOTE: This suite selection algorithm should be the same as the one in
5802 ** ssl3_HandleV2ClientHello().
5804 for (j
= 0; j
< ssl_V3_SUITES_IMPLEMENTED
; j
++) {
5805 ssl3CipherSuiteCfg
*suite
= &ss
->cipherSuites
[j
];
5806 if (!config_match(suite
, ss
->ssl3
.policy
, PR_TRUE
))
5808 for (i
= 0; i
< suites
.len
; i
+= 2) {
5809 if ((suites
.data
[i
] == MSB(suite
->cipher_suite
)) &&
5810 (suites
.data
[i
+ 1] == LSB(suite
->cipher_suite
))) {
5812 ss
->ssl3
.hs
.cipher_suite
= suite
->cipher_suite
;
5813 ss
->ssl3
.hs
.suite_def
=
5814 ssl_LookupCipherSuiteDef(ss
->ssl3
.hs
.cipher_suite
);
5819 errCode
= SSL_ERROR_NO_CYPHER_OVERLAP
;
5823 /* Look for a matching compression algorithm. */
5824 for (i
= 0; i
< comps
.len
; i
++) {
5825 for (j
= 0; j
< compressionMethodsCount
; j
++) {
5826 if (comps
.data
[i
] == compressions
[j
]) {
5827 ss
->ssl3
.hs
.compression
=
5828 (SSL3CompressionMethod
)compressions
[j
];
5829 goto compression_found
;
5833 errCode
= SSL_ERROR_NO_COMPRESSION_OVERLAP
;
5834 /* null compression must be supported */
5841 ss
->sec
.send
= ssl3_SendApplicationData
;
5843 /* If there are any failures while processing the old sid,
5844 * we don't consider them to be errors. Instead, We just behave
5845 * as if the client had sent us no sid to begin with, and make a new one.
5847 if (sid
!= NULL
) do {
5848 ssl3CipherSpec
*pwSpec
;
5849 SECItem wrappedMS
; /* wrapped key */
5851 if (sid
->version
!= ss
->version
||
5852 sid
->u
.ssl3
.cipherSuite
!= ss
->ssl3
.hs
.cipher_suite
) {
5853 break; /* not an error */
5856 if (ss
->sec
.ci
.sid
) {
5857 ss
->sec
.uncache(ss
->sec
.ci
.sid
);
5858 PORT_Assert(ss
->sec
.ci
.sid
!= sid
); /* should be impossible, but ... */
5859 if (ss
->sec
.ci
.sid
!= sid
) {
5860 ssl_FreeSID(ss
->sec
.ci
.sid
);
5862 ss
->sec
.ci
.sid
= NULL
;
5864 /* we need to resurrect the master secret.... */
5866 ssl_GetSpecWriteLock(ss
); haveSpecWriteLock
= PR_TRUE
;
5867 pwSpec
= ss
->ssl3
.pwSpec
;
5868 if (sid
->u
.ssl3
.keys
.msIsWrapped
) {
5869 PK11SymKey
* wrapKey
; /* wrapping key */
5870 CK_FLAGS keyFlags
= 0;
5871 if (ss
->opt
.bypassPKCS11
) {
5872 /* we cannot restart a non-bypass session in a
5878 wrapKey
= getWrappingKey(ss
, NULL
, sid
->u
.ssl3
.exchKeyType
,
5879 sid
->u
.ssl3
.masterWrapMech
,
5882 /* we have a SID cache entry, but no wrapping key for it??? */
5886 if (ss
->version
> SSL_LIBRARY_VERSION_3_0
) { /* isTLS */
5887 keyFlags
= CKF_SIGN
| CKF_VERIFY
;
5890 wrappedMS
.data
= sid
->u
.ssl3
.keys
.wrapped_master_secret
;
5891 wrappedMS
.len
= sid
->u
.ssl3
.keys
.wrapped_master_secret_len
;
5893 /* unwrap the master secret. */
5894 pwSpec
->master_secret
=
5895 PK11_UnwrapSymKeyWithFlags(wrapKey
, sid
->u
.ssl3
.masterWrapMech
,
5896 NULL
, &wrappedMS
, CKM_SSL3_MASTER_KEY_DERIVE
,
5897 CKA_DERIVE
, sizeof(SSL3MasterSecret
), keyFlags
);
5898 PK11_FreeSymKey(wrapKey
);
5899 if (pwSpec
->master_secret
== NULL
) {
5900 break; /* not an error */
5902 } else if (ss
->opt
.bypassPKCS11
) {
5903 wrappedMS
.data
= sid
->u
.ssl3
.keys
.wrapped_master_secret
;
5904 wrappedMS
.len
= sid
->u
.ssl3
.keys
.wrapped_master_secret_len
;
5905 memcpy(pwSpec
->raw_master_secret
, wrappedMS
.data
, wrappedMS
.len
);
5906 pwSpec
->msItem
.data
= pwSpec
->raw_master_secret
;
5907 pwSpec
->msItem
.len
= wrappedMS
.len
;
5909 /* We CAN restart a bypass session in a non-bypass socket. */
5910 /* need to import the raw master secret to session object */
5911 PK11SlotInfo
* slot
;
5912 wrappedMS
.data
= sid
->u
.ssl3
.keys
.wrapped_master_secret
;
5913 wrappedMS
.len
= sid
->u
.ssl3
.keys
.wrapped_master_secret_len
;
5914 slot
= PK11_GetInternalSlot();
5915 pwSpec
->master_secret
=
5916 PK11_ImportSymKey(slot
, CKM_SSL3_MASTER_KEY_DERIVE
,
5917 PK11_OriginUnwrap
, CKA_ENCRYPT
, &wrappedMS
,
5919 PK11_FreeSlot(slot
);
5920 if (pwSpec
->master_secret
== NULL
) {
5921 break; /* not an error */
5924 ss
->sec
.ci
.sid
= sid
;
5925 if (sid
->peerCert
!= NULL
) {
5926 ss
->sec
.peerCert
= CERT_DupCertificate(sid
->peerCert
);
5930 * Old SID passed all tests, so resume this old session.
5932 * XXX make sure compression still matches
5934 SSL_AtomicIncrementLong(& ssl3stats
.hch_sid_cache_hits
);
5935 if (ss
->statelessResume
)
5936 SSL_AtomicIncrementLong(& ssl3stats
.hch_sid_stateless_resumes
);
5937 ss
->ssl3
.hs
.isResuming
= PR_TRUE
;
5939 ss
->sec
.authAlgorithm
= sid
->authAlgorithm
;
5940 ss
->sec
.authKeyBits
= sid
->authKeyBits
;
5941 ss
->sec
.keaType
= sid
->keaType
;
5942 ss
->sec
.keaKeyBits
= sid
->keaKeyBits
;
5944 /* server sids don't remember the server cert we previously sent,
5945 ** but they do remember the kea type we originally used, so we
5946 ** can locate it again, provided that the current ssl socket
5947 ** has had its server certs configured the same as the previous one.
5950 CERT_DupCertificate(ss
->serverCerts
[sid
->keaType
].serverCert
);
5952 ssl_GetXmitBufLock(ss
); haveXmitBufLock
= PR_TRUE
;
5954 rv
= ssl3_SendServerHello(ss
);
5955 if (rv
!= SECSuccess
) {
5956 errCode
= PORT_GetError();
5960 if (haveSpecWriteLock
) {
5961 ssl_ReleaseSpecWriteLock(ss
);
5962 haveSpecWriteLock
= PR_FALSE
;
5965 /* NULL value for PMS signifies re-use of the old MS */
5966 rv
= ssl3_InitPendingCipherSpec(ss
, NULL
);
5967 if (rv
!= SECSuccess
) {
5968 errCode
= PORT_GetError();
5972 rv
= ssl3_SendChangeCipherSpecs(ss
);
5973 if (rv
!= SECSuccess
) {
5974 errCode
= PORT_GetError();
5977 rv
= ssl3_SendFinished(ss
, 0);
5978 ss
->ssl3
.hs
.ws
= wait_change_cipher
;
5979 if (rv
!= SECSuccess
) {
5980 errCode
= PORT_GetError();
5984 if (haveXmitBufLock
) {
5985 ssl_ReleaseXmitBufLock(ss
);
5986 haveXmitBufLock
= PR_FALSE
;
5992 if (haveSpecWriteLock
) {
5993 ssl_ReleaseSpecWriteLock(ss
);
5994 haveSpecWriteLock
= PR_FALSE
;
5997 if (sid
) { /* we had a sid, but it's no longer valid, free it */
5998 SSL_AtomicIncrementLong(& ssl3stats
.hch_sid_cache_not_ok
);
5999 ss
->sec
.uncache(sid
);
6003 SSL_AtomicIncrementLong(& ssl3stats
.hch_sid_cache_misses
);
6005 sid
= ssl3_NewSessionID(ss
, PR_TRUE
);
6007 errCode
= PORT_GetError();
6008 goto loser
; /* memory error is set. */
6010 ss
->sec
.ci
.sid
= sid
;
6012 ss
->ssl3
.hs
.isResuming
= PR_FALSE
;
6013 ssl_GetXmitBufLock(ss
);
6014 rv
= ssl3_SendServerHelloSequence(ss
);
6015 ssl_ReleaseXmitBufLock(ss
);
6016 if (rv
!= SECSuccess
) {
6017 errCode
= PORT_GetError();
6021 if (haveXmitBufLock
) {
6022 ssl_ReleaseXmitBufLock(ss
);
6023 haveXmitBufLock
= PR_FALSE
;
6029 if (haveSpecWriteLock
) {
6030 ssl_ReleaseSpecWriteLock(ss
);
6031 haveSpecWriteLock
= PR_FALSE
;
6033 (void)SSL3_SendAlert(ss
, alert_fatal
, desc
);
6036 if (haveSpecWriteLock
) {
6037 ssl_ReleaseSpecWriteLock(ss
);
6038 haveSpecWriteLock
= PR_FALSE
;
6041 if (haveXmitBufLock
) {
6042 ssl_ReleaseXmitBufLock(ss
);
6043 haveXmitBufLock
= PR_FALSE
;
6046 PORT_SetError(errCode
);
6051 * ssl3_HandleV2ClientHello is used when a V2 formatted hello comes
6052 * in asking to use the V3 handshake.
6053 * Called from ssl2_HandleClientHelloMessage() in sslcon.c
6056 ssl3_HandleV2ClientHello(sslSocket
*ss
, unsigned char *buffer
, int length
)
6058 sslSessionID
* sid
= NULL
;
6059 unsigned char * suites
;
6060 unsigned char * random
;
6061 SSL3ProtocolVersion version
;
6068 int errCode
= SSL_ERROR_RX_MALFORMED_CLIENT_HELLO
;
6069 SSL3AlertDescription desc
= handshake_failure
;
6071 SSL_TRC(3, ("%d: SSL3[%d]: handle v2 client_hello", SSL_GETPID(), ss
->fd
));
6073 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
6075 ssl_GetSSL3HandshakeLock(ss
);
6077 PORT_Memset(&ss
->xtnData
, 0, sizeof(TLSExtensionData
));
6079 rv
= ssl3_InitState(ss
);
6080 if (rv
!= SECSuccess
) {
6081 ssl_ReleaseSSL3HandshakeLock(ss
);
6082 return rv
; /* ssl3_InitState has set the error code. */
6085 if (ss
->ssl3
.hs
.ws
!= wait_client_hello
) {
6086 desc
= unexpected_message
;
6087 errCode
= SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO
;
6088 goto loser
; /* alert_loser */
6091 version
= (buffer
[1] << 8) | buffer
[2];
6092 suite_length
= (buffer
[3] << 8) | buffer
[4];
6093 sid_length
= (buffer
[5] << 8) | buffer
[6];
6094 rand_length
= (buffer
[7] << 8) | buffer
[8];
6095 ss
->clientHelloVersion
= version
;
6097 rv
= ssl3_NegotiateVersion(ss
, version
);
6098 if (rv
!= SECSuccess
) {
6099 /* send back which ever alert client will understand. */
6100 desc
= (version
> SSL_LIBRARY_VERSION_3_0
) ? protocol_version
: handshake_failure
;
6101 errCode
= SSL_ERROR_NO_CYPHER_OVERLAP
;
6105 /* if we get a non-zero SID, just ignore it. */
6107 SSL_HL_CLIENT_HELLO_HBYTES
+ suite_length
+ sid_length
+ rand_length
) {
6108 SSL_DBG(("%d: SSL3[%d]: bad v2 client hello message, len=%d should=%d",
6109 SSL_GETPID(), ss
->fd
, length
,
6110 SSL_HL_CLIENT_HELLO_HBYTES
+ suite_length
+ sid_length
+
6112 goto loser
; /* malformed */ /* alert_loser */
6115 suites
= buffer
+ SSL_HL_CLIENT_HELLO_HBYTES
;
6116 random
= suites
+ suite_length
+ sid_length
;
6118 if (rand_length
< SSL_MIN_CHALLENGE_BYTES
||
6119 rand_length
> SSL_MAX_CHALLENGE_BYTES
) {
6120 goto loser
; /* malformed */ /* alert_loser */
6123 PORT_Assert(SSL_MAX_CHALLENGE_BYTES
== SSL3_RANDOM_LENGTH
);
6125 PORT_Memset(&ss
->ssl3
.hs
.client_random
, 0, SSL3_RANDOM_LENGTH
);
6127 &ss
->ssl3
.hs
.client_random
.rand
[SSL3_RANDOM_LENGTH
- rand_length
],
6128 random
, rand_length
);
6130 PRINT_BUF(60, (ss
, "client random:", &ss
->ssl3
.hs
.client_random
.rand
[0],
6131 SSL3_RANDOM_LENGTH
));
6132 #ifdef NSS_ENABLE_ECC
6133 /* Disable any ECC cipher suites for which we have no cert. */
6134 ssl3_FilterECCipherSuitesByServerCerts(ss
);
6136 i
= ssl3_config_match_init(ss
);
6138 errCode
= PORT_GetError(); /* error code is already set. */
6142 /* Select a cipher suite.
6143 ** NOTE: This suite selection algorithm should be the same as the one in
6144 ** ssl3_HandleClientHello().
6146 for (j
= 0; j
< ssl_V3_SUITES_IMPLEMENTED
; j
++) {
6147 ssl3CipherSuiteCfg
*suite
= &ss
->cipherSuites
[j
];
6148 if (!config_match(suite
, ss
->ssl3
.policy
, PR_TRUE
))
6150 for (i
= 0; i
< suite_length
; i
+= 3) {
6151 if ((suites
[i
] == 0) &&
6152 (suites
[i
+1] == MSB(suite
->cipher_suite
)) &&
6153 (suites
[i
+2] == LSB(suite
->cipher_suite
))) {
6155 ss
->ssl3
.hs
.cipher_suite
= suite
->cipher_suite
;
6156 ss
->ssl3
.hs
.suite_def
=
6157 ssl_LookupCipherSuiteDef(ss
->ssl3
.hs
.cipher_suite
);
6162 errCode
= SSL_ERROR_NO_CYPHER_OVERLAP
;
6167 ss
->ssl3
.hs
.compression
= compression_null
;
6168 ss
->sec
.send
= ssl3_SendApplicationData
;
6170 /* we don't even search for a cache hit here. It's just a miss. */
6171 SSL_AtomicIncrementLong(& ssl3stats
.hch_sid_cache_misses
);
6172 sid
= ssl3_NewSessionID(ss
, PR_TRUE
);
6174 errCode
= PORT_GetError();
6175 goto loser
; /* memory error is set. */
6177 ss
->sec
.ci
.sid
= sid
;
6178 /* do not worry about memory leak of sid since it now belongs to ci */
6180 /* We have to update the handshake hashes before we can send stuff */
6181 rv
= ssl3_UpdateHandshakeHashes(ss
, buffer
, length
);
6182 if (rv
!= SECSuccess
) {
6183 errCode
= PORT_GetError();
6187 ssl_GetXmitBufLock(ss
);
6188 rv
= ssl3_SendServerHelloSequence(ss
);
6189 ssl_ReleaseXmitBufLock(ss
);
6190 if (rv
!= SECSuccess
) {
6191 errCode
= PORT_GetError();
6195 /* XXX_1 The call stack to here is:
6196 * ssl_Do1stHandshake -> ssl2_HandleClientHelloMessage -> here.
6197 * ssl2_HandleClientHelloMessage returns whatever we return here.
6198 * ssl_Do1stHandshake will continue looping if it gets back either
6199 * SECSuccess or SECWouldBlock.
6200 * SECSuccess is preferable here. See XXX_1 in sslgathr.c.
6202 ssl_ReleaseSSL3HandshakeLock(ss
);
6206 SSL3_SendAlert(ss
, alert_fatal
, desc
);
6208 ssl_ReleaseSSL3HandshakeLock(ss
);
6209 PORT_SetError(errCode
);
6213 /* The negotiated version number has been already placed in ss->version.
6215 ** Called from: ssl3_HandleClientHello (resuming session),
6216 ** ssl3_SendServerHelloSequence <- ssl3_HandleClientHello (new session),
6217 ** ssl3_SendServerHelloSequence <- ssl3_HandleV2ClientHello (new session)
6220 ssl3_SendServerHello(sslSocket
*ss
)
6224 PRUint32 maxBytes
= 65535;
6226 PRInt32 extensions_len
= 0;
6228 SSL_TRC(3, ("%d: SSL3[%d]: send server_hello handshake", SSL_GETPID(),
6231 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
));
6232 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
6233 PORT_Assert( MSB(ss
->version
) == MSB(SSL_LIBRARY_VERSION_3_0
));
6235 if (MSB(ss
->version
) != MSB(SSL_LIBRARY_VERSION_3_0
)) {
6236 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP
);
6240 sid
= ss
->sec
.ci
.sid
;
6242 extensions_len
= ssl3_CallHelloExtensionSenders(ss
, PR_FALSE
, maxBytes
,
6243 &ss
->xtnData
.serverSenders
[0]);
6244 if (extensions_len
> 0)
6245 extensions_len
+= 2; /* Add sizeof total extension length */
6247 length
= sizeof(SSL3ProtocolVersion
) + SSL3_RANDOM_LENGTH
+ 1 +
6248 ((sid
== NULL
) ? 0: sid
->u
.ssl3
.sessionIDLength
) +
6249 sizeof(ssl3CipherSuite
) + 1 + extensions_len
;
6250 rv
= ssl3_AppendHandshakeHeader(ss
, server_hello
, length
);
6251 if (rv
!= SECSuccess
) {
6252 return rv
; /* err set by AppendHandshake. */
6255 rv
= ssl3_AppendHandshakeNumber(ss
, ss
->version
, 2);
6256 if (rv
!= SECSuccess
) {
6257 return rv
; /* err set by AppendHandshake. */
6259 rv
= ssl3_GetNewRandom(&ss
->ssl3
.hs
.server_random
);
6260 if (rv
!= SECSuccess
) {
6261 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE
);
6264 rv
= ssl3_AppendHandshake(
6265 ss
, &ss
->ssl3
.hs
.server_random
, SSL3_RANDOM_LENGTH
);
6266 if (rv
!= SECSuccess
) {
6267 return rv
; /* err set by AppendHandshake. */
6271 rv
= ssl3_AppendHandshakeVariable(
6272 ss
, sid
->u
.ssl3
.sessionID
, sid
->u
.ssl3
.sessionIDLength
, 1);
6274 rv
= ssl3_AppendHandshakeVariable(ss
, NULL
, 0, 1);
6275 if (rv
!= SECSuccess
) {
6276 return rv
; /* err set by AppendHandshake. */
6279 rv
= ssl3_AppendHandshakeNumber(ss
, ss
->ssl3
.hs
.cipher_suite
, 2);
6280 if (rv
!= SECSuccess
) {
6281 return rv
; /* err set by AppendHandshake. */
6283 rv
= ssl3_AppendHandshakeNumber(ss
, ss
->ssl3
.hs
.compression
, 1);
6284 if (rv
!= SECSuccess
) {
6285 return rv
; /* err set by AppendHandshake. */
6287 if (extensions_len
) {
6290 extensions_len
-= 2;
6291 rv
= ssl3_AppendHandshakeNumber(ss
, extensions_len
, 2);
6292 if (rv
!= SECSuccess
)
6293 return rv
; /* err set by ssl3_SetupPendingCipherSpec */
6294 sent_len
= ssl3_CallHelloExtensionSenders(ss
, PR_TRUE
, extensions_len
,
6295 &ss
->xtnData
.serverSenders
[0]);
6296 PORT_Assert(sent_len
== extensions_len
);
6297 if (sent_len
!= extensions_len
) {
6299 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE
);
6303 rv
= ssl3_SetupPendingCipherSpec(ss
);
6304 if (rv
!= SECSuccess
) {
6305 return rv
; /* err set by ssl3_SetupPendingCipherSpec */
6313 ssl3_SendServerKeyExchange(sslSocket
*ss
)
6315 const ssl3KEADef
* kea_def
= ss
->ssl3
.hs
.kea_def
;
6316 SECStatus rv
= SECFailure
;
6319 SECItem signed_hash
= {siBuffer
, NULL
, 0};
6321 SECKEYPublicKey
* sdPub
; /* public key for step-down */
6323 SSL_TRC(3, ("%d: SSL3[%d]: send server_key_exchange handshake",
6324 SSL_GETPID(), ss
->fd
));
6326 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
));
6327 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
6329 switch (kea_def
->exchKeyType
) {
6331 /* Perform SSL Step-Down here. */
6332 sdPub
= ss
->stepDownKeyPair
->pubKey
;
6333 PORT_Assert(sdPub
!= NULL
);
6335 PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE
);
6338 rv
= ssl3_ComputeExportRSAKeyHash(sdPub
->u
.rsa
.modulus
,
6339 sdPub
->u
.rsa
.publicExponent
,
6340 &ss
->ssl3
.hs
.client_random
,
6341 &ss
->ssl3
.hs
.server_random
,
6342 &hashes
, ss
->opt
.bypassPKCS11
);
6343 if (rv
!= SECSuccess
) {
6344 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE
);
6348 isTLS
= (PRBool
)(ss
->ssl3
.pwSpec
->version
> SSL_LIBRARY_VERSION_3_0
);
6349 rv
= ssl3_SignHashes(&hashes
, ss
->serverCerts
[kt_rsa
].SERVERKEY
,
6350 &signed_hash
, isTLS
);
6351 if (rv
!= SECSuccess
) {
6352 goto loser
; /* ssl3_SignHashes has set err. */
6354 if (signed_hash
.data
== NULL
) {
6355 /* how can this happen and rv == SECSuccess ?? */
6356 PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE
);
6359 length
= 2 + sdPub
->u
.rsa
.modulus
.len
+
6360 2 + sdPub
->u
.rsa
.publicExponent
.len
+
6361 2 + signed_hash
.len
;
6363 rv
= ssl3_AppendHandshakeHeader(ss
, server_key_exchange
, length
);
6364 if (rv
!= SECSuccess
) {
6365 goto loser
; /* err set by AppendHandshake. */
6368 rv
= ssl3_AppendHandshakeVariable(ss
, sdPub
->u
.rsa
.modulus
.data
,
6369 sdPub
->u
.rsa
.modulus
.len
, 2);
6370 if (rv
!= SECSuccess
) {
6371 goto loser
; /* err set by AppendHandshake. */
6374 rv
= ssl3_AppendHandshakeVariable(
6375 ss
, sdPub
->u
.rsa
.publicExponent
.data
,
6376 sdPub
->u
.rsa
.publicExponent
.len
, 2);
6377 if (rv
!= SECSuccess
) {
6378 goto loser
; /* err set by AppendHandshake. */
6381 rv
= ssl3_AppendHandshakeVariable(ss
, signed_hash
.data
,
6382 signed_hash
.len
, 2);
6383 if (rv
!= SECSuccess
) {
6384 goto loser
; /* err set by AppendHandshake. */
6386 PORT_Free(signed_hash
.data
);
6389 #ifdef NSS_ENABLE_ECC
6391 rv
= ssl3_SendECDHServerKeyExchange(ss
);
6394 #endif /* NSS_ENABLE_ECC */
6399 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG
);
6403 if (signed_hash
.data
!= NULL
)
6404 PORT_Free(signed_hash
.data
);
6410 ssl3_SendCertificateRequest(sslSocket
*ss
)
6413 CERTDistNames
*ca_list
;
6414 const uint8
* certTypes
;
6415 SECItem
* names
= NULL
;
6421 int certTypesLength
;
6423 SSL_TRC(3, ("%d: SSL3[%d]: send certificate_request handshake",
6424 SSL_GETPID(), ss
->fd
));
6426 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
));
6427 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
6429 /* ssl3.ca_list is initialized to NULL, and never changed. */
6430 ca_list
= ss
->ssl3
.ca_list
;
6432 ca_list
= ssl3_server_ca_list
;
6435 if (ca_list
!= NULL
) {
6436 names
= ca_list
->names
;
6437 nnames
= ca_list
->nnames
;
6441 PORT_SetError(SSL_ERROR_NO_TRUSTED_SSL_CLIENT_CA
);
6445 for (i
= 0, name
= names
; i
< nnames
; i
++, name
++) {
6446 calen
+= 2 + name
->len
;
6449 certTypes
= certificate_types
;
6450 certTypesLength
= sizeof certificate_types
;
6452 length
= 1 + certTypesLength
+ 2 + calen
;
6454 rv
= ssl3_AppendHandshakeHeader(ss
, certificate_request
, length
);
6455 if (rv
!= SECSuccess
) {
6456 return rv
; /* err set by AppendHandshake. */
6458 rv
= ssl3_AppendHandshakeVariable(ss
, certTypes
, certTypesLength
, 1);
6459 if (rv
!= SECSuccess
) {
6460 return rv
; /* err set by AppendHandshake. */
6462 rv
= ssl3_AppendHandshakeNumber(ss
, calen
, 2);
6463 if (rv
!= SECSuccess
) {
6464 return rv
; /* err set by AppendHandshake. */
6466 for (i
= 0, name
= names
; i
< nnames
; i
++, name
++) {
6467 rv
= ssl3_AppendHandshakeVariable(ss
, name
->data
, name
->len
, 2);
6468 if (rv
!= SECSuccess
) {
6469 return rv
; /* err set by AppendHandshake. */
6477 ssl3_SendServerHelloDone(sslSocket
*ss
)
6481 SSL_TRC(3, ("%d: SSL3[%d]: send server_hello_done handshake",
6482 SSL_GETPID(), ss
->fd
));
6484 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
));
6485 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
6487 rv
= ssl3_AppendHandshakeHeader(ss
, server_hello_done
, 0);
6488 if (rv
!= SECSuccess
) {
6489 return rv
; /* err set by AppendHandshake. */
6491 rv
= ssl3_FlushHandshake(ss
, 0);
6492 if (rv
!= SECSuccess
) {
6493 return rv
; /* error code set by ssl3_FlushHandshake */
6498 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
6499 * ssl3 Certificate Verify message
6500 * Caller must hold Handshake and RecvBuf locks.
6503 ssl3_HandleCertificateVerify(sslSocket
*ss
, SSL3Opaque
*b
, PRUint32 length
,
6506 SECItem signed_hash
= {siBuffer
, NULL
, 0};
6508 int errCode
= SSL_ERROR_RX_MALFORMED_CERT_VERIFY
;
6509 SSL3AlertDescription desc
= handshake_failure
;
6512 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_verify handshake",
6513 SSL_GETPID(), ss
->fd
));
6514 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
6515 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
6517 if (ss
->ssl3
.hs
.ws
!= wait_cert_verify
|| ss
->sec
.peerCert
== NULL
) {
6518 desc
= unexpected_message
;
6519 errCode
= SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY
;
6523 rv
= ssl3_ConsumeHandshakeVariable(ss
, &signed_hash
, 2, &b
, &length
);
6524 if (rv
!= SECSuccess
) {
6525 goto loser
; /* malformed. */
6528 isTLS
= (PRBool
)(ss
->ssl3
.prSpec
->version
> SSL_LIBRARY_VERSION_3_0
);
6530 /* XXX verify that the key & kea match */
6531 rv
= ssl3_VerifySignedHashes(hashes
, ss
->sec
.peerCert
, &signed_hash
,
6532 isTLS
, ss
->pkcs11PinArg
);
6533 if (rv
!= SECSuccess
) {
6534 errCode
= PORT_GetError();
6535 desc
= isTLS
? decrypt_error
: handshake_failure
;
6539 signed_hash
.data
= NULL
;
6542 desc
= isTLS
? decode_error
: illegal_parameter
;
6543 goto alert_loser
; /* malformed */
6545 ss
->ssl3
.hs
.ws
= wait_change_cipher
;
6549 SSL3_SendAlert(ss
, alert_fatal
, desc
);
6551 PORT_SetError(errCode
);
6556 /* find a slot that is able to generate a PMS and wrap it with RSA.
6557 * Then generate and return the PMS.
6558 * If the serverKeySlot parameter is non-null, this function will use
6559 * that slot to do the job, otherwise it will find a slot.
6561 * Called from ssl3_DeriveConnectionKeysPKCS11() (above)
6562 * sendRSAClientKeyExchange() (above)
6563 * ssl3_HandleRSAClientKeyExchange() (below)
6564 * Caller must hold the SpecWriteLock, the SSL3HandshakeLock
6567 ssl3_GenerateRSAPMS(sslSocket
*ss
, ssl3CipherSpec
*spec
,
6568 PK11SlotInfo
* serverKeySlot
)
6570 PK11SymKey
* pms
= NULL
;
6571 PK11SlotInfo
* slot
= serverKeySlot
;
6572 void * pwArg
= ss
->pkcs11PinArg
;
6575 CK_MECHANISM_TYPE mechanism_array
[3];
6577 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
6580 SSLCipherAlgorithm calg
;
6581 /* The specReadLock would suffice here, but we cannot assert on
6582 ** read locks. Also, all the callers who call with a non-null
6583 ** slot already hold the SpecWriteLock.
6585 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSpecWriteLock(ss
));
6586 PORT_Assert(ss
->ssl3
.prSpec
== ss
->ssl3
.pwSpec
);
6588 calg
= spec
->cipher_def
->calg
;
6589 PORT_Assert(alg2Mech
[calg
].calg
== calg
);
6591 /* First get an appropriate slot. */
6592 mechanism_array
[0] = CKM_SSL3_PRE_MASTER_KEY_GEN
;
6593 mechanism_array
[1] = CKM_RSA_PKCS
;
6594 mechanism_array
[2] = alg2Mech
[calg
].cmech
;
6596 slot
= PK11_GetBestSlotMultiple(mechanism_array
, 3, pwArg
);
6598 /* can't find a slot with all three, find a slot with the minimum */
6599 slot
= PK11_GetBestSlotMultiple(mechanism_array
, 2, pwArg
);
6601 PORT_SetError(SSL_ERROR_TOKEN_SLOT_NOT_FOUND
);
6602 return pms
; /* which is NULL */
6607 /* Generate the pre-master secret ... */
6608 version
.major
= MSB(ss
->clientHelloVersion
);
6609 version
.minor
= LSB(ss
->clientHelloVersion
);
6611 param
.data
= (unsigned char *)&version
;
6612 param
.len
= sizeof version
;
6614 pms
= PK11_KeyGen(slot
, CKM_SSL3_PRE_MASTER_KEY_GEN
, ¶m
, 0, pwArg
);
6616 PK11_FreeSlot(slot
);
6618 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE
);
6623 /* Note: The Bleichenbacher attack on PKCS#1 necessitates that we NEVER
6624 * return any indication of failure of the Client Key Exchange message,
6625 * where that failure is caused by the content of the client's message.
6626 * This function must not return SECFailure for any reason that is directly
6627 * or indirectly caused by the content of the client's encrypted PMS.
6628 * We must not send an alert and also not drop the connection.
6629 * Instead, we generate a random PMS. This will cause a failure
6630 * in the processing the finished message, which is exactly where
6631 * the failure must occur.
6633 * Called from ssl3_HandleClientKeyExchange
6636 ssl3_HandleRSAClientKeyExchange(sslSocket
*ss
,
6639 SECKEYPrivateKey
*serverKey
)
6642 unsigned char * cr
= (unsigned char *)&ss
->ssl3
.hs
.client_random
;
6643 unsigned char * sr
= (unsigned char *)&ss
->ssl3
.hs
.server_random
;
6644 ssl3CipherSpec
* pwSpec
= ss
->ssl3
.pwSpec
;
6645 unsigned int outLen
= 0;
6646 PRBool isTLS
= PR_FALSE
;
6649 unsigned char rsaPmsBuf
[SSL3_RSA_PMS_LENGTH
];
6650 SECItem pmsItem
= {siBuffer
, NULL
, 0};
6652 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
6653 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
6656 enc_pms
.len
= length
;
6657 pmsItem
.data
= rsaPmsBuf
;
6658 pmsItem
.len
= sizeof rsaPmsBuf
;
6660 if (ss
->ssl3
.prSpec
->version
> SSL_LIBRARY_VERSION_3_0
) { /* isTLS */
6662 kLen
= ssl3_ConsumeHandshakeNumber(ss
, 2, &enc_pms
.data
, &enc_pms
.len
);
6664 PORT_SetError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE
);
6667 if ((unsigned)kLen
< enc_pms
.len
) {
6672 isTLS
= (PRBool
)(ss
->ssl3
.hs
.kea_def
->tls_keygen
!= 0);
6675 if (ss
->opt
.bypassPKCS11
) {
6676 /* TRIPLE BYPASS, get PMS directly from RSA decryption.
6677 * Use PK11_PrivDecryptPKCS1 to decrypt the PMS to a buffer,
6678 * then, check for version rollback attack, then
6679 * do the equivalent of ssl3_DeriveMasterSecret, placing the MS in
6680 * pwSpec->msItem. Finally call ssl3_InitPendingCipherSpec with
6681 * ss and NULL, so that it will use the MS we've already derived here.
6684 rv
= PK11_PrivDecryptPKCS1(serverKey
, rsaPmsBuf
, &outLen
,
6685 sizeof rsaPmsBuf
, enc_pms
.data
, enc_pms
.len
);
6686 if (rv
!= SECSuccess
) {
6687 /* triple bypass failed. Let's try for a double bypass. */
6689 } else if (ss
->opt
.detectRollBack
) {
6690 SSL3ProtocolVersion client_version
=
6691 (rsaPmsBuf
[0] << 8) | rsaPmsBuf
[1];
6692 if (client_version
!= ss
->clientHelloVersion
) {
6693 /* Version roll-back detected. ensure failure. */
6694 rv
= PK11_GenerateRandom(rsaPmsBuf
, sizeof rsaPmsBuf
);
6697 /* have PMS, build MS without PKCS11 */
6698 rv
= ssl3_MasterKeyDeriveBypass(pwSpec
, cr
, sr
, &pmsItem
, isTLS
,
6700 if (rv
!= SECSuccess
) {
6701 pwSpec
->msItem
.data
= pwSpec
->raw_master_secret
;
6702 pwSpec
->msItem
.len
= SSL3_MASTER_SECRET_LENGTH
;
6703 PK11_GenerateRandom(pwSpec
->msItem
.data
, pwSpec
->msItem
.len
);
6705 rv
= ssl3_InitPendingCipherSpec(ss
, NULL
);
6709 * unwrap pms out of the incoming buffer
6710 * Note: CKM_SSL3_MASTER_KEY_DERIVE is NOT the mechanism used to do
6711 * the unwrap. Rather, it is the mechanism with which the
6712 * unwrapped pms will be used.
6714 pms
= PK11_PubUnwrapSymKey(serverKey
, &enc_pms
,
6715 CKM_SSL3_MASTER_KEY_DERIVE
, CKA_DERIVE
, 0);
6717 PRINT_BUF(60, (ss
, "decrypted premaster secret:",
6718 PK11_GetKeyData(pms
)->data
,
6719 PK11_GetKeyData(pms
)->len
));
6721 /* unwrap failed. Generate a bogus PMS and carry on. */
6722 PK11SlotInfo
* slot
= PK11_GetSlotFromPrivateKey(serverKey
);
6724 ssl_GetSpecWriteLock(ss
);
6725 pms
= ssl3_GenerateRSAPMS(ss
, ss
->ssl3
.prSpec
, slot
);
6726 ssl_ReleaseSpecWriteLock(ss
);
6727 PK11_FreeSlot(slot
);
6732 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE
);
6736 /* This step will derive the MS from the PMS, among other things. */
6737 rv
= ssl3_InitPendingCipherSpec(ss
, pms
);
6738 PK11_FreeSymKey(pms
);
6741 if (rv
!= SECSuccess
) {
6743 return SECFailure
; /* error code set by ssl3_InitPendingCipherSpec */
6749 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
6750 * ssl3 ClientKeyExchange message from the remote client
6751 * Caller must hold Handshake and RecvBuf locks.
6754 ssl3_HandleClientKeyExchange(sslSocket
*ss
, SSL3Opaque
*b
, PRUint32 length
)
6756 SECKEYPrivateKey
*serverKey
= NULL
;
6758 const ssl3KEADef
* kea_def
;
6759 ssl3KeyPair
*serverKeyPair
= NULL
;
6760 #ifdef NSS_ENABLE_ECC
6761 SECKEYPublicKey
*serverPubKey
= NULL
;
6762 #endif /* NSS_ENABLE_ECC */
6764 SSL_TRC(3, ("%d: SSL3[%d]: handle client_key_exchange handshake",
6765 SSL_GETPID(), ss
->fd
));
6767 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
6768 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
6770 if (ss
->ssl3
.hs
.ws
!= wait_client_key
) {
6771 SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
6772 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH
);
6776 kea_def
= ss
->ssl3
.hs
.kea_def
;
6778 if (ss
->ssl3
.hs
.usedStepDownKey
) {
6779 PORT_Assert(kea_def
->is_limited
/* XXX OR cert is signing only */
6780 && kea_def
->exchKeyType
== kt_rsa
6781 && ss
->stepDownKeyPair
!= NULL
);
6782 if (!kea_def
->is_limited
||
6783 kea_def
->exchKeyType
!= kt_rsa
||
6784 ss
->stepDownKeyPair
== NULL
) {
6785 /* shouldn't happen, don't use step down if it does */
6788 serverKeyPair
= ss
->stepDownKeyPair
;
6789 ss
->sec
.keaKeyBits
= EXPORT_RSA_KEY_LENGTH
* BPB
;
6792 #ifdef NSS_ENABLE_ECC
6793 /* XXX Using SSLKEAType to index server certifiates
6794 * does not work for (EC)DHE ciphers. Until we have
6795 * an indexing mechanism general enough for all key
6796 * exchange algorithms, we'll need to deal with each
6799 if ((kea_def
->kea
== kea_ecdhe_rsa
) ||
6800 (kea_def
->kea
== kea_ecdhe_ecdsa
)) {
6801 if (ss
->ephemeralECDHKeyPair
!= NULL
) {
6802 serverKeyPair
= ss
->ephemeralECDHKeyPair
;
6803 if (serverKeyPair
->pubKey
) {
6804 ss
->sec
.keaKeyBits
=
6805 SECKEY_PublicKeyStrengthInBits(serverKeyPair
->pubKey
);
6811 sslServerCerts
* sc
= ss
->serverCerts
+ kea_def
->exchKeyType
;
6812 serverKeyPair
= sc
->serverKeyPair
;
6813 ss
->sec
.keaKeyBits
= sc
->serverKeyBits
;
6816 if (serverKeyPair
) {
6817 serverKey
= serverKeyPair
->privKey
;
6820 if (serverKey
== NULL
) {
6822 PORT_SetError(SSL_ERROR_NO_SERVER_KEY_FOR_ALG
);
6826 ss
->sec
.keaType
= kea_def
->exchKeyType
;
6828 switch (kea_def
->exchKeyType
) {
6830 rv
= ssl3_HandleRSAClientKeyExchange(ss
, b
, length
, serverKey
);
6831 if (rv
!= SECSuccess
) {
6833 return SECFailure
; /* error code set */
6838 #ifdef NSS_ENABLE_ECC
6840 /* XXX We really ought to be able to store multiple
6841 * EC certs (a requirement if we wish to support both
6842 * ECDH-RSA and ECDH-ECDSA key exchanges concurrently).
6843 * When we make that change, we'll need an index other
6844 * than kt_ecdh to pick the right EC certificate.
6846 if (serverKeyPair
) {
6847 serverPubKey
= serverKeyPair
->pubKey
;
6849 if (serverPubKey
== NULL
) {
6850 /* XXX Is this the right error code? */
6851 PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE
);
6854 rv
= ssl3_HandleECDHClientKeyExchange(ss
, b
, length
,
6855 serverPubKey
, serverKey
);
6856 if (rv
!= SECSuccess
) {
6857 return SECFailure
; /* error code set */
6860 #endif /* NSS_ENABLE_ECC */
6863 (void) ssl3_HandshakeFailure(ss
);
6864 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG
);
6867 ss
->ssl3
.hs
.ws
= ss
->sec
.peerCert
? wait_cert_verify
: wait_change_cipher
;
6872 /* This is TLS's equivalent of sending a no_certificate alert. */
6874 ssl3_SendEmptyCertificate(sslSocket
*ss
)
6878 rv
= ssl3_AppendHandshakeHeader(ss
, certificate
, 3);
6879 if (rv
== SECSuccess
) {
6880 rv
= ssl3_AppendHandshakeNumber(ss
, 0, 3);
6882 return rv
; /* error, if any, set by functions called above. */
6886 ssl3_HandleNewSessionTicket(sslSocket
*ss
, SSL3Opaque
*b
, PRUint32 length
)
6889 NewSessionTicket session_ticket
;
6891 SSL_TRC(3, ("%d: SSL3[%d]: handle session_ticket handshake",
6892 SSL_GETPID(), ss
->fd
));
6894 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
6895 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
6897 if (ss
->ssl3
.hs
.ws
!= wait_new_session_ticket
) {
6898 SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
6899 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET
);
6903 session_ticket
.received_timestamp
= ssl_Time();
6905 (void)SSL3_SendAlert(ss
, alert_fatal
, decode_error
);
6906 PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET
);
6909 session_ticket
.ticket_lifetime_hint
=
6910 (PRUint32
)ssl3_ConsumeHandshakeNumber(ss
, 4, &b
, &length
);
6912 rv
= ssl3_ConsumeHandshakeVariable(ss
, &session_ticket
.ticket
, 2,
6914 if (length
!= 0 || rv
!= SECSuccess
) {
6915 (void)SSL3_SendAlert(ss
, alert_fatal
, decode_error
);
6916 PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET
);
6917 return SECFailure
; /* malformed */
6920 rv
= ssl3_SetSIDSessionTicket(ss
->sec
.ci
.sid
, &session_ticket
);
6921 if (rv
!= SECSuccess
) {
6922 (void)SSL3_SendAlert(ss
, alert_fatal
, handshake_failure
);
6923 PORT_SetError(SSL_ERROR_INTERNAL_ERROR_ALERT
);
6926 ss
->ssl3
.hs
.ws
= wait_change_cipher
;
6931 static PRInt32 connNum
= 0;
6934 get_fake_cert(SECItem
*pCertItem
, int *pIndex
)
6940 const char *extension
;
6942 PRInt32 numBytes
= 0;
6947 pCertItem
->data
= 0;
6948 if ((testdir
= PR_GetEnv("NISCC_TEST")) == NULL
) {
6951 *pIndex
= (NULL
!= strstr(testdir
, "root"));
6952 extension
= (strstr(testdir
, "simple") ? "" : ".der");
6953 fileNum
= PR_AtomicIncrement(&connNum
) - 1;
6954 if ((startat
= PR_GetEnv("START_AT")) != NULL
) {
6955 fileNum
+= atoi(startat
);
6957 if ((stopat
= PR_GetEnv("STOP_AT")) != NULL
&&
6958 fileNum
>= atoi(stopat
)) {
6962 sprintf(cfn
, "%s/%08d%s", testdir
, fileNum
, extension
);
6963 cf
= PR_Open(cfn
, PR_RDONLY
, 0);
6967 prStatus
= PR_GetOpenFileInfo(cf
, &info
);
6968 if (prStatus
!= PR_SUCCESS
) {
6972 pCertItem
= SECITEM_AllocItem(NULL
, pCertItem
, info
.size
);
6974 numBytes
= PR_Read(cf
, pCertItem
->data
, info
.size
);
6977 if (numBytes
!= info
.size
) {
6978 SECITEM_FreeItem(pCertItem
, PR_FALSE
);
6979 PORT_SetError(SEC_ERROR_IO
);
6982 fprintf(stderr
, "using %s\n", cfn
);
6986 fprintf(stderr
, "failed to use %s\n", cfn
);
6993 * Used by both client and server.
6994 * Called from HandleServerHelloDone and from SendServerHelloSequence.
6997 ssl3_SendCertificate(sslSocket
*ss
)
7000 CERTCertificateList
*certChain
;
7003 SSL3KEAType certIndex
;
7009 SSL_TRC(3, ("%d: SSL3[%d]: send certificate handshake",
7010 SSL_GETPID(), ss
->fd
));
7012 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
));
7013 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
7015 if (ss
->sec
.localCert
)
7016 CERT_DestroyCertificate(ss
->sec
.localCert
);
7017 if (ss
->sec
.isServer
) {
7018 sslServerCerts
* sc
= NULL
;
7020 /* XXX SSLKEAType isn't really a good choice for
7021 * indexing certificates (it breaks when we deal
7022 * with (EC)DHE-* cipher suites. This hack ensures
7023 * the RSA cert is picked for (EC)DHE-RSA.
7024 * Revisit this when we add server side support
7025 * for ECDHE-ECDSA or client-side authentication
7026 * using EC certificates.
7028 if ((ss
->ssl3
.hs
.kea_def
->kea
== kea_ecdhe_rsa
) ||
7029 (ss
->ssl3
.hs
.kea_def
->kea
== kea_dhe_rsa
)) {
7032 certIndex
= ss
->ssl3
.hs
.kea_def
->exchKeyType
;
7034 sc
= ss
->serverCerts
+ certIndex
;
7035 certChain
= sc
->serverCertChain
;
7036 ss
->sec
.authKeyBits
= sc
->serverKeyBits
;
7037 ss
->sec
.authAlgorithm
= ss
->ssl3
.hs
.kea_def
->signKeyType
;
7038 ss
->sec
.localCert
= CERT_DupCertificate(sc
->serverCert
);
7040 certChain
= ss
->ssl3
.clientCertChain
;
7041 ss
->sec
.localCert
= CERT_DupCertificate(ss
->ssl3
.clientCertificate
);
7045 rv
= get_fake_cert(&fakeCert
, &ndex
);
7049 for (i
= 0; i
< certChain
->len
; i
++) {
7051 if (fakeCert
.len
> 0 && i
== ndex
) {
7052 len
+= fakeCert
.len
+ 3;
7054 len
+= certChain
->certs
[i
].len
+ 3;
7057 len
+= certChain
->certs
[i
].len
+ 3;
7062 rv
= ssl3_AppendHandshakeHeader(ss
, certificate
, len
+ 3);
7063 if (rv
!= SECSuccess
) {
7064 return rv
; /* err set by AppendHandshake. */
7066 rv
= ssl3_AppendHandshakeNumber(ss
, len
, 3);
7067 if (rv
!= SECSuccess
) {
7068 return rv
; /* err set by AppendHandshake. */
7071 for (i
= 0; i
< certChain
->len
; i
++) {
7073 if (fakeCert
.len
> 0 && i
== ndex
) {
7074 rv
= ssl3_AppendHandshakeVariable(ss
, fakeCert
.data
,
7076 SECITEM_FreeItem(&fakeCert
, PR_FALSE
);
7078 rv
= ssl3_AppendHandshakeVariable(ss
, certChain
->certs
[i
].data
,
7079 certChain
->certs
[i
].len
, 3);
7082 rv
= ssl3_AppendHandshakeVariable(ss
, certChain
->certs
[i
].data
,
7083 certChain
->certs
[i
].len
, 3);
7085 if (rv
!= SECSuccess
) {
7086 return rv
; /* err set by AppendHandshake. */
7094 /* This is used to delete the CA certificates in the peer certificate chain
7095 * from the cert database after they've been validated.
7098 ssl3_CleanupPeerCerts(sslSocket
*ss
)
7100 PRArenaPool
* arena
= ss
->ssl3
.peerCertArena
;
7101 ssl3CertNode
*certs
= (ssl3CertNode
*)ss
->ssl3
.peerCertChain
;
7103 for (; certs
; certs
= certs
->next
) {
7104 CERT_DestroyCertificate(certs
->cert
);
7106 if (arena
) PORT_FreeArena(arena
, PR_FALSE
);
7107 ss
->ssl3
.peerCertArena
= NULL
;
7108 ss
->ssl3
.peerCertChain
= NULL
;
7111 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
7112 * ssl3 Certificate message.
7113 * Caller must hold Handshake and RecvBuf locks.
7116 ssl3_HandleCertificate(sslSocket
*ss
, SSL3Opaque
*b
, PRUint32 length
)
7119 ssl3CertNode
* certs
= NULL
;
7120 PRArenaPool
* arena
= NULL
;
7121 CERTCertificate
*cert
;
7122 PRInt32 remaining
= 0;
7125 PRBool isServer
= (PRBool
)(!!ss
->sec
.isServer
);
7126 PRBool trusted
= PR_FALSE
;
7128 SSL3AlertDescription desc
= bad_certificate
;
7129 int errCode
= SSL_ERROR_RX_MALFORMED_CERTIFICATE
;
7132 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate handshake",
7133 SSL_GETPID(), ss
->fd
));
7134 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
7135 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
7137 if ((ss
->ssl3
.hs
.ws
!= wait_server_cert
) &&
7138 (ss
->ssl3
.hs
.ws
!= wait_client_cert
)) {
7139 desc
= unexpected_message
;
7140 errCode
= SSL_ERROR_RX_UNEXPECTED_CERTIFICATE
;
7144 if (ss
->sec
.peerCert
!= NULL
) {
7145 if (ss
->sec
.peerKey
) {
7146 SECKEY_DestroyPublicKey(ss
->sec
.peerKey
);
7147 ss
->sec
.peerKey
= NULL
;
7149 CERT_DestroyCertificate(ss
->sec
.peerCert
);
7150 ss
->sec
.peerCert
= NULL
;
7153 ssl3_CleanupPeerCerts(ss
);
7154 isTLS
= (PRBool
)(ss
->ssl3
.prSpec
->version
> SSL_LIBRARY_VERSION_3_0
);
7156 /* It is reported that some TLS client sends a Certificate message
7157 ** with a zero-length message body. We'll treat that case like a
7158 ** normal no_certificates message to maximize interoperability.
7161 remaining
= ssl3_ConsumeHandshakeNumber(ss
, 3, &b
, &length
);
7163 goto loser
; /* fatal alert already sent by ConsumeHandshake. */
7164 if ((PRUint32
)remaining
> length
)
7169 if (!(isTLS
&& isServer
))
7171 /* This is TLS's version of a no_certificate alert. */
7172 /* I'm a server. I've requested a client cert. He hasn't got one. */
7173 rv
= ssl3_HandleNoCertificate(ss
);
7174 if (rv
!= SECSuccess
) {
7175 errCode
= PORT_GetError();
7181 ss
->ssl3
.peerCertArena
= arena
= PORT_NewArena(DER_DEFAULT_CHUNKSIZE
);
7182 if ( arena
== NULL
) {
7183 goto loser
; /* don't send alerts on memory errors */
7186 /* First get the peer cert. */
7191 size
= ssl3_ConsumeHandshakeNumber(ss
, 3, &b
, &length
);
7193 goto loser
; /* fatal alert already sent by ConsumeHandshake. */
7195 if (remaining
< size
)
7199 certItem
.len
= size
;
7204 ss
->sec
.peerCert
= CERT_NewTempCertificate(ss
->dbHandle
, &certItem
, NULL
,
7206 if (ss
->sec
.peerCert
== NULL
) {
7207 /* We should report an alert if the cert was bad, but not if the
7208 * problem was just some local problem, like memory error.
7213 /* Now get all of the CA certs. */
7214 while (remaining
> 0) {
7219 size
= ssl3_ConsumeHandshakeNumber(ss
, 3, &b
, &length
);
7221 goto loser
; /* fatal alert already sent by ConsumeHandshake. */
7223 if (remaining
< size
)
7227 certItem
.len
= size
;
7232 c
= PORT_ArenaNew(arena
, ssl3CertNode
);
7234 goto loser
; /* don't send alerts on memory errors */
7237 c
->cert
= CERT_NewTempCertificate(ss
->dbHandle
, &certItem
, NULL
,
7239 if (c
->cert
== NULL
) {
7253 SECKEY_UpdateCertPQG(ss
->sec
.peerCert
);
7256 * Ask caller-supplied callback function to validate cert chain.
7258 rv
= (SECStatus
)(*ss
->authCertificate
)(ss
->authCertificateArg
, ss
->fd
,
7261 errCode
= PORT_GetError();
7262 if (!ss
->handleBadCert
) {
7265 rv
= (SECStatus
)(*ss
->handleBadCert
)(ss
->badCertArg
, ss
->fd
);
7267 if ( rv
== SECWouldBlock
) {
7268 /* someone will handle this connection asynchronously*/
7269 SSL_DBG(("%d: SSL3[%d]: go to async cert handler",
7270 SSL_GETPID(), ss
->fd
));
7271 ss
->ssl3
.peerCertChain
= certs
;
7273 ssl_SetAlwaysBlock(ss
);
7282 /* start SSL Step Up, if appropriate */
7283 cert
= ss
->sec
.peerCert
;
7285 ssl3_global_policy_some_restricted
&&
7286 ss
->ssl3
.policy
== SSL_ALLOWED
&&
7287 anyRestrictedEnabled(ss
) &&
7288 SECSuccess
== CERT_VerifyCertNow(cert
->dbhandle
, cert
,
7289 PR_FALSE
, /* checkSig */
7290 certUsageSSLServerWithStepUp
,
7291 /*XXX*/ ss
->authCertificateArg
) ) {
7292 ss
->ssl3
.policy
= SSL_RESTRICTED
;
7293 ss
->ssl3
.hs
.rehandshake
= PR_TRUE
;
7296 ss
->sec
.ci
.sid
->peerCert
= CERT_DupCertificate(ss
->sec
.peerCert
);
7298 if (!ss
->sec
.isServer
) {
7299 /* set the server authentication and key exchange types and sizes
7300 ** from the value in the cert. If the key exchange key is different,
7301 ** it will get fixed when we handle the server key exchange message.
7303 SECKEYPublicKey
* pubKey
= CERT_ExtractPublicKey(cert
);
7304 ss
->sec
.authAlgorithm
= ss
->ssl3
.hs
.kea_def
->signKeyType
;
7305 ss
->sec
.keaType
= ss
->ssl3
.hs
.kea_def
->exchKeyType
;
7307 ss
->sec
.keaKeyBits
= ss
->sec
.authKeyBits
=
7308 SECKEY_PublicKeyStrengthInBits(pubKey
);
7309 #ifdef NSS_ENABLE_ECC
7310 if (ss
->sec
.keaType
== kt_ecdh
) {
7311 /* Get authKeyBits from signing key.
7312 * XXX The code below uses a quick approximation of
7313 * key size based on cert->signatureWrap.signature.data
7314 * (which contains the DER encoded signature). The field
7315 * cert->signatureWrap.signature.len contains the
7316 * length of the encoded signature in bits.
7318 if (ss
->ssl3
.hs
.kea_def
->kea
== kea_ecdh_ecdsa
) {
7319 ss
->sec
.authKeyBits
=
7320 cert
->signatureWrap
.signature
.data
[3]*8;
7321 if (cert
->signatureWrap
.signature
.data
[4] == 0x00)
7322 ss
->sec
.authKeyBits
-= 8;
7324 * XXX: if cert is not signed by ecdsa we should
7325 * destroy pubKey and goto bad_cert
7327 } else if (ss
->ssl3
.hs
.kea_def
->kea
== kea_ecdh_rsa
) {
7328 ss
->sec
.authKeyBits
= cert
->signatureWrap
.signature
.len
;
7330 * XXX: if cert is not signed by rsa we should
7331 * destroy pubKey and goto bad_cert
7335 #endif /* NSS_ENABLE_ECC */
7336 SECKEY_DestroyPublicKey(pubKey
);
7341 ss
->ssl3
.peerCertChain
= certs
; certs
= NULL
; arena
= NULL
;
7344 if (ss
->sec
.isServer
) {
7345 ss
->ssl3
.hs
.ws
= wait_client_key
;
7347 ss
->ssl3
.hs
.ws
= wait_cert_request
; /* disallow server_key_exchange */
7348 if (ss
->ssl3
.hs
.kea_def
->is_limited
||
7349 /* XXX OR server cert is signing only. */
7350 #ifdef NSS_ENABLE_ECC
7351 ss
->ssl3
.hs
.kea_def
->kea
== kea_ecdhe_ecdsa
||
7352 ss
->ssl3
.hs
.kea_def
->kea
== kea_ecdhe_rsa
||
7353 #endif /* NSS_ENABLE_ECC */
7354 ss
->ssl3
.hs
.kea_def
->exchKeyType
== kt_dh
) {
7355 ss
->ssl3
.hs
.ws
= wait_server_key
; /* allow server_key_exchange */
7359 /* rv must normally be equal to SECSuccess here. If we called
7360 * handleBadCert, it can also be SECWouldBlock.
7365 errCode
= PORT_GetError();
7367 case PR_OUT_OF_MEMORY_ERROR
:
7368 case SEC_ERROR_BAD_DATABASE
:
7369 case SEC_ERROR_NO_MEMORY
:
7371 desc
= internal_error
;
7376 /* fall through to bad_cert. */
7378 bad_cert
: /* caller has set errCode. */
7380 case SEC_ERROR_LIBRARY_FAILURE
: desc
= unsupported_certificate
; break;
7381 case SEC_ERROR_EXPIRED_CERTIFICATE
: desc
= certificate_expired
; break;
7382 case SEC_ERROR_REVOKED_CERTIFICATE
: desc
= certificate_revoked
; break;
7383 case SEC_ERROR_INADEQUATE_KEY_USAGE
:
7384 case SEC_ERROR_INADEQUATE_CERT_TYPE
:
7385 desc
= certificate_unknown
; break;
7386 case SEC_ERROR_UNTRUSTED_CERT
:
7387 desc
= isTLS
? access_denied
: certificate_unknown
; break;
7388 case SEC_ERROR_UNKNOWN_ISSUER
:
7389 case SEC_ERROR_UNTRUSTED_ISSUER
:
7390 desc
= isTLS
? unknown_ca
: certificate_unknown
; break;
7391 case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE
:
7392 desc
= isTLS
? unknown_ca
: certificate_expired
; break;
7394 case SEC_ERROR_CERT_NOT_IN_NAME_SPACE
:
7395 case SEC_ERROR_PATH_LEN_CONSTRAINT_INVALID
:
7396 case SEC_ERROR_CA_CERT_INVALID
:
7397 case SEC_ERROR_BAD_SIGNATURE
:
7398 default: desc
= bad_certificate
; break;
7400 SSL_DBG(("%d: SSL3[%d]: peer certificate is no good: error=%d",
7401 SSL_GETPID(), ss
->fd
, errCode
));
7406 desc
= isTLS
? decode_error
: bad_certificate
;
7409 (void)SSL3_SendAlert(ss
, alert_fatal
, desc
);
7412 ss
->ssl3
.peerCertChain
= certs
; certs
= NULL
; arena
= NULL
;
7413 ssl3_CleanupPeerCerts(ss
);
7415 if (ss
->sec
.peerCert
!= NULL
) {
7416 CERT_DestroyCertificate(ss
->sec
.peerCert
);
7417 ss
->sec
.peerCert
= NULL
;
7419 (void)ssl_MapLowLevelError(errCode
);
7424 /* restart an SSL connection that we stopped to run certificate dialogs
7425 ** XXX Need to document here how an application marks a cert to show that
7426 ** the application has accepted it (overridden CERT_VerifyCert).
7428 * XXX This code only works on the initial handshake on a connection, XXX
7429 * It does not work on a subsequent handshake (redo).
7433 * Caller holds 1stHandshakeLock.
7436 ssl3_RestartHandshakeAfterServerCert(sslSocket
*ss
)
7438 CERTCertificate
* cert
;
7439 int rv
= SECSuccess
;
7441 if (MSB(ss
->version
) != MSB(SSL_LIBRARY_VERSION_3_0
)) {
7445 if (!ss
->ssl3
.initialized
) {
7450 cert
= ss
->sec
.peerCert
;
7452 /* Permit step up if user decided to accept the cert */
7453 if (!ss
->sec
.isServer
&&
7454 ssl3_global_policy_some_restricted
&&
7455 ss
->ssl3
.policy
== SSL_ALLOWED
&&
7456 anyRestrictedEnabled(ss
) &&
7457 (SECSuccess
== CERT_VerifyCertNow(cert
->dbhandle
, cert
,
7458 PR_FALSE
, /* checksig */
7459 certUsageSSLServerWithStepUp
,
7460 /*XXX*/ ss
->authCertificateArg
) )) {
7461 ss
->ssl3
.policy
= SSL_RESTRICTED
;
7462 ss
->ssl3
.hs
.rehandshake
= PR_TRUE
;
7465 if (ss
->handshake
!= NULL
) {
7466 ss
->handshake
= ssl_GatherRecord1stHandshake
;
7467 ss
->sec
.ci
.sid
->peerCert
= CERT_DupCertificate(ss
->sec
.peerCert
);
7469 ssl_GetRecvBufLock(ss
);
7470 if (ss
->ssl3
.hs
.msgState
.buf
!= NULL
) {
7471 rv
= ssl3_HandleRecord(ss
, NULL
, &ss
->gs
.buf
);
7473 ssl_ReleaseRecvBufLock(ss
);
7480 ssl3_ComputeTLSFinished(ssl3CipherSpec
*spec
,
7482 const SSL3Finished
* hashes
,
7483 TLSFinished
* tlsFinished
)
7489 label
= isServer
? "server finished" : "client finished";
7492 if (spec
->master_secret
&& !spec
->bypassCiphers
) {
7493 SECItem param
= {siBuffer
, NULL
, 0};
7494 PK11Context
*prf_context
=
7495 PK11_CreateContextBySymKey(CKM_TLS_PRF_GENERAL
, CKA_SIGN
,
7496 spec
->master_secret
, ¶m
);
7500 rv
= PK11_DigestBegin(prf_context
);
7501 rv
|= PK11_DigestOp(prf_context
, (const unsigned char *) label
, len
);
7502 rv
|= PK11_DigestOp(prf_context
, hashes
->md5
, sizeof *hashes
);
7503 rv
|= PK11_DigestFinal(prf_context
, tlsFinished
->verify_data
,
7504 &len
, sizeof tlsFinished
->verify_data
);
7505 PORT_Assert(rv
!= SECSuccess
|| len
== sizeof *tlsFinished
);
7507 PK11_DestroyContext(prf_context
, PR_TRUE
);
7510 SECItem inData
= { siBuffer
, };
7511 SECItem outData
= { siBuffer
, };
7512 PRBool isFIPS
= PR_FALSE
;
7514 inData
.data
= (unsigned char *)hashes
->md5
;
7515 inData
.len
= sizeof hashes
[0];
7516 outData
.data
= tlsFinished
->verify_data
;
7517 outData
.len
= sizeof tlsFinished
->verify_data
;
7518 rv
= TLS_PRF(&spec
->msItem
, label
, &inData
, &outData
, isFIPS
);
7519 PORT_Assert(rv
!= SECSuccess
|| \
7520 outData
.len
== sizeof tlsFinished
->verify_data
);
7525 /* called from ssl3_HandleServerHelloDone
7526 * ssl3_HandleClientHello
7527 * ssl3_HandleFinished
7530 ssl3_SendFinished(sslSocket
*ss
, PRInt32 flags
)
7532 ssl3CipherSpec
*cwSpec
;
7534 PRBool isServer
= ss
->sec
.isServer
;
7536 SSL3Sender sender
= isServer
? sender_server
: sender_client
;
7537 SSL3Finished hashes
;
7538 TLSFinished tlsFinished
;
7540 SSL_TRC(3, ("%d: SSL3[%d]: send finished handshake", SSL_GETPID(), ss
->fd
));
7542 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveXmitBufLock(ss
));
7543 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
7545 ssl_GetSpecReadLock(ss
);
7546 cwSpec
= ss
->ssl3
.cwSpec
;
7547 isTLS
= (PRBool
)(cwSpec
->version
> SSL_LIBRARY_VERSION_3_0
);
7548 rv
= ssl3_ComputeHandshakeHashes(ss
, cwSpec
, &hashes
, sender
);
7549 if (isTLS
&& rv
== SECSuccess
) {
7550 rv
= ssl3_ComputeTLSFinished(cwSpec
, isServer
, &hashes
, &tlsFinished
);
7552 ssl_ReleaseSpecReadLock(ss
);
7553 if (rv
!= SECSuccess
) {
7554 goto fail
; /* err code was set by ssl3_ComputeHandshakeHashes */
7558 rv
= ssl3_AppendHandshakeHeader(ss
, finished
, sizeof tlsFinished
);
7559 if (rv
!= SECSuccess
)
7560 goto fail
; /* err set by AppendHandshake. */
7561 rv
= ssl3_AppendHandshake(ss
, &tlsFinished
, sizeof tlsFinished
);
7562 if (rv
!= SECSuccess
)
7563 goto fail
; /* err set by AppendHandshake. */
7565 rv
= ssl3_AppendHandshakeHeader(ss
, finished
, sizeof hashes
);
7566 if (rv
!= SECSuccess
)
7567 goto fail
; /* err set by AppendHandshake. */
7568 rv
= ssl3_AppendHandshake(ss
, &hashes
, sizeof hashes
);
7569 if (rv
!= SECSuccess
)
7570 goto fail
; /* err set by AppendHandshake. */
7572 rv
= ssl3_FlushHandshake(ss
, flags
);
7573 if (rv
!= SECSuccess
) {
7574 goto fail
; /* error code set by ssl3_FlushHandshake */
7582 /* wrap the master secret, and put it into the SID.
7583 * Caller holds the Spec read lock.
7586 ssl3_CacheWrappedMasterSecret(sslSocket
*ss
, sslSessionID
*sid
,
7587 ssl3CipherSpec
*spec
, SSL3KEAType effectiveExchKeyType
)
7589 PK11SymKey
* wrappingKey
= NULL
;
7590 PK11SlotInfo
* symKeySlot
;
7591 void * pwArg
= ss
->pkcs11PinArg
;
7592 SECStatus rv
= SECFailure
;
7593 PRBool isServer
= ss
->sec
.isServer
;
7594 CK_MECHANISM_TYPE mechanism
= CKM_INVALID_MECHANISM
;
7595 symKeySlot
= PK11_GetSlotFromKey(spec
->master_secret
);
7600 /* these next few functions are mere accessors and don't fail. */
7601 sid
->u
.ssl3
.masterWrapIndex
= wrapKeyIndex
=
7602 PK11_GetCurrentWrapIndex(symKeySlot
);
7603 PORT_Assert(wrapKeyIndex
== 0); /* array has only one entry! */
7605 sid
->u
.ssl3
.masterWrapSeries
= incarnation
=
7606 PK11_GetSlotSeries(symKeySlot
);
7607 sid
->u
.ssl3
.masterSlotID
= PK11_GetSlotID(symKeySlot
);
7608 sid
->u
.ssl3
.masterModuleID
= PK11_GetModuleID(symKeySlot
);
7609 sid
->u
.ssl3
.masterValid
= PR_TRUE
;
7610 /* Get the default wrapping key, for wrapping the master secret before
7611 * placing it in the SID cache entry. */
7612 wrappingKey
= PK11_GetWrapKey(symKeySlot
, wrapKeyIndex
,
7613 CKM_INVALID_MECHANISM
, incarnation
,
7616 mechanism
= PK11_GetMechanism(wrappingKey
); /* can't fail. */
7619 /* if the wrappingKey doesn't exist, attempt to create it.
7620 * Note: we intentionally ignore errors here. If we cannot
7621 * generate a wrapping key, it is not fatal to this SSL connection,
7622 * but we will not be able to restart this session.
7624 mechanism
= PK11_GetBestWrapMechanism(symKeySlot
);
7625 keyLength
= PK11_GetBestKeyLength(symKeySlot
, mechanism
);
7626 /* Zero length means fixed key length algorithm, or error.
7629 wrappingKey
= PK11_KeyGen(symKeySlot
, mechanism
, NULL
,
7632 PK11_SetWrapKey(symKeySlot
, wrapKeyIndex
, wrappingKey
);
7636 /* server socket using session cache. */
7637 mechanism
= PK11_GetBestWrapMechanism(symKeySlot
);
7638 if (mechanism
!= CKM_INVALID_MECHANISM
) {
7640 getWrappingKey(ss
, symKeySlot
, effectiveExchKeyType
,
7643 mechanism
= PK11_GetMechanism(wrappingKey
); /* can't fail. */
7648 sid
->u
.ssl3
.masterWrapMech
= mechanism
;
7649 PK11_FreeSlot(symKeySlot
);
7654 wmsItem
.data
= sid
->u
.ssl3
.keys
.wrapped_master_secret
;
7655 wmsItem
.len
= sizeof sid
->u
.ssl3
.keys
.wrapped_master_secret
;
7656 rv
= PK11_WrapSymKey(mechanism
, NULL
, wrappingKey
,
7657 spec
->master_secret
, &wmsItem
);
7658 /* rv is examined below. */
7659 sid
->u
.ssl3
.keys
.wrapped_master_secret_len
= wmsItem
.len
;
7660 PK11_FreeSymKey(wrappingKey
);
7665 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
7666 * ssl3 Finished message from the peer.
7667 * Caller must hold Handshake and RecvBuf locks.
7670 ssl3_HandleFinished(sslSocket
*ss
, SSL3Opaque
*b
, PRUint32 length
,
7671 const SSL3Hashes
*hashes
)
7673 sslSessionID
* sid
= ss
->sec
.ci
.sid
;
7674 SECStatus rv
= SECSuccess
;
7675 PRBool isServer
= ss
->sec
.isServer
;
7678 SSL3KEAType effectiveExchKeyType
;
7680 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
7681 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
7683 SSL_TRC(3, ("%d: SSL3[%d]: handle finished handshake",
7684 SSL_GETPID(), ss
->fd
));
7686 if (ss
->ssl3
.hs
.ws
!= wait_finished
) {
7687 SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
7688 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_FINISHED
);
7692 isTLS
= (PRBool
)(ss
->ssl3
.crSpec
->version
> SSL_LIBRARY_VERSION_3_0
);
7694 TLSFinished tlsFinished
;
7696 if (length
!= sizeof tlsFinished
) {
7697 (void)SSL3_SendAlert(ss
, alert_fatal
, decode_error
);
7698 PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED
);
7701 rv
= ssl3_ComputeTLSFinished(ss
->ssl3
.crSpec
, !isServer
,
7702 hashes
, &tlsFinished
);
7703 if (rv
!= SECSuccess
||
7704 0 != PORT_Memcmp(&tlsFinished
, b
, length
)) {
7705 (void)SSL3_SendAlert(ss
, alert_fatal
, decrypt_error
);
7706 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE
);
7710 if (length
!= sizeof(SSL3Hashes
)) {
7711 (void)ssl3_IllegalParameter(ss
);
7712 PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED
);
7716 if (0 != PORT_Memcmp(hashes
, b
, length
)) {
7717 (void)ssl3_HandshakeFailure(ss
);
7718 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE
);
7723 doStepUp
= (PRBool
)(!isServer
&& ss
->ssl3
.hs
.rehandshake
);
7725 ssl_GetXmitBufLock(ss
); /*************************************/
7727 if ((isServer
&& !ss
->ssl3
.hs
.isResuming
) ||
7728 (!isServer
&& ss
->ssl3
.hs
.isResuming
)) {
7731 /* Send a NewSessionTicket message if the client sent us
7732 * either an empty session ticket, or one that did not verify.
7733 * (Note that if either of these conditions was met, then the
7734 * server has sent a SessionTicket extension in the
7735 * ServerHello message.)
7737 if (isServer
&& !ss
->ssl3
.hs
.isResuming
&&
7738 ssl3_ExtensionNegotiated(ss
, session_ticket_xtn
)) {
7739 rv
= ssl3_SendNewSessionTicket(ss
);
7740 if (rv
!= SECSuccess
) {
7745 rv
= ssl3_SendChangeCipherSpecs(ss
);
7746 if (rv
!= SECSuccess
) {
7747 goto xmit_loser
; /* err is set. */
7749 /* If this thread is in SSL_SecureSend (trying to write some data)
7750 ** or if it is going to step up,
7751 ** then set the ssl_SEND_FLAG_FORCE_INTO_BUFFER flag, so that the
7752 ** last two handshake messages (change cipher spec and finished)
7753 ** will be sent in the same send/write call as the application data.
7755 if (doStepUp
|| ss
->writerThread
== PR_GetCurrentThread()) {
7756 flags
= ssl_SEND_FLAG_FORCE_INTO_BUFFER
;
7758 rv
= ssl3_SendFinished(ss
, flags
);
7759 if (rv
!= SECSuccess
) {
7760 goto xmit_loser
; /* err is set. */
7764 /* Optimization: don't cache this connection if we're going to step up. */
7767 ss
->sec
.ci
.sid
= sid
= NULL
;
7768 ss
->ssl3
.hs
.rehandshake
= PR_FALSE
;
7769 rv
= ssl3_SendClientHello(ss
);
7771 ssl_ReleaseXmitBufLock(ss
);
7772 return rv
; /* err code is set if appropriate. */
7775 ssl_ReleaseXmitBufLock(ss
); /*************************************/
7777 /* The first handshake is now completed. */
7778 ss
->handshake
= NULL
;
7779 ss
->firstHsDone
= PR_TRUE
;
7780 ss
->gs
.writeOffset
= 0;
7781 ss
->gs
.readOffset
= 0;
7783 if (ss
->ssl3
.hs
.kea_def
->kea
== kea_ecdhe_rsa
) {
7784 effectiveExchKeyType
= kt_rsa
;
7786 effectiveExchKeyType
= ss
->ssl3
.hs
.kea_def
->exchKeyType
;
7789 if (sid
->cached
== never_cached
&& !ss
->opt
.noCache
&& ss
->sec
.cache
) {
7790 /* fill in the sid */
7791 sid
->u
.ssl3
.cipherSuite
= ss
->ssl3
.hs
.cipher_suite
;
7792 sid
->u
.ssl3
.compression
= ss
->ssl3
.hs
.compression
;
7793 sid
->u
.ssl3
.policy
= ss
->ssl3
.policy
;
7794 #ifdef NSS_ENABLE_ECC
7795 sid
->u
.ssl3
.negotiatedECCurves
= ss
->ssl3
.hs
.negotiatedECCurves
;
7797 sid
->u
.ssl3
.exchKeyType
= effectiveExchKeyType
;
7798 sid
->version
= ss
->version
;
7799 sid
->authAlgorithm
= ss
->sec
.authAlgorithm
;
7800 sid
->authKeyBits
= ss
->sec
.authKeyBits
;
7801 sid
->keaType
= ss
->sec
.keaType
;
7802 sid
->keaKeyBits
= ss
->sec
.keaKeyBits
;
7803 sid
->lastAccessTime
= sid
->creationTime
= ssl_Time();
7804 sid
->expirationTime
= sid
->creationTime
+ ssl3_sid_timeout
;
7805 sid
->localCert
= CERT_DupCertificate(ss
->sec
.localCert
);
7807 ssl_GetSpecReadLock(ss
); /*************************************/
7809 /* Copy the master secret (wrapped or unwrapped) into the sid */
7810 if (ss
->ssl3
.crSpec
->msItem
.len
&& ss
->ssl3
.crSpec
->msItem
.data
) {
7811 sid
->u
.ssl3
.keys
.wrapped_master_secret_len
=
7812 ss
->ssl3
.crSpec
->msItem
.len
;
7813 memcpy(sid
->u
.ssl3
.keys
.wrapped_master_secret
,
7814 ss
->ssl3
.crSpec
->msItem
.data
, ss
->ssl3
.crSpec
->msItem
.len
);
7815 sid
->u
.ssl3
.masterValid
= PR_TRUE
;
7816 sid
->u
.ssl3
.keys
.msIsWrapped
= PR_FALSE
;
7819 rv
= ssl3_CacheWrappedMasterSecret(ss
, ss
->sec
.ci
.sid
,
7821 effectiveExchKeyType
);
7822 sid
->u
.ssl3
.keys
.msIsWrapped
= PR_TRUE
;
7824 ssl_ReleaseSpecReadLock(ss
); /*************************************/
7826 /* If the wrap failed, we don't cache the sid.
7827 * The connection continues normally however.
7829 if (rv
== SECSuccess
) {
7830 (*ss
->sec
.cache
)(sid
);
7833 ss
->ssl3
.hs
.ws
= idle_handshake
;
7835 /* Do the handshake callback for sslv3 here. */
7836 if (ss
->handshakeCallback
!= NULL
) {
7837 (ss
->handshakeCallback
)(ss
->fd
, ss
->handshakeCallbackData
);
7843 /* Called from ssl3_HandleHandshake() when it has gathered a complete ssl3
7845 * Caller must hold Handshake and RecvBuf locks.
7848 ssl3_HandleHandshakeMessage(sslSocket
*ss
, SSL3Opaque
*b
, PRUint32 length
)
7850 SECStatus rv
= SECSuccess
;
7851 SSL3HandshakeType type
= ss
->ssl3
.hs
.msg_type
;
7852 SSL3Hashes hashes
; /* computed hashes are put here. */
7855 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
7856 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
7858 * We have to compute the hashes before we update them with the
7861 ssl_GetSpecReadLock(ss
); /************************************/
7862 if((type
== finished
) || (type
== certificate_verify
)) {
7863 SSL3Sender sender
= (SSL3Sender
)0;
7864 ssl3CipherSpec
*rSpec
= ss
->ssl3
.prSpec
;
7866 if (type
== finished
) {
7867 sender
= ss
->sec
.isServer
? sender_client
: sender_server
;
7868 rSpec
= ss
->ssl3
.crSpec
;
7870 rv
= ssl3_ComputeHandshakeHashes(ss
, rSpec
, &hashes
, sender
);
7872 ssl_ReleaseSpecReadLock(ss
); /************************************/
7873 if (rv
!= SECSuccess
) {
7874 return rv
; /* error code was set by ssl3_ComputeHandshakeHashes*/
7876 SSL_TRC(30,("%d: SSL3[%d]: handle handshake message: %s", SSL_GETPID(),
7877 ss
->fd
, ssl3_DecodeHandshakeType(ss
->ssl3
.hs
.msg_type
)));
7878 PRINT_BUF(60, (ss
, "MD5 handshake hash:",
7879 (unsigned char*)ss
->ssl3
.hs
.md5_cx
, MD5_LENGTH
));
7880 PRINT_BUF(95, (ss
, "SHA handshake hash:",
7881 (unsigned char*)ss
->ssl3
.hs
.sha_cx
, SHA1_LENGTH
));
7883 hdr
[0] = (PRUint8
)ss
->ssl3
.hs
.msg_type
;
7884 hdr
[1] = (PRUint8
)(length
>> 16);
7885 hdr
[2] = (PRUint8
)(length
>> 8);
7886 hdr
[3] = (PRUint8
)(length
);
7888 /* Start new handshake hashes when we start a new handshake */
7889 if (ss
->ssl3
.hs
.msg_type
== client_hello
) {
7890 SSL_TRC(30,("%d: SSL3[%d]: reset handshake hashes",
7891 SSL_GETPID(), ss
->fd
));
7892 rv
= ssl3_RestartHandshakeHashes(ss
);
7893 if (rv
!= SECSuccess
) {
7897 /* We should not include hello_request messages in the handshake hashes */
7898 if (ss
->ssl3
.hs
.msg_type
!= hello_request
) {
7899 rv
= ssl3_UpdateHandshakeHashes(ss
, (unsigned char*) hdr
, 4);
7900 if (rv
!= SECSuccess
) return rv
; /* err code already set. */
7901 rv
= ssl3_UpdateHandshakeHashes(ss
, b
, length
);
7902 if (rv
!= SECSuccess
) return rv
; /* err code already set. */
7905 PORT_SetError(0); /* each message starts with no error. */
7906 switch (ss
->ssl3
.hs
.msg_type
) {
7909 (void)ssl3_DecodeError(ss
);
7910 PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_REQUEST
);
7913 if (ss
->sec
.isServer
) {
7914 (void)SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
7915 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST
);
7918 rv
= ssl3_HandleHelloRequest(ss
);
7921 if (!ss
->sec
.isServer
) {
7922 (void)SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
7923 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO
);
7926 rv
= ssl3_HandleClientHello(ss
, b
, length
);
7929 if (ss
->sec
.isServer
) {
7930 (void)SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
7931 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO
);
7934 rv
= ssl3_HandleServerHello(ss
, b
, length
);
7937 rv
= ssl3_HandleCertificate(ss
, b
, length
);
7939 case server_key_exchange
:
7940 if (ss
->sec
.isServer
) {
7941 (void)SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
7942 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH
);
7945 rv
= ssl3_HandleServerKeyExchange(ss
, b
, length
);
7947 case certificate_request
:
7948 if (ss
->sec
.isServer
) {
7949 (void)SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
7950 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST
);
7953 rv
= ssl3_HandleCertificateRequest(ss
, b
, length
);
7955 case server_hello_done
:
7957 (void)ssl3_DecodeError(ss
);
7958 PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_DONE
);
7961 if (ss
->sec
.isServer
) {
7962 (void)SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
7963 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE
);
7966 rv
= ssl3_HandleServerHelloDone(ss
);
7968 case certificate_verify
:
7969 if (!ss
->sec
.isServer
) {
7970 (void)SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
7971 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY
);
7974 rv
= ssl3_HandleCertificateVerify(ss
, b
, length
, &hashes
);
7976 case client_key_exchange
:
7977 if (!ss
->sec
.isServer
) {
7978 (void)SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
7979 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH
);
7982 rv
= ssl3_HandleClientKeyExchange(ss
, b
, length
);
7984 case new_session_ticket
:
7985 if (ss
->sec
.isServer
) {
7986 (void)SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
7987 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET
);
7990 rv
= ssl3_HandleNewSessionTicket(ss
, b
, length
);
7993 rv
= ssl3_HandleFinished(ss
, b
, length
, &hashes
);
7996 (void)SSL3_SendAlert(ss
, alert_fatal
, unexpected_message
);
7997 PORT_SetError(SSL_ERROR_RX_UNKNOWN_HANDSHAKE
);
8003 /* Called only from ssl3_HandleRecord, for each (deciphered) ssl3 record.
8004 * origBuf is the decrypted ssl record content.
8005 * Caller must hold the handshake and RecvBuf locks.
8008 ssl3_HandleHandshake(sslSocket
*ss
, sslBuffer
*origBuf
)
8011 * There may be a partial handshake message already in the handshake
8012 * state. The incoming buffer may contain another portion, or a
8013 * complete message or several messages followed by another portion.
8015 * Each message is made contiguous before being passed to the actual
8018 sslBuffer
*buf
= &ss
->ssl3
.hs
.msgState
; /* do not lose the original buffer pointer */
8021 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
8022 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
8024 if (buf
->buf
== NULL
) {
8027 while (buf
->len
> 0) {
8028 if (ss
->ssl3
.hs
.header_bytes
< 4) {
8032 if (ss
->ssl3
.hs
.header_bytes
++ == 0)
8033 ss
->ssl3
.hs
.msg_type
= (SSL3HandshakeType
)t
;
8035 ss
->ssl3
.hs
.msg_len
= (ss
->ssl3
.hs
.msg_len
<< 8) + t
;
8036 if (ss
->ssl3
.hs
.header_bytes
< 4)
8039 #define MAX_HANDSHAKE_MSG_LEN 0x1ffff /* 128k - 1 */
8040 if (ss
->ssl3
.hs
.msg_len
> MAX_HANDSHAKE_MSG_LEN
) {
8041 (void)ssl3_DecodeError(ss
);
8042 PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG
);
8045 #undef MAX_HANDSHAKE_MSG_LEN
8047 /* If msg_len is zero, be sure we fall through,
8048 ** even if buf->len is zero.
8050 if (ss
->ssl3
.hs
.msg_len
> 0)
8055 * Header has been gathered and there is at least one byte of new
8056 * data available for this message. If it can be done right out
8057 * of the original buffer, then use it from there.
8059 if (ss
->ssl3
.hs
.msg_body
.len
== 0 && buf
->len
>= ss
->ssl3
.hs
.msg_len
) {
8060 /* handle it from input buffer */
8061 rv
= ssl3_HandleHandshakeMessage(ss
, buf
->buf
, ss
->ssl3
.hs
.msg_len
);
8062 if (rv
== SECFailure
) {
8063 /* This test wants to fall through on either
8064 * SECSuccess or SECWouldBlock.
8065 * ssl3_HandleHandshakeMessage MUST set the error code.
8069 buf
->buf
+= ss
->ssl3
.hs
.msg_len
;
8070 buf
->len
-= ss
->ssl3
.hs
.msg_len
;
8071 ss
->ssl3
.hs
.msg_len
= 0;
8072 ss
->ssl3
.hs
.header_bytes
= 0;
8073 if (rv
!= SECSuccess
) { /* return if SECWouldBlock. */
8077 /* must be copied to msg_body and dealt with from there */
8080 PORT_Assert(ss
->ssl3
.hs
.msg_body
.len
<= ss
->ssl3
.hs
.msg_len
);
8081 bytes
= PR_MIN(buf
->len
, ss
->ssl3
.hs
.msg_len
- ss
->ssl3
.hs
.msg_body
.len
);
8083 /* Grow the buffer if needed */
8084 rv
= sslBuffer_Grow(&ss
->ssl3
.hs
.msg_body
, ss
->ssl3
.hs
.msg_len
);
8085 if (rv
!= SECSuccess
) {
8086 /* sslBuffer_Grow has set a memory error code. */
8090 PORT_Memcpy(ss
->ssl3
.hs
.msg_body
.buf
+ ss
->ssl3
.hs
.msg_body
.len
,
8092 ss
->ssl3
.hs
.msg_body
.len
+= bytes
;
8096 PORT_Assert(ss
->ssl3
.hs
.msg_body
.len
<= ss
->ssl3
.hs
.msg_len
);
8098 /* if we have a whole message, do it */
8099 if (ss
->ssl3
.hs
.msg_body
.len
== ss
->ssl3
.hs
.msg_len
) {
8100 rv
= ssl3_HandleHandshakeMessage(
8101 ss
, ss
->ssl3
.hs
.msg_body
.buf
, ss
->ssl3
.hs
.msg_len
);
8103 * XXX This appears to be wrong. This error handling
8104 * should clean up after a SECWouldBlock return, like the
8105 * error handling used 40 lines before/above this one,
8107 if (rv
!= SECSuccess
) {
8108 /* ssl3_HandleHandshakeMessage MUST set error code. */
8111 ss
->ssl3
.hs
.msg_body
.len
= 0;
8112 ss
->ssl3
.hs
.msg_len
= 0;
8113 ss
->ssl3
.hs
.header_bytes
= 0;
8115 PORT_Assert(buf
->len
== 0);
8121 origBuf
->len
= 0; /* So ssl3_GatherAppDataRecord will keep looping. */
8122 buf
->buf
= NULL
; /* not a leak. */
8126 /* if cText is non-null, then decipher, check MAC, and decompress the
8127 * SSL record from cText->buf (typically gs->inbuf)
8128 * into databuf (typically gs->buf), and any previous contents of databuf
8129 * is lost. Then handle databuf according to its SSL record type,
8130 * unless it's an application record.
8132 * If cText is NULL, then the ciphertext has previously been deciphered and
8133 * checked, and is already sitting in databuf. It is processed as an SSL
8134 * Handshake message.
8136 * DOES NOT process the decrypted/decompressed application data.
8137 * On return, databuf contains the decrypted/decompressed record.
8139 * Called from ssl3_GatherCompleteHandshake
8140 * ssl3_RestartHandshakeAfterCertReq
8141 * ssl3_RestartHandshakeAfterServerCert
8143 * Caller must hold the RecvBufLock.
8145 * This function aquires and releases the SSL3Handshake Lock, holding the
8146 * lock around any calls to functions that handle records other than
8147 * Application Data records.
8150 ssl3_HandleRecord(sslSocket
*ss
, SSL3Ciphertext
*cText
, sslBuffer
*databuf
)
8152 const ssl3BulkCipherDef
*cipher_def
;
8153 ssl3CipherSpec
* crSpec
;
8155 unsigned int hashBytes
= MAX_MAC_LENGTH
+ 1;
8156 unsigned int padding_length
;
8158 PRBool padIsBad
= PR_FALSE
;
8159 SSL3ContentType rType
;
8160 SSL3Opaque hash
[MAX_MAC_LENGTH
];
8162 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveRecvBufLock(ss
) );
8164 if (!ss
->ssl3
.initialized
) {
8165 ssl_GetSSL3HandshakeLock(ss
);
8166 rv
= ssl3_InitState(ss
);
8167 ssl_ReleaseSSL3HandshakeLock(ss
);
8168 if (rv
!= SECSuccess
) {
8169 return rv
; /* ssl3_InitState has set the error code. */
8173 /* check for Token Presence */
8174 if (!ssl3_ClientAuthTokenPresent(ss
->sec
.ci
.sid
)) {
8175 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL
);
8179 /* cText is NULL when we're called from ssl3_RestartHandshakeAfterXXX().
8180 * This implies that databuf holds a previously deciphered SSL Handshake
8183 if (cText
== NULL
) {
8184 SSL_DBG(("%d: SSL3[%d]: HandleRecord, resuming handshake",
8185 SSL_GETPID(), ss
->fd
));
8186 rType
= content_handshake
;
8190 databuf
->len
= 0; /* filled in by decode call below. */
8191 if (databuf
->space
< MAX_FRAGMENT_LENGTH
) {
8192 rv
= sslBuffer_Grow(databuf
, MAX_FRAGMENT_LENGTH
+ 2048);
8193 if (rv
!= SECSuccess
) {
8194 SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes",
8195 SSL_GETPID(), ss
->fd
, MAX_FRAGMENT_LENGTH
+ 2048));
8196 /* sslBuffer_Grow has set a memory error code. */
8197 /* Perhaps we should send an alert. (but we have no memory!) */
8202 PRINT_BUF(80, (ss
, "ciphertext:", cText
->buf
->buf
, cText
->buf
->len
));
8204 ssl_GetSpecReadLock(ss
); /******************************************/
8206 crSpec
= ss
->ssl3
.crSpec
;
8207 cipher_def
= crSpec
->cipher_def
;
8208 isTLS
= (PRBool
)(crSpec
->version
> SSL_LIBRARY_VERSION_3_0
);
8210 if (isTLS
&& cText
->buf
->len
> (MAX_FRAGMENT_LENGTH
+ 2048)) {
8211 ssl_ReleaseSpecReadLock(ss
);
8212 SSL3_SendAlert(ss
, alert_fatal
, record_overflow
);
8213 PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG
);
8216 /* decrypt from cText buf to databuf. */
8217 rv
= crSpec
->decode(
8218 crSpec
->decodeContext
, databuf
->buf
, (int *)&databuf
->len
,
8219 databuf
->space
, cText
->buf
->buf
, cText
->buf
->len
);
8221 PRINT_BUF(80, (ss
, "cleartext:", databuf
->buf
, databuf
->len
));
8222 if (rv
!= SECSuccess
) {
8223 int err
= ssl_MapLowLevelError(SSL_ERROR_DECRYPTION_FAILURE
);
8224 ssl_ReleaseSpecReadLock(ss
);
8225 SSL3_SendAlert(ss
, alert_fatal
,
8226 isTLS
? decryption_failed
: bad_record_mac
);
8231 /* If it's a block cipher, check and strip the padding. */
8232 if (cipher_def
->type
== type_block
) {
8233 padding_length
= *(databuf
->buf
+ databuf
->len
- 1);
8234 /* TLS permits padding to exceed the block size, up to 255 bytes. */
8235 if (padding_length
+ 1 + crSpec
->mac_size
> databuf
->len
)
8237 /* if TLS, check value of first padding byte. */
8238 else if (padding_length
&& isTLS
&&
8240 *(databuf
->buf
+ databuf
->len
- (padding_length
+ 1)))
8243 databuf
->len
-= padding_length
+ 1;
8246 /* Remove the MAC. */
8247 if (databuf
->len
>= crSpec
->mac_size
)
8248 databuf
->len
-= crSpec
->mac_size
;
8250 padIsBad
= PR_TRUE
; /* really macIsBad */
8252 /* compute the MAC */
8253 rType
= cText
->type
;
8254 rv
= ssl3_ComputeRecordMAC( crSpec
, (PRBool
)(!ss
->sec
.isServer
),
8255 rType
, cText
->version
, crSpec
->read_seq_num
,
8256 databuf
->buf
, databuf
->len
, hash
, &hashBytes
);
8257 if (rv
!= SECSuccess
) {
8258 int err
= ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE
);
8259 ssl_ReleaseSpecReadLock(ss
);
8260 SSL3_SendAlert(ss
, alert_fatal
, bad_record_mac
);
8266 if (hashBytes
!= (unsigned)crSpec
->mac_size
|| padIsBad
||
8267 PORT_Memcmp(databuf
->buf
+ databuf
->len
, hash
, crSpec
->mac_size
) != 0) {
8268 /* must not hold spec lock when calling SSL3_SendAlert. */
8269 ssl_ReleaseSpecReadLock(ss
);
8270 SSL3_SendAlert(ss
, alert_fatal
, bad_record_mac
);
8271 /* always log mac error, in case attacker can read server logs. */
8272 PORT_SetError(SSL_ERROR_BAD_MAC_READ
);
8274 SSL_DBG(("%d: SSL3[%d]: mac check failed", SSL_GETPID(), ss
->fd
));
8279 ssl3_BumpSequenceNumber(&crSpec
->read_seq_num
);
8281 ssl_ReleaseSpecReadLock(ss
); /*****************************************/
8284 * The decrypted data is now in databuf.
8286 * the null decompression routine is right here
8290 ** Having completed the decompression, check the length again.
8292 if (isTLS
&& databuf
->len
> (MAX_FRAGMENT_LENGTH
+ 1024)) {
8293 SSL3_SendAlert(ss
, alert_fatal
, record_overflow
);
8294 PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG
);
8298 /* Application data records are processed by the caller of this
8299 ** function, not by this function.
8301 if (rType
== content_application_data
) {
8305 /* It's a record that must be handled by ssl itself, not the application.
8308 /* XXX Get the xmit lock here. Odds are very high that we'll be xmiting
8309 * data ang getting the xmit lock here prevents deadlocks.
8311 ssl_GetSSL3HandshakeLock(ss
);
8313 /* All the functions called in this switch MUST set error code if
8314 ** they return SECFailure or SECWouldBlock.
8317 case content_change_cipher_spec
:
8318 rv
= ssl3_HandleChangeCipherSpecs(ss
, databuf
);
8321 rv
= ssl3_HandleAlert(ss
, databuf
);
8323 case content_handshake
:
8324 rv
= ssl3_HandleHandshake(ss
, databuf
);
8327 case content_application_data is handled before this switch
8330 SSL_DBG(("%d: SSL3[%d]: bogus content type=%d",
8331 SSL_GETPID(), ss
->fd
, cText
->type
));
8332 /* XXX Send an alert ??? */
8333 PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE
);
8338 ssl_ReleaseSSL3HandshakeLock(ss
);
8344 * Initialization functions
8347 /* Called from ssl3_InitState, immediately below. */
8348 /* Caller must hold the SpecWriteLock. */
8350 ssl3_InitCipherSpec(sslSocket
*ss
, ssl3CipherSpec
*spec
)
8352 spec
->cipher_def
= &bulk_cipher_defs
[cipher_null
];
8353 PORT_Assert(spec
->cipher_def
->cipher
== cipher_null
);
8354 spec
->mac_def
= &mac_defs
[mac_null
];
8355 PORT_Assert(spec
->mac_def
->mac
== mac_null
);
8356 spec
->encode
= Null_Cipher
;
8357 spec
->decode
= Null_Cipher
;
8358 spec
->destroy
= NULL
;
8360 spec
->master_secret
= NULL
;
8361 spec
->bypassCiphers
= PR_FALSE
;
8363 spec
->msItem
.data
= NULL
;
8364 spec
->msItem
.len
= 0;
8366 spec
->client
.write_key
= NULL
;
8367 spec
->client
.write_mac_key
= NULL
;
8368 spec
->client
.write_mac_context
= NULL
;
8370 spec
->server
.write_key
= NULL
;
8371 spec
->server
.write_mac_key
= NULL
;
8372 spec
->server
.write_mac_context
= NULL
;
8374 spec
->write_seq_num
.high
= 0;
8375 spec
->write_seq_num
.low
= 0;
8377 spec
->read_seq_num
.high
= 0;
8378 spec
->read_seq_num
.low
= 0;
8380 spec
->version
= ss
->opt
.enableTLS
8381 ? SSL_LIBRARY_VERSION_3_1_TLS
8382 : SSL_LIBRARY_VERSION_3_0
;
8385 /* Called from: ssl3_SendRecord
8386 ** ssl3_StartHandshakeHash() <- ssl2_BeginClientHandshake()
8387 ** ssl3_SendClientHello()
8388 ** ssl3_HandleServerHello()
8389 ** ssl3_HandleClientHello()
8390 ** ssl3_HandleV2ClientHello()
8391 ** ssl3_HandleRecord()
8393 ** This function should perhaps acquire and release the SpecWriteLock.
8398 ssl3_InitState(sslSocket
*ss
)
8401 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
));
8403 if (ss
->ssl3
.initialized
)
8404 return SECSuccess
; /* Function should be idempotent */
8406 ss
->ssl3
.policy
= SSL_ALLOWED
;
8408 ssl_GetSpecWriteLock(ss
);
8409 ss
->ssl3
.crSpec
= ss
->ssl3
.cwSpec
= &ss
->ssl3
.specs
[0];
8410 ss
->ssl3
.prSpec
= ss
->ssl3
.pwSpec
= &ss
->ssl3
.specs
[1];
8411 ss
->ssl3
.hs
.rehandshake
= PR_FALSE
;
8412 ssl3_InitCipherSpec(ss
, ss
->ssl3
.crSpec
);
8413 ssl3_InitCipherSpec(ss
, ss
->ssl3
.prSpec
);
8415 ss
->ssl3
.hs
.ws
= (ss
->sec
.isServer
) ? wait_client_hello
: wait_server_hello
;
8416 #ifdef NSS_ENABLE_ECC
8417 ss
->ssl3
.hs
.negotiatedECCurves
= SSL3_SUPPORTED_CURVES_MASK
;
8419 ssl_ReleaseSpecWriteLock(ss
);
8421 PORT_Memset(&ss
->xtnData
, 0, sizeof(TLSExtensionData
));
8423 rv
= ssl3_NewHandshakeHashes(ss
);
8424 if (rv
== SECSuccess
) {
8425 ss
->ssl3
.initialized
= PR_TRUE
;
8431 /* Returns a reference counted object that contains a key pair.
8432 * Or NULL on failure. Initial ref count is 1.
8433 * Uses the keys in the pair as input.
8436 ssl3_NewKeyPair( SECKEYPrivateKey
* privKey
, SECKEYPublicKey
* pubKey
)
8440 if (!privKey
|| !pubKey
) {
8441 PORT_SetError(PR_INVALID_ARGUMENT_ERROR
);
8444 pair
= PORT_ZNew(ssl3KeyPair
);
8446 return NULL
; /* error code is set. */
8448 pair
->privKey
= privKey
;
8449 pair
->pubKey
= pubKey
;
8450 return pair
; /* success */
8454 ssl3_GetKeyPairRef(ssl3KeyPair
* keyPair
)
8456 PR_AtomicIncrement(&keyPair
->refCount
);
8461 ssl3_FreeKeyPair(ssl3KeyPair
* keyPair
)
8463 PRInt32 newCount
= PR_AtomicDecrement(&keyPair
->refCount
);
8465 if (keyPair
->privKey
)
8466 SECKEY_DestroyPrivateKey(keyPair
->privKey
);
8467 if (keyPair
->pubKey
)
8468 SECKEY_DestroyPublicKey( keyPair
->pubKey
);
8476 * Creates the public and private RSA keys for SSL Step down.
8477 * Called from SSL_ConfigSecureServer in sslsecur.c
8480 ssl3_CreateRSAStepDownKeys(sslSocket
*ss
)
8482 SECStatus rv
= SECSuccess
;
8483 SECKEYPrivateKey
* privKey
; /* RSA step down key */
8484 SECKEYPublicKey
* pubKey
; /* RSA step down key */
8486 if (ss
->stepDownKeyPair
)
8487 ssl3_FreeKeyPair(ss
->stepDownKeyPair
);
8488 ss
->stepDownKeyPair
= NULL
;
8489 #ifndef HACKED_EXPORT_SERVER
8490 /* Sigh, should have a get key strength call for private keys */
8491 if (PK11_GetPrivateModulusLen(ss
->serverCerts
[kt_rsa
].SERVERKEY
) >
8492 EXPORT_RSA_KEY_LENGTH
) {
8493 /* need to ask for the key size in bits */
8494 privKey
= SECKEY_CreateRSAPrivateKey(EXPORT_RSA_KEY_LENGTH
* BPB
,
8496 if (!privKey
|| !pubKey
||
8497 !(ss
->stepDownKeyPair
= ssl3_NewKeyPair(privKey
, pubKey
))) {
8498 ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL
);
8507 /* record the export policy for this cipher suite */
8509 ssl3_SetPolicy(ssl3CipherSuite which
, int policy
)
8511 ssl3CipherSuiteCfg
*suite
;
8513 suite
= ssl_LookupCipherSuiteCfg(which
, cipherSuites
);
8514 if (suite
== NULL
) {
8515 return SECFailure
; /* err code was set by ssl_LookupCipherSuiteCfg */
8517 suite
->policy
= policy
;
8519 if (policy
== SSL_RESTRICTED
) {
8520 ssl3_global_policy_some_restricted
= PR_TRUE
;
8527 ssl3_GetPolicy(ssl3CipherSuite which
, PRInt32
*oPolicy
)
8529 ssl3CipherSuiteCfg
*suite
;
8533 suite
= ssl_LookupCipherSuiteCfg(which
, cipherSuites
);
8535 policy
= suite
->policy
;
8538 policy
= SSL_NOT_ALLOWED
;
8539 rv
= SECFailure
; /* err code was set by Lookup. */
8545 /* record the user preference for this suite */
8547 ssl3_CipherPrefSetDefault(ssl3CipherSuite which
, PRBool enabled
)
8549 ssl3CipherSuiteCfg
*suite
;
8551 suite
= ssl_LookupCipherSuiteCfg(which
, cipherSuites
);
8552 if (suite
== NULL
) {
8553 return SECFailure
; /* err code was set by ssl_LookupCipherSuiteCfg */
8555 suite
->enabled
= enabled
;
8559 /* return the user preference for this suite */
8561 ssl3_CipherPrefGetDefault(ssl3CipherSuite which
, PRBool
*enabled
)
8563 ssl3CipherSuiteCfg
*suite
;
8567 suite
= ssl_LookupCipherSuiteCfg(which
, cipherSuites
);
8569 pref
= suite
->enabled
;
8572 pref
= SSL_NOT_ALLOWED
;
8573 rv
= SECFailure
; /* err code was set by Lookup. */
8580 ssl3_CipherPrefSet(sslSocket
*ss
, ssl3CipherSuite which
, PRBool enabled
)
8582 ssl3CipherSuiteCfg
*suite
;
8584 suite
= ssl_LookupCipherSuiteCfg(which
, ss
->cipherSuites
);
8585 if (suite
== NULL
) {
8586 return SECFailure
; /* err code was set by ssl_LookupCipherSuiteCfg */
8588 suite
->enabled
= enabled
;
8593 ssl3_CipherPrefGet(sslSocket
*ss
, ssl3CipherSuite which
, PRBool
*enabled
)
8595 ssl3CipherSuiteCfg
*suite
;
8599 suite
= ssl_LookupCipherSuiteCfg(which
, ss
->cipherSuites
);
8601 pref
= suite
->enabled
;
8604 pref
= SSL_NOT_ALLOWED
;
8605 rv
= SECFailure
; /* err code was set by Lookup. */
8611 /* copy global default policy into socket. */
8613 ssl3_InitSocketPolicy(sslSocket
*ss
)
8615 PORT_Memcpy(ss
->cipherSuites
, cipherSuites
, sizeof cipherSuites
);
8618 /* ssl3_config_match_init must have already been called by
8619 * the caller of this function.
8622 ssl3_ConstructV2CipherSpecsHack(sslSocket
*ss
, unsigned char *cs
, int *size
)
8626 PORT_Assert(ss
!= 0);
8628 PORT_SetError(PR_INVALID_ARGUMENT_ERROR
);
8631 if (!ss
->opt
.enableSSL3
&& !ss
->opt
.enableTLS
) {
8636 *size
= count_cipher_suites(ss
, SSL_ALLOWED
, PR_TRUE
);
8640 /* ssl3_config_match_init was called by the caller of this function. */
8641 for (i
= 0; i
< ssl_V3_SUITES_IMPLEMENTED
; i
++) {
8642 ssl3CipherSuiteCfg
*suite
= &ss
->cipherSuites
[i
];
8643 if (config_match(suite
, SSL_ALLOWED
, PR_TRUE
)) {
8646 *cs
++ = (suite
->cipher_suite
>> 8) & 0xFF;
8647 *cs
++ = suite
->cipher_suite
& 0xFF;
8657 ** If ssl3 socket has completed the first handshake, and is in idle state,
8658 ** then start a new handshake.
8659 ** If flushCache is true, the SID cache will be flushed first, forcing a
8660 ** "Full" handshake (not a session restart handshake), to be done.
8662 ** called from SSL_RedoHandshake(), which already holds the handshake locks.
8665 ssl3_RedoHandshake(sslSocket
*ss
, PRBool flushCache
)
8667 sslSessionID
* sid
= ss
->sec
.ci
.sid
;
8670 PORT_Assert( ss
->opt
.noLocks
|| ssl_HaveSSL3HandshakeLock(ss
) );
8672 if (!ss
->firstHsDone
||
8673 ((ss
->version
>= SSL_LIBRARY_VERSION_3_0
) &&
8674 ss
->ssl3
.initialized
&&
8675 (ss
->ssl3
.hs
.ws
!= idle_handshake
))) {
8676 PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED
);
8679 if (sid
&& flushCache
) {
8680 ss
->sec
.uncache(sid
); /* remove it from whichever cache it's in. */
8681 ssl_FreeSID(sid
); /* dec ref count and free if zero. */
8682 ss
->sec
.ci
.sid
= NULL
;
8685 ssl_GetXmitBufLock(ss
); /**************************************/
8687 /* start off a new handshake. */
8688 rv
= (ss
->sec
.isServer
) ? ssl3_SendHelloRequest(ss
)
8689 : ssl3_SendClientHello(ss
);
8691 ssl_ReleaseXmitBufLock(ss
); /**************************************/
8695 /* Called from ssl_DestroySocketContents() in sslsock.c */
8697 ssl3_DestroySSL3Info(sslSocket
*ss
)
8700 if (ss
->ssl3
.clientCertificate
!= NULL
)
8701 CERT_DestroyCertificate(ss
->ssl3
.clientCertificate
);
8703 if (ss
->ssl3
.clientPrivateKey
!= NULL
)
8704 SECKEY_DestroyPrivateKey(ss
->ssl3
.clientPrivateKey
);
8706 if (ss
->ssl3
.peerCertArena
!= NULL
)
8707 ssl3_CleanupPeerCerts(ss
);
8709 if (ss
->ssl3
.clientCertChain
!= NULL
) {
8710 CERT_DestroyCertificateList(ss
->ssl3
.clientCertChain
);
8711 ss
->ssl3
.clientCertChain
= NULL
;
8714 /* clean up handshake */
8715 if (ss
->opt
.bypassPKCS11
) {
8716 SHA1_DestroyContext((SHA1Context
*)ss
->ssl3
.hs
.sha_cx
, PR_FALSE
);
8717 MD5_DestroyContext((MD5Context
*)ss
->ssl3
.hs
.md5_cx
, PR_FALSE
);
8719 if (ss
->ssl3
.hs
.md5
) {
8720 PK11_DestroyContext(ss
->ssl3
.hs
.md5
,PR_TRUE
);
8722 if (ss
->ssl3
.hs
.sha
) {
8723 PK11_DestroyContext(ss
->ssl3
.hs
.sha
,PR_TRUE
);
8725 if (ss
->ssl3
.hs
.messages
.buf
) {
8726 PORT_Free(ss
->ssl3
.hs
.messages
.buf
);
8727 ss
->ssl3
.hs
.messages
.buf
= NULL
;
8728 ss
->ssl3
.hs
.messages
.len
= 0;
8729 ss
->ssl3
.hs
.messages
.space
= 0;
8732 /* free the SSL3Buffer (msg_body) */
8733 PORT_Free(ss
->ssl3
.hs
.msg_body
.buf
);
8735 /* free up the CipherSpecs */
8736 ssl3_DestroyCipherSpec(&ss
->ssl3
.specs
[0]);
8737 ssl3_DestroyCipherSpec(&ss
->ssl3
.specs
[1]);
8739 ss
->ssl3
.initialized
= PR_FALSE
;
8742 /* End of ssl3con.c */