Bug Summary

File:s/lib/ssl/ssl3con.c
Warning:line 8058, column 9
Null pointer passed to 2nd parameter expecting 'nonnull'

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name ssl3con.c -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -mframe-pointer=all -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fdebug-compilation-dir=/var/lib/jenkins/workspace/nss-scan-build/nss/lib/ssl -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/var/lib/jenkins/workspace/nss-scan-build/nss/lib/ssl -resource-dir /usr/lib/llvm-18/lib/clang/18 -D HAVE_STRERROR -D LINUX -D linux -D XP_UNIX -D XP_UNIX -D DEBUG -U NDEBUG -D _DEFAULT_SOURCE -D _BSD_SOURCE -D _POSIX_SOURCE -D SDB_MEASURE_USE_TEMP_DIR -D _REENTRANT -D DEBUG -U NDEBUG -D _DEFAULT_SOURCE -D _BSD_SOURCE -D _POSIX_SOURCE -D SDB_MEASURE_USE_TEMP_DIR -D _REENTRANT -D NSS_DISABLE_SSE3 -D NSS_NO_INIT_SUPPORT -D USE_UTIL_DIRECTLY -D NO_NSPR_10_SUPPORT -D SSL_DISABLE_DEPRECATED_CIPHER_SUITE_NAMES -D NSS_ALLOW_SSLKEYLOGFILE=1 -I ../../../dist/Linux4.19_x86_64_gcc_glibc_PTH_64_DBG.OBJ/include -I ../../../dist/public/nss -I ../../../dist/private/nss -internal-isystem /usr/lib/llvm-18/lib/clang/18/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/14/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -std=c99 -ferror-limit 19 -fgnuc-version=4.2.1 -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2024-05-18-082241-28900-1 -x c ssl3con.c
1/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2/*
3 * SSL3 Protocol
4 *
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
8
9/* TODO(ekr): Implement HelloVerifyRequest on server side. OK for now. */
10
11#include "cert.h"
12#include "ssl.h"
13#include "cryptohi.h" /* for DSAU_ stuff */
14#include "keyhi.h"
15#include "secder.h"
16#include "secitem.h"
17#include "sechash.h"
18
19#include "sslimpl.h"
20#include "sslproto.h"
21#include "sslerr.h"
22#include "ssl3ext.h"
23#include "ssl3exthandle.h"
24#include "tls13ech.h"
25#include "tls13exthandle.h"
26#include "tls13psk.h"
27#include "tls13subcerts.h"
28#include "prtime.h"
29#include "prinrval.h"
30#include "prerror.h"
31#include "pratom.h"
32#include "prthread.h"
33#include "nss.h"
34#include "nssoptions.h"
35
36#include "pk11func.h"
37#include "secmod.h"
38#include "blapi.h"
39
40#include <stdio.h>
41
42static PK11SymKey *ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec,
43 PK11SlotInfo *serverKeySlot);
44static SECStatus ssl3_ComputeMasterSecret(sslSocket *ss, PK11SymKey *pms,
45 PK11SymKey **msp);
46static SECStatus ssl3_DeriveConnectionKeys(sslSocket *ss,
47 PK11SymKey *masterSecret);
48static SECStatus ssl3_HandshakeFailure(sslSocket *ss);
49static SECStatus ssl3_SendCertificate(sslSocket *ss);
50static SECStatus ssl3_SendCertificateRequest(sslSocket *ss);
51static SECStatus ssl3_SendNextProto(sslSocket *ss);
52static SECStatus ssl3_SendFinished(sslSocket *ss, PRInt32 flags);
53static SECStatus ssl3_SendServerHelloDone(sslSocket *ss);
54static SECStatus ssl3_SendServerKeyExchange(sslSocket *ss);
55static SECStatus ssl3_HandleClientHelloPart2(sslSocket *ss,
56 SECItem *suites,
57 sslSessionID *sid,
58 const PRUint8 *msg,
59 unsigned int len);
60static SECStatus ssl3_HandleServerHelloPart2(sslSocket *ss,
61 const SECItem *sidBytes,
62 int *retErrCode);
63static SECStatus ssl3_HandlePostHelloHandshakeMessage(sslSocket *ss,
64 PRUint8 *b,
65 PRUint32 length);
66static SECStatus ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags);
67static CK_MECHANISM_TYPE ssl3_GetHashMechanismByHashType(SSLHashType hashType);
68static CK_MECHANISM_TYPE ssl3_GetMgfMechanismByHashType(SSLHashType hash);
69PRBool ssl_IsRsaPssSignatureScheme(SSLSignatureScheme scheme);
70PRBool ssl_IsRsaeSignatureScheme(SSLSignatureScheme scheme);
71PRBool ssl_IsRsaPkcs1SignatureScheme(SSLSignatureScheme scheme);
72PRBool ssl_IsDsaSignatureScheme(SSLSignatureScheme scheme);
73static SECStatus ssl3_UpdateDefaultHandshakeHashes(sslSocket *ss,
74 const unsigned char *b,
75 unsigned int l);
76const PRUint32 kSSLSigSchemePolicy =
77 NSS_USE_ALG_IN_SSL_KX0x00000004 | NSS_USE_ALG_IN_ANY_SIGNATURE0x00000020;
78
79const PRUint8 ssl_hello_retry_random[] = {
80 0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11,
81 0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91,
82 0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E,
83 0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C
84};
85PR_STATIC_ASSERT(PR_ARRAY_SIZE(ssl_hello_retry_random) == SSL3_RANDOM_LENGTH)extern void pr_static_assert(int arg[((sizeof(ssl_hello_retry_random
)/sizeof((ssl_hello_retry_random)[0])) == 32) ? 1 : -1])
;
86
87/* This list of SSL3 cipher suites is sorted in descending order of
88 * precedence (desirability). It only includes cipher suites we implement.
89 * This table is modified by SSL3_SetPolicy(). The ordering of cipher suites
90 * in this table must match the ordering in SSL_ImplementedCiphers (sslenum.c)
91 *
92 * Important: See bug 946147 before enabling, reordering, or adding any cipher
93 * suites to this list.
94 */
95/* clang-format off */
96static ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED71] = {
97 /* cipher_suite policy enabled isPresent */
98 /* Special TLS 1.3 suites. */
99 { TLS_AES_128_GCM_SHA2560x1301, SSL_ALLOWED1, PR_TRUE1, PR_FALSE0 },
100 { TLS_CHACHA20_POLY1305_SHA2560x1303, SSL_ALLOWED1, PR_TRUE1, PR_FALSE0 },
101 { TLS_AES_256_GCM_SHA3840x1302, SSL_ALLOWED1, PR_TRUE1, PR_FALSE0 },
102
103 { TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA2560xC02B, SSL_ALLOWED1, PR_TRUE1, PR_FALSE0},
104 { TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA2560xC02F, SSL_ALLOWED1, PR_TRUE1, PR_FALSE0},
105 { TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA2560xCCA9, SSL_ALLOWED1, PR_TRUE1, PR_FALSE0},
106 { TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA2560xCCA8, SSL_ALLOWED1, PR_TRUE1, PR_FALSE0},
107 { TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA3840xC02C, SSL_ALLOWED1, PR_TRUE1, PR_FALSE0},
108 { TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA3840xC030, SSL_ALLOWED1, PR_TRUE1, PR_FALSE0},
109 /* TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA is out of order to work around
110 * bug 946147.
111 */
112 { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA0xC00A, SSL_ALLOWED1, PR_TRUE1, PR_FALSE0},
113 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA0xC009, SSL_ALLOWED1, PR_TRUE1, PR_FALSE0},
114 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA0xC013, SSL_ALLOWED1, PR_TRUE1, PR_FALSE0},
115 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA2560xC023, SSL_ALLOWED1, PR_TRUE1, PR_FALSE0},
116 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA2560xC027, SSL_ALLOWED1, PR_TRUE1, PR_FALSE0},
117 { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA0xC014, SSL_ALLOWED1, PR_TRUE1, PR_FALSE0},
118 { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA3840xC024, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
119 { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA3840xC028, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
120 { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA0xC008, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
121 { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA0xC012, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
122 { TLS_ECDHE_ECDSA_WITH_RC4_128_SHA0xC007, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
123 { TLS_ECDHE_RSA_WITH_RC4_128_SHA0xC011, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
124
125 { TLS_DHE_RSA_WITH_AES_128_GCM_SHA2560x009E, SSL_ALLOWED1, PR_TRUE1, PR_FALSE0},
126 { TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA2560xCCAA,SSL_ALLOWED1,PR_TRUE1, PR_FALSE0},
127 { TLS_DHE_DSS_WITH_AES_128_GCM_SHA2560x00A2, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
128 { TLS_DHE_RSA_WITH_AES_256_GCM_SHA3840x009F, SSL_ALLOWED1, PR_TRUE1, PR_FALSE0},
129 { TLS_DHE_DSS_WITH_AES_256_GCM_SHA3840x00A3, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
130 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA0x0033, SSL_ALLOWED1, PR_TRUE1, PR_FALSE0},
131 { TLS_DHE_DSS_WITH_AES_128_CBC_SHA0x0032, SSL_ALLOWED1, PR_TRUE1, PR_FALSE0},
132 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA2560x0067, SSL_ALLOWED1, PR_TRUE1, PR_FALSE0},
133 { TLS_DHE_DSS_WITH_AES_128_CBC_SHA2560x0040, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
134 { TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA0x0045, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
135 { TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA0x0044, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
136 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA0x0039, SSL_ALLOWED1, PR_TRUE1, PR_FALSE0},
137 { TLS_DHE_DSS_WITH_AES_256_CBC_SHA0x0038, SSL_ALLOWED1, PR_TRUE1, PR_FALSE0},
138 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA2560x006B, SSL_ALLOWED1, PR_TRUE1, PR_FALSE0},
139 { TLS_DHE_DSS_WITH_AES_256_CBC_SHA2560x006A, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
140 { TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA0x0088, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
141 { TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA0x0087, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
142 { TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA0x0016, SSL_ALLOWED1, PR_TRUE1, PR_FALSE0},
143 { TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA0x0013, SSL_ALLOWED1, PR_TRUE1, PR_FALSE0},
144 { TLS_DHE_DSS_WITH_RC4_128_SHA0x0066, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
145
146 { TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA0xC004, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
147 { TLS_ECDH_RSA_WITH_AES_128_CBC_SHA0xC00E, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
148 { TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA0xC005, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
149 { TLS_ECDH_RSA_WITH_AES_256_CBC_SHA0xC00F, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
150 { TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA0xC003, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
151 { TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA0xC00D, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
152 { TLS_ECDH_ECDSA_WITH_RC4_128_SHA0xC002, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
153 { TLS_ECDH_RSA_WITH_RC4_128_SHA0xC00C, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
154
155 /* RSA */
156 { TLS_RSA_WITH_AES_128_GCM_SHA2560x009C, SSL_ALLOWED1, PR_TRUE1, PR_FALSE0},
157 { TLS_RSA_WITH_AES_256_GCM_SHA3840x009D, SSL_ALLOWED1, PR_TRUE1, PR_FALSE0},
158 { TLS_RSA_WITH_AES_128_CBC_SHA0x002F, SSL_ALLOWED1, PR_TRUE1, PR_FALSE0},
159 { TLS_RSA_WITH_AES_128_CBC_SHA2560x003C, SSL_ALLOWED1, PR_TRUE1, PR_FALSE0},
160 { TLS_RSA_WITH_CAMELLIA_128_CBC_SHA0x0041, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
161 { TLS_RSA_WITH_AES_256_CBC_SHA0x0035, SSL_ALLOWED1, PR_TRUE1, PR_FALSE0},
162 { TLS_RSA_WITH_AES_256_CBC_SHA2560x003D, SSL_ALLOWED1, PR_TRUE1, PR_FALSE0},
163 { TLS_RSA_WITH_CAMELLIA_256_CBC_SHA0x0084, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
164 { TLS_RSA_WITH_SEED_CBC_SHA0x0096, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
165 { TLS_RSA_WITH_3DES_EDE_CBC_SHA0x000a, SSL_ALLOWED1, PR_TRUE1, PR_FALSE0},
166 { TLS_RSA_WITH_RC4_128_SHA0x0005, SSL_ALLOWED1, PR_TRUE1, PR_FALSE0},
167 { TLS_RSA_WITH_RC4_128_MD50x0004, SSL_ALLOWED1, PR_TRUE1, PR_FALSE0},
168
169 /* 56-bit DES "domestic" cipher suites */
170 { TLS_DHE_RSA_WITH_DES_CBC_SHA0x0015, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
171 { TLS_DHE_DSS_WITH_DES_CBC_SHA0x0012, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
172 { TLS_RSA_WITH_DES_CBC_SHA0x0009, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
173
174 /* ciphersuites with no encryption */
175 { TLS_ECDHE_ECDSA_WITH_NULL_SHA0xC006, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
176 { TLS_ECDHE_RSA_WITH_NULL_SHA0xC010, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
177 { TLS_ECDH_RSA_WITH_NULL_SHA0xC00B, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
178 { TLS_ECDH_ECDSA_WITH_NULL_SHA0xC001, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
179 { TLS_RSA_WITH_NULL_SHA0x0002, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
180 { TLS_RSA_WITH_NULL_SHA2560x003B, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
181 { TLS_RSA_WITH_NULL_MD50x0001, SSL_ALLOWED1, PR_FALSE0, PR_FALSE0},
182};
183/* clang-format on */
184
185/* This is the default supported set of signature schemes. The order of the
186 * hashes here is all that is important, since that will (sometimes) determine
187 * which hash we use. The key pair (i.e., cert) is the primary thing that
188 * determines what we use and this doesn't affect how we select key pairs. The
189 * order of signature types is based on the same rules for ordering we use for
190 * cipher suites just for consistency.
191 */
192static const SSLSignatureScheme defaultSignatureSchemes[] = {
193 ssl_sig_ecdsa_secp256r1_sha256,
194 ssl_sig_ecdsa_secp384r1_sha384,
195 ssl_sig_ecdsa_secp521r1_sha512,
196 ssl_sig_ecdsa_sha1,
197 ssl_sig_rsa_pss_rsae_sha256,
198 ssl_sig_rsa_pss_rsae_sha384,
199 ssl_sig_rsa_pss_rsae_sha512,
200 ssl_sig_rsa_pkcs1_sha256,
201 ssl_sig_rsa_pkcs1_sha384,
202 ssl_sig_rsa_pkcs1_sha512,
203 ssl_sig_rsa_pkcs1_sha1,
204 ssl_sig_dsa_sha256,
205 ssl_sig_dsa_sha384,
206 ssl_sig_dsa_sha512,
207 ssl_sig_dsa_sha1
208};
209PR_STATIC_ASSERT(PR_ARRAY_SIZE(defaultSignatureSchemes) <=extern void pr_static_assert(int arg[((sizeof(defaultSignatureSchemes
)/sizeof((defaultSignatureSchemes)[0])) <= 18) ? 1 : -1])
210 MAX_SIGNATURE_SCHEMES)extern void pr_static_assert(int arg[((sizeof(defaultSignatureSchemes
)/sizeof((defaultSignatureSchemes)[0])) <= 18) ? 1 : -1])
;
211
212/* Verify that SSL_ImplementedCiphers and cipherSuites are in consistent order.
213 */
214#ifdef DEBUG1
215void
216ssl3_CheckCipherSuiteOrderConsistency()
217{
218 unsigned int i;
219
220 PORT_Assert(SSL_NumImplementedCiphers == PR_ARRAY_SIZE(cipherSuites))((SSL_NumImplementedCiphers == (sizeof(cipherSuites)/sizeof((
cipherSuites)[0])))?((void)0):PR_Assert("SSL_NumImplementedCiphers == PR_ARRAY_SIZE(cipherSuites)"
,"ssl3con.c",220))
;
221
222 for (i = 0; i < PR_ARRAY_SIZE(cipherSuites)(sizeof(cipherSuites)/sizeof((cipherSuites)[0])); ++i) {
223 PORT_Assert(SSL_ImplementedCiphers[i] == cipherSuites[i].cipher_suite)((SSL_ImplementedCiphers[i] == cipherSuites[i].cipher_suite)?
((void)0):PR_Assert("SSL_ImplementedCiphers[i] == cipherSuites[i].cipher_suite"
,"ssl3con.c",223))
;
224 }
225}
226#endif
227
228static const /*SSL3ClientCertificateType */ PRUint8 certificate_types[] = {
229 ct_RSA_sign,
230 ct_ECDSA_sign,
231 ct_DSS_sign,
232};
233
234static SSL3Statistics ssl3stats;
235
236static const ssl3KEADef kea_defs[] = {
237 /* indexed by SSL3KeyExchangeAlgorithm */
238 /* kea exchKeyType signKeyType authKeyType ephemeral oid */
239 { kea_null, ssl_kea_null, nullKey, ssl_auth_null, PR_FALSE0, 0 },
240 { kea_rsa, ssl_kea_rsa, nullKey, ssl_auth_rsa_decrypt, PR_FALSE0, SEC_OID_TLS_RSA },
241 { kea_dh_dss, ssl_kea_dh, dsaKey, ssl_auth_dsa, PR_FALSE0, SEC_OID_TLS_DH_DSS },
242 { kea_dh_rsa, ssl_kea_dh, rsaKey, ssl_auth_rsa_sign, PR_FALSE0, SEC_OID_TLS_DH_RSA },
243 { kea_dhe_dss, ssl_kea_dh, dsaKey, ssl_auth_dsa, PR_TRUE1, SEC_OID_TLS_DHE_DSS },
244 { kea_dhe_rsa, ssl_kea_dh, rsaKey, ssl_auth_rsa_sign, PR_TRUE1, SEC_OID_TLS_DHE_RSA },
245 { kea_dh_anon, ssl_kea_dh, nullKey, ssl_auth_null, PR_TRUE1, SEC_OID_TLS_DH_ANON },
246 { kea_ecdh_ecdsa, ssl_kea_ecdh, nullKey, ssl_auth_ecdh_ecdsa, PR_FALSE0, SEC_OID_TLS_ECDH_ECDSA },
247 { kea_ecdhe_ecdsa, ssl_kea_ecdh, ecKey, ssl_auth_ecdsa, PR_TRUE1, SEC_OID_TLS_ECDHE_ECDSA },
248 { kea_ecdh_rsa, ssl_kea_ecdh, nullKey, ssl_auth_ecdh_rsa, PR_FALSE0, SEC_OID_TLS_ECDH_RSA },
249 { kea_ecdhe_rsa, ssl_kea_ecdh, rsaKey, ssl_auth_rsa_sign, PR_TRUE1, SEC_OID_TLS_ECDHE_RSA },
250 { kea_ecdh_anon, ssl_kea_ecdh, nullKey, ssl_auth_null, PR_TRUE1, SEC_OID_TLS_ECDH_ANON },
251 { kea_ecdhe_psk, ssl_kea_ecdh_psk, nullKey, ssl_auth_psk, PR_TRUE1, SEC_OID_TLS_ECDHE_PSK },
252 { kea_dhe_psk, ssl_kea_dh_psk, nullKey, ssl_auth_psk, PR_TRUE1, SEC_OID_TLS_DHE_PSK },
253 { kea_tls13_any, ssl_kea_tls13_any, nullKey, ssl_auth_tls13_any, PR_TRUE1, SEC_OID_TLS13_KEA_ANY },
254};
255
256/* must use ssl_LookupCipherSuiteDef to access */
257static const ssl3CipherSuiteDef cipher_suite_defs[] = {
258 /* cipher_suite bulk_cipher_alg mac_alg key_exchange_alg prf_hash */
259 /* Note that the prf_hash_alg is the hash function used by the PRF, see sslimpl.h. */
260
261 { TLS_NULL_WITH_NULL_NULL0x0000, cipher_null, ssl_mac_null, kea_null, ssl_hash_none },
262 { TLS_RSA_WITH_NULL_MD50x0001, cipher_null, ssl_mac_md5, kea_rsa, ssl_hash_none },
263 { TLS_RSA_WITH_NULL_SHA0x0002, cipher_null, ssl_mac_sha, kea_rsa, ssl_hash_none },
264 { TLS_RSA_WITH_NULL_SHA2560x003B, cipher_null, ssl_hmac_sha256, kea_rsa, ssl_hash_sha256 },
265 { TLS_RSA_WITH_RC4_128_MD50x0004, cipher_rc4, ssl_mac_md5, kea_rsa, ssl_hash_none },
266 { TLS_RSA_WITH_RC4_128_SHA0x0005, cipher_rc4, ssl_mac_sha, kea_rsa, ssl_hash_none },
267 { TLS_RSA_WITH_DES_CBC_SHA0x0009, cipher_des, ssl_mac_sha, kea_rsa, ssl_hash_none },
268 { TLS_RSA_WITH_3DES_EDE_CBC_SHA0x000a, cipher_3des, ssl_mac_sha, kea_rsa, ssl_hash_none },
269 { TLS_DHE_DSS_WITH_DES_CBC_SHA0x0012, cipher_des, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
270 { TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA0x0013,
271 cipher_3des, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
272 { TLS_DHE_DSS_WITH_RC4_128_SHA0x0066, cipher_rc4, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
273 { TLS_DHE_RSA_WITH_DES_CBC_SHA0x0015, cipher_des, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
274 { TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA0x0016,
275 cipher_3des, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
276
277 /* New TLS cipher suites */
278 { TLS_RSA_WITH_AES_128_CBC_SHA0x002F, cipher_aes_128, ssl_mac_sha, kea_rsa, ssl_hash_none },
279 { TLS_RSA_WITH_AES_128_CBC_SHA2560x003C, cipher_aes_128, ssl_hmac_sha256, kea_rsa, ssl_hash_sha256 },
280 { TLS_DHE_DSS_WITH_AES_128_CBC_SHA0x0032, cipher_aes_128, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
281 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA0x0033, cipher_aes_128, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
282 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA2560x0067, cipher_aes_128, ssl_hmac_sha256, kea_dhe_rsa, ssl_hash_sha256 },
283 { TLS_RSA_WITH_AES_256_CBC_SHA0x0035, cipher_aes_256, ssl_mac_sha, kea_rsa, ssl_hash_none },
284 { TLS_RSA_WITH_AES_256_CBC_SHA2560x003D, cipher_aes_256, ssl_hmac_sha256, kea_rsa, ssl_hash_sha256 },
285 { TLS_DHE_DSS_WITH_AES_256_CBC_SHA0x0038, cipher_aes_256, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
286 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA0x0039, cipher_aes_256, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
287 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA2560x006B, cipher_aes_256, ssl_hmac_sha256, kea_dhe_rsa, ssl_hash_sha256 },
288 { TLS_DHE_RSA_WITH_AES_256_GCM_SHA3840x009F, cipher_aes_256_gcm, ssl_mac_aead, kea_dhe_rsa, ssl_hash_sha384 },
289
290 { TLS_RSA_WITH_SEED_CBC_SHA0x0096, cipher_seed, ssl_mac_sha, kea_rsa, ssl_hash_none },
291
292 { TLS_RSA_WITH_CAMELLIA_128_CBC_SHA0x0041, cipher_camellia_128, ssl_mac_sha, kea_rsa, ssl_hash_none },
293 { TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA0x0044,
294 cipher_camellia_128, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
295 { TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA0x0045,
296 cipher_camellia_128, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
297 { TLS_RSA_WITH_CAMELLIA_256_CBC_SHA0x0084, cipher_camellia_256, ssl_mac_sha, kea_rsa, ssl_hash_none },
298 { TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA0x0087,
299 cipher_camellia_256, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
300 { TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA0x0088,
301 cipher_camellia_256, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
302
303 { TLS_DHE_RSA_WITH_AES_128_GCM_SHA2560x009E, cipher_aes_128_gcm, ssl_mac_aead, kea_dhe_rsa, ssl_hash_sha256 },
304 { TLS_RSA_WITH_AES_128_GCM_SHA2560x009C, cipher_aes_128_gcm, ssl_mac_aead, kea_rsa, ssl_hash_sha256 },
305
306 { TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA2560xC02F, cipher_aes_128_gcm, ssl_mac_aead, kea_ecdhe_rsa, ssl_hash_sha256 },
307 { TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA2560xC02B, cipher_aes_128_gcm, ssl_mac_aead, kea_ecdhe_ecdsa, ssl_hash_sha256 },
308 { TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA3840xC02C, cipher_aes_256_gcm, ssl_mac_aead, kea_ecdhe_ecdsa, ssl_hash_sha384 },
309 { TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA3840xC030, cipher_aes_256_gcm, ssl_mac_aead, kea_ecdhe_rsa, ssl_hash_sha384 },
310 { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA3840xC024, cipher_aes_256, ssl_hmac_sha384, kea_ecdhe_ecdsa, ssl_hash_sha384 },
311 { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA3840xC028, cipher_aes_256, ssl_hmac_sha384, kea_ecdhe_rsa, ssl_hash_sha384 },
312 { TLS_DHE_DSS_WITH_AES_128_GCM_SHA2560x00A2, cipher_aes_128_gcm, ssl_mac_aead, kea_dhe_dss, ssl_hash_sha256 },
313 { TLS_DHE_DSS_WITH_AES_128_CBC_SHA2560x0040, cipher_aes_128, ssl_hmac_sha256, kea_dhe_dss, ssl_hash_sha256 },
314 { TLS_DHE_DSS_WITH_AES_256_CBC_SHA2560x006A, cipher_aes_256, ssl_hmac_sha256, kea_dhe_dss, ssl_hash_sha256 },
315 { TLS_DHE_DSS_WITH_AES_256_GCM_SHA3840x00A3, cipher_aes_256_gcm, ssl_mac_aead, kea_dhe_dss, ssl_hash_sha384 },
316 { TLS_RSA_WITH_AES_256_GCM_SHA3840x009D, cipher_aes_256_gcm, ssl_mac_aead, kea_rsa, ssl_hash_sha384 },
317
318 { TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA2560xCCAA, cipher_chacha20, ssl_mac_aead, kea_dhe_rsa, ssl_hash_sha256 },
319
320 { TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA2560xCCA8, cipher_chacha20, ssl_mac_aead, kea_ecdhe_rsa, ssl_hash_sha256 },
321 { TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA2560xCCA9, cipher_chacha20, ssl_mac_aead, kea_ecdhe_ecdsa, ssl_hash_sha256 },
322
323 { TLS_ECDH_ECDSA_WITH_NULL_SHA0xC001, cipher_null, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
324 { TLS_ECDH_ECDSA_WITH_RC4_128_SHA0xC002, cipher_rc4, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
325 { TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA0xC003, cipher_3des, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
326 { TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA0xC004, cipher_aes_128, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
327 { TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA0xC005, cipher_aes_256, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
328
329 { TLS_ECDHE_ECDSA_WITH_NULL_SHA0xC006, cipher_null, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
330 { TLS_ECDHE_ECDSA_WITH_RC4_128_SHA0xC007, cipher_rc4, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
331 { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA0xC008, cipher_3des, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
332 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA0xC009, cipher_aes_128, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
333 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA2560xC023, cipher_aes_128, ssl_hmac_sha256, kea_ecdhe_ecdsa, ssl_hash_sha256 },
334 { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA0xC00A, cipher_aes_256, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
335
336 { TLS_ECDH_RSA_WITH_NULL_SHA0xC00B, cipher_null, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
337 { TLS_ECDH_RSA_WITH_RC4_128_SHA0xC00C, cipher_rc4, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
338 { TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA0xC00D, cipher_3des, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
339 { TLS_ECDH_RSA_WITH_AES_128_CBC_SHA0xC00E, cipher_aes_128, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
340 { TLS_ECDH_RSA_WITH_AES_256_CBC_SHA0xC00F, cipher_aes_256, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
341
342 { TLS_ECDHE_RSA_WITH_NULL_SHA0xC010, cipher_null, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
343 { TLS_ECDHE_RSA_WITH_RC4_128_SHA0xC011, cipher_rc4, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
344 { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA0xC012, cipher_3des, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
345 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA0xC013, cipher_aes_128, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
346 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA2560xC027, cipher_aes_128, ssl_hmac_sha256, kea_ecdhe_rsa, ssl_hash_sha256 },
347 { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA0xC014, cipher_aes_256, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
348
349 { TLS_AES_128_GCM_SHA2560x1301, cipher_aes_128_gcm, ssl_mac_aead, kea_tls13_any, ssl_hash_sha256 },
350 { TLS_CHACHA20_POLY1305_SHA2560x1303, cipher_chacha20, ssl_mac_aead, kea_tls13_any, ssl_hash_sha256 },
351 { TLS_AES_256_GCM_SHA3840x1302, cipher_aes_256_gcm, ssl_mac_aead, kea_tls13_any, ssl_hash_sha384 },
352};
353
354static const CK_MECHANISM_TYPE auth_alg_defs[] = {
355 CKM_INVALID_MECHANISM0xffffffffUL, /* ssl_auth_null */
356 CKM_RSA_PKCS0x00000001UL, /* ssl_auth_rsa_decrypt */
357 CKM_DSA0x00000011UL, /* ? _SHA1 */ /* ssl_auth_dsa */
358 CKM_INVALID_MECHANISM0xffffffffUL, /* ssl_auth_kea (unused) */
359 CKM_ECDSA0x00001041UL, /* ssl_auth_ecdsa */
360 CKM_ECDH1_DERIVE0x00001050UL, /* ssl_auth_ecdh_rsa */
361 CKM_ECDH1_DERIVE0x00001050UL, /* ssl_auth_ecdh_ecdsa */
362 CKM_RSA_PKCS0x00000001UL, /* ssl_auth_rsa_sign */
363 CKM_RSA_PKCS_PSS0x0000000DUL, /* ssl_auth_rsa_pss */
364 CKM_NSS_HKDF_SHA256((0x80000000UL | 0x4E534350) + 4), /* ssl_auth_psk (just check for HKDF) */
365 CKM_INVALID_MECHANISM0xffffffffUL /* ssl_auth_tls13_any */
366};
367PR_STATIC_ASSERT(PR_ARRAY_SIZE(auth_alg_defs) == ssl_auth_size)extern void pr_static_assert(int arg[((sizeof(auth_alg_defs)/
sizeof((auth_alg_defs)[0])) == ssl_auth_size) ? 1 : -1])
;
368
369static const CK_MECHANISM_TYPE kea_alg_defs[] = {
370 CKM_INVALID_MECHANISM0xffffffffUL, /* ssl_kea_null */
371 CKM_RSA_PKCS0x00000001UL, /* ssl_kea_rsa */
372 CKM_DH_PKCS_DERIVE0x00000021UL, /* ssl_kea_dh */
373 CKM_INVALID_MECHANISM0xffffffffUL, /* ssl_kea_fortezza (unused) */
374 CKM_ECDH1_DERIVE0x00001050UL, /* ssl_kea_ecdh */
375 CKM_ECDH1_DERIVE0x00001050UL, /* ssl_kea_ecdh_psk */
376 CKM_DH_PKCS_DERIVE0x00000021UL, /* ssl_kea_dh_psk */
377 CKM_INVALID_MECHANISM0xffffffffUL, /* ssl_kea_tls13_any */
378 CKM_INVALID_MECHANISM0xffffffffUL, /* ssl_kea_ecdh_hybrid */
379 CKM_INVALID_MECHANISM0xffffffffUL, /* ssl_kea_ecdh_hybrid_psk */
380};
381PR_STATIC_ASSERT(PR_ARRAY_SIZE(kea_alg_defs) == ssl_kea_size)extern void pr_static_assert(int arg[((sizeof(kea_alg_defs)/sizeof
((kea_alg_defs)[0])) == ssl_kea_size) ? 1 : -1])
;
382
383typedef struct SSLCipher2MechStr {
384 SSLCipherAlgorithm calg;
385 CK_MECHANISM_TYPE cmech;
386} SSLCipher2Mech;
387
388/* indexed by type SSLCipherAlgorithm */
389static const SSLCipher2Mech alg2Mech[] = {
390 /* calg, cmech */
391 { ssl_calg_null, CKM_INVALID_MECHANISM0xffffffffUL },
392 { ssl_calg_rc4, CKM_RC40x00000111UL },
393 { ssl_calg_rc2, CKM_RC2_CBC0x00000102UL },
394 { ssl_calg_des, CKM_DES_CBC0x00000122UL },
395 { ssl_calg_3des, CKM_DES3_CBC0x00000133UL },
396 { ssl_calg_idea, CKM_IDEA_CBC0x00000342UL },
397 { ssl_calg_fortezza, CKM_SKIPJACK_CBC640x00001002UL },
398 { ssl_calg_aes, CKM_AES_CBC0x00001082UL },
399 { ssl_calg_camellia, CKM_CAMELLIA_CBC0x00000552UL },
400 { ssl_calg_seed, CKM_SEED_CBC0x00000652UL },
401 { ssl_calg_aes_gcm, CKM_AES_GCM0x00001087UL },
402 { ssl_calg_chacha20, CKM_CHACHA20_POLY13050x00004021UL },
403};
404
405const PRUint8 tls12_downgrade_random[] = { 0x44, 0x4F, 0x57, 0x4E,
406 0x47, 0x52, 0x44, 0x01 };
407const PRUint8 tls1_downgrade_random[] = { 0x44, 0x4F, 0x57, 0x4E,
408 0x47, 0x52, 0x44, 0x00 };
409PR_STATIC_ASSERT(sizeof(tls12_downgrade_random) ==extern void pr_static_assert(int arg[(sizeof(tls12_downgrade_random
) == sizeof(tls1_downgrade_random)) ? 1 : -1])
410 sizeof(tls1_downgrade_random))extern void pr_static_assert(int arg[(sizeof(tls12_downgrade_random
) == sizeof(tls1_downgrade_random)) ? 1 : -1])
;
411
412/* The ECCWrappedKeyInfo structure defines how various pieces of
413 * information are laid out within wrappedSymmetricWrappingkey
414 * for ECDH key exchange. Since wrappedSymmetricWrappingkey is
415 * a 512-byte buffer (see sslimpl.h), the variable length field
416 * in ECCWrappedKeyInfo can be at most (512 - 8) = 504 bytes.
417 *
418 * XXX For now, NSS only supports named elliptic curves of size 571 bits
419 * or smaller. The public value will fit within 145 bytes and EC params
420 * will fit within 12 bytes. We'll need to revisit this when NSS
421 * supports arbitrary curves.
422 */
423#define MAX_EC_WRAPPED_KEY_BUFLEN504 504
424
425typedef struct ECCWrappedKeyInfoStr {
426 PRUint16 size; /* EC public key size in bits */
427 PRUint16 encodedParamLen; /* length (in bytes) of DER encoded EC params */
428 PRUint16 pubValueLen; /* length (in bytes) of EC public value */
429 PRUint16 wrappedKeyLen; /* length (in bytes) of the wrapped key */
430 PRUint8 var[MAX_EC_WRAPPED_KEY_BUFLEN504]; /* this buffer contains the */
431 /* EC public-key params, the EC public value and the wrapped key */
432} ECCWrappedKeyInfo;
433
434CK_MECHANISM_TYPE
435ssl3_Alg2Mech(SSLCipherAlgorithm calg)
436{
437 PORT_Assert(alg2Mech[calg].calg == calg)((alg2Mech[calg].calg == calg)?((void)0):PR_Assert("alg2Mech[calg].calg == calg"
,"ssl3con.c",437))
;
438 return alg2Mech[calg].cmech;
439}
440
441#if defined(TRACE)
442
443static char *
444ssl3_DecodeHandshakeType(int msgType)
445{
446 char *rv;
447 static char line[40];
448
449 switch (msgType) {
450 case ssl_hs_hello_request:
451 rv = "hello_request (0)";
452 break;
453 case ssl_hs_client_hello:
454 rv = "client_hello (1)";
455 break;
456 case ssl_hs_server_hello:
457 rv = "server_hello (2)";
458 break;
459 case ssl_hs_hello_verify_request:
460 rv = "hello_verify_request (3)";
461 break;
462 case ssl_hs_new_session_ticket:
463 rv = "new_session_ticket (4)";
464 break;
465 case ssl_hs_end_of_early_data:
466 rv = "end_of_early_data (5)";
467 break;
468 case ssl_hs_hello_retry_request:
469 rv = "hello_retry_request (6)";
470 break;
471 case ssl_hs_encrypted_extensions:
472 rv = "encrypted_extensions (8)";
473 break;
474 case ssl_hs_certificate:
475 rv = "certificate (11)";
476 break;
477 case ssl_hs_server_key_exchange:
478 rv = "server_key_exchange (12)";
479 break;
480 case ssl_hs_certificate_request:
481 rv = "certificate_request (13)";
482 break;
483 case ssl_hs_server_hello_done:
484 rv = "server_hello_done (14)";
485 break;
486 case ssl_hs_certificate_verify:
487 rv = "certificate_verify (15)";
488 break;
489 case ssl_hs_client_key_exchange:
490 rv = "client_key_exchange (16)";
491 break;
492 case ssl_hs_finished:
493 rv = "finished (20)";
494 break;
495 case ssl_hs_certificate_status:
496 rv = "certificate_status (22)";
497 break;
498 case ssl_hs_key_update:
499 rv = "key_update (24)";
500 break;
501 case ssl_hs_compressed_certificate:
502 rv = "compressed certificate (25)";
503 break;
504 default:
505 snprintf(line, sizeof(line), "*UNKNOWN* handshake type! (%d)", msgType);
506 rv = line;
507 }
508 return rv;
509}
510
511static char *
512ssl3_DecodeContentType(int msgType)
513{
514 char *rv;
515 static char line[40];
516
517 switch (msgType) {
518 case ssl_ct_change_cipher_spec:
519 rv = "change_cipher_spec (20)";
520 break;
521 case ssl_ct_alert:
522 rv = "alert (21)";
523 break;
524 case ssl_ct_handshake:
525 rv = "handshake (22)";
526 break;
527 case ssl_ct_application_data:
528 rv = "application_data (23)";
529 break;
530 case ssl_ct_ack:
531 rv = "ack (26)";
532 break;
533 default:
534 snprintf(line, sizeof(line), "*UNKNOWN* record type! (%d)", msgType);
535 rv = line;
536 }
537 return rv;
538}
539
540#endif
541
542SSL3Statistics *
543SSL_GetStatistics(void)
544{
545 return &ssl3stats;
546}
547
548typedef struct tooLongStr {
549#if defined(IS_LITTLE_ENDIAN1)
550 PRInt32 low;
551 PRInt32 high;
552#else
553 PRInt32 high;
554 PRInt32 low;
555#endif
556} tooLong;
557
558void
559SSL_AtomicIncrementLong(long *x)
560{
561 if ((sizeof *x) == sizeof(PRInt32)) {
562 PR_ATOMIC_INCREMENT((PRInt32 *)x)__sync_add_and_fetch((PRInt32 *)x, 1);
563 } else {
564 tooLong *tl = (tooLong *)x;
565 if (PR_ATOMIC_INCREMENT(&tl->low)__sync_add_and_fetch(&tl->low, 1) == 0)
566 PR_ATOMIC_INCREMENT(&tl->high)__sync_add_and_fetch(&tl->high, 1);
567 }
568}
569
570PRBool
571ssl3_CipherSuiteAllowedForVersionRange(ssl3CipherSuite cipherSuite,
572 const SSLVersionRange *vrange)
573{
574 switch (cipherSuite) {
575 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA2560x006B:
576 case TLS_RSA_WITH_AES_256_CBC_SHA2560x003D:
577 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA2560xC023:
578 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA3840xC024:
579 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA2560xC027:
580 case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA3840xC028:
581 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA2560x0067:
582 case TLS_RSA_WITH_AES_128_CBC_SHA2560x003C:
583 case TLS_RSA_WITH_AES_128_GCM_SHA2560x009C:
584 case TLS_RSA_WITH_AES_256_GCM_SHA3840x009D:
585 case TLS_DHE_DSS_WITH_AES_128_CBC_SHA2560x0040:
586 case TLS_DHE_DSS_WITH_AES_256_CBC_SHA2560x006A:
587 case TLS_RSA_WITH_NULL_SHA2560x003B:
588 case TLS_DHE_DSS_WITH_AES_128_GCM_SHA2560x00A2:
589 case TLS_DHE_DSS_WITH_AES_256_GCM_SHA3840x00A3:
590 case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA2560xC02B:
591 case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA3840xC02C:
592 case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA2560xC02F:
593 case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA3840xC030:
594 case TLS_DHE_RSA_WITH_AES_128_GCM_SHA2560x009E:
595 case TLS_DHE_RSA_WITH_AES_256_GCM_SHA3840x009F:
596 case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA2560xCCA9:
597 case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA2560xCCA8:
598 case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA2560xCCAA:
599 return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_20x0303 &&
600 vrange->min < SSL_LIBRARY_VERSION_TLS_1_30x0304;
601
602 /* RFC 4492: ECC cipher suites need TLS extensions to negotiate curves and
603 * point formats.*/
604 case TLS_ECDH_ECDSA_WITH_NULL_SHA0xC001:
605 case TLS_ECDH_ECDSA_WITH_RC4_128_SHA0xC002:
606 case TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA0xC003:
607 case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA0xC004:
608 case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA0xC005:
609 case TLS_ECDHE_ECDSA_WITH_NULL_SHA0xC006:
610 case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA0xC007:
611 case TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA0xC008:
612 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA0xC009:
613 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA0xC00A:
614 case TLS_ECDH_RSA_WITH_NULL_SHA0xC00B:
615 case TLS_ECDH_RSA_WITH_RC4_128_SHA0xC00C:
616 case TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA0xC00D:
617 case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA0xC00E:
618 case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA0xC00F:
619 case TLS_ECDHE_RSA_WITH_NULL_SHA0xC010:
620 case TLS_ECDHE_RSA_WITH_RC4_128_SHA0xC011:
621 case TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA0xC012:
622 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA0xC013:
623 case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA0xC014:
624 return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_00x0301 &&
625 vrange->min < SSL_LIBRARY_VERSION_TLS_1_30x0304;
626
627 case TLS_AES_128_GCM_SHA2560x1301:
628 case TLS_AES_256_GCM_SHA3840x1302:
629 case TLS_CHACHA20_POLY1305_SHA2560x1303:
630 return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_30x0304;
631
632 default:
633 return vrange->min < SSL_LIBRARY_VERSION_TLS_1_30x0304;
634 }
635}
636
637/* return pointer to ssl3CipherSuiteDef for suite, or NULL */
638/* XXX This does a linear search. A binary search would be better. */
639const ssl3CipherSuiteDef *
640ssl_LookupCipherSuiteDef(ssl3CipherSuite suite)
641{
642 int cipher_suite_def_len =
643 sizeof(cipher_suite_defs) / sizeof(cipher_suite_defs[0]);
644 int i;
645
646 for (i = 0; i < cipher_suite_def_len; i++) {
647 if (cipher_suite_defs[i].cipher_suite == suite)
648 return &cipher_suite_defs[i];
649 }
650 PORT_Assert(PR_FALSE)((0)?((void)0):PR_Assert("PR_FALSE","ssl3con.c",650)); /* We should never get here. */
651 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
652 return NULL((void*)0);
653}
654
655/* Find the cipher configuration struct associate with suite */
656/* XXX This does a linear search. A binary search would be better. */
657static ssl3CipherSuiteCfg *
658ssl_LookupCipherSuiteCfgMutable(ssl3CipherSuite suite,
659 ssl3CipherSuiteCfg *suites)
660{
661 int i;
662
663 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED71; i++) {
664 if (suites[i].cipher_suite == suite)
665 return &suites[i];
666 }
667 /* return NULL and let the caller handle it. */
668 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
669 return NULL((void*)0);
670}
671
672const ssl3CipherSuiteCfg *
673ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite, const ssl3CipherSuiteCfg *suites)
674{
675 return ssl_LookupCipherSuiteCfgMutable(suite,
676 CONST_CAST(ssl3CipherSuiteCfg, suites)((ssl3CipherSuiteCfg *)(suites)));
677}
678
679static PRBool
680ssl_NamedGroupTypeEnabled(const sslSocket *ss, SSLKEAType keaType)
681{
682 unsigned int i;
683 for (i = 0; i < SSL_NAMED_GROUP_COUNT32; ++i) {
684 if (ss->namedGroupPreferences[i] &&
685 ss->namedGroupPreferences[i]->keaType == keaType) {
686 return PR_TRUE1;
687 }
688 }
689 return PR_FALSE0;
690}
691
692static PRBool
693ssl_KEAEnabled(const sslSocket *ss, SSLKEAType keaType)
694{
695 switch (keaType) {
696 case ssl_kea_rsa:
697 return PR_TRUE1;
698
699 case ssl_kea_dh:
700 case ssl_kea_dh_psk: {
701 if (ss->sec.isServer && !ss->opt.enableServerDhe) {
702 return PR_FALSE0;
703 }
704
705 if (ss->sec.isServer) {
706 /* If the server requires named FFDHE groups, then the client
707 * must have included an FFDHE group. peerSupportsFfdheGroups
708 * is set to true in ssl_HandleSupportedGroupsXtn(). */
709 if (ss->opt.requireDHENamedGroups &&
710 !ss->xtnData.peerSupportsFfdheGroups) {
711 return PR_FALSE0;
712 }
713
714 /* We can use the weak DH group if all of these are true:
715 * 1. We don't require named groups.
716 * 2. The peer doesn't support named groups.
717 * 3. This isn't TLS 1.3.
718 * 4. The weak group is enabled. */
719 if (!ss->opt.requireDHENamedGroups &&
720 !ss->xtnData.peerSupportsFfdheGroups &&
721 ss->version < SSL_LIBRARY_VERSION_TLS_1_30x0304 &&
722 ss->ssl3.dheWeakGroupEnabled) {
723 return PR_TRUE1;
724 }
725 } else {
726 if (ss->vrange.min < SSL_LIBRARY_VERSION_TLS_1_30x0304 &&
727 !ss->opt.requireDHENamedGroups) {
728 /* The client enables DHE cipher suites even if no DHE groups
729 * are enabled. Only if this isn't TLS 1.3 and named groups
730 * are not required. */
731 return PR_TRUE1;
732 }
733 }
734 return ssl_NamedGroupTypeEnabled(ss, ssl_kea_dh);
735 }
736
737 case ssl_kea_ecdh:
738 case ssl_kea_ecdh_psk:
739 return ssl_NamedGroupTypeEnabled(ss, ssl_kea_ecdh);
740
741 case ssl_kea_ecdh_hybrid:
742 case ssl_kea_ecdh_hybrid_psk:
743 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_30x0304) {
744 return PR_FALSE0;
745 }
746 return ssl_NamedGroupTypeEnabled(ss, ssl_kea_ecdh_hybrid);
747
748 case ssl_kea_tls13_any:
749 return PR_TRUE1;
750
751 case ssl_kea_fortezza:
752 default:
753 PORT_Assert(0)((0)?((void)0):PR_Assert("0","ssl3con.c",753));
754 }
755 return PR_FALSE0;
756}
757
758static PRBool
759ssl_HasCert(const sslSocket *ss, PRUint16 maxVersion, SSLAuthType authType)
760{
761 PRCList *cursor;
762 if (authType == ssl_auth_null || authType == ssl_auth_psk || authType == ssl_auth_tls13_any) {
763 return PR_TRUE1;
764 }
765 for (cursor = PR_NEXT_LINK(&ss->serverCerts)((&ss->serverCerts)->next);
766 cursor != &ss->serverCerts;
767 cursor = PR_NEXT_LINK(cursor)((cursor)->next)) {
768 sslServerCert *cert = (sslServerCert *)cursor;
769 if (!cert->serverKeyPair ||
770 !cert->serverKeyPair->privKey ||
771 !cert->serverCertChain ||
772 !SSL_CERT_IS(cert, authType)((cert)->authTypes & (1 << (authType)))) {
773 continue;
774 }
775 /* When called from ssl3_config_match_init(), all the EC curves will be
776 * enabled, so this will essentially do nothing (unless we implement
777 * curve configuration). However, once we have seen the
778 * supported_groups extension and this is called from config_match(),
779 * this will filter out certificates with an unsupported curve.
780 *
781 * If we might negotiate TLS 1.3, skip this test as group configuration
782 * doesn't affect choices in TLS 1.3.
783 */
784 if (maxVersion < SSL_LIBRARY_VERSION_TLS_1_30x0304 &&
785 (authType == ssl_auth_ecdsa ||
786 authType == ssl_auth_ecdh_ecdsa ||
787 authType == ssl_auth_ecdh_rsa) &&
788 !ssl_NamedGroupEnabled(ss, cert->namedCurve)) {
789 continue;
790 }
791 return PR_TRUE1;
792 }
793 if (authType == ssl_auth_rsa_sign) {
794 return ssl_HasCert(ss, maxVersion, ssl_auth_rsa_pss);
795 }
796 return PR_FALSE0;
797}
798
799/* return true if the scheme is allowed by policy, This prevents
800 * failures later when our actual signatures are rejected by
801 * policy by either ssl code, or lower level NSS code */
802static PRBool
803ssl_SchemePolicyOK(SSLSignatureScheme scheme, PRUint32 require)
804{
805 /* Hash policy. */
806 PRUint32 policy;
807 SECOidTag hashOID = ssl3_HashTypeToOID(ssl_SignatureSchemeToHashType(scheme));
808 SECOidTag sigOID;
809
810 /* policy bits needed to enable a SignatureScheme */
811 SECStatus rv = NSS_GetAlgorithmPolicy(hashOID, &policy);
812 if (rv == SECSuccess &&
813 (policy & require) != require) {
814 return PR_FALSE0;
815 }
816
817 /* ssl_SignatureSchemeToAuthType reports rsa for rsa_pss_rsae, but we
818 * actually implement pss signatures when we sign, so just use RSA_PSS
819 * for all RSA PSS Siganture schemes */
820 if (ssl_IsRsaPssSignatureScheme(scheme)) {
821 sigOID = SEC_OID_PKCS1_RSA_PSS_SIGNATURE;
822 } else {
823 sigOID = ssl3_AuthTypeToOID(ssl_SignatureSchemeToAuthType(scheme));
824 }
825 /* Signature Policy. */
826 rv = NSS_GetAlgorithmPolicy(sigOID, &policy);
827 if (rv == SECSuccess &&
828 (policy & require) != require) {
829 return PR_FALSE0;
830 }
831 return PR_TRUE1;
832}
833
834/* Check that a signature scheme is accepted.
835 * Both by policy and by having a token that supports it. */
836static PRBool
837ssl_SignatureSchemeAccepted(PRUint16 minVersion,
838 SSLSignatureScheme scheme,
839 PRBool forCert)
840{
841 /* Disable RSA-PSS schemes if there are no tokens to verify them. */
842 if (ssl_IsRsaPssSignatureScheme(scheme)) {
843 if (!PK11_TokenExists(auth_alg_defs[ssl_auth_rsa_pss])) {
844 return PR_FALSE0;
845 }
846 } else if (!forCert && ssl_IsRsaPkcs1SignatureScheme(scheme)) {
847 /* Disable PKCS#1 signatures if we are limited to TLS 1.3.
848 * We still need to advertise PKCS#1 signatures in CH and CR
849 * for certificate signatures.
850 */
851 if (minVersion >= SSL_LIBRARY_VERSION_TLS_1_30x0304) {
852 return PR_FALSE0;
853 }
854 } else if (ssl_IsDsaSignatureScheme(scheme)) {
855 /* DSA: not in TLS 1.3, and check policy. */
856 if (minVersion >= SSL_LIBRARY_VERSION_TLS_1_30x0304) {
857 return PR_FALSE0;
858 }
859 }
860
861 return ssl_SchemePolicyOK(scheme, kSSLSigSchemePolicy);
862}
863
864static SECStatus
865ssl_CheckSignatureSchemes(sslSocket *ss)
866{
867 if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_20x0303) {
868 return SECSuccess;
869 }
870
871 /* If this is a server using TLS 1.3, we just need to have one signature
872 * scheme for which we have a usable certificate.
873 *
874 * Note: Certificates for earlier TLS versions are checked along with the
875 * cipher suite in ssl3_config_match_init. */
876 if (ss->sec.isServer && ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_30x0304) {
877 PRBool foundCert = PR_FALSE0;
878 for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
879 SSLAuthType authType =
880 ssl_SignatureSchemeToAuthType(ss->ssl3.signatureSchemes[i]);
881 if (ssl_HasCert(ss, ss->vrange.max, authType)) {
882 foundCert = PR_TRUE1;
883 break;
884 }
885 }
886 if (!foundCert) {
887 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM);
888 return SECFailure;
889 }
890 }
891
892 /* Ensure that there is a signature scheme that can be accepted.*/
893 for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
894 if (ssl_SignatureSchemeAccepted(ss->vrange.min,
895 ss->ssl3.signatureSchemes[i],
896 PR_FALSE0 /* forCert */)) {
897 return SECSuccess;
898 }
899 }
900 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM);
901 return SECFailure;
902}
903
904/* For a server, check that a signature scheme that can be used with the
905 * provided authType is both enabled and usable. */
906static PRBool
907ssl_HasSignatureScheme(const sslSocket *ss, SSLAuthType authType)
908{
909 PORT_Assert(ss->sec.isServer)((ss->sec.isServer)?((void)0):PR_Assert("ss->sec.isServer"
,"ssl3con.c",909))
;
910 PORT_Assert(ss->ssl3.hs.preliminaryInfo & ssl_preinfo_version)((ss->ssl3.hs.preliminaryInfo & (1U << 0))?((void
)0):PR_Assert("ss->ssl3.hs.preliminaryInfo & ssl_preinfo_version"
,"ssl3con.c",910))
;
911 PORT_Assert(authType != ssl_auth_null)((authType != ssl_auth_null)?((void)0):PR_Assert("authType != ssl_auth_null"
,"ssl3con.c",911))
;
912 PORT_Assert(authType != ssl_auth_tls13_any)((authType != ssl_auth_tls13_any)?((void)0):PR_Assert("authType != ssl_auth_tls13_any"
,"ssl3con.c",912))
;
913 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_20x0303 ||
914 authType == ssl_auth_rsa_decrypt ||
915 authType == ssl_auth_ecdh_rsa ||
916 authType == ssl_auth_ecdh_ecdsa) {
917 return PR_TRUE1;
918 }
919 for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
920 SSLSignatureScheme scheme = ss->ssl3.signatureSchemes[i];
921 SSLAuthType schemeAuthType = ssl_SignatureSchemeToAuthType(scheme);
922 PRBool acceptable = authType == schemeAuthType ||
923 (schemeAuthType == ssl_auth_rsa_pss &&
924 authType == ssl_auth_rsa_sign);
925 if (acceptable && ssl_SignatureSchemeAccepted(ss->version, scheme, PR_FALSE0 /* forCert */)) {
926 return PR_TRUE1;
927 }
928 }
929 return PR_FALSE0;
930}
931
932/* Initialize the suite->isPresent value for config_match
933 * Returns count of enabled ciphers supported by extant tokens,
934 * regardless of policy or user preference.
935 * If this returns zero, the user cannot do SSL v3.
936 */
937unsigned int
938ssl3_config_match_init(sslSocket *ss)
939{
940 ssl3CipherSuiteCfg *suite;
941 const ssl3CipherSuiteDef *cipher_def;
942 SSLCipherAlgorithm cipher_alg;
943 CK_MECHANISM_TYPE cipher_mech;
944 SSLAuthType authType;
945 SSLKEAType keaType;
946 unsigned int i;
947 unsigned int numPresent = 0;
948 unsigned int numEnabled = 0;
949
950 PORT_Assert(ss)((ss)?((void)0):PR_Assert("ss","ssl3con.c",950));
951 if (!ss) {
952 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
953 return 0;
954 }
955 if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)((&ss->vrange)->min == 0)) {
956 return 0;
957 }
958 if (ss->sec.isServer && ss->psk &&
959 PR_CLIST_IS_EMPTY(&ss->serverCerts)((&ss->serverCerts)->next == (&ss->serverCerts
))
&&
960 (ss->opt.requestCertificate || ss->opt.requireCertificate)) {
961 /* PSK and certificate auth cannot be combined. */
962 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_NO_CERTIFICATE);
963 return 0;
964 }
965 if (ssl_CheckSignatureSchemes(ss) != SECSuccess) {
966 return 0; /* Code already set. */
967 }
968
969 ssl_FilterSupportedGroups(ss);
970 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED71; i++) {
971 suite = &ss->cipherSuites[i];
972 if (suite->enabled) {
973 ++numEnabled;
974 /* We need the cipher defs to see if we have a token that can handle
975 * this cipher. It isn't part of the static definition.
976 */
977 cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite);
978 if (!cipher_def) {
979 suite->isPresent = PR_FALSE0;
980 continue;
981 }
982 cipher_alg = ssl_GetBulkCipherDef(cipher_def)->calg;
983 cipher_mech = ssl3_Alg2Mech(cipher_alg);
984
985 /* Mark the suites that are backed by real tokens, certs and keys */
986 suite->isPresent = PR_TRUE1;
987
988 authType = kea_defs[cipher_def->key_exchange_alg].authKeyType;
989 if (authType != ssl_auth_null && authType != ssl_auth_tls13_any) {
990 if (ss->sec.isServer &&
991 !(ssl_HasCert(ss, ss->vrange.max, authType) &&
992 ssl_HasSignatureScheme(ss, authType))) {
993 suite->isPresent = PR_FALSE0;
994 } else if (!PK11_TokenExists(auth_alg_defs[authType])) {
995 suite->isPresent = PR_FALSE0;
996 }
997 }
998
999 keaType = kea_defs[cipher_def->key_exchange_alg].exchKeyType;
1000 if (keaType != ssl_kea_null &&
1001 keaType != ssl_kea_tls13_any &&
1002 !PK11_TokenExists(kea_alg_defs[keaType])) {
1003 suite->isPresent = PR_FALSE0;
1004 }
1005
1006 if (cipher_alg != ssl_calg_null &&
1007 !PK11_TokenExists(cipher_mech)) {
1008 suite->isPresent = PR_FALSE0;
1009 }
1010
1011 if (suite->isPresent) {
1012 ++numPresent;
1013 }
1014 }
1015 }
1016 PORT_AssertArg(numPresent > 0 || numEnabled == 0)((numPresent > 0 || numEnabled == 0)?((void)0):PR_Assert("numPresent > 0 || numEnabled == 0"
,"ssl3con.c",1016))
;
1017 if (numPresent == 0) {
1018 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_NO_CIPHERS_SUPPORTED);
1019 }
1020 return numPresent;
1021}
1022
1023/* Return PR_TRUE if suite is usable. This if the suite is permitted by policy,
1024 * enabled, has a certificate (as needed), has a viable key agreement method, is
1025 * usable with the negotiated TLS version, and is otherwise usable. */
1026PRBool
1027ssl3_config_match(const ssl3CipherSuiteCfg *suite, PRUint8 policy,
1028 const SSLVersionRange *vrange, const sslSocket *ss)
1029{
1030 const ssl3CipherSuiteDef *cipher_def;
1031 const ssl3KEADef *kea_def;
1032
1033 if (!suite) {
1034 PORT_Assert(suite)((suite)?((void)0):PR_Assert("suite","ssl3con.c",1034));
1035 return PR_FALSE0;
1036 }
1037
1038 PORT_Assert(policy != SSL_NOT_ALLOWED)((policy != 0)?((void)0):PR_Assert("policy != SSL_NOT_ALLOWED"
,"ssl3con.c",1038))
;
1039 if (policy == SSL_NOT_ALLOWED0)
1040 return PR_FALSE0;
1041
1042 if (!suite->enabled || !suite->isPresent)
1043 return PR_FALSE0;
1044
1045 if ((suite->policy == SSL_NOT_ALLOWED0) ||
1046 (suite->policy > policy))
1047 return PR_FALSE0;
1048
1049 PORT_Assert(ss != NULL)((ss != ((void*)0))?((void)0):PR_Assert("ss != NULL","ssl3con.c"
,1049))
;
1050 cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite);
1051 PORT_Assert(cipher_def != NULL)((cipher_def != ((void*)0))?((void)0):PR_Assert("cipher_def != NULL"
,"ssl3con.c",1051))
;
1052 kea_def = &kea_defs[cipher_def->key_exchange_alg];
1053 PORT_Assert(kea_def != NULL)((kea_def != ((void*)0))?((void)0):PR_Assert("kea_def != NULL"
,"ssl3con.c",1053))
;
1054 if (!ssl_KEAEnabled(ss, kea_def->exchKeyType)) {
1055 return PR_FALSE0;
1056 }
1057
1058 if (ss->sec.isServer && !ssl_HasCert(ss, vrange->max, kea_def->authKeyType)) {
1059 return PR_FALSE0;
1060 }
1061
1062 /* If a PSK is selected, disable suites that use a different hash than
1063 * the PSK. We advertise non-PSK-compatible suites in the CH, as we could
1064 * fallback to certificate auth. The client handler will check hash
1065 * compatibility before committing to use the PSK. */
1066 if (ss->xtnData.selectedPsk) {
1067 if (ss->xtnData.selectedPsk->hash != cipher_def->prf_hash) {
1068 return PR_FALSE0;
1069 }
1070 }
1071
1072 return ssl3_CipherSuiteAllowedForVersionRange(suite->cipher_suite, vrange);
1073}
1074
1075/* For TLS 1.3, when resuming, check for a ciphersuite that is both compatible
1076 * with the identified ciphersuite and enabled. */
1077static PRBool
1078tls13_ResumptionCompatible(sslSocket *ss, ssl3CipherSuite suite)
1079{
1080 SSLVersionRange vrange = { SSL_LIBRARY_VERSION_TLS_1_30x0304,
1081 SSL_LIBRARY_VERSION_TLS_1_30x0304 };
1082 SSLHashType hash = tls13_GetHashForCipherSuite(suite);
1083 for (unsigned int i = 0; i < PR_ARRAY_SIZE(cipher_suite_defs)(sizeof(cipher_suite_defs)/sizeof((cipher_suite_defs)[0])); i++) {
1084 if (cipher_suite_defs[i].prf_hash == hash) {
1085 const ssl3CipherSuiteCfg *suiteCfg =
1086 ssl_LookupCipherSuiteCfg(cipher_suite_defs[i].cipher_suite,
1087 ss->cipherSuites);
1088 if (suite && ssl3_config_match(suiteCfg, ss->ssl3.policy, &vrange, ss)) {
1089 return PR_TRUE1;
1090 }
1091 }
1092 }
1093 return PR_FALSE0;
1094}
1095
1096/*
1097 * Null compression, mac and encryption functions
1098 */
1099SECStatus
1100Null_Cipher(void *ctx, unsigned char *output, unsigned int *outputLen, unsigned int maxOutputLen,
1101 const unsigned char *input, unsigned int inputLen)
1102{
1103 if (inputLen > maxOutputLen) {
1104 *outputLen = 0; /* Match PK11_CipherOp in setting outputLen */
1105 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_OUTPUT_LEN);
1106 return SECFailure;
1107 }
1108 *outputLen = inputLen;
1109 if (inputLen > 0 && input != output) {
1110 PORT_Memcpymemcpy(output, input, inputLen);
1111 }
1112 return SECSuccess;
1113}
1114
1115/*
1116 * SSL3 Utility functions
1117 */
1118
1119static void
1120ssl_SetSpecVersions(sslSocket *ss, ssl3CipherSpec *spec)
1121{
1122 spec->version = ss->version;
1123 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_30x0304) {
1124 tls13_SetSpecRecordVersion(ss, spec);
1125 } else if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
1126 spec->recordVersion = dtls_TLSVersionToDTLSVersion(ss->version);
1127 } else {
1128 spec->recordVersion = ss->version;
1129 }
1130}
1131
1132/* allowLargerPeerVersion controls whether the function will select the
1133 * highest enabled SSL version or fail when peerVersion is greater than the
1134 * highest enabled version.
1135 *
1136 * If allowLargerPeerVersion is true, peerVersion is the peer's highest
1137 * enabled version rather than the peer's selected version.
1138 */
1139SECStatus
1140ssl3_NegotiateVersion(sslSocket *ss, SSL3ProtocolVersion peerVersion,
1141 PRBool allowLargerPeerVersion)
1142{
1143 SSL3ProtocolVersion negotiated;
1144
1145 /* Prevent negotiating to a lower version in response to a TLS 1.3 HRR. */
1146 if (ss->ssl3.hs.helloRetry) {
1147 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_UNSUPPORTED_VERSION);
1148 return SECFailure;
1149 }
1150
1151 if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)((&ss->vrange)->min == 0)) {
1152 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_SSL_DISABLED);
1153 return SECFailure;
1154 }
1155
1156 if (peerVersion < ss->vrange.min ||
1157 (peerVersion > ss->vrange.max && !allowLargerPeerVersion)) {
1158 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_UNSUPPORTED_VERSION);
1159 return SECFailure;
1160 }
1161
1162 negotiated = PR_MIN(peerVersion, ss->vrange.max)((peerVersion)<(ss->vrange.max)?(peerVersion):(ss->vrange
.max))
;
1163 PORT_Assert(ssl3_VersionIsSupported(ss->protocolVariant, negotiated))((ssl3_VersionIsSupported(ss->protocolVariant, negotiated)
)?((void)0):PR_Assert("ssl3_VersionIsSupported(ss->protocolVariant, negotiated)"
,"ssl3con.c",1163))
;
1164 if (ss->firstHsDone && ss->version != negotiated) {
1165 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_UNSUPPORTED_VERSION);
1166 return SECFailure;
1167 }
1168
1169 ss->version = negotiated;
1170 return SECSuccess;
1171}
1172
1173/* Used by the client when the server produces a version number.
1174 * This reads, validates, and normalizes the value. */
1175SECStatus
1176ssl_ClientReadVersion(sslSocket *ss, PRUint8 **b, unsigned int *len,
1177 SSL3ProtocolVersion *version)
1178{
1179 SSL3ProtocolVersion v;
1180 PRUint32 temp;
1181 SECStatus rv;
1182
1183 rv = ssl3_ConsumeHandshakeNumber(ss, &temp, 2, b, len);
1184 if (rv != SECSuccess) {
1185 return SECFailure; /* alert has been sent */
1186 }
1187 v = (SSL3ProtocolVersion)temp;
1188
1189 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
1190 v = dtls_DTLSVersionToTLSVersion(v);
1191 /* Check for failure. */
1192 if (!v || v > SSL_LIBRARY_VERSION_MAX_SUPPORTED0x0304) {
1193 SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
1194 return SECFailure;
1195 }
1196 }
1197
1198 /* You can't negotiate TLS 1.3 this way. */
1199 if (v >= SSL_LIBRARY_VERSION_TLS_1_30x0304) {
1200 SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
1201 return SECFailure;
1202 }
1203 *version = v;
1204 return SECSuccess;
1205}
1206
1207SECStatus
1208ssl3_GetNewRandom(SSL3Random random)
1209{
1210 SECStatus rv;
1211
1212 rv = PK11_GenerateRandom(random, SSL3_RANDOM_LENGTH32);
1213 if (rv != SECSuccess) {
1214 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
1215 }
1216 return rv;
1217}
1218
1219SECStatus
1220ssl3_SignHashesWithPrivKey(SSL3Hashes *hash, SECKEYPrivateKey *key,
1221 SSLSignatureScheme scheme, PRBool isTls, SECItem *buf)
1222{
1223 SECStatus rv = SECFailure;
1224 PRBool doDerEncode = PR_FALSE0;
1225 PRBool useRsaPss = ssl_IsRsaPssSignatureScheme(scheme);
1226 SECItem hashItem;
1227
1228 buf->data = NULL((void*)0);
1229
1230 switch (SECKEY_GetPrivateKeyType(key)) {
1231 case rsaKey:
1232 hashItem.data = hash->u.raw;
1233 hashItem.len = hash->len;
1234 break;
1235 case dsaKey:
1236 doDerEncode = isTls;
1237 /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
1238 * In that case, we use just the SHA1 part. */
1239 if (hash->hashAlg == ssl_hash_none) {
1240 hashItem.data = hash->u.s.sha;
1241 hashItem.len = sizeof(hash->u.s.sha);
1242 } else {
1243 hashItem.data = hash->u.raw;
1244 hashItem.len = hash->len;
1245 }
1246 break;
1247 case ecKey:
1248 doDerEncode = PR_TRUE1;
1249 /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
1250 * In that case, we use just the SHA1 part. */
1251 if (hash->hashAlg == ssl_hash_none) {
1252 hashItem.data = hash->u.s.sha;
1253 hashItem.len = sizeof(hash->u.s.sha);
1254 } else {
1255 hashItem.data = hash->u.raw;
1256 hashItem.len = hash->len;
1257 }
1258 break;
1259 default:
1260 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_KEY);
1261 goto done;
1262 }
1263 PRINT_BUF(60, (NULL, "hash(es) to be signed", hashItem.data, hashItem.len))if (ssl_trace >= (60)) ssl_PrintBuf (((void*)0), "hash(es) to be signed"
, hashItem.data, hashItem.len)
;
1264
1265 if (useRsaPss || hash->hashAlg == ssl_hash_none) {
1266 CK_MECHANISM_TYPE mech = PK11_MapSignKeyType(key->keyType);
1267 int signatureLen = PK11_SignatureLen(key);
1268
1269 SECItem *params = NULL((void*)0);
1270 CK_RSA_PKCS_PSS_PARAMS pssParams;
1271 SECItem pssParamsItem = { siBuffer,
1272 (unsigned char *)&pssParams,
1273 sizeof(pssParams) };
1274
1275 if (signatureLen <= 0) {
1276 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_KEY);
1277 goto done;
1278 }
1279
1280 buf->len = (unsigned)signatureLen;
1281 buf->data = (unsigned char *)PORT_AllocPORT_Alloc_Util(signatureLen);
1282 if (!buf->data)
1283 goto done; /* error code was set. */
1284
1285 if (useRsaPss) {
1286 pssParams.hashAlg = ssl3_GetHashMechanismByHashType(hash->hashAlg);
1287 pssParams.mgf = ssl3_GetMgfMechanismByHashType(hash->hashAlg);
1288 pssParams.sLen = hashItem.len;
1289 params = &pssParamsItem;
1290 mech = CKM_RSA_PKCS_PSS0x0000000DUL;
1291 }
1292
1293 rv = PK11_SignWithMechanism(key, mech, params, buf, &hashItem);
1294 } else {
1295 SECOidTag hashOID = ssl3_HashTypeToOID(hash->hashAlg);
1296 rv = SGN_Digest(key, hashOID, buf, &hashItem);
1297 }
1298 if (rv != SECSuccess) {
1299 ssl_MapLowLevelError(SSL_ERROR_SIGN_HASHES_FAILURE);
1300 } else if (doDerEncode) {
1301 SECItem derSig = { siBuffer, NULL((void*)0), 0 };
1302
1303 /* This also works for an ECDSA signature */
1304 rv = DSAU_EncodeDerSigWithLen(&derSig, buf, buf->len);
1305 if (rv == SECSuccess) {
1306 PORT_FreePORT_Free_Util(buf->data); /* discard unencoded signature. */
1307 *buf = derSig; /* give caller encoded signature. */
1308 } else if (derSig.data) {
1309 PORT_FreePORT_Free_Util(derSig.data);
1310 }
1311 }
1312
1313 PRINT_BUF(60, (NULL, "signed hashes", (unsigned char *)buf->data, buf->len))if (ssl_trace >= (60)) ssl_PrintBuf (((void*)0), "signed hashes"
, (unsigned char *)buf->data, buf->len)
;
1314done:
1315 if (rv != SECSuccess && buf->data) {
1316 PORT_FreePORT_Free_Util(buf->data);
1317 buf->data = NULL((void*)0);
1318 }
1319 return rv;
1320}
1321
1322/* Called by ssl3_SendServerKeyExchange and ssl3_SendCertificateVerify */
1323SECStatus
1324ssl3_SignHashes(sslSocket *ss, SSL3Hashes *hash, SECKEYPrivateKey *key,
1325 SECItem *buf)
1326{
1327 SECStatus rv = SECFailure;
1328 PRBool isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_00x0300);
1329 SSLSignatureScheme scheme = ss->ssl3.hs.signatureScheme;
1330
1331 rv = ssl3_SignHashesWithPrivKey(hash, key, scheme, isTLS, buf);
1332 if (rv != SECSuccess) {
1333 return SECFailure;
1334 }
1335
1336 if (ss->sec.isServer) {
1337 ss->sec.signatureScheme = scheme;
1338 ss->sec.authType = ssl_SignatureSchemeToAuthType(scheme);
1339 }
1340
1341 return SECSuccess;
1342}
1343
1344/* Called from ssl3_VerifySignedHashes and tls13_HandleCertificateVerify. */
1345SECStatus
1346ssl_VerifySignedHashesWithPubKey(sslSocket *ss, SECKEYPublicKey *key,
1347 SSLSignatureScheme scheme,
1348 SSL3Hashes *hash, SECItem *buf)
1349{
1350 SECItem *signature = NULL((void*)0);
1351 SECStatus rv = SECFailure;
1352 SECItem hashItem;
1353 SECOidTag encAlg;
1354 SECOidTag hashAlg;
1355 void *pwArg = ss->pkcs11PinArg;
1356 PRBool isRsaPssScheme = ssl_IsRsaPssSignatureScheme(scheme);
1357
1358 PRINT_BUF(60, (NULL, "check signed hashes", buf->data, buf->len))if (ssl_trace >= (60)) ssl_PrintBuf (((void*)0), "check signed hashes"
, buf->data, buf->len)
;
1359
1360 hashAlg = ssl3_HashTypeToOID(hash->hashAlg);
1361 switch (SECKEY_GetPublicKeyType(key)) {
1362 case rsaKey:
1363 encAlg = SEC_OID_PKCS1_RSA_ENCRYPTION;
1364 hashItem.data = hash->u.raw;
1365 hashItem.len = hash->len;
1366 if (scheme == ssl_sig_none) {
1367 scheme = ssl_sig_rsa_pkcs1_sha1md5;
1368 }
1369 break;
1370 case dsaKey:
1371 encAlg = SEC_OID_ANSIX9_DSA_SIGNATURE;
1372 /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
1373 * In that case, we use just the SHA1 part. */
1374 if (hash->hashAlg == ssl_hash_none) {
1375 hashItem.data = hash->u.s.sha;
1376 hashItem.len = sizeof(hash->u.s.sha);
1377 } else {
1378 hashItem.data = hash->u.raw;
1379 hashItem.len = hash->len;
1380 }
1381 /* Allow DER encoded DSA signatures in SSL 3.0 */
1382 if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_00x0300 ||
1383 buf->len != SECKEY_SignatureLen(key)) {
1384 signature = DSAU_DecodeDerSigToLen(buf, SECKEY_SignatureLen(key));
1385 if (!signature) {
1386 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
1387 goto loser;
1388 }
1389 buf = signature;
1390 }
1391 if (scheme == ssl_sig_none) {
1392 scheme = ssl_sig_dsa_sha1;
1393 }
1394 break;
1395
1396 case ecKey:
1397 encAlg = SEC_OID_ANSIX962_EC_PUBLIC_KEY;
1398 /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
1399 * In that case, we use just the SHA1 part.
1400 * ECDSA signatures always encode the integers r and s using ASN.1
1401 * (unlike DSA where ASN.1 encoding is used with TLS but not with
1402 * SSL3). So we can use VFY_VerifyDigestDirect for ECDSA.
1403 */
1404 if (hash->hashAlg == ssl_hash_none) {
1405 hashAlg = SEC_OID_SHA1;
1406 hashItem.data = hash->u.s.sha;
1407 hashItem.len = sizeof(hash->u.s.sha);
1408 } else {
1409 hashItem.data = hash->u.raw;
1410 hashItem.len = hash->len;
1411 }
1412 if (scheme == ssl_sig_none) {
1413 scheme = ssl_sig_ecdsa_sha1;
1414 }
1415 break;
1416
1417 default:
1418 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_UNSUPPORTED_KEYALG);
1419 goto loser;
1420 }
1421
1422 PRINT_BUF(60, (NULL, "hash(es) to be verified",if (ssl_trace >= (60)) ssl_PrintBuf (((void*)0), "hash(es) to be verified"
, hashItem.data, hashItem.len)
1423 hashItem.data, hashItem.len))if (ssl_trace >= (60)) ssl_PrintBuf (((void*)0), "hash(es) to be verified"
, hashItem.data, hashItem.len)
;
1424
1425 if (isRsaPssScheme ||
1426 hashAlg == SEC_OID_UNKNOWN ||
1427 SECKEY_GetPublicKeyType(key) == dsaKey) {
1428 /* VFY_VerifyDigestDirect requires DSA signatures to be DER-encoded.
1429 * DSA signatures are DER-encoded in TLS but not in SSL3 and the code
1430 * above always removes the DER encoding of DSA signatures when
1431 * present. Thus DSA signatures are always verified with PK11_Verify.
1432 */
1433 CK_MECHANISM_TYPE mech = PK11_MapSignKeyType(key->keyType);
1434
1435 SECItem *params = NULL((void*)0);
1436 CK_RSA_PKCS_PSS_PARAMS pssParams;
1437 SECItem pssParamsItem = { siBuffer,
1438 (unsigned char *)&pssParams,
1439 sizeof(pssParams) };
1440
1441 if (isRsaPssScheme) {
1442 pssParams.hashAlg = ssl3_GetHashMechanismByHashType(hash->hashAlg);
1443 pssParams.mgf = ssl3_GetMgfMechanismByHashType(hash->hashAlg);
1444 pssParams.sLen = hashItem.len;
1445 params = &pssParamsItem;
1446 mech = CKM_RSA_PKCS_PSS0x0000000DUL;
1447 }
1448
1449 rv = PK11_VerifyWithMechanism(key, mech, params, buf, &hashItem, pwArg);
1450 } else {
1451 rv = VFY_VerifyDigestDirect(&hashItem, key, buf, encAlg, hashAlg,
1452 pwArg);
1453 }
1454 if (signature) {
1455 SECITEM_FreeItemSECITEM_FreeItem_Util(signature, PR_TRUE1);
1456 }
1457 if (rv != SECSuccess) {
1458 ssl_MapLowLevelError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
1459 }
1460 if (!ss->sec.isServer) {
1461 ss->sec.signatureScheme = scheme;
1462 ss->sec.authType = ssl_SignatureSchemeToAuthType(scheme);
1463 }
1464
1465loser:
1466#ifdef UNSAFE_FUZZER_MODE
1467 rv = SECSuccess;
1468 PORT_SetErrorPORT_SetError_Util(0);
1469#endif
1470 return rv;
1471}
1472
1473/* Called from ssl3_HandleServerKeyExchange, ssl3_HandleCertificateVerify */
1474SECStatus
1475ssl3_VerifySignedHashes(sslSocket *ss, SSLSignatureScheme scheme, SSL3Hashes *hash,
1476 SECItem *buf)
1477{
1478 SECKEYPublicKey *pubKey =
1479 SECKEY_ExtractPublicKey(&ss->sec.peerCert->subjectPublicKeyInfo);
1480 if (pubKey == NULL((void*)0)) {
1481 ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
1482 return SECFailure;
1483 }
1484 SECStatus rv = ssl_VerifySignedHashesWithPubKey(ss, pubKey, scheme,
1485 hash, buf);
1486 SECKEY_DestroyPublicKey(pubKey);
1487 return rv;
1488}
1489
1490/* Caller must set hiLevel error code. */
1491/* Called from ssl3_ComputeDHKeyHash
1492 * which are called from ssl3_HandleServerKeyExchange.
1493 *
1494 * hashAlg: ssl_hash_none indicates the pre-1.2, MD5/SHA1 combination hash.
1495 */
1496SECStatus
1497ssl3_ComputeCommonKeyHash(SSLHashType hashAlg,
1498 PRUint8 *hashBuf, unsigned int bufLen,
1499 SSL3Hashes *hashes)
1500{
1501 SECStatus rv;
1502 SECOidTag hashOID;
1503 PRUint32 policy;
1504
1505 if (hashAlg == ssl_hash_none) {
1506 if ((NSS_GetAlgorithmPolicy(SEC_OID_SHA1, &policy) == SECSuccess) &&
1507 !(policy & NSS_USE_ALG_IN_SSL_KX0x00000004)) {
1508 ssl_MapLowLevelError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
1509 return SECFailure;
1510 }
1511 rv = PK11_HashBuf(SEC_OID_MD5, hashes->u.s.md5, hashBuf, bufLen);
1512 if (rv != SECSuccess) {
1513 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
1514 return rv;
1515 }
1516 rv = PK11_HashBuf(SEC_OID_SHA1, hashes->u.s.sha, hashBuf, bufLen);
1517 if (rv != SECSuccess) {
1518 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
1519 return rv;
1520 }
1521 hashes->len = MD5_LENGTH16 + SHA1_LENGTH20;
1522 } else {
1523 hashOID = ssl3_HashTypeToOID(hashAlg);
1524 if ((NSS_GetAlgorithmPolicy(hashOID, &policy) == SECSuccess) &&
1525 !(policy & NSS_USE_ALG_IN_SSL_KX0x00000004)) {
1526 ssl_MapLowLevelError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
1527 return SECFailure;
1528 }
1529 hashes->len = HASH_ResultLenByOidTag(hashOID);
1530 if (hashes->len == 0 || hashes->len > sizeof(hashes->u.raw)) {
1531 ssl_MapLowLevelError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
1532 return SECFailure;
1533 }
1534 rv = PK11_HashBuf(hashOID, hashes->u.raw, hashBuf, bufLen);
1535 if (rv != SECSuccess) {
1536 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
1537 return rv;
1538 }
1539 }
1540 hashes->hashAlg = hashAlg;
1541 return SECSuccess;
1542}
1543
1544/* Caller must set hiLevel error code. */
1545/* Called from ssl3_HandleServerKeyExchange. */
1546static SECStatus
1547ssl3_ComputeDHKeyHash(sslSocket *ss, SSLHashType hashAlg, SSL3Hashes *hashes,
1548 SECItem dh_p, SECItem dh_g, SECItem dh_Ys, PRBool padY)
1549{
1550 sslBuffer buf = SSL_BUFFER_EMPTY{ ((void*)0), 0, 0, 0 };
1551 SECStatus rv;
1552 unsigned int yLen;
1553 unsigned int i;
1554
1555 PORT_Assert(dh_p.data)((dh_p.data)?((void)0):PR_Assert("dh_p.data","ssl3con.c",1555
))
;
1556 PORT_Assert(dh_g.data)((dh_g.data)?((void)0):PR_Assert("dh_g.data","ssl3con.c",1556
))
;
1557 PORT_Assert(dh_Ys.data)((dh_Ys.data)?((void)0):PR_Assert("dh_Ys.data","ssl3con.c",1557
))
;
1558
1559 rv = sslBuffer_Append(&buf, ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH32);
1560 if (rv != SECSuccess) {
1561 goto loser;
1562 }
1563 rv = sslBuffer_Append(&buf, ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH32);
1564 if (rv != SECSuccess) {
1565 goto loser;
1566 }
1567 /* p */
1568 rv = sslBuffer_AppendVariable(&buf, dh_p.data, dh_p.len, 2);
1569 if (rv != SECSuccess) {
1570 goto loser;
1571 }
1572 /* g */
1573 rv = sslBuffer_AppendVariable(&buf, dh_g.data, dh_g.len, 2);
1574 if (rv != SECSuccess) {
1575 goto loser;
1576 }
1577 /* y - complicated by padding */
1578 yLen = padY ? dh_p.len : dh_Ys.len;
1579 rv = sslBuffer_AppendNumber(&buf, yLen, 2);
1580 if (rv != SECSuccess) {
1581 goto loser;
1582 }
1583 /* If we're padding Y, dh_Ys can't be longer than dh_p. */
1584 PORT_Assert(!padY || dh_p.len >= dh_Ys.len)((!padY || dh_p.len >= dh_Ys.len)?((void)0):PR_Assert("!padY || dh_p.len >= dh_Ys.len"
,"ssl3con.c",1584))
;
1585 for (i = dh_Ys.len; i < yLen; ++i) {
1586 rv = sslBuffer_AppendNumber(&buf, 0, 1);
1587 if (rv != SECSuccess) {
1588 goto loser;
1589 }
1590 }
1591 rv = sslBuffer_Append(&buf, dh_Ys.data, dh_Ys.len);
1592 if (rv != SECSuccess) {
1593 goto loser;
1594 }
1595
1596 rv = ssl3_ComputeCommonKeyHash(hashAlg, SSL_BUFFER_BASE(&buf)((&buf)->buf),
1597 SSL_BUFFER_LEN(&buf)((&buf)->len), hashes);
1598 if (rv != SECSuccess) {
1599 goto loser;
1600 }
1601
1602 PRINT_BUF(95, (NULL, "DHkey hash: ", SSL_BUFFER_BASE(&buf),if (ssl_trace >= (95)) ssl_PrintBuf (((void*)0), "DHkey hash: "
, ((&buf)->buf), ((&buf)->len))
1603 SSL_BUFFER_LEN(&buf)))if (ssl_trace >= (95)) ssl_PrintBuf (((void*)0), "DHkey hash: "
, ((&buf)->buf), ((&buf)->len))
;
1604 if (hashAlg == ssl_hash_none) {
1605 PRINT_BUF(95, (NULL, "DHkey hash: MD5 result",if (ssl_trace >= (95)) ssl_PrintBuf (((void*)0), "DHkey hash: MD5 result"
, hashes->u.s.md5, 16)
1606 hashes->u.s.md5, MD5_LENGTH))if (ssl_trace >= (95)) ssl_PrintBuf (((void*)0), "DHkey hash: MD5 result"
, hashes->u.s.md5, 16)
;
1607 PRINT_BUF(95, (NULL, "DHkey hash: SHA1 result",if (ssl_trace >= (95)) ssl_PrintBuf (((void*)0), "DHkey hash: SHA1 result"
, hashes->u.s.sha, 20)
1608 hashes->u.s.sha, SHA1_LENGTH))if (ssl_trace >= (95)) ssl_PrintBuf (((void*)0), "DHkey hash: SHA1 result"
, hashes->u.s.sha, 20)
;
1609 } else {
1610 PRINT_BUF(95, (NULL, "DHkey hash: result",if (ssl_trace >= (95)) ssl_PrintBuf (((void*)0), "DHkey hash: result"
, hashes->u.raw, hashes->len)
1611 hashes->u.raw, hashes->len))if (ssl_trace >= (95)) ssl_PrintBuf (((void*)0), "DHkey hash: result"
, hashes->u.raw, hashes->len)
;
1612 }
1613
1614 sslBuffer_Clear(&buf);
1615 return SECSuccess;
1616
1617loser:
1618 sslBuffer_Clear(&buf);
1619 return SECFailure;
1620}
1621
1622static SECStatus
1623ssl3_SetupPendingCipherSpec(sslSocket *ss, SSLSecretDirection direction,
1624 const ssl3CipherSuiteDef *suiteDef,
1625 ssl3CipherSpec **specp)
1626{
1627 ssl3CipherSpec *spec;
1628 const ssl3CipherSpec *prev;
1629
1630 prev = (direction == ssl_secret_write) ? ss->ssl3.cwSpec : ss->ssl3.crSpec;
1631 if (prev->epoch == PR_UINT16_MAX65535U) {
1632 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
1633 return SECFailure;
1634 }
1635
1636 spec = ssl_CreateCipherSpec(ss, direction);
1637 if (!spec) {
1638 return SECFailure;
1639 }
1640
1641 spec->cipherDef = ssl_GetBulkCipherDef(suiteDef);
1642 spec->macDef = ssl_GetMacDef(ss, suiteDef);
1643
1644 spec->epoch = prev->epoch + 1;
1645 spec->nextSeqNum = 0;
1646 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram) && direction == ssl_secret_read) {
1647 dtls_InitRecvdRecords(&spec->recvdRecords);
1648 }
1649 ssl_SetSpecVersions(ss, spec);
1650
1651 ssl_SaveCipherSpec(ss, spec);
1652 *specp = spec;
1653 return SECSuccess;
1654}
1655
1656/* Fill in the pending cipher spec with info from the selected ciphersuite.
1657** This is as much initialization as we can do without having key material.
1658** Called from ssl3_HandleServerHello(), ssl3_SendServerHello()
1659** Caller must hold the ssl3 handshake lock.
1660** Acquires & releases SpecWriteLock.
1661*/
1662SECStatus
1663ssl3_SetupBothPendingCipherSpecs(sslSocket *ss)
1664{
1665 ssl3CipherSuite suite = ss->ssl3.hs.cipher_suite;
1666 SSL3KeyExchangeAlgorithm kea;
1667 const ssl3CipherSuiteDef *suiteDef;
1668 SECStatus rv;
1669
1670 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",1670))
;
1671 PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3)((ss->version < 0x0304)?((void)0):PR_Assert("ss->version < SSL_LIBRARY_VERSION_TLS_1_3"
,"ssl3con.c",1671))
;
1672
1673 ssl_GetSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_LockWrite_Util((ss)->
specLock); }
; /*******************************/
1674
1675 /* This hack provides maximal interoperability with SSL 3 servers. */
1676 if (ss->ssl3.cwSpec->macDef->mac == ssl_mac_null) {
1677 /* SSL records are not being MACed. */
1678 ss->ssl3.cwSpec->version = ss->version;
1679 }
1680
1681 SSL_TRC(3, ("%d: SSL3[%d]: Set XXX Pending Cipher Suite to 0x%04x",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: Set XXX Pending Cipher Suite to 0x%04x"
, getpid(), ss->fd, suite)
1682 SSL_GETPID(), ss->fd, suite))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: Set XXX Pending Cipher Suite to 0x%04x"
, getpid(), ss->fd, suite)
;
1683
1684 suiteDef = ssl_LookupCipherSuiteDef(suite);
1685 if (suiteDef == NULL((void*)0)) {
1686 goto loser;
1687 }
1688
1689 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
1690 /* Double-check that we did not pick an RC4 suite */
1691 PORT_Assert(suiteDef->bulk_cipher_alg != cipher_rc4)((suiteDef->bulk_cipher_alg != cipher_rc4)?((void)0):PR_Assert
("suiteDef->bulk_cipher_alg != cipher_rc4","ssl3con.c",1691
))
;
1692 }
1693
1694 ss->ssl3.hs.suite_def = suiteDef;
1695
1696 kea = suiteDef->key_exchange_alg;
1697 ss->ssl3.hs.kea_def = &kea_defs[kea];
1698 PORT_Assert(ss->ssl3.hs.kea_def->kea == kea)((ss->ssl3.hs.kea_def->kea == kea)?((void)0):PR_Assert(
"ss->ssl3.hs.kea_def->kea == kea","ssl3con.c",1698))
;
1699
1700 rv = ssl3_SetupPendingCipherSpec(ss, ssl_secret_read, suiteDef,
1701 &ss->ssl3.prSpec);
1702 if (rv != SECSuccess) {
1703 goto loser;
1704 }
1705 rv = ssl3_SetupPendingCipherSpec(ss, ssl_secret_write, suiteDef,
1706 &ss->ssl3.pwSpec);
1707 if (rv != SECSuccess) {
1708 goto loser;
1709 }
1710
1711 if (ssl3_ExtensionNegotiated(ss, ssl_record_size_limit_xtn)) {
1712 ss->ssl3.prSpec->recordSizeLimit = PR_MIN(MAX_FRAGMENT_LENGTH,((16384)<(ss->opt.recordSizeLimit)?(16384):(ss->opt.
recordSizeLimit))
1713 ss->opt.recordSizeLimit)((16384)<(ss->opt.recordSizeLimit)?(16384):(ss->opt.
recordSizeLimit))
;
1714 ss->ssl3.pwSpec->recordSizeLimit = PR_MIN(MAX_FRAGMENT_LENGTH,((16384)<(ss->xtnData.recordSizeLimit)?(16384):(ss->
xtnData.recordSizeLimit))
1715 ss->xtnData.recordSizeLimit)((16384)<(ss->xtnData.recordSizeLimit)?(16384):(ss->
xtnData.recordSizeLimit))
;
1716 }
1717
1718 ssl_ReleaseSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockWrite_Util((ss)->
specLock); }
; /*******************************/
1719 return SECSuccess;
1720
1721loser:
1722 ssl_ReleaseSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockWrite_Util((ss)->
specLock); }
;
1723 return SECFailure;
1724}
1725
1726/* ssl3_BuildRecordPseudoHeader writes the SSL/TLS pseudo-header (the data which
1727 * is included in the MAC or AEAD additional data) to |buf|. See
1728 * https://tools.ietf.org/html/rfc5246#section-6.2.3.3 for the definition of the
1729 * AEAD additional data.
1730 *
1731 * TLS pseudo-header includes the record's version field, SSL's doesn't. Which
1732 * pseudo-header definition to use should be decided based on the version of
1733 * the protocol that was negotiated when the cipher spec became current, NOT
1734 * based on the version value in the record itself, and the decision is passed
1735 * to this function as the |includesVersion| argument. But, the |version|
1736 * argument should be the record's version value.
1737 */
1738static SECStatus
1739ssl3_BuildRecordPseudoHeader(DTLSEpoch epoch,
1740 sslSequenceNumber seqNum,
1741 SSLContentType ct,
1742 PRBool includesVersion,
1743 SSL3ProtocolVersion version,
1744 PRBool isDTLS,
1745 int length,
1746 sslBuffer *buf, SSL3ProtocolVersion v)
1747{
1748 SECStatus rv;
1749 if (isDTLS && v < SSL_LIBRARY_VERSION_TLS_1_30x0304) {
1750 rv = sslBuffer_AppendNumber(buf, epoch, 2);
1751 if (rv != SECSuccess) {
1752 return SECFailure;
1753 }
1754 rv = sslBuffer_AppendNumber(buf, seqNum, 6);
1755 } else {
1756 rv = sslBuffer_AppendNumber(buf, seqNum, 8);
1757 }
1758 if (rv != SECSuccess) {
1759 return SECFailure;
1760 }
1761 rv = sslBuffer_AppendNumber(buf, ct, 1);
1762 if (rv != SECSuccess) {
1763 return SECFailure;
1764 }
1765
1766 /* SSL3 MAC doesn't include the record's version field. */
1767 if (includesVersion) {
1768 /* TLS MAC and AEAD additional data include version. */
1769 rv = sslBuffer_AppendNumber(buf, version, 2);
1770 if (rv != SECSuccess) {
1771 return SECFailure;
1772 }
1773 }
1774 rv = sslBuffer_AppendNumber(buf, length, 2);
1775 if (rv != SECSuccess) {
1776 return SECFailure;
1777 }
1778
1779 return SECSuccess;
1780}
1781
1782/* Initialize encryption and MAC contexts for pending spec.
1783 * Master Secret already is derived.
1784 * Caller holds Spec write lock.
1785 */
1786static SECStatus
1787ssl3_InitPendingContexts(sslSocket *ss, ssl3CipherSpec *spec)
1788{
1789 CK_MECHANISM_TYPE encMechanism;
1790 CK_ATTRIBUTE_TYPE encMode;
1791 SECItem macParam;
1792 CK_ULONG macLength;
1793 SECItem iv;
1794 SSLCipherAlgorithm calg;
1795
1796 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",1796))
;
1797 PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss))((ss->opt.noLocks || (NSSRWLock_HaveWriteLock_Util((ss)->
specLock)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)"
,"ssl3con.c",1797))
;
1798
1799 calg = spec->cipherDef->calg;
1800 PORT_Assert(alg2Mech[calg].calg == calg)((alg2Mech[calg].calg == calg)?((void)0):PR_Assert("alg2Mech[calg].calg == calg"
,"ssl3con.c",1800))
;
1801
1802 if (spec->cipherDef->type != type_aead) {
1803 macLength = spec->macDef->mac_size;
1804
1805 /*
1806 ** Now setup the MAC contexts,
1807 ** crypto contexts are setup below.
1808 */
1809 macParam.data = (unsigned char *)&macLength;
1810 macParam.len = sizeof(macLength);
1811 macParam.type = siBuffer;
1812
1813 spec->keyMaterial.macContext = PK11_CreateContextBySymKey(
1814 spec->macDef->mmech, CKA_SIGN0x00000108UL, spec->keyMaterial.macKey, &macParam);
1815 if (!spec->keyMaterial.macContext) {
1816 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
1817 return SECFailure;
1818 }
1819 }
1820
1821 /*
1822 ** Now setup the crypto contexts.
1823 */
1824 if (calg == ssl_calg_null) {
1825 spec->cipher = Null_Cipher;
1826 return SECSuccess;
1827 }
1828
1829 encMechanism = ssl3_Alg2Mech(calg);
1830 encMode = (spec->direction == ssl_secret_write) ? CKA_ENCRYPT0x00000104UL : CKA_DECRYPT0x00000105UL;
1831 if (spec->cipherDef->type == type_aead) {
1832 encMode |= CKA_NSS_MESSAGE0x82000000L;
1833 iv.data = NULL((void*)0);
1834 iv.len = 0;
1835 } else {
1836 spec->cipher = (SSLCipher)PK11_CipherOp;
1837 iv.data = spec->keyMaterial.iv;
1838 iv.len = spec->cipherDef->iv_size;
1839 }
1840
1841 /*
1842 * build the context
1843 */
1844 spec->cipherContext = PK11_CreateContextBySymKey(encMechanism, encMode,
1845 spec->keyMaterial.key,
1846 &iv);
1847 if (!spec->cipherContext) {
1848 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
1849 return SECFailure;
1850 }
1851
1852 return SECSuccess;
1853}
1854
1855/* Complete the initialization of all keys, ciphers, MACs and their contexts
1856 * for the pending Cipher Spec.
1857 * Called from: ssl3_SendClientKeyExchange (for Full handshake)
1858 * ssl3_HandleRSAClientKeyExchange (for Full handshake)
1859 * ssl3_HandleServerHello (for session restart)
1860 * ssl3_HandleClientHello (for session restart)
1861 * Sets error code, but caller probably should override to disambiguate.
1862 *
1863 * If |secret| is a master secret from a previous connection is reused, |derive|
1864 * is PR_FALSE. If the secret is a pre-master secret, then |derive| is PR_TRUE
1865 * and the master secret is derived from |secret|.
1866 */
1867SECStatus
1868ssl3_InitPendingCipherSpecs(sslSocket *ss, PK11SymKey *secret, PRBool derive)
1869{
1870 PK11SymKey *masterSecret;
1871 ssl3CipherSpec *pwSpec;
1872 ssl3CipherSpec *prSpec;
1873 SECStatus rv;
1874
1875 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",1875))
;
1876 PORT_Assert(secret)((secret)?((void)0):PR_Assert("secret","ssl3con.c",1876));
1877
1878 ssl_GetSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_LockWrite_Util((ss)->
specLock); }
; /**************************************/
1879
1880 PORT_Assert(ss->ssl3.pwSpec)((ss->ssl3.pwSpec)?((void)0):PR_Assert("ss->ssl3.pwSpec"
,"ssl3con.c",1880))
;
1881 PORT_Assert(ss->ssl3.cwSpec->epoch == ss->ssl3.crSpec->epoch)((ss->ssl3.cwSpec->epoch == ss->ssl3.crSpec->epoch
)?((void)0):PR_Assert("ss->ssl3.cwSpec->epoch == ss->ssl3.crSpec->epoch"
,"ssl3con.c",1881))
;
1882 prSpec = ss->ssl3.prSpec;
1883 pwSpec = ss->ssl3.pwSpec;
1884
1885 if (ss->ssl3.cwSpec->epoch == PR_UINT16_MAX65535U) {
1886 /* The problem here is that we have rehandshaked too many
1887 * times (you are not allowed to wrap the epoch). The
1888 * spec says you should be discarding the connection
1889 * and start over, so not much we can do here. */
1890 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
1891 goto loser;
1892 }
1893
1894 if (derive) {
1895 rv = ssl3_ComputeMasterSecret(ss, secret, &masterSecret);
1896 if (rv != SECSuccess) {
1897 goto loser;
1898 }
1899 } else {
1900 masterSecret = secret;
1901 }
1902
1903 PORT_Assert(masterSecret)((masterSecret)?((void)0):PR_Assert("masterSecret","ssl3con.c"
,1903))
;
1904 rv = ssl3_DeriveConnectionKeys(ss, masterSecret);
1905 if (rv != SECSuccess) {
1906 if (derive) {
1907 /* masterSecret was created here. */
1908 PK11_FreeSymKey(masterSecret);
1909 }
1910 goto loser;
1911 }
1912
1913 /* Both cipher specs maintain a reference to the master secret, since each
1914 * is managed and freed independently. */
1915 prSpec->masterSecret = masterSecret;
1916 pwSpec->masterSecret = PK11_ReferenceSymKey(masterSecret);
1917 rv = ssl3_InitPendingContexts(ss, ss->ssl3.prSpec);
1918 if (rv != SECSuccess) {
1919 goto loser;
1920 }
1921
1922 rv = ssl3_InitPendingContexts(ss, ss->ssl3.pwSpec);
1923 if (rv != SECSuccess) {
1924 goto loser;
1925 }
1926
1927 ssl_ReleaseSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockWrite_Util((ss)->
specLock); }
; /******************************/
1928 return SECSuccess;
1929
1930loser:
1931 ssl_ReleaseSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockWrite_Util((ss)->
specLock); }
; /******************************/
1932 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
1933 return SECFailure;
1934}
1935
1936/*
1937 * 60 bytes is 3 times the maximum length MAC size that is supported.
1938 */
1939static const unsigned char mac_pad_1[60] = {
1940 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1941 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1942 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1943 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1944 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1945 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1946 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
1947 0x36, 0x36, 0x36, 0x36
1948};
1949static const unsigned char mac_pad_2[60] = {
1950 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1951 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1952 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1953 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1954 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1955 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1956 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
1957 0x5c, 0x5c, 0x5c, 0x5c
1958};
1959
1960/* Called from: ssl3_SendRecord()
1961** Caller must already hold the SpecReadLock. (wish we could assert that!)
1962*/
1963static SECStatus
1964ssl3_ComputeRecordMAC(
1965 ssl3CipherSpec *spec,
1966 const unsigned char *header,
1967 unsigned int headerLen,
1968 const PRUint8 *input,
1969 int inputLen,
1970 unsigned char *outbuf,
1971 unsigned int *outLen)
1972{
1973 PK11Context *context;
1974 int macSize = spec->macDef->mac_size;
1975 SECStatus rv;
1976
1977 PRINT_BUF(95, (NULL, "frag hash1: header", header, headerLen))if (ssl_trace >= (95)) ssl_PrintBuf (((void*)0), "frag hash1: header"
, header, headerLen)
;
1978 PRINT_BUF(95, (NULL, "frag hash1: input", input, inputLen))if (ssl_trace >= (95)) ssl_PrintBuf (((void*)0), "frag hash1: input"
, input, inputLen)
;
1979
1980 if (spec->macDef->mac == ssl_mac_null) {
1981 *outLen = 0;
1982 return SECSuccess;
1983 }
1984
1985 context = spec->keyMaterial.macContext;
1986 rv = PK11_DigestBegin(context);
1987 rv |= PK11_DigestOp(context, header, headerLen);
1988 rv |= PK11_DigestOp(context, input, inputLen);
1989 rv |= PK11_DigestFinal(context, outbuf, outLen, macSize);
1990 PORT_Assert(rv != SECSuccess || *outLen == (unsigned)macSize)((rv != SECSuccess || *outLen == (unsigned)macSize)?((void)0)
:PR_Assert("rv != SECSuccess || *outLen == (unsigned)macSize"
,"ssl3con.c",1990))
;
1991
1992 PRINT_BUF(95, (NULL, "frag hash2: result", outbuf, *outLen))if (ssl_trace >= (95)) ssl_PrintBuf (((void*)0), "frag hash2: result"
, outbuf, *outLen)
;
1993
1994 if (rv != SECSuccess) {
1995 rv = SECFailure;
1996 ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
1997 }
1998 return rv;
1999}
2000
2001/* Called from: ssl3_HandleRecord()
2002 * Caller must already hold the SpecReadLock. (wish we could assert that!)
2003 *
2004 * On entry:
2005 * originalLen >= inputLen >= MAC size
2006 */
2007static SECStatus
2008ssl3_ComputeRecordMACConstantTime(
2009 ssl3CipherSpec *spec,
2010 const unsigned char *header,
2011 unsigned int headerLen,
2012 const PRUint8 *input,
2013 int inputLen,
2014 int originalLen,
2015 unsigned char *outbuf,
2016 unsigned int *outLen)
2017{
2018 CK_MECHANISM_TYPE macType;
2019 CK_NSS_MAC_CONSTANT_TIME_PARAMS params;
2020 SECItem param, inputItem, outputItem;
2021 int macSize = spec->macDef->mac_size;
2022 SECStatus rv;
2023
2024 PORT_Assert(inputLen >= spec->macDef->mac_size)((inputLen >= spec->macDef->mac_size)?((void)0):PR_Assert
("inputLen >= spec->macDef->mac_size","ssl3con.c",2024
))
;
2025 PORT_Assert(originalLen >= inputLen)((originalLen >= inputLen)?((void)0):PR_Assert("originalLen >= inputLen"
,"ssl3con.c",2025))
;
2026
2027 if (spec->macDef->mac == ssl_mac_null) {
2028 *outLen = 0;
2029 return SECSuccess;
2030 }
2031
2032 macType = CKM_NSS_HMAC_CONSTANT_TIME((0x80000000UL | 0x4E534350) + 19);
2033 if (spec->version == SSL_LIBRARY_VERSION_3_00x0300) {
2034 macType = CKM_NSS_SSL3_MAC_CONSTANT_TIME((0x80000000UL | 0x4E534350) + 20);
2035 }
2036
2037 params.macAlg = spec->macDef->mmech;
2038 params.ulBodyTotalLen = originalLen;
2039 params.pHeader = (unsigned char *)header; /* const cast */
2040 params.ulHeaderLen = headerLen;
2041
2042 param.data = (unsigned char *)&params;
2043 param.len = sizeof(params);
2044 param.type = 0;
2045
2046 inputItem.data = (unsigned char *)input;
2047 inputItem.len = inputLen;
2048 inputItem.type = 0;
2049
2050 outputItem.data = outbuf;
2051 outputItem.len = *outLen;
2052 outputItem.type = 0;
2053
2054 rv = PK11_SignWithSymKey(spec->keyMaterial.macKey, macType, &param,
2055 &outputItem, &inputItem);
2056 if (rv != SECSuccess) {
2057 if (PORT_GetErrorPORT_GetError_Util() == SEC_ERROR_INVALID_ALGORITHM) {
2058 /* ssl3_ComputeRecordMAC() expects the MAC to have been removed
2059 * from the input length already. */
2060 return ssl3_ComputeRecordMAC(spec, header, headerLen,
2061 input, inputLen - macSize,
2062 outbuf, outLen);
2063 }
2064
2065 *outLen = 0;
2066 rv = SECFailure;
2067 ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
2068 return rv;
2069 }
2070
2071 PORT_Assert(outputItem.len == (unsigned)macSize)((outputItem.len == (unsigned)macSize)?((void)0):PR_Assert("outputItem.len == (unsigned)macSize"
,"ssl3con.c",2071))
;
2072 *outLen = outputItem.len;
2073
2074 return rv;
2075}
2076
2077static PRBool
2078ssl3_ClientAuthTokenPresent(sslSessionID *sid)
2079{
2080 PK11SlotInfo *slot = NULL((void*)0);
2081 PRBool isPresent = PR_TRUE1;
2082
2083 /* we only care if we are doing client auth */
2084 if (!sid || !sid->u.ssl3.clAuthValid) {
2085 return PR_TRUE1;
2086 }
2087
2088 /* get the slot */
2089 slot = SECMOD_LookupSlot(sid->u.ssl3.clAuthModuleID,
2090 sid->u.ssl3.clAuthSlotID);
2091 if (slot == NULL((void*)0) ||
2092 !PK11_IsPresent(slot) ||
2093 sid->u.ssl3.clAuthSeries != PK11_GetSlotSeries(slot) ||
2094 sid->u.ssl3.clAuthSlotID != PK11_GetSlotID(slot) ||
2095 sid->u.ssl3.clAuthModuleID != PK11_GetModuleID(slot) ||
2096 (PK11_NeedLogin(slot) && !PK11_IsLoggedIn(slot, NULL((void*)0)))) {
2097 isPresent = PR_FALSE0;
2098 }
2099 if (slot) {
2100 PK11_FreeSlot(slot);
2101 }
2102 return isPresent;
2103}
2104
2105/* Caller must hold the spec read lock. */
2106SECStatus
2107ssl3_MACEncryptRecord(ssl3CipherSpec *cwSpec,
2108 PRBool isServer,
2109 PRBool isDTLS,
2110 SSLContentType ct,
2111 const PRUint8 *pIn,
2112 PRUint32 contentLen,
2113 sslBuffer *wrBuf)
2114{
2115 SECStatus rv;
2116 PRUint32 macLen = 0;
2117 PRUint32 fragLen;
2118 PRUint32 p1Len, p2Len, oddLen = 0;
2119 unsigned int ivLen = 0;
2120 unsigned char pseudoHeaderBuf[13];
2121 sslBuffer pseudoHeader = SSL_BUFFER(pseudoHeaderBuf){ pseudoHeaderBuf, 0, sizeof(pseudoHeaderBuf), 1 };
2122 unsigned int len;
2123
2124 if (cwSpec->cipherDef->type == type_block &&
2125 cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_10x0302) {
2126 /* Prepend the per-record explicit IV using technique 2b from
2127 * RFC 4346 section 6.2.3.2: The IV is a cryptographically
2128 * strong random number XORed with the CBC residue from the previous
2129 * record.
2130 */
2131 ivLen = cwSpec->cipherDef->iv_size;
2132 if (ivLen > SSL_BUFFER_SPACE(wrBuf)((wrBuf)->space - (wrBuf)->len)) {
2133 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
2134 return SECFailure;
2135 }
2136 rv = PK11_GenerateRandom(SSL_BUFFER_NEXT(wrBuf)((wrBuf)->buf + (wrBuf)->len), ivLen);
2137 if (rv != SECSuccess) {
2138 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
2139 return rv;
2140 }
2141 rv = cwSpec->cipher(cwSpec->cipherContext,
2142 SSL_BUFFER_NEXT(wrBuf)((wrBuf)->buf + (wrBuf)->len), /* output */
2143 &len, /* outlen */
2144 ivLen, /* max outlen */
2145 SSL_BUFFER_NEXT(wrBuf)((wrBuf)->buf + (wrBuf)->len), /* input */
2146 ivLen); /* input len */
2147 if (rv != SECSuccess || len != ivLen) {
2148 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_ENCRYPTION_FAILURE);
2149 return SECFailure;
2150 }
2151
2152 rv = sslBuffer_Skip(wrBuf, len, NULL((void*)0));
2153 PORT_Assert(rv == SECSuccess)((rv == SECSuccess)?((void)0):PR_Assert("rv == SECSuccess","ssl3con.c"
,2153))
; /* Can't fail. */
2154 }
2155 rv = ssl3_BuildRecordPseudoHeader(
2156 cwSpec->epoch, cwSpec->nextSeqNum, ct,
2157 cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_00x0301, cwSpec->recordVersion,
2158 isDTLS, contentLen, &pseudoHeader, cwSpec->version);
2159 PORT_Assert(rv == SECSuccess)((rv == SECSuccess)?((void)0):PR_Assert("rv == SECSuccess","ssl3con.c"
,2159))
;
2160 if (cwSpec->cipherDef->type == type_aead) {
2161 const unsigned int nonceLen = cwSpec->cipherDef->explicit_nonce_size;
2162 const unsigned int tagLen = cwSpec->cipherDef->tag_size;
2163 unsigned int ivOffset = 0;
2164 CK_GENERATOR_FUNCTION gen;
2165 /* ivOut includes the iv and the nonce and is the internal iv/nonce
2166 * for the AEAD function. On Encrypt, this is an in/out parameter */
2167 unsigned char ivOut[MAX_IV_LENGTH24];
2168 ivLen = cwSpec->cipherDef->iv_size;
2169
2170 PORT_Assert((ivLen + nonceLen) <= MAX_IV_LENGTH)(((ivLen + nonceLen) <= 24)?((void)0):PR_Assert("(ivLen + nonceLen) <= MAX_IV_LENGTH"
,"ssl3con.c",2170))
;
2171 PORT_Assert((ivLen + nonceLen) >= sizeof(sslSequenceNumber))(((ivLen + nonceLen) >= sizeof(sslSequenceNumber))?((void)
0):PR_Assert("(ivLen + nonceLen) >= sizeof(sslSequenceNumber)"
,"ssl3con.c",2171))
;
2172
2173 if (nonceLen + contentLen + tagLen > SSL_BUFFER_SPACE(wrBuf)((wrBuf)->space - (wrBuf)->len)) {
2174 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
2175 return SECFailure;
2176 }
2177
2178 if (nonceLen == 0) {
2179 ivOffset = ivLen - sizeof(sslSequenceNumber);
2180 gen = CKG_GENERATE_COUNTER_XOR0x00000004UL;
2181 } else {
2182 ivOffset = ivLen;
2183 gen = CKG_GENERATE_COUNTER0x00000002UL;
2184 }
2185 ivOffset = tls13_SetupAeadIv(isDTLS, cwSpec->version, ivOut, cwSpec->keyMaterial.iv,
2186 ivOffset, ivLen, cwSpec->epoch);
2187 rv = tls13_AEAD(cwSpec->cipherContext,
2188 PR_FALSE0,
2189 gen, ivOffset * BPB8, /* iv generator params */
2190 ivOut, /* iv in */
2191 ivOut, /* iv out */
2192 ivLen + nonceLen, /* full iv length */
2193 NULL((void*)0), 0, /* nonce is generated*/
2194 SSL_BUFFER_BASE(&pseudoHeader)((&pseudoHeader)->buf), /* aad */
2195 SSL_BUFFER_LEN(&pseudoHeader)((&pseudoHeader)->len), /* aadlen */
2196 SSL_BUFFER_NEXT(wrBuf)((wrBuf)->buf + (wrBuf)->len) + nonceLen, /* output */
2197 &len, /* out len */
2198 SSL_BUFFER_SPACE(wrBuf)((wrBuf)->space - (wrBuf)->len) - nonceLen, /* max out */
2199 tagLen,
2200 pIn, contentLen); /* input */
2201 if (rv != SECSuccess) {
2202 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_ENCRYPTION_FAILURE);
2203 return SECFailure;
2204 }
2205 len += nonceLen; /* include the nonce at the beginning */
2206 /* copy out the generated iv if we are using explict nonces */
2207 if (nonceLen) {
2208 PORT_Memcpymemcpy(SSL_BUFFER_NEXT(wrBuf)((wrBuf)->buf + (wrBuf)->len), ivOut + ivLen, nonceLen);
2209 }
2210
2211 rv = sslBuffer_Skip(wrBuf, len, NULL((void*)0));
2212 PORT_Assert(rv == SECSuccess)((rv == SECSuccess)?((void)0):PR_Assert("rv == SECSuccess","ssl3con.c"
,2212))
; /* Can't fail. */
2213 } else {
2214 int blockSize = cwSpec->cipherDef->block_size;
2215
2216 /*
2217 * Add the MAC
2218 */
2219 rv = ssl3_ComputeRecordMAC(cwSpec, SSL_BUFFER_BASE(&pseudoHeader)((&pseudoHeader)->buf),
2220 SSL_BUFFER_LEN(&pseudoHeader)((&pseudoHeader)->len),
2221 pIn, contentLen,
2222 SSL_BUFFER_NEXT(wrBuf)((wrBuf)->buf + (wrBuf)->len) + contentLen, &macLen);
2223 if (rv != SECSuccess) {
2224 ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
2225 return SECFailure;
2226 }
2227 p1Len = contentLen;
2228 p2Len = macLen;
2229 fragLen = contentLen + macLen; /* needs to be encrypted */
2230 PORT_Assert(fragLen <= MAX_FRAGMENT_LENGTH + 1024)((fragLen <= 16384 + 1024)?((void)0):PR_Assert("fragLen <= MAX_FRAGMENT_LENGTH + 1024"
,"ssl3con.c",2230))
;
2231
2232 /*
2233 * Pad the text (if we're doing a block cipher)
2234 * then Encrypt it
2235 */
2236 if (cwSpec->cipherDef->type == type_block) {
2237 unsigned char *pBuf;
2238 int padding_length;
2239 int i;
2240
2241 oddLen = contentLen % blockSize;
2242 /* Assume blockSize is a power of two */
2243 padding_length = blockSize - 1 - ((fragLen) & (blockSize - 1));
2244 fragLen += padding_length + 1;
2245 PORT_Assert((fragLen % blockSize) == 0)(((fragLen % blockSize) == 0)?((void)0):PR_Assert("(fragLen % blockSize) == 0"
,"ssl3con.c",2245))
;
2246
2247 /* Pad according to TLS rules (also acceptable to SSL3). */
2248 pBuf = SSL_BUFFER_NEXT(wrBuf)((wrBuf)->buf + (wrBuf)->len) + fragLen - 1;
2249 for (i = padding_length + 1; i > 0; --i) {
2250 *pBuf-- = padding_length;
2251 }
2252 /* now, if contentLen is not a multiple of block size, fix it */
2253 p2Len = fragLen - p1Len;
2254 }
2255 if (p1Len < 256) {
2256 oddLen = p1Len;
2257 p1Len = 0;
2258 } else {
2259 p1Len -= oddLen;
2260 }
2261 if (oddLen) {
2262 p2Len += oddLen;
2263 PORT_Assert((blockSize < 2) ||(((blockSize < 2) || (p2Len % blockSize) == 0)?((void)0):PR_Assert
("(blockSize < 2) || (p2Len % blockSize) == 0","ssl3con.c"
,2264))
2264 (p2Len % blockSize) == 0)(((blockSize < 2) || (p2Len % blockSize) == 0)?((void)0):PR_Assert
("(blockSize < 2) || (p2Len % blockSize) == 0","ssl3con.c"
,2264))
;
2265 memmove(SSL_BUFFER_NEXT(wrBuf)((wrBuf)->buf + (wrBuf)->len) + p1Len, pIn + p1Len, oddLen);
2266 }
2267 if (p1Len > 0) {
2268 unsigned int cipherBytesPart1 = 0;
2269 rv = cwSpec->cipher(cwSpec->cipherContext,
2270 SSL_BUFFER_NEXT(wrBuf)((wrBuf)->buf + (wrBuf)->len), /* output */
2271 &cipherBytesPart1, /* actual outlen */
2272 p1Len, /* max outlen */
2273 pIn,
2274 p1Len); /* input, and inputlen */
2275 PORT_Assert(rv == SECSuccess && cipherBytesPart1 == p1Len)((rv == SECSuccess && cipherBytesPart1 == p1Len)?((void
)0):PR_Assert("rv == SECSuccess && cipherBytesPart1 == p1Len"
,"ssl3con.c",2275))
;
2276 if (rv != SECSuccess || cipherBytesPart1 != p1Len) {
2277 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_ENCRYPTION_FAILURE);
2278 return SECFailure;
2279 }
2280 rv = sslBuffer_Skip(wrBuf, p1Len, NULL((void*)0));
2281 PORT_Assert(rv == SECSuccess)((rv == SECSuccess)?((void)0):PR_Assert("rv == SECSuccess","ssl3con.c"
,2281))
;
2282 }
2283 if (p2Len > 0) {
2284 unsigned int cipherBytesPart2 = 0;
2285 rv = cwSpec->cipher(cwSpec->cipherContext,
2286 SSL_BUFFER_NEXT(wrBuf)((wrBuf)->buf + (wrBuf)->len),
2287 &cipherBytesPart2, /* output and actual outLen */
2288 p2Len, /* max outlen */
2289 SSL_BUFFER_NEXT(wrBuf)((wrBuf)->buf + (wrBuf)->len),
2290 p2Len); /* input and inputLen*/
2291 PORT_Assert(rv == SECSuccess && cipherBytesPart2 == p2Len)((rv == SECSuccess && cipherBytesPart2 == p2Len)?((void
)0):PR_Assert("rv == SECSuccess && cipherBytesPart2 == p2Len"
,"ssl3con.c",2291))
;
2292 if (rv != SECSuccess || cipherBytesPart2 != p2Len) {
2293 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_ENCRYPTION_FAILURE);
2294 return SECFailure;
2295 }
2296 rv = sslBuffer_Skip(wrBuf, p2Len, NULL((void*)0));
2297 PORT_Assert(rv == SECSuccess)((rv == SECSuccess)?((void)0):PR_Assert("rv == SECSuccess","ssl3con.c"
,2297))
;
2298 }
2299 }
2300
2301 return SECSuccess;
2302}
2303
2304/* Note: though this can report failure, it shouldn't. */
2305SECStatus
2306ssl_InsertRecordHeader(const sslSocket *ss, ssl3CipherSpec *cwSpec,
2307 SSLContentType contentType, sslBuffer *wrBuf,
2308 PRBool *needsLength)
2309{
2310 SECStatus rv;
2311
2312#ifndef UNSAFE_FUZZER_MODE
2313 if (cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_30x0304 &&
2314 cwSpec->epoch > TrafficKeyClearText) {
2315 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
2316 return dtls13_InsertCipherTextHeader(ss, cwSpec, wrBuf,
2317 needsLength);
2318 }
2319 contentType = ssl_ct_application_data;
2320 }
2321#endif
2322 rv = sslBuffer_AppendNumber(wrBuf, contentType, 1);
2323 if (rv != SECSuccess) {
2324 return SECFailure;
2325 }
2326
2327 rv = sslBuffer_AppendNumber(wrBuf, cwSpec->recordVersion, 2);
2328 if (rv != SECSuccess) {
2329 return SECFailure;
2330 }
2331 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
2332 rv = sslBuffer_AppendNumber(wrBuf, cwSpec->epoch, 2);
2333 if (rv != SECSuccess) {
2334 return SECFailure;
2335 }
2336 rv = sslBuffer_AppendNumber(wrBuf, cwSpec->nextSeqNum, 6);
2337 if (rv != SECSuccess) {
2338 return SECFailure;
2339 }
2340 }
2341 *needsLength = PR_TRUE1;
2342 return SECSuccess;
2343}
2344
2345SECStatus
2346ssl_ProtectRecord(sslSocket *ss, ssl3CipherSpec *cwSpec, SSLContentType ct,
2347 const PRUint8 *pIn, PRUint32 contentLen, sslBuffer *wrBuf)
2348{
2349 PRBool needsLength;
2350 unsigned int lenOffset;
2351 SECStatus rv;
2352
2353 PORT_Assert(cwSpec->direction == ssl_secret_write)((cwSpec->direction == ssl_secret_write)?((void)0):PR_Assert
("cwSpec->direction == ssl_secret_write","ssl3con.c",2353)
)
;
2354 PORT_Assert(SSL_BUFFER_LEN(wrBuf) == 0)((((wrBuf)->len) == 0)?((void)0):PR_Assert("SSL_BUFFER_LEN(wrBuf) == 0"
,"ssl3con.c",2354))
;
2355 PORT_Assert(cwSpec->cipherDef->max_records <= RECORD_SEQ_MAX)((cwSpec->cipherDef->max_records <= ((1ULL << 48
) - 1))?((void)0):PR_Assert("cwSpec->cipherDef->max_records <= RECORD_SEQ_MAX"
,"ssl3con.c",2355))
;
2356
2357 if (cwSpec->nextSeqNum >= cwSpec->cipherDef->max_records) {
2358 SSL_TRC(3, ("%d: SSL[-]: write sequence number at limit 0x%0llx",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL[-]: write sequence number at limit 0x%0llx"
, getpid(), cwSpec->nextSeqNum)
2359 SSL_GETPID(), cwSpec->nextSeqNum))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL[-]: write sequence number at limit 0x%0llx"
, getpid(), cwSpec->nextSeqNum)
;
2360 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_TOO_MANY_RECORDS);
2361 return SECFailure;
2362 }
2363
2364 rv = ssl_InsertRecordHeader(ss, cwSpec, ct, wrBuf, &needsLength);
2365 if (rv != SECSuccess) {
2366 return SECFailure;
2367 }
2368 if (needsLength) {
2369 rv = sslBuffer_Skip(wrBuf, 2, &lenOffset);
2370 if (rv != SECSuccess) {
2371 return SECFailure;
2372 }
2373 }
2374
2375#ifdef UNSAFE_FUZZER_MODE
2376 {
2377 unsigned int len;
2378 rv = Null_Cipher(NULL((void*)0), SSL_BUFFER_NEXT(wrBuf)((wrBuf)->buf + (wrBuf)->len), &len,
2379 SSL_BUFFER_SPACE(wrBuf)((wrBuf)->space - (wrBuf)->len), pIn, contentLen);
2380 if (rv != SECSuccess) {
2381 return SECFailure; /* error was set */
2382 }
2383 rv = sslBuffer_Skip(wrBuf, len, NULL((void*)0));
2384 PORT_Assert(rv == SECSuccess)((rv == SECSuccess)?((void)0):PR_Assert("rv == SECSuccess","ssl3con.c"
,2384))
; /* Can't fail. */
2385 }
2386#else
2387 if (cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_30x0304) {
2388 PRUint8 *cipherText = SSL_BUFFER_NEXT(wrBuf)((wrBuf)->buf + (wrBuf)->len);
2389 unsigned int bufLen = SSL_BUFFER_LEN(wrBuf)((wrBuf)->len);
2390 rv = tls13_ProtectRecord(ss, cwSpec, ct, pIn, contentLen, wrBuf);
2391 if (rv != SECSuccess) {
2392 return SECFailure;
2393 }
2394 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
2395 bufLen = SSL_BUFFER_LEN(wrBuf)((wrBuf)->len) - bufLen;
2396 rv = dtls13_MaskSequenceNumber(ss, cwSpec,
2397 SSL_BUFFER_BASE(wrBuf)((wrBuf)->buf),
2398 cipherText, bufLen);
2399 }
2400 } else {
2401 rv = ssl3_MACEncryptRecord(cwSpec, ss->sec.isServer, IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram), ct,
2402 pIn, contentLen, wrBuf);
2403 }
2404#endif
2405 if (rv != SECSuccess) {
2406 return SECFailure; /* error was set */
2407 }
2408
2409 if (needsLength) {
2410 /* Insert the length. */
2411 rv = sslBuffer_InsertLength(wrBuf, lenOffset, 2);
2412 if (rv != SECSuccess) {
2413 PORT_Assert(0)((0)?((void)0):PR_Assert("0","ssl3con.c",2413)); /* Can't fail. */
2414 return SECFailure;
2415 }
2416 }
2417
2418 ++cwSpec->nextSeqNum;
2419 return SECSuccess;
2420}
2421
2422SECStatus
2423ssl_ProtectNextRecord(sslSocket *ss, ssl3CipherSpec *spec, SSLContentType ct,
2424 const PRUint8 *pIn, unsigned int nIn,
2425 unsigned int *written)
2426{
2427 sslBuffer *wrBuf = &ss->sec.writeBuf;
2428 unsigned int contentLen;
2429 unsigned int spaceNeeded;
2430 SECStatus rv;
2431
2432 contentLen = PR_MIN(nIn, spec->recordSizeLimit)((nIn)<(spec->recordSizeLimit)?(nIn):(spec->recordSizeLimit
))
;
2433 spaceNeeded = contentLen + SSL3_BUFFER_FUDGE100;
2434 if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_10x0302 &&
2435 spec->cipherDef->type == type_block) {
2436 spaceNeeded += spec->cipherDef->iv_size;
2437 }
2438 if (spaceNeeded > SSL_BUFFER_SPACE(wrBuf)((wrBuf)->space - (wrBuf)->len)) {
2439 rv = sslBuffer_Grow(wrBuf, spaceNeeded);
2440 if (rv != SECSuccess) {
2441 SSL_DBG(("%d: SSL3[%d]: failed to expand write buffer to %d",if (ssl_debug) ssl_Trace ("%d: SSL3[%d]: failed to expand write buffer to %d"
, getpid(), ss->fd, spaceNeeded)
2442 SSL_GETPID(), ss->fd, spaceNeeded))if (ssl_debug) ssl_Trace ("%d: SSL3[%d]: failed to expand write buffer to %d"
, getpid(), ss->fd, spaceNeeded)
;
2443 return SECFailure;
2444 }
2445 }
2446
2447 rv = ssl_ProtectRecord(ss, spec, ct, pIn, contentLen, wrBuf);
2448 if (rv != SECSuccess) {
2449 return SECFailure;
2450 }
2451 PRINT_BUF(50, (ss, "send (encrypted) record data:",if (ssl_trace >= (50)) ssl_PrintBuf (ss, "send (encrypted) record data:"
, ((wrBuf)->buf), ((wrBuf)->len))
2452 SSL_BUFFER_BASE(wrBuf), SSL_BUFFER_LEN(wrBuf)))if (ssl_trace >= (50)) ssl_PrintBuf (ss, "send (encrypted) record data:"
, ((wrBuf)->buf), ((wrBuf)->len))
;
2453 *written = contentLen;
2454 return SECSuccess;
2455}
2456
2457/* Process the plain text before sending it.
2458 * Returns the number of bytes of plaintext that were successfully sent
2459 * plus the number of bytes of plaintext that were copied into the
2460 * output (write) buffer.
2461 * Returns -1 on an error. PR_WOULD_BLOCK_ERROR is set if the error is blocking
2462 * and not terminal.
2463 *
2464 * Notes on the use of the private ssl flags:
2465 * (no private SSL flags)
2466 * Attempt to make and send SSL records for all plaintext
2467 * If non-blocking and a send gets WOULD_BLOCK,
2468 * or if the pending (ciphertext) buffer is not empty,
2469 * then buffer remaining bytes of ciphertext into pending buf,
2470 * and continue to do that for all succssive records until all
2471 * bytes are used.
2472 * ssl_SEND_FLAG_FORCE_INTO_BUFFER
2473 * As above, except this suppresses all write attempts, and forces
2474 * all ciphertext into the pending ciphertext buffer.
2475 * ssl_SEND_FLAG_USE_EPOCH (for DTLS)
2476 * Forces the use of the provided epoch
2477 */
2478PRInt32
2479ssl3_SendRecord(sslSocket *ss,
2480 ssl3CipherSpec *cwSpec, /* non-NULL for DTLS retransmits */
2481 SSLContentType ct,
2482 const PRUint8 *pIn, /* input buffer */
2483 PRInt32 nIn, /* bytes of input */
2484 PRInt32 flags)
2485{
2486 sslBuffer *wrBuf = &ss->sec.writeBuf;
2487 ssl3CipherSpec *spec;
2488 SECStatus rv;
2489 PRInt32 totalSent = 0;
2490
2491 SSL_TRC(3, ("%d: SSL3[%d] SendRecord type: %s nIn=%d",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d] SendRecord type: %s nIn=%d"
, getpid(), ss->fd, ssl3_DecodeContentType(ct), nIn)
2492 SSL_GETPID(), ss->fd, ssl3_DecodeContentType(ct),if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d] SendRecord type: %s nIn=%d"
, getpid(), ss->fd, ssl3_DecodeContentType(ct), nIn)
2493 nIn))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d] SendRecord type: %s nIn=%d"
, getpid(), ss->fd, ssl3_DecodeContentType(ct), nIn)
;
2494 PRINT_BUF(50, (ss, "Send record (plain text)", pIn, nIn))if (ssl_trace >= (50)) ssl_PrintBuf (ss, "Send record (plain text)"
, pIn, nIn)
;
2495
2496 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->xmitBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveXmitBufLock(ss)"
,"ssl3con.c",2496))
;
2497 PORT_Assert(SSL_BUFFER_LEN(wrBuf) == 0)((((wrBuf)->len) == 0)?((void)0):PR_Assert("SSL_BUFFER_LEN(wrBuf) == 0"
,"ssl3con.c",2497))
;
2498
2499 if (ss->ssl3.fatalAlertSent) {
2500 SSL_TRC(3, ("%d: SSL3[%d] Suppress write, fatal alert already sent",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d] Suppress write, fatal alert already sent"
, getpid(), ss->fd)
2501 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d] Suppress write, fatal alert already sent"
, getpid(), ss->fd)
;
2502 if (ct != ssl_ct_alert) {
2503 /* If we are sending an alert, then we already have an
2504 * error, so don't overwrite. */
2505 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_HANDSHAKE_FAILED);
2506 }
2507 return -1;
2508 }
2509
2510 /* check for Token Presence */
2511 if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
2512 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
2513 return -1;
2514 }
2515
2516 if (ss->recordWriteCallback) {
2517 PRUint16 epoch;
2518 ssl_GetSpecReadLock(ss){ if (!ss->opt.noLocks) NSSRWLock_LockRead_Util((ss)->specLock
); }
;
2519 epoch = ss->ssl3.cwSpec->epoch;
2520 ssl_ReleaseSpecReadLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockRead_Util((ss)->
specLock); }
;
2521 rv = ss->recordWriteCallback(ss->fd, epoch, ct, pIn, nIn,
2522 ss->recordWriteCallbackArg);
2523 if (rv != SECSuccess) {
2524 return -1;
2525 }
2526 return nIn;
2527 }
2528
2529 if (cwSpec) {
2530 /* cwSpec can only be set for retransmissions of the DTLS handshake. */
2531 PORT_Assert(IS_DTLS(ss) &&(((ss->protocolVariant == ssl_variant_datagram) &&
(ct == ssl_ct_handshake || ct == ssl_ct_change_cipher_spec))
?((void)0):PR_Assert("IS_DTLS(ss) && (ct == ssl_ct_handshake || ct == ssl_ct_change_cipher_spec)"
,"ssl3con.c",2533))
2532 (ct == ssl_ct_handshake ||(((ss->protocolVariant == ssl_variant_datagram) &&
(ct == ssl_ct_handshake || ct == ssl_ct_change_cipher_spec))
?((void)0):PR_Assert("IS_DTLS(ss) && (ct == ssl_ct_handshake || ct == ssl_ct_change_cipher_spec)"
,"ssl3con.c",2533))
2533 ct == ssl_ct_change_cipher_spec))(((ss->protocolVariant == ssl_variant_datagram) &&
(ct == ssl_ct_handshake || ct == ssl_ct_change_cipher_spec))
?((void)0):PR_Assert("IS_DTLS(ss) && (ct == ssl_ct_handshake || ct == ssl_ct_change_cipher_spec)"
,"ssl3con.c",2533))
;
2534 spec = cwSpec;
2535 } else {
2536 spec = ss->ssl3.cwSpec;
2537 }
2538
2539 while (nIn > 0) {
2540 unsigned int written = 0;
2541 PRInt32 sent;
2542
2543 ssl_GetSpecReadLock(ss){ if (!ss->opt.noLocks) NSSRWLock_LockRead_Util((ss)->specLock
); }
;
2544 rv = ssl_ProtectNextRecord(ss, spec, ct, pIn, nIn, &written);
2545 ssl_ReleaseSpecReadLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockRead_Util((ss)->
specLock); }
;
2546 if (rv != SECSuccess) {
2547 goto loser;
2548 }
2549
2550 PORT_Assert(written > 0)((written > 0)?((void)0):PR_Assert("written > 0","ssl3con.c"
,2550))
;
2551 /* DTLS should not fragment non-application data here. */
2552 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram) && ct != ssl_ct_application_data) {
2553 PORT_Assert(written == nIn)((written == nIn)?((void)0):PR_Assert("written == nIn","ssl3con.c"
,2553))
;
2554 }
2555
2556 pIn += written;
2557 nIn -= written;
2558 PORT_Assert(nIn >= 0)((nIn >= 0)?((void)0):PR_Assert("nIn >= 0","ssl3con.c",
2558))
;
2559
2560 /* If there's still some previously saved ciphertext,
2561 * or the caller doesn't want us to send the data yet,
2562 * then add all our new ciphertext to the amount previously saved.
2563 */
2564 if ((ss->pendingBuf.len > 0) ||
2565 (flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER0x40000000)) {
2566
2567 rv = ssl_SaveWriteData(ss, SSL_BUFFER_BASE(wrBuf)((wrBuf)->buf),
2568 SSL_BUFFER_LEN(wrBuf)((wrBuf)->len));
2569 if (rv != SECSuccess) {
2570 /* presumably a memory error, SEC_ERROR_NO_MEMORY */
2571 goto loser;
2572 }
2573
2574 if (!(flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER0x40000000)) {
2575 ss->handshakeBegun = 1;
2576 sent = ssl_SendSavedWriteData(ss);
2577 if (sent < 0 && PR_GetError() != PR_WOULD_BLOCK_ERROR(-5998L)) {
2578 ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
2579 goto loser;
2580 }
2581 if (ss->pendingBuf.len) {
2582 flags |= ssl_SEND_FLAG_FORCE_INTO_BUFFER0x40000000;
2583 }
2584 }
2585 } else {
2586 PORT_Assert(SSL_BUFFER_LEN(wrBuf) > 0)((((wrBuf)->len) > 0)?((void)0):PR_Assert("SSL_BUFFER_LEN(wrBuf) > 0"
,"ssl3con.c",2586))
;
2587 ss->handshakeBegun = 1;
2588 sent = ssl_DefSend(ss, SSL_BUFFER_BASE(wrBuf)((wrBuf)->buf),
2589 SSL_BUFFER_LEN(wrBuf)((wrBuf)->len),
2590 flags & ~ssl_SEND_FLAG_MASK0x7f000000);
2591 if (sent < 0) {
2592 if (PORT_GetErrorPORT_GetError_Util() != PR_WOULD_BLOCK_ERROR(-5998L)) {
2593 ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
2594 goto loser;
2595 }
2596 /* we got PR_WOULD_BLOCK_ERROR, which means none was sent. */
2597 sent = 0;
2598 }
2599 if (SSL_BUFFER_LEN(wrBuf)((wrBuf)->len) > (unsigned int)sent) {
2600 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
2601 /* DTLS just says no in this case. No buffering */
2602 PORT_SetErrorPORT_SetError_Util(PR_WOULD_BLOCK_ERROR(-5998L));
2603 goto loser;
2604 }
2605 /* now take all the remaining unsent new ciphertext and
2606 * append it to the buffer of previously unsent ciphertext.
2607 */
2608 rv = ssl_SaveWriteData(ss, SSL_BUFFER_BASE(wrBuf)((wrBuf)->buf) + sent,
2609 SSL_BUFFER_LEN(wrBuf)((wrBuf)->len) - sent);
2610 if (rv != SECSuccess) {
2611 /* presumably a memory error, SEC_ERROR_NO_MEMORY */
2612 goto loser;
2613 }
2614 }
2615 }
2616 wrBuf->len = 0;
2617 totalSent += written;
2618 }
2619 return totalSent;
2620
2621loser:
2622 /* Don't leave bits of buffer lying around. */
2623 wrBuf->len = 0;
2624 return -1;
2625}
2626
2627#define SSL3_PENDING_HIGH_WATER1024 1024
2628
2629/* Attempt to send the content of "in" in an SSL application_data record.
2630 * Returns "len" or -1 on failure.
2631 */
2632int
2633ssl3_SendApplicationData(sslSocket *ss, const unsigned char *in,
2634 PRInt32 len, PRInt32 flags)
2635{
2636 PRInt32 totalSent = 0;
2637 PRInt32 discarded = 0;
2638 PRBool splitNeeded = PR_FALSE0;
2639
2640 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->xmitBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveXmitBufLock(ss)"
,"ssl3con.c",2640))
;
2641 /* These flags for internal use only */
2642 PORT_Assert(!(flags & ssl_SEND_FLAG_NO_RETRANSMIT))((!(flags & 0x08000000))?((void)0):PR_Assert("!(flags & ssl_SEND_FLAG_NO_RETRANSMIT)"
,"ssl3con.c",2642))
;
2643 if (len < 0 || !in) {
2644 PORT_SetErrorPORT_SetError_Util(PR_INVALID_ARGUMENT_ERROR(-5987L));
2645 return -1;
2646 }
2647
2648 if (ss->pendingBuf.len > SSL3_PENDING_HIGH_WATER1024 &&
2649 !ssl_SocketIsBlocking(ss)) {
2650 PORT_Assert(!ssl_SocketIsBlocking(ss))((!ssl_SocketIsBlocking(ss))?((void)0):PR_Assert("!ssl_SocketIsBlocking(ss)"
,"ssl3con.c",2650))
;
2651 PORT_SetErrorPORT_SetError_Util(PR_WOULD_BLOCK_ERROR(-5998L));
2652 return -1;
2653 }
2654
2655 if (ss->appDataBuffered && len) {
2656 PORT_Assert(in[0] == (unsigned char)(ss->appDataBuffered))((in[0] == (unsigned char)(ss->appDataBuffered))?((void)0)
:PR_Assert("in[0] == (unsigned char)(ss->appDataBuffered)"
,"ssl3con.c",2656))
;
2657 if (in[0] != (unsigned char)(ss->appDataBuffered)) {
2658 PORT_SetErrorPORT_SetError_Util(PR_INVALID_ARGUMENT_ERROR(-5987L));
2659 return -1;
2660 }
2661 in++;
2662 len--;
2663 discarded = 1;
2664 }
2665
2666 /* We will split the first byte of the record into its own record, as
2667 * explained in the documentation for SSL_CBC_RANDOM_IV in ssl.h.
2668 */
2669 if (len > 1 && ss->opt.cbcRandomIV &&
2670 ss->version < SSL_LIBRARY_VERSION_TLS_1_10x0302 &&
2671 ss->ssl3.cwSpec->cipherDef->type == type_block /* CBC */) {
2672 splitNeeded = PR_TRUE1;
2673 }
2674
2675 while (len > totalSent) {
2676 PRInt32 sent, toSend;
2677
2678 if (totalSent > 0) {
2679 /*
2680 * The thread yield is intended to give the reader thread a
2681 * chance to get some cycles while the writer thread is in
2682 * the middle of a large application data write. (See
2683 * Bugzilla bug 127740, comment #1.)
2684 */
2685 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
;
2686 PR_Sleep(PR_INTERVAL_NO_WAIT0UL); /* PR_Yield(); */
2687 ssl_GetXmitBufLock(ss){ if (!ss->opt.noLocks) PR_EnterMonitor(((ss)->xmitBufLock
)); }
;
2688 }
2689
2690 if (splitNeeded) {
2691 toSend = 1;
2692 splitNeeded = PR_FALSE0;
2693 } else {
2694 toSend = PR_MIN(len - totalSent, MAX_FRAGMENT_LENGTH)((len - totalSent)<(16384)?(len - totalSent):(16384));
2695 }
2696
2697 /*
2698 * Note that the 0 epoch is OK because flags will never require
2699 * its use, as guaranteed by the PORT_Assert above.
2700 */
2701 sent = ssl3_SendRecord(ss, NULL((void*)0), ssl_ct_application_data,
2702 in + totalSent, toSend, flags);
2703 if (sent < 0) {
2704 if (totalSent > 0 && PR_GetError() == PR_WOULD_BLOCK_ERROR(-5998L)) {
2705 PORT_Assert(ss->lastWriteBlocked)((ss->lastWriteBlocked)?((void)0):PR_Assert("ss->lastWriteBlocked"
,"ssl3con.c",2705))
;
2706 break;
2707 }
2708 return -1; /* error code set by ssl3_SendRecord */
2709 }
2710 totalSent += sent;
2711 if (ss->pendingBuf.len) {
2712 /* must be a non-blocking socket */
2713 PORT_Assert(!ssl_SocketIsBlocking(ss))((!ssl_SocketIsBlocking(ss))?((void)0):PR_Assert("!ssl_SocketIsBlocking(ss)"
,"ssl3con.c",2713))
;
2714 PORT_Assert(ss->lastWriteBlocked)((ss->lastWriteBlocked)?((void)0):PR_Assert("ss->lastWriteBlocked"
,"ssl3con.c",2714))
;
2715 break;
2716 }
2717 }
2718 if (ss->pendingBuf.len) {
2719 /* Must be non-blocking. */
2720 PORT_Assert(!ssl_SocketIsBlocking(ss))((!ssl_SocketIsBlocking(ss))?((void)0):PR_Assert("!ssl_SocketIsBlocking(ss)"
,"ssl3con.c",2720))
;
2721 if (totalSent > 0) {
2722 ss->appDataBuffered = 0x100 | in[totalSent - 1];
2723 }
2724
2725 totalSent = totalSent + discarded - 1;
2726 if (totalSent <= 0) {
2727 PORT_SetErrorPORT_SetError_Util(PR_WOULD_BLOCK_ERROR(-5998L));
2728 totalSent = SECFailure;
2729 }
2730 return totalSent;
2731 }
2732 ss->appDataBuffered = 0;
2733 return totalSent + discarded;
2734}
2735
2736/* Attempt to send buffered handshake messages.
2737 * Always set sendBuf.len to 0, even when returning SECFailure.
2738 *
2739 * Depending on whether we are doing DTLS or not, this either calls
2740 *
2741 * - ssl3_FlushHandshakeMessages if non-DTLS
2742 * - dtls_FlushHandshakeMessages if DTLS
2743 *
2744 * Called from SSL3_SendAlert(), ssl3_SendChangeCipherSpecs(),
2745 * ssl3_AppendHandshake(), ssl3_SendClientHello(),
2746 * ssl3_SendHelloRequest(), ssl3_SendServerHelloDone(),
2747 * ssl3_SendFinished(),
2748 */
2749SECStatus
2750ssl3_FlushHandshake(sslSocket *ss, PRInt32 flags)
2751{
2752 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
2753 return dtls_FlushHandshakeMessages(ss, flags);
2754 }
2755 return ssl3_FlushHandshakeMessages(ss, flags);
2756}
2757
2758/* Attempt to send the content of sendBuf buffer in an SSL handshake record.
2759 * Always set sendBuf.len to 0, even when returning SECFailure.
2760 *
2761 * Called from ssl3_FlushHandshake
2762 */
2763static SECStatus
2764ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags)
2765{
2766 static const PRInt32 allowedFlags = ssl_SEND_FLAG_FORCE_INTO_BUFFER0x40000000;
2767 PRInt32 count = -1;
2768 SECStatus rv;
2769
2770 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",2770))
;
2771 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->xmitBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveXmitBufLock(ss)"
,"ssl3con.c",2771))
;
2772
2773 if (!ss->sec.ci.sendBuf.buf || !ss->sec.ci.sendBuf.len)
2774 return SECSuccess;
2775
2776 /* only these flags are allowed */
2777 PORT_Assert(!(flags & ~allowedFlags))((!(flags & ~allowedFlags))?((void)0):PR_Assert("!(flags & ~allowedFlags)"
,"ssl3con.c",2777))
;
2778 if ((flags & ~allowedFlags) != 0) {
2779 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
2780 return SECFailure;
2781 }
2782 count = ssl3_SendRecord(ss, NULL((void*)0), ssl_ct_handshake,
2783 ss->sec.ci.sendBuf.buf,
2784 ss->sec.ci.sendBuf.len, flags);
2785 if (count < 0) {
2786 int err = PORT_GetErrorPORT_GetError_Util();
2787 PORT_Assert(err != PR_WOULD_BLOCK_ERROR)((err != (-5998L))?((void)0):PR_Assert("err != PR_WOULD_BLOCK_ERROR"
,"ssl3con.c",2787))
;
2788 if (err == PR_WOULD_BLOCK_ERROR(-5998L)) {
2789 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
2790 }
2791 rv = SECFailure;
2792 } else if ((unsigned int)count < ss->sec.ci.sendBuf.len) {
2793 /* short write should never happen */
2794 PORT_Assert((unsigned int)count >= ss->sec.ci.sendBuf.len)(((unsigned int)count >= ss->sec.ci.sendBuf.len)?((void
)0):PR_Assert("(unsigned int)count >= ss->sec.ci.sendBuf.len"
,"ssl3con.c",2794))
;
2795 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
2796 rv = SECFailure;
2797 } else {
2798 rv = SECSuccess;
2799 }
2800
2801 /* Whether we succeeded or failed, toss the old handshake data. */
2802 ss->sec.ci.sendBuf.len = 0;
2803 return rv;
2804}
2805
2806/*
2807 * Called from ssl3_HandleAlert and from ssl3_HandleCertificate when
2808 * the remote client sends a negative response to our certificate request.
2809 * Returns SECFailure if the application has required client auth.
2810 * SECSuccess otherwise.
2811 */
2812SECStatus
2813ssl3_HandleNoCertificate(sslSocket *ss)
2814{
2815 ssl3_CleanupPeerCerts(ss);
2816
2817 /* If the server has required client-auth blindly but doesn't
2818 * actually look at the certificate it won't know that no
2819 * certificate was presented so we shutdown the socket to ensure
2820 * an error. We only do this if we haven't already completed the
2821 * first handshake because if we're redoing the handshake we
2822 * know the server is paying attention to the certificate.
2823 */
2824 if ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS((PRBool)1)) ||
2825 (!ss->firstHsDone &&
2826 (ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE((PRBool)2)))) {
2827 PRFileDesc *lower;
2828
2829 ssl_UncacheSessionID(ss);
2830
2831 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_30x0304) {
2832 SSL3_SendAlert(ss, alert_fatal, certificate_required);
2833 } else {
2834 SSL3_SendAlert(ss, alert_fatal, bad_certificate);
2835 }
2836
2837 lower = ss->fd->lower;
2838#ifdef _WIN32
2839 lower->methods->shutdown(lower, PR_SHUTDOWN_SEND);
2840#else
2841 lower->methods->shutdown(lower, PR_SHUTDOWN_BOTH);
2842#endif
2843 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_NO_CERTIFICATE);
2844 return SECFailure;
2845 }
2846 return SECSuccess;
2847}
2848
2849/************************************************************************
2850 * Alerts
2851 */
2852
2853/*
2854** Acquires both handshake and XmitBuf locks.
2855** Called from: ssl3_IllegalParameter <-
2856** ssl3_HandshakeFailure <-
2857** ssl3_HandleAlert <- ssl3_HandleRecord.
2858** ssl3_HandleChangeCipherSpecs <- ssl3_HandleRecord
2859** ssl3_ConsumeHandshakeVariable <-
2860** ssl3_HandleHelloRequest <-
2861** ssl3_HandleServerHello <-
2862** ssl3_HandleServerKeyExchange <-
2863** ssl3_HandleCertificateRequest <-
2864** ssl3_HandleServerHelloDone <-
2865** ssl3_HandleClientHello <-
2866** ssl3_HandleV2ClientHello <-
2867** ssl3_HandleCertificateVerify <-
2868** ssl3_HandleClientKeyExchange <-
2869** ssl3_HandleCertificate <-
2870** ssl3_HandleFinished <-
2871** ssl3_HandleHandshakeMessage <-
2872** ssl3_HandlePostHelloHandshakeMessage <-
2873** ssl3_HandleRecord <-
2874**
2875*/
2876SECStatus
2877SSL3_SendAlert(sslSocket *ss, SSL3AlertLevel level, SSL3AlertDescription desc)
2878{
2879 PRUint8 bytes[2];
2880 SECStatus rv;
2881 PRBool needHsLock = !ssl_HaveSSL3HandshakeLock(ss)((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock)) > 0
))
;
2882
2883 /* Check that if I need the HS lock I also need the Xmit lock */
2884 PORT_Assert(!needHsLock || !ssl_HaveXmitBufLock(ss))((!needHsLock || !((PR_GetMonitorEntryCount(((ss)->xmitBufLock
)) > 0)))?((void)0):PR_Assert("!needHsLock || !ssl_HaveXmitBufLock(ss)"
,"ssl3con.c",2884))
;
2885
2886 SSL_TRC(3, ("%d: SSL3[%d]: send alert record, level=%d desc=%d",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: send alert record, level=%d desc=%d"
, getpid(), ss->fd, level, desc)
2887 SSL_GETPID(), ss->fd, level, desc))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: send alert record, level=%d desc=%d"
, getpid(), ss->fd, level, desc)
;
2888
2889 bytes[0] = level;
2890 bytes[1] = desc;
2891
2892 if (needHsLock) {
2893 ssl_GetSSL3HandshakeLock(ss){ if (!ss->opt.noLocks) { ((!((PR_GetMonitorEntryCount(((ss
)->xmitBufLock)) > 0)))?((void)0):PR_Assert("!ssl_HaveXmitBufLock(ss)"
,"ssl3con.c",2893)); PR_EnterMonitor(((ss)->ssl3HandshakeLock
)); } }
;
2894 }
2895 if (level == alert_fatal) {
2896 if (ss->sec.ci.sid) {
2897 ssl_UncacheSessionID(ss);
2898 }
2899 }
2900
2901 rv = tls13_SetAlertCipherSpec(ss);
2902 if (rv != SECSuccess) {
2903 if (needHsLock) {
2904 ssl_ReleaseSSL3HandshakeLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->ssl3HandshakeLock
)); }
;
2905 }
2906 return rv;
2907 }
2908
2909 ssl_GetXmitBufLock(ss){ if (!ss->opt.noLocks) PR_EnterMonitor(((ss)->xmitBufLock
)); }
;
2910 rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER0x40000000);
2911 if (rv == SECSuccess) {
2912 PRInt32 sent;
2913 sent = ssl3_SendRecord(ss, NULL((void*)0), ssl_ct_alert, bytes, 2,
2914 (desc == no_certificate) ? ssl_SEND_FLAG_FORCE_INTO_BUFFER0x40000000 : 0);
2915 rv = (sent >= 0) ? SECSuccess : (SECStatus)sent;
2916 }
2917 if (level == alert_fatal) {
2918 ss->ssl3.fatalAlertSent = PR_TRUE1;
2919 }
2920 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
;
2921 if (needHsLock) {
2922 ssl_ReleaseSSL3HandshakeLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->ssl3HandshakeLock
)); }
;
2923 }
2924 if (rv == SECSuccess && ss->alertSentCallback) {
2925 SSLAlert alert = { level, desc };
2926 ss->alertSentCallback(ss->fd, ss->alertSentCallbackArg, &alert);
2927 }
2928 return rv; /* error set by ssl3_FlushHandshake or ssl3_SendRecord */
2929}
2930
2931/*
2932 * Send illegal_parameter alert. Set generic error number.
2933 */
2934static SECStatus
2935ssl3_IllegalParameter(sslSocket *ss)
2936{
2937 (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
2938 PORT_SetErrorPORT_SetError_Util(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
2939 : SSL_ERROR_BAD_SERVER);
2940 return SECFailure;
2941}
2942
2943/*
2944 * Send handshake_Failure alert. Set generic error number.
2945 */
2946static SECStatus
2947ssl3_HandshakeFailure(sslSocket *ss)
2948{
2949 (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
2950 PORT_SetErrorPORT_SetError_Util(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
2951 : SSL_ERROR_BAD_SERVER);
2952 return SECFailure;
2953}
2954
2955void
2956ssl3_SendAlertForCertError(sslSocket *ss, PRErrorCode errCode)
2957{
2958 SSL3AlertDescription desc = bad_certificate;
2959 PRBool isTLS = ss->version >= SSL_LIBRARY_VERSION_3_1_TLS0x0301;
2960
2961 switch (errCode) {
2962 case SEC_ERROR_LIBRARY_FAILURE:
2963 desc = unsupported_certificate;
2964 break;
2965 case SEC_ERROR_EXPIRED_CERTIFICATE:
2966 desc = certificate_expired;
2967 break;
2968 case SEC_ERROR_REVOKED_CERTIFICATE:
2969 desc = certificate_revoked;
2970 break;
2971 case SEC_ERROR_INADEQUATE_KEY_USAGE:
2972 case SEC_ERROR_INADEQUATE_CERT_TYPE:
2973 desc = certificate_unknown;
2974 break;
2975 case SEC_ERROR_UNTRUSTED_CERT:
2976 desc = isTLS ? access_denied : certificate_unknown;
2977 break;
2978 case SEC_ERROR_UNKNOWN_ISSUER:
2979 case SEC_ERROR_UNTRUSTED_ISSUER:
2980 desc = isTLS ? unknown_ca : certificate_unknown;
2981 break;
2982 case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE:
2983 desc = isTLS ? unknown_ca : certificate_expired;
2984 break;
2985
2986 case SEC_ERROR_CERT_NOT_IN_NAME_SPACE:
2987 case SEC_ERROR_PATH_LEN_CONSTRAINT_INVALID:
2988 case SEC_ERROR_CA_CERT_INVALID:
2989 case SEC_ERROR_BAD_SIGNATURE:
2990 default:
2991 desc = bad_certificate;
2992 break;
2993 }
2994 SSL_DBG(("%d: SSL3[%d]: peer certificate is no good: error=%d",if (ssl_debug) ssl_Trace ("%d: SSL3[%d]: peer certificate is no good: error=%d"
, getpid(), ss->fd, errCode)
2995 SSL_GETPID(), ss->fd, errCode))if (ssl_debug) ssl_Trace ("%d: SSL3[%d]: peer certificate is no good: error=%d"
, getpid(), ss->fd, errCode)
;
2996
2997 (void)SSL3_SendAlert(ss, alert_fatal, desc);
2998}
2999
3000/*
3001 * Send decode_error alert. Set generic error number.
3002 */
3003SECStatus
3004ssl3_DecodeError(sslSocket *ss)
3005{
3006 (void)SSL3_SendAlert(ss, alert_fatal,
3007 ss->version > SSL_LIBRARY_VERSION_3_00x0300 ? decode_error
3008 : illegal_parameter);
3009 PORT_SetErrorPORT_SetError_Util(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
3010 : SSL_ERROR_BAD_SERVER);
3011 return SECFailure;
3012}
3013
3014/* Called from ssl3_HandleRecord.
3015** Caller must hold both RecvBuf and Handshake locks.
3016*/
3017static SECStatus
3018ssl3_HandleAlert(sslSocket *ss, sslBuffer *buf)
3019{
3020 SSL3AlertLevel level;
3021 SSL3AlertDescription desc;
3022 int error;
3023
3024 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->recvBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveRecvBufLock(ss)"
,"ssl3con.c",3024))
;
3025 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",3025))
;
3026
3027 SSL_TRC(3, ("%d: SSL3[%d]: handle alert record", SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: handle alert record"
, getpid(), ss->fd)
;
3028
3029 if (buf->len != 2) {
3030 (void)ssl3_DecodeError(ss);
3031 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_MALFORMED_ALERT);
3032 return SECFailure;
3033 }
3034 level = (SSL3AlertLevel)buf->buf[0];
3035 desc = (SSL3AlertDescription)buf->buf[1];
3036 buf->len = 0;
3037 SSL_TRC(5, ("%d: SSL3[%d] received alert, level = %d, description = %d",if (ssl_trace >= (5)) ssl_Trace ("%d: SSL3[%d] received alert, level = %d, description = %d"
, getpid(), ss->fd, level, desc)
3038 SSL_GETPID(), ss->fd, level, desc))if (ssl_trace >= (5)) ssl_Trace ("%d: SSL3[%d] received alert, level = %d, description = %d"
, getpid(), ss->fd, level, desc)
;
3039
3040 if (ss->alertReceivedCallback) {
3041 SSLAlert alert = { level, desc };
3042 ss->alertReceivedCallback(ss->fd, ss->alertReceivedCallbackArg, &alert);
3043 }
3044
3045 switch (desc) {
3046 case close_notify:
3047 ss->recvdCloseNotify = 1;
3048 error = SSL_ERROR_CLOSE_NOTIFY_ALERT;
3049 break;
3050 case unexpected_message:
3051 error = SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT;
3052 break;
3053 case bad_record_mac:
3054 error = SSL_ERROR_BAD_MAC_ALERT;
3055 break;
3056 case decryption_failed_RESERVED:
3057 error = SSL_ERROR_DECRYPTION_FAILED_ALERT;
3058 break;
3059 case record_overflow:
3060 error = SSL_ERROR_RECORD_OVERFLOW_ALERT;
3061 break;
3062 case decompression_failure:
3063 error = SSL_ERROR_DECOMPRESSION_FAILURE_ALERT;
3064 break;
3065 case handshake_failure:
3066 error = SSL_ERROR_HANDSHAKE_FAILURE_ALERT;
3067 break;
3068 case no_certificate:
3069 error = SSL_ERROR_NO_CERTIFICATE;
3070 break;
3071 case certificate_required:
3072 error = SSL_ERROR_RX_CERTIFICATE_REQUIRED_ALERT;
3073 break;
3074 case bad_certificate:
3075 error = SSL_ERROR_BAD_CERT_ALERT;
3076 break;
3077 case unsupported_certificate:
3078 error = SSL_ERROR_UNSUPPORTED_CERT_ALERT;
3079 break;
3080 case certificate_revoked:
3081 error = SSL_ERROR_REVOKED_CERT_ALERT;
3082 break;
3083 case certificate_expired:
3084 error = SSL_ERROR_EXPIRED_CERT_ALERT;
3085 break;
3086 case certificate_unknown:
3087 error = SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT;
3088 break;
3089 case illegal_parameter:
3090 error = SSL_ERROR_ILLEGAL_PARAMETER_ALERT;
3091 break;
3092 case inappropriate_fallback:
3093 error = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT;
3094 break;
3095
3096 /* All alerts below are TLS only. */
3097 case unknown_ca:
3098 error = SSL_ERROR_UNKNOWN_CA_ALERT;
3099 break;
3100 case access_denied:
3101 error = SSL_ERROR_ACCESS_DENIED_ALERT;
3102 break;
3103 case decode_error:
3104 error = SSL_ERROR_DECODE_ERROR_ALERT;
3105 break;
3106 case decrypt_error:
3107 error = SSL_ERROR_DECRYPT_ERROR_ALERT;
3108 break;
3109 case export_restriction:
3110 error = SSL_ERROR_EXPORT_RESTRICTION_ALERT;
3111 break;
3112 case protocol_version:
3113 error = SSL_ERROR_PROTOCOL_VERSION_ALERT;
3114 break;
3115 case insufficient_security:
3116 error = SSL_ERROR_INSUFFICIENT_SECURITY_ALERT;
3117 break;
3118 case internal_error:
3119 error = SSL_ERROR_INTERNAL_ERROR_ALERT;
3120 break;
3121 case user_canceled:
3122 error = SSL_ERROR_USER_CANCELED_ALERT;
3123 break;
3124 case no_renegotiation:
3125 error = SSL_ERROR_NO_RENEGOTIATION_ALERT;
3126 break;
3127
3128 /* Alerts for TLS client hello extensions */
3129 case missing_extension:
3130 error = SSL_ERROR_MISSING_EXTENSION_ALERT;
3131 break;
3132 case unsupported_extension:
3133 error = SSL_ERROR_UNSUPPORTED_EXTENSION_ALERT;
3134 break;
3135 case certificate_unobtainable:
3136 error = SSL_ERROR_CERTIFICATE_UNOBTAINABLE_ALERT;
3137 break;
3138 case unrecognized_name:
3139 error = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
3140 break;
3141 case bad_certificate_status_response:
3142 error = SSL_ERROR_BAD_CERT_STATUS_RESPONSE_ALERT;
3143 break;
3144 case bad_certificate_hash_value:
3145 error = SSL_ERROR_BAD_CERT_HASH_VALUE_ALERT;
3146 break;
3147 case no_application_protocol:
3148 error = SSL_ERROR_NEXT_PROTOCOL_NO_PROTOCOL;
3149 break;
3150 case ech_required:
3151 error = SSL_ERROR_ECH_REQUIRED_ALERT;
3152 break;
3153 default:
3154 error = SSL_ERROR_RX_UNKNOWN_ALERT;
3155 break;
3156 }
3157 if ((ss->version >= SSL_LIBRARY_VERSION_TLS_1_30x0304) &&
3158 (ss->ssl3.hs.ws != wait_server_hello)) {
3159 /* TLS 1.3 requires all but "end of data" alerts to be
3160 * treated as fatal. */
3161 switch (desc) {
3162 case close_notify:
3163 case user_canceled:
3164 break;
3165 default:
3166 level = alert_fatal;
3167 }
3168 }
3169 if (level == alert_fatal) {
3170 ssl_UncacheSessionID(ss);
3171 if ((ss->ssl3.hs.ws == wait_server_hello) &&
3172 (desc == handshake_failure)) {
3173 /* XXX This is a hack. We're assuming that any handshake failure
3174 * XXX on the client hello is a failure to match ciphers.
3175 */
3176 error = SSL_ERROR_NO_CYPHER_OVERLAP;
3177 }
3178 PORT_SetErrorPORT_SetError_Util(error);
3179 return SECFailure;
3180 }
3181 if ((desc == no_certificate) && (ss->ssl3.hs.ws == wait_client_cert)) {
3182 /* I'm a server. I've requested a client cert. He hasn't got one. */
3183 SECStatus rv;
3184
3185 PORT_Assert(ss->sec.isServer)((ss->sec.isServer)?((void)0):PR_Assert("ss->sec.isServer"
,"ssl3con.c",3185))
;
3186 ss->ssl3.hs.ws = wait_client_key;
3187 rv = ssl3_HandleNoCertificate(ss);
3188 return rv;
3189 }
3190 return SECSuccess;
3191}
3192
3193/*
3194 * Change Cipher Specs
3195 * Called from ssl3_HandleServerHelloDone,
3196 * ssl3_HandleClientHello,
3197 * and ssl3_HandleFinished
3198 *
3199 * Acquires and releases spec write lock, to protect switching the current
3200 * and pending write spec pointers.
3201 */
3202
3203SECStatus
3204ssl3_SendChangeCipherSpecsInt(sslSocket *ss)
3205{
3206 PRUint8 change = change_cipher_spec_choice;
3207 SECStatus rv;
3208
3209 SSL_TRC(3, ("%d: SSL3[%d]: send change_cipher_spec record",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: send change_cipher_spec record"
, getpid(), ss->fd)
3210 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: send change_cipher_spec record"
, getpid(), ss->fd)
;
3211
3212 rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER0x40000000);
3213 if (rv != SECSuccess) {
3214 return SECFailure; /* error code set by ssl3_FlushHandshake */
3215 }
3216
3217 if (!IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
3218 PRInt32 sent;
3219 sent = ssl3_SendRecord(ss, NULL((void*)0), ssl_ct_change_cipher_spec,
3220 &change, 1, ssl_SEND_FLAG_FORCE_INTO_BUFFER0x40000000);
3221 if (sent < 0) {
3222 return SECFailure; /* error code set by ssl3_SendRecord */
3223 }
3224 } else {
3225 rv = dtls_QueueMessage(ss, ssl_ct_change_cipher_spec, &change, 1);
3226 if (rv != SECSuccess) {
3227 return SECFailure;
3228 }
3229 }
3230 return SECSuccess;
3231}
3232
3233static SECStatus
3234ssl3_SendChangeCipherSpecs(sslSocket *ss)
3235{
3236 SECStatus rv;
3237
3238 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->xmitBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveXmitBufLock(ss)"
,"ssl3con.c",3238))
;
3239 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",3239))
;
3240
3241 rv = ssl3_SendChangeCipherSpecsInt(ss);
3242 if (rv != SECSuccess) {
3243 return rv; /* Error code set. */
3244 }
3245
3246 /* swap the pending and current write specs. */
3247 ssl_GetSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_LockWrite_Util((ss)->
specLock); }
; /**************************************/
3248
3249 ssl_CipherSpecRelease(ss->ssl3.cwSpec);
3250 ss->ssl3.cwSpec = ss->ssl3.pwSpec;
3251 ss->ssl3.pwSpec = NULL((void*)0);
3252
3253 SSL_TRC(3, ("%d: SSL3[%d] Set Current Write Cipher Suite to Pending",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d] Set Current Write Cipher Suite to Pending"
, getpid(), ss->fd)
3254 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d] Set Current Write Cipher Suite to Pending"
, getpid(), ss->fd)
;
3255
3256 /* With DTLS, we need to set a holddown timer in case the final
3257 * message got lost */
3258 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram) && ss->ssl3.crSpec->epoch == ss->ssl3.cwSpec->epoch) {
3259 rv = dtls_StartHolddownTimer(ss);
3260 }
3261 ssl_ReleaseSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockWrite_Util((ss)->
specLock); }
; /**************************************/
3262
3263 return rv;
3264}
3265
3266/* Called from ssl3_HandleRecord.
3267** Caller must hold both RecvBuf and Handshake locks.
3268*
3269* Acquires and releases spec write lock, to protect switching the current
3270* and pending write spec pointers.
3271*/
3272static SECStatus
3273ssl3_HandleChangeCipherSpecs(sslSocket *ss, sslBuffer *buf)
3274{
3275 SSL3WaitState ws = ss->ssl3.hs.ws;
3276 SSL3ChangeCipherSpecChoice change;
3277
3278 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->recvBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveRecvBufLock(ss)"
,"ssl3con.c",3278))
;
3279 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",3279))
;
3280
3281 SSL_TRC(3, ("%d: SSL3[%d]: handle change_cipher_spec record",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: handle change_cipher_spec record"
, getpid(), ss->fd)
3282 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: handle change_cipher_spec record"
, getpid(), ss->fd)
;
3283
3284 /* For DTLS: Ignore this if we aren't expecting it. Don't kill a connection
3285 * as a result of receiving trash.
3286 * For TLS: Maybe ignore, but only after checking format. */
3287 if (ws != wait_change_cipher && IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
3288 /* Ignore this because it's out of order. */
3289 SSL_TRC(3, ("%d: SSL3[%d]: discard out of order "if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: discard out of order "
"DTLS change_cipher_spec", getpid(), ss->fd)
3290 "DTLS change_cipher_spec",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: discard out of order "
"DTLS change_cipher_spec", getpid(), ss->fd)
3291 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: discard out of order "
"DTLS change_cipher_spec", getpid(), ss->fd)
;
3292 buf->len = 0;
3293 return SECSuccess;
3294 }
3295
3296 /* Handshake messages should not span ChangeCipherSpec. */
3297 if (ss->ssl3.hs.header_bytes) {
3298 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
3299 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER);
3300 return SECFailure;
3301 }
3302 if (buf->len != 1) {
3303 (void)ssl3_DecodeError(ss);
3304 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
3305 return SECFailure;
3306 }
3307 change = (SSL3ChangeCipherSpecChoice)buf->buf[0];
3308 if (change != change_cipher_spec_choice) {
3309 /* illegal_parameter is correct here for both SSL3 and TLS. */
3310 (void)ssl3_IllegalParameter(ss);
3311 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
3312 return SECFailure;
3313 }
3314
3315 buf->len = 0;
3316 if (ws != wait_change_cipher) {
3317 /* Ignore a CCS for TLS 1.3. This only happens if the server sends a
3318 * HelloRetryRequest. In other cases, the CCS will fail decryption and
3319 * will be discarded by ssl3_HandleRecord(). */
3320 if (ws == wait_server_hello &&
3321 ss->version >= SSL_LIBRARY_VERSION_TLS_1_30x0304 &&
3322 ss->ssl3.hs.helloRetry) {
3323 PORT_Assert(!ss->sec.isServer)((!ss->sec.isServer)?((void)0):PR_Assert("!ss->sec.isServer"
,"ssl3con.c",3323))
;
3324 return SECSuccess;
3325 }
3326 /* Note: For a server, we can't test ss->ssl3.hs.helloRetry or
3327 * ss->version because the server might be stateless (and so it won't
3328 * have set either value yet). Set a flag so that at least we will
3329 * guarantee that the server will treat any ClientHello properly. */
3330 if (ws == wait_client_hello &&
3331 ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_30x0304 &&
3332 !ss->ssl3.hs.receivedCcs) {
3333 PORT_Assert(ss->sec.isServer)((ss->sec.isServer)?((void)0):PR_Assert("ss->sec.isServer"
,"ssl3con.c",3333))
;
3334 ss->ssl3.hs.receivedCcs = PR_TRUE1;
3335 return SECSuccess;
3336 }
3337 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
3338 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER);
3339 return SECFailure;
3340 }
3341
3342 SSL_TRC(3, ("%d: SSL3[%d] Set Current Read Cipher Suite to Pending",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d] Set Current Read Cipher Suite to Pending"
, getpid(), ss->fd)
3343 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d] Set Current Read Cipher Suite to Pending"
, getpid(), ss->fd)
;
3344 ssl_GetSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_LockWrite_Util((ss)->
specLock); }
; /*************************************/
3345 PORT_Assert(ss->ssl3.prSpec)((ss->ssl3.prSpec)?((void)0):PR_Assert("ss->ssl3.prSpec"
,"ssl3con.c",3345))
;
3346 ssl_CipherSpecRelease(ss->ssl3.crSpec);
3347 ss->ssl3.crSpec = ss->ssl3.prSpec;
3348 ss->ssl3.prSpec = NULL((void*)0);
3349 ssl_ReleaseSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockWrite_Util((ss)->
specLock); }
; /*************************************/
3350
3351 ss->ssl3.hs.ws = wait_finished;
3352 return SECSuccess;
3353}
3354
3355static CK_MECHANISM_TYPE
3356ssl3_GetMgfMechanismByHashType(SSLHashType hash)
3357{
3358 switch (hash) {
3359 case ssl_hash_sha256:
3360 return CKG_MGF1_SHA2560x00000002UL;
3361 case ssl_hash_sha384:
3362 return CKG_MGF1_SHA3840x00000003UL;
3363 case ssl_hash_sha512:
3364 return CKG_MGF1_SHA5120x00000004UL;
3365 default:
3366 PORT_Assert(0)((0)?((void)0):PR_Assert("0","ssl3con.c",3366));
3367 }
3368 return CKG_MGF1_SHA2560x00000002UL;
3369}
3370
3371/* Function valid for >= TLS 1.2, only. */
3372static CK_MECHANISM_TYPE
3373ssl3_GetHashMechanismByHashType(SSLHashType hashType)
3374{
3375 switch (hashType) {
3376 case ssl_hash_sha512:
3377 return CKM_SHA5120x00000270UL;
3378 case ssl_hash_sha384:
3379 return CKM_SHA3840x00000260UL;
3380 case ssl_hash_sha256:
3381 case ssl_hash_none:
3382 /* ssl_hash_none is for pre-1.2 suites, which use SHA-256. */
3383 return CKM_SHA2560x00000250UL;
3384 case ssl_hash_sha1:
3385 return CKM_SHA_10x00000220UL;
3386 default:
3387 PORT_Assert(0)((0)?((void)0):PR_Assert("0","ssl3con.c",3387));
3388 }
3389 return CKM_SHA2560x00000250UL;
3390}
3391
3392/* Function valid for >= TLS 1.2, only. */
3393static CK_MECHANISM_TYPE
3394ssl3_GetPrfHashMechanism(sslSocket *ss)
3395{
3396 return ssl3_GetHashMechanismByHashType(ss->ssl3.hs.suite_def->prf_hash);
3397}
3398
3399static SSLHashType
3400ssl3_GetSuitePrfHash(sslSocket *ss)
3401{
3402 /* ssl_hash_none is for pre-1.2 suites, which use SHA-256. */
3403 if (ss->ssl3.hs.suite_def->prf_hash == ssl_hash_none) {
3404 return ssl_hash_sha256;
3405 }
3406 return ss->ssl3.hs.suite_def->prf_hash;
3407}
3408
3409/* This method completes the derivation of the MS from the PMS.
3410**
3411** 1. Derive the MS, if possible, else return an error.
3412**
3413** 2. Check the version if |pms_version| is non-zero and if wrong,
3414** return an error.
3415**
3416** 3. If |msp| is nonzero, return MS in |*msp|.
3417
3418** Called from:
3419** ssl3_ComputeMasterSecretInt
3420** tls_ComputeExtendedMasterSecretInt
3421*/
3422static SECStatus
3423ssl3_ComputeMasterSecretFinish(sslSocket *ss,
3424 CK_MECHANISM_TYPE master_derive,
3425 CK_MECHANISM_TYPE key_derive,
3426 CK_VERSION *pms_version,
3427 SECItem *params, CK_FLAGS keyFlags,
3428 PK11SymKey *pms, PK11SymKey **msp)
3429{
3430 PK11SymKey *ms = NULL((void*)0);
3431
3432 ms = PK11_DeriveWithFlags(pms, master_derive,
3433 params, key_derive,
3434 CKA_DERIVE0x0000010CUL, 0, keyFlags);
3435 if (!ms) {
3436 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3437 return SECFailure;
3438 }
3439
3440 if (pms_version && ss->opt.detectRollBack) {
3441 SSL3ProtocolVersion client_version;
3442 client_version = pms_version->major << 8 | pms_version->minor;
3443
3444 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
3445 client_version = dtls_DTLSVersionToTLSVersion(client_version);
3446 }
3447
3448 if (client_version != ss->clientHelloVersion) {
3449 /* Destroy MS. Version roll-back detected. */
3450 PK11_FreeSymKey(ms);
3451 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3452 return SECFailure;
3453 }
3454 }
3455
3456 if (msp) {
3457 *msp = ms;
3458 } else {
3459 PK11_FreeSymKey(ms);
3460 }
3461
3462 return SECSuccess;
3463}
3464
3465/* Compute the ordinary (pre draft-ietf-tls-session-hash) master
3466 ** secret and return it in |*msp|.
3467 **
3468 ** Called from: ssl3_ComputeMasterSecret
3469 */
3470static SECStatus
3471ssl3_ComputeMasterSecretInt(sslSocket *ss, PK11SymKey *pms,
3472 PK11SymKey **msp)
3473{
3474 PRBool isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_00x0300);
3475 PRBool isTLS12 = (PRBool)(ss->version >= SSL_LIBRARY_VERSION_TLS_1_20x0303);
3476 /*
3477 * Whenever isDH is true, we need to use CKM_TLS_MASTER_KEY_DERIVE_DH
3478 * which, unlike CKM_TLS_MASTER_KEY_DERIVE, converts arbitrary size
3479 * data into a 48-byte value, and does not expect to return the version.
3480 */
3481 PRBool isDH = (PRBool)((ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_dh) ||
3482 (ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_ecdh) ||
3483 (ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_ecdh_hybrid));
3484 CK_MECHANISM_TYPE master_derive;
3485 CK_MECHANISM_TYPE key_derive;
3486 SECItem params;
3487 CK_FLAGS keyFlags;
3488 CK_VERSION pms_version;
3489 CK_VERSION *pms_version_ptr = NULL((void*)0);
3490 /* master_params may be used as a CK_SSL3_MASTER_KEY_DERIVE_PARAMS */
3491 CK_TLS12_MASTER_KEY_DERIVE_PARAMS master_params;
3492 unsigned int master_params_len;
3493
3494 if (isTLS12) {
3495 if (isDH)
3496 master_derive = CKM_TLS12_MASTER_KEY_DERIVE_DH0x000003E2UL;
3497 else
3498 master_derive = CKM_TLS12_MASTER_KEY_DERIVE0x000003E0UL;
3499 key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE0x000003E1UL;
3500 keyFlags = CKF_SIGN0x00000800UL | CKF_VERIFY0x00002000;
3501 } else if (isTLS) {
3502 if (isDH)
3503 master_derive = CKM_TLS_MASTER_KEY_DERIVE_DH0x00000377UL;
3504 else
3505 master_derive = CKM_TLS_MASTER_KEY_DERIVE0x00000375UL;
3506 key_derive = CKM_TLS_KEY_AND_MAC_DERIVE0x00000376UL;
3507 keyFlags = CKF_SIGN0x00000800UL | CKF_VERIFY0x00002000;
3508 } else {
3509 if (isDH)
3510 master_derive = CKM_SSL3_MASTER_KEY_DERIVE_DH0x00000373UL;
3511 else
3512 master_derive = CKM_SSL3_MASTER_KEY_DERIVE0x00000371UL;
3513 key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE0x00000372UL;
3514 keyFlags = 0;
3515 }
3516
3517 if (!isDH) {
3518 pms_version_ptr = &pms_version;
3519 }
3520
3521 master_params.pVersion = pms_version_ptr;
3522 master_params.RandomInfo.pClientRandom = ss->ssl3.hs.client_random;
3523 master_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH32;
3524 master_params.RandomInfo.pServerRandom = ss->ssl3.hs.server_random;
3525 master_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH32;
3526 if (isTLS12) {
3527 master_params.prfHashMechanism = ssl3_GetPrfHashMechanism(ss);
3528 master_params_len = sizeof(CK_TLS12_MASTER_KEY_DERIVE_PARAMS);
3529 } else {
3530 /* prfHashMechanism is not relevant with this PRF */
3531 master_params_len = sizeof(CK_SSL3_MASTER_KEY_DERIVE_PARAMS);
3532 }
3533
3534 params.data = (unsigned char *)&master_params;
3535 params.len = master_params_len;
3536
3537 return ssl3_ComputeMasterSecretFinish(ss, master_derive, key_derive,
3538 pms_version_ptr, &params,
3539 keyFlags, pms, msp);
3540}
3541
3542/* Compute the draft-ietf-tls-session-hash master
3543** secret and return it in |*msp|.
3544**
3545** Called from: ssl3_ComputeMasterSecret
3546*/
3547static SECStatus
3548tls_ComputeExtendedMasterSecretInt(sslSocket *ss, PK11SymKey *pms,
3549 PK11SymKey **msp)
3550{
3551 ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec;
3552 CK_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE_PARAMS extended_master_params;
3553 SSL3Hashes hashes;
3554 /*
3555 * Determine whether to use the DH/ECDH or RSA derivation modes.
3556 */
3557 /*
3558 * TODO(ekr@rtfm.com): Verify that the slot can handle this key expansion
3559 * mode. Bug 1198298 */
3560 PRBool isDH = (PRBool)((ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_dh) ||
3561 (ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_ecdh) ||
3562 (ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_ecdh_hybrid));
3563 CK_MECHANISM_TYPE master_derive;
3564 CK_MECHANISM_TYPE key_derive;
3565 SECItem params;
3566 const CK_FLAGS keyFlags = CKF_SIGN0x00000800UL | CKF_VERIFY0x00002000;
3567 CK_VERSION pms_version;
3568 CK_VERSION *pms_version_ptr = NULL((void*)0);
3569 SECStatus rv;
3570
3571 rv = ssl3_ComputeHandshakeHashes(ss, pwSpec, &hashes, 0);
3572 if (rv != SECSuccess) {
3573 PORT_Assert(0)((0)?((void)0):PR_Assert("0","ssl3con.c",3573)); /* Should never fail */
3574 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3575 return SECFailure;
3576 }
3577
3578 if (isDH) {
3579 master_derive = CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE_DH((0x80000000UL | 0x4E534350) + 26);
3580 } else {
3581 master_derive = CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE((0x80000000UL | 0x4E534350) + 25);
3582 pms_version_ptr = &pms_version;
3583 }
3584
3585 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_20x0303) {
3586 /* TLS 1.2+ */
3587 extended_master_params.prfHashMechanism = ssl3_GetPrfHashMechanism(ss);
3588 key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE0x000003E1UL;
3589 } else {
3590 /* TLS < 1.2 */
3591 extended_master_params.prfHashMechanism = CKM_TLS_PRF0x00000378UL;
3592 key_derive = CKM_TLS_KEY_AND_MAC_DERIVE0x00000376UL;
3593 }
3594
3595 extended_master_params.pVersion = pms_version_ptr;
3596 extended_master_params.pSessionHash = hashes.u.raw;
3597 extended_master_params.ulSessionHashLen = hashes.len;
3598
3599 params.data = (unsigned char *)&extended_master_params;
3600 params.len = sizeof extended_master_params;
3601
3602 return ssl3_ComputeMasterSecretFinish(ss, master_derive, key_derive,
3603 pms_version_ptr, &params,
3604 keyFlags, pms, msp);
3605}
3606
3607/* Wrapper method to compute the master secret and return it in |*msp|.
3608**
3609** Called from ssl3_ComputeMasterSecret
3610*/
3611static SECStatus
3612ssl3_ComputeMasterSecret(sslSocket *ss, PK11SymKey *pms,
3613 PK11SymKey **msp)
3614{
3615 PORT_Assert(pms != NULL)((pms != ((void*)0))?((void)0):PR_Assert("pms != NULL","ssl3con.c"
,3615))
;
3616 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",3616))
;
3617
3618 if (ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) {
3619 return tls_ComputeExtendedMasterSecretInt(ss, pms, msp);
3620 } else {
3621 return ssl3_ComputeMasterSecretInt(ss, pms, msp);
3622 }
3623}
3624
3625/*
3626 * Derive encryption and MAC Keys (and IVs) from master secret
3627 * Sets a useful error code when returning SECFailure.
3628 *
3629 * Called only from ssl3_InitPendingCipherSpec(),
3630 * which in turn is called from
3631 * ssl3_SendRSAClientKeyExchange (for Full handshake)
3632 * ssl3_SendDHClientKeyExchange (for Full handshake)
3633 * ssl3_HandleClientKeyExchange (for Full handshake)
3634 * ssl3_HandleServerHello (for session restart)
3635 * ssl3_HandleClientHello (for session restart)
3636 * Caller MUST hold the specWriteLock, and SSL3HandshakeLock.
3637 * ssl3_InitPendingCipherSpec does that.
3638 *
3639 */
3640static SECStatus
3641ssl3_DeriveConnectionKeys(sslSocket *ss, PK11SymKey *masterSecret)
3642{
3643 ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec;
3644 ssl3CipherSpec *prSpec = ss->ssl3.prSpec;
3645 ssl3CipherSpec *clientSpec;
3646 ssl3CipherSpec *serverSpec;
3647 PRBool isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_00x0300);
3648 PRBool isTLS12 =
3649 (PRBool)(isTLS && ss->version >= SSL_LIBRARY_VERSION_TLS_1_20x0303);
3650 const ssl3BulkCipherDef *cipher_def = pwSpec->cipherDef;
3651 PK11SlotInfo *slot = NULL((void*)0);
3652 PK11SymKey *derivedKeyHandle = NULL((void*)0);
3653 void *pwArg = ss->pkcs11PinArg;
3654 int keySize;
3655 CK_TLS12_KEY_MAT_PARAMS key_material_params; /* may be used as a
3656 * CK_SSL3_KEY_MAT_PARAMS */
3657 unsigned int key_material_params_len;
3658 CK_SSL3_KEY_MAT_OUT returnedKeys;
3659 CK_MECHANISM_TYPE key_derive;
3660 CK_MECHANISM_TYPE bulk_mechanism;
3661 SSLCipherAlgorithm calg;
3662 SECItem params;
3663 PRBool skipKeysAndIVs = (PRBool)(cipher_def->calg == ssl_calg_null);
3664
3665 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",3665))
;
3666 PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss))((ss->opt.noLocks || (NSSRWLock_HaveWriteLock_Util((ss)->
specLock)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)"
,"ssl3con.c",3666))
;
3667 PORT_Assert(masterSecret)((masterSecret)?((void)0):PR_Assert("masterSecret","ssl3con.c"
,3667))
;
3668
3669 /* These functions operate in terms of who is writing specs. */
3670 if (ss->sec.isServer) {
3671 clientSpec = prSpec;
3672 serverSpec = pwSpec;
3673 } else {
3674 clientSpec = pwSpec;
3675 serverSpec = prSpec;
3676 }
3677
3678 /*
3679 * generate the key material
3680 */
3681 if (cipher_def->type == type_block &&
3682 ss->version >= SSL_LIBRARY_VERSION_TLS_1_10x0302) {
3683 /* Block ciphers in >= TLS 1.1 use a per-record, explicit IV. */
3684 key_material_params.ulIVSizeInBits = 0;
3685 PORT_Memsetmemset(clientSpec->keyMaterial.iv, 0, cipher_def->iv_size);
3686 PORT_Memsetmemset(serverSpec->keyMaterial.iv, 0, cipher_def->iv_size);
3687 }
3688
3689 key_material_params.bIsExport = PR_FALSE0;
3690 key_material_params.RandomInfo.pClientRandom = ss->ssl3.hs.client_random;
3691 key_material_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH32;
3692 key_material_params.RandomInfo.pServerRandom = ss->ssl3.hs.server_random;
3693 key_material_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH32;
3694 key_material_params.pReturnedKeyMaterial = &returnedKeys;
3695
3696 if (skipKeysAndIVs) {
3697 keySize = 0;
3698 returnedKeys.pIVClient = NULL((void*)0);
3699 returnedKeys.pIVServer = NULL((void*)0);
3700 key_material_params.ulKeySizeInBits = 0;
3701 key_material_params.ulIVSizeInBits = 0;
3702 } else {
3703 keySize = cipher_def->key_size;
3704 returnedKeys.pIVClient = clientSpec->keyMaterial.iv;
3705 returnedKeys.pIVServer = serverSpec->keyMaterial.iv;
3706 key_material_params.ulKeySizeInBits = cipher_def->secret_key_size * BPB8;
3707 key_material_params.ulIVSizeInBits = cipher_def->iv_size * BPB8;
3708 }
3709 key_material_params.ulMacSizeInBits = pwSpec->macDef->mac_size * BPB8;
3710
3711 calg = cipher_def->calg;
3712 bulk_mechanism = ssl3_Alg2Mech(calg);
3713
3714 if (isTLS12) {
3715 key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE0x000003E1UL;
3716 key_material_params.prfHashMechanism = ssl3_GetPrfHashMechanism(ss);
3717 key_material_params_len = sizeof(CK_TLS12_KEY_MAT_PARAMS);
3718 } else if (isTLS) {
3719 key_derive = CKM_TLS_KEY_AND_MAC_DERIVE0x00000376UL;
3720 key_material_params_len = sizeof(CK_SSL3_KEY_MAT_PARAMS);
3721 } else {
3722 key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE0x00000372UL;
3723 key_material_params_len = sizeof(CK_SSL3_KEY_MAT_PARAMS);
3724 }
3725
3726 params.data = (unsigned char *)&key_material_params;
3727 params.len = key_material_params_len;
3728
3729 /* CKM_SSL3_KEY_AND_MAC_DERIVE is defined to set ENCRYPT, DECRYPT, and
3730 * DERIVE by DEFAULT */
3731 derivedKeyHandle = PK11_Derive(masterSecret, key_derive, &params,
3732 bulk_mechanism, CKA_ENCRYPT0x00000104UL, keySize);
3733 if (!derivedKeyHandle) {
3734 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3735 return SECFailure;
3736 }
3737 /* we really should use the actual mac'ing mechanism here, but we
3738 * don't because these types are used to map keytype anyway and both
3739 * mac's map to the same keytype.
3740 */
3741 slot = PK11_GetSlotFromKey(derivedKeyHandle);
3742
3743 PK11_FreeSlot(slot); /* slot is held until the key is freed */
3744 clientSpec->keyMaterial.macKey =
3745 PK11_SymKeyFromHandle(slot, derivedKeyHandle, PK11_OriginDerive,
3746 CKM_SSL3_SHA1_MAC0x00000381UL, returnedKeys.hClientMacSecret,
3747 PR_TRUE1, pwArg);
3748 if (clientSpec->keyMaterial.macKey == NULL((void*)0)) {
3749 goto loser; /* loser sets err */
3750 }
3751 serverSpec->keyMaterial.macKey =
3752 PK11_SymKeyFromHandle(slot, derivedKeyHandle, PK11_OriginDerive,
3753 CKM_SSL3_SHA1_MAC0x00000381UL, returnedKeys.hServerMacSecret,
3754 PR_TRUE1, pwArg);
3755 if (serverSpec->keyMaterial.macKey == NULL((void*)0)) {
3756 goto loser; /* loser sets err */
3757 }
3758 if (!skipKeysAndIVs) {
3759 clientSpec->keyMaterial.key =
3760 PK11_SymKeyFromHandle(slot, derivedKeyHandle, PK11_OriginDerive,
3761 bulk_mechanism, returnedKeys.hClientKey,
3762 PR_TRUE1, pwArg);
3763 if (clientSpec->keyMaterial.key == NULL((void*)0)) {
3764 goto loser; /* loser sets err */
3765 }
3766 serverSpec->keyMaterial.key =
3767 PK11_SymKeyFromHandle(slot, derivedKeyHandle, PK11_OriginDerive,
3768 bulk_mechanism, returnedKeys.hServerKey,
3769 PR_TRUE1, pwArg);
3770 if (serverSpec->keyMaterial.key == NULL((void*)0)) {
3771 goto loser; /* loser sets err */
3772 }
3773 }
3774 PK11_FreeSymKey(derivedKeyHandle);
3775 return SECSuccess;
3776
3777loser:
3778 PK11_FreeSymKey(derivedKeyHandle);
3779 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
3780 return SECFailure;
3781}
3782
3783void
3784ssl3_CoalesceEchHandshakeHashes(sslSocket *ss)
3785{
3786 /* |sha| contains the CHOuter transcript, which is the singular
3787 * transcript if not doing ECH. If the server responded with 1.2,
3788 * contexts are not yet initialized. */
3789 if (ss->ssl3.hs.echAccepted) {
3790 if (ss->ssl3.hs.sha) {
3791 PORT_Assert(ss->ssl3.hs.shaEchInner)((ss->ssl3.hs.shaEchInner)?((void)0):PR_Assert("ss->ssl3.hs.shaEchInner"
,"ssl3con.c",3791))
;
3792 PK11_DestroyContext(ss->ssl3.hs.sha, PR_TRUE1);
3793 ss->ssl3.hs.sha = ss->ssl3.hs.shaEchInner;
3794 ss->ssl3.hs.shaEchInner = NULL((void*)0);
3795 }
3796 } else {
3797 if (ss->ssl3.hs.shaEchInner) {
3798 PK11_DestroyContext(ss->ssl3.hs.shaEchInner, PR_TRUE1);
3799 ss->ssl3.hs.shaEchInner = NULL((void*)0);
3800 }
3801 }
3802}
3803
3804/* ssl3_InitHandshakeHashes creates handshake hash contexts and hashes in
3805 * buffered messages in ss->ssl3.hs.messages. Called from
3806 * ssl3_NegotiateCipherSuite(), tls13_HandleClientHelloPart2(),
3807 * and ssl3_HandleServerHello. */
3808SECStatus
3809ssl3_InitHandshakeHashes(sslSocket *ss)
3810{
3811 SSL_TRC(30, ("%d: SSL3[%d]: start handshake hashes", SSL_GETPID(), ss->fd))if (ssl_trace >= (30)) ssl_Trace ("%d: SSL3[%d]: start handshake hashes"
, getpid(), ss->fd)
;
3812
3813 PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_unknown)((ss->ssl3.hs.hashType == handshake_hash_unknown)?((void)0
):PR_Assert("ss->ssl3.hs.hashType == handshake_hash_unknown"
,"ssl3con.c",3813))
;
3814 if (ss->version == SSL_LIBRARY_VERSION_TLS_1_20x0303) {
3815 ss->ssl3.hs.hashType = handshake_hash_record;
3816 } else {
3817 PORT_Assert(!ss->ssl3.hs.md5 && !ss->ssl3.hs.sha)((!ss->ssl3.hs.md5 && !ss->ssl3.hs.sha)?((void)
0):PR_Assert("!ss->ssl3.hs.md5 && !ss->ssl3.hs.sha"
,"ssl3con.c",3817))
;
3818 /*
3819 * note: We should probably lookup an SSL3 slot for these
3820 * handshake hashes in hopes that we wind up with the same slots
3821 * that the master secret will wind up in ...
3822 */
3823 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_30x0304) {
3824 /* determine the hash from the prf */
3825 const SECOidData *hash_oid =
3826 SECOID_FindOIDByMechanism(ssl3_GetPrfHashMechanism(ss));
3827
3828 /* Get the PKCS #11 mechanism for the Hash from the cipher suite (prf_hash)
3829 * Convert that to the OidTag. We can then use that OidTag to create our
3830 * PK11Context */
3831 PORT_Assert(hash_oid != NULL)((hash_oid != ((void*)0))?((void)0):PR_Assert("hash_oid != NULL"
,"ssl3con.c",3831))
;
3832 if (hash_oid == NULL((void*)0)) {
3833 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
3834 return SECFailure;
3835 }
3836
3837 ss->ssl3.hs.sha = PK11_CreateDigestContext(hash_oid->offset);
3838 if (ss->ssl3.hs.sha == NULL((void*)0)) {
3839 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3840 return SECFailure;
3841 }
3842 ss->ssl3.hs.hashType = handshake_hash_single;
3843 if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) {
3844 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
3845 return SECFailure;
3846 }
3847
3848 /* Transcript hash used on ECH client. */
3849 if (!ss->sec.isServer && ss->ssl3.hs.echHpkeCtx) {
3850 ss->ssl3.hs.shaEchInner = PK11_CreateDigestContext(hash_oid->offset);
3851 if (ss->ssl3.hs.shaEchInner == NULL((void*)0)) {
3852 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3853 return SECFailure;
3854 }
3855 if (PK11_DigestBegin(ss->ssl3.hs.shaEchInner) != SECSuccess) {
3856 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
3857 return SECFailure;
3858 }
3859 }
3860 } else {
3861 /* Both ss->ssl3.hs.md5 and ss->ssl3.hs.sha should be NULL or
3862 * created successfully. */
3863 ss->ssl3.hs.md5 = PK11_CreateDigestContext(SEC_OID_MD5);
3864 if (ss->ssl3.hs.md5 == NULL((void*)0)) {
3865 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3866 return SECFailure;
3867 }
3868 ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA1);
3869 if (ss->ssl3.hs.sha == NULL((void*)0)) {
3870 PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE1);
3871 ss->ssl3.hs.md5 = NULL((void*)0);
3872 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3873 return SECFailure;
3874 }
3875 ss->ssl3.hs.hashType = handshake_hash_combo;
3876
3877 if (PK11_DigestBegin(ss->ssl3.hs.md5) != SECSuccess) {
3878 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
3879 return SECFailure;
3880 }
3881 if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) {
3882 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3883 return SECFailure;
3884 }
3885 }
3886 }
3887
3888 if (ss->ssl3.hs.hashType != handshake_hash_record &&
3889 ss->ssl3.hs.messages.len > 0) {
3890 /* When doing ECH, ssl3_UpdateHandshakeHashes will store outer messages
3891 * into the both the outer and inner transcripts.
3892 * ssl3_UpdateDefaultHandshakeHashes uses the default context which is
3893 * the outer when doing client ECH. For ECH shared-mode or backend
3894 * servers only the hs.messages buffer is used. */
3895 if (ssl3_UpdateDefaultHandshakeHashes(ss, ss->ssl3.hs.messages.buf,
3896 ss->ssl3.hs.messages.len) != SECSuccess) {
3897 return SECFailure;
3898 }
3899 /* When doing ECH, deriving the accept_confirmation value requires all
3900 * messages up to and including the ServerHello
3901 * (see draft-ietf-tls-esni-14, Section 7.2).
3902 *
3903 * Don't free the transcript buffer until confirmation calculation. */
3904 if (!ss->ssl3.hs.echHpkeCtx && !ss->opt.enableTls13BackendEch) {
3905 sslBuffer_Clear(&ss->ssl3.hs.messages);
3906 }
3907 }
3908 if (ss->ssl3.hs.shaEchInner &&
3909 ss->ssl3.hs.echInnerMessages.len > 0) {
3910 if (PK11_DigestOp(ss->ssl3.hs.shaEchInner, ss->ssl3.hs.echInnerMessages.buf,
3911 ss->ssl3.hs.echInnerMessages.len) != SECSuccess) {
3912 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
3913 return SECFailure;
3914 }
3915 if (!ss->ssl3.hs.echHpkeCtx) {
3916 sslBuffer_Clear(&ss->ssl3.hs.echInnerMessages);
3917 }
3918 }
3919
3920 return SECSuccess;
3921}
3922
3923void
3924ssl3_RestartHandshakeHashes(sslSocket *ss)
3925{
3926 SSL_TRC(30, ("%d: SSL3[%d]: reset handshake hashes",if (ssl_trace >= (30)) ssl_Trace ("%d: SSL3[%d]: reset handshake hashes"
, getpid(), ss->fd)
3927 SSL_GETPID(), ss->fd))if (ssl_trace >= (30)) ssl_Trace ("%d: SSL3[%d]: reset handshake hashes"
, getpid(), ss->fd)
;
3928 ss->ssl3.hs.hashType = handshake_hash_unknown;
3929 ss->ssl3.hs.messages.len = 0;
3930 ss->ssl3.hs.echInnerMessages.len = 0;
3931 if (ss->ssl3.hs.md5) {
3932 PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE1);
3933 ss->ssl3.hs.md5 = NULL((void*)0);
3934 }
3935 if (ss->ssl3.hs.sha) {
3936 PK11_DestroyContext(ss->ssl3.hs.sha, PR_TRUE1);
3937 ss->ssl3.hs.sha = NULL((void*)0);
3938 }
3939 if (ss->ssl3.hs.shaEchInner) {
3940 PK11_DestroyContext(ss->ssl3.hs.shaEchInner, PR_TRUE1);
3941 ss->ssl3.hs.shaEchInner = NULL((void*)0);
3942 }
3943 if (ss->ssl3.hs.shaPostHandshake) {
3944 PK11_DestroyContext(ss->ssl3.hs.shaPostHandshake, PR_TRUE1);
3945 ss->ssl3.hs.shaPostHandshake = NULL((void*)0);
3946 }
3947}
3948
3949/* Add the provided bytes to the handshake hash context. When doing
3950 * TLS 1.3 ECH, |target| may be provided to specify only the inner/outer
3951 * transcript, else the input is added to both contexts. This happens
3952 * only on the client. On the server, only the default context is used. */
3953SECStatus
3954ssl3_UpdateHandshakeHashesInt(sslSocket *ss, const unsigned char *b,
3955 unsigned int l, sslBuffer *target)
3956{
3957
3958 SECStatus rv = SECSuccess;
3959 PRBool explicit = (target != NULL((void*)0));
3960 PRBool appendToEchInner = !ss->sec.isServer &&
3961 ss->ssl3.hs.echHpkeCtx &&
3962 !explicit;
3963 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",3963))
;
3964 PORT_Assert(target != &ss->ssl3.hs.echInnerMessages ||((target != &ss->ssl3.hs.echInnerMessages || !ss->sec
.isServer)?((void)0):PR_Assert("target != &ss->ssl3.hs.echInnerMessages || !ss->sec.isServer"
,"ssl3con.c",3965))
3965 !ss->sec.isServer)((target != &ss->ssl3.hs.echInnerMessages || !ss->sec
.isServer)?((void)0):PR_Assert("target != &ss->ssl3.hs.echInnerMessages || !ss->sec.isServer"
,"ssl3con.c",3965))
;
3966
3967 if (target == NULL((void*)0)) {
3968 /* Default context. */
3969 target = &ss->ssl3.hs.messages;
3970 }
3971 /* With TLS 1.3, and versions TLS.1.1 and older, we keep the hash(es)
3972 * always up to date. However, we must initially buffer the handshake
3973 * messages, until we know what to do.
3974 * If ss->ssl3.hs.hashType != handshake_hash_unknown,
3975 * it means we know what to do. We calculate (hash our input),
3976 * and we stop appending to the buffer.
3977 *
3978 * With TLS 1.2, we always append all handshake messages,
3979 * and never update the hash, because the hash function we must use for
3980 * certificate_verify might be different from the hash function we use
3981 * when signing other handshake hashes. */
3982 if (ss->ssl3.hs.hashType == handshake_hash_unknown ||
3983 ss->ssl3.hs.hashType == handshake_hash_record) {
3984 rv = sslBuffer_Append(target, b, l);
3985 if (rv != SECSuccess) {
3986 return SECFailure;
3987 }
3988 if (appendToEchInner) {
3989 return sslBuffer_Append(&ss->ssl3.hs.echInnerMessages, b, l);
3990 }
3991 return SECSuccess;
3992 }
3993
3994 PRINT_BUF(90, (ss, "handshake hash input:", b, l))if (ssl_trace >= (90)) ssl_PrintBuf (ss, "handshake hash input:"
, b, l)
;
3995
3996 if (ss->ssl3.hs.hashType == handshake_hash_single) {
3997 PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3)((ss->version >= 0x0304)?((void)0):PR_Assert("ss->version >= SSL_LIBRARY_VERSION_TLS_1_3"
,"ssl3con.c",3997))
;
3998 if (target == &ss->ssl3.hs.messages) {
3999 rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l);
4000 if (rv != SECSuccess) {
4001 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4002 return rv;
4003 }
4004 }
4005 if (ss->ssl3.hs.shaEchInner &&
4006 (target == &ss->ssl3.hs.echInnerMessages || !explicit)) {
4007 rv = PK11_DigestOp(ss->ssl3.hs.shaEchInner, b, l);
4008 if (rv != SECSuccess) {
4009 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4010 return rv;
4011 }
4012 }
4013 } else if (ss->ssl3.hs.hashType == handshake_hash_combo) {
4014 rv = PK11_DigestOp(ss->ssl3.hs.md5, b, l);
4015 if (rv != SECSuccess) {
4016 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4017 return rv;
4018 }
4019 rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l);
4020 if (rv != SECSuccess) {
4021 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4022 return rv;
4023 }
4024 }
4025 return rv;
4026}
4027
4028static SECStatus
4029ssl3_UpdateDefaultHandshakeHashes(sslSocket *ss, const unsigned char *b,
4030 unsigned int l)
4031{
4032 return ssl3_UpdateHandshakeHashesInt(ss, b, l,
4033 &ss->ssl3.hs.messages);
4034}
4035
4036static SECStatus
4037ssl3_UpdateInnerHandshakeHashes(sslSocket *ss, const unsigned char *b,
4038 unsigned int l)
4039{
4040 return ssl3_UpdateHandshakeHashesInt(ss, b, l,
4041 &ss->ssl3.hs.echInnerMessages);
4042}
4043
4044/*
4045 * Handshake messages
4046 */
4047/* Called from ssl3_InitHandshakeHashes()
4048** ssl3_AppendHandshake()
4049** ssl3_HandleV2ClientHello()
4050** ssl3_HandleHandshakeMessage()
4051** Caller must hold the ssl3Handshake lock.
4052*/
4053SECStatus
4054ssl3_UpdateHandshakeHashes(sslSocket *ss, const unsigned char *b, unsigned int l)
4055{
4056 return ssl3_UpdateHandshakeHashesInt(ss, b, l, NULL((void*)0));
4057}
4058
4059SECStatus
4060ssl3_UpdatePostHandshakeHashes(sslSocket *ss, const unsigned char *b, unsigned int l)
4061{
4062 SECStatus rv = SECSuccess;
4063
4064 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",4064))
;
4065
4066 PRINT_BUF(90, (ss, "post handshake hash input:", b, l))if (ssl_trace >= (90)) ssl_PrintBuf (ss, "post handshake hash input:"
, b, l)
;
4067
4068 PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_single)((ss->ssl3.hs.hashType == handshake_hash_single)?((void)0)
:PR_Assert("ss->ssl3.hs.hashType == handshake_hash_single"
,"ssl3con.c",4068))
;
4069 PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3)((ss->version >= 0x0304)?((void)0):PR_Assert("ss->version >= SSL_LIBRARY_VERSION_TLS_1_3"
,"ssl3con.c",4069))
;
4070 rv = PK11_DigestOp(ss->ssl3.hs.shaPostHandshake, b, l);
4071 if (rv != SECSuccess) {
4072 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_DIGEST_FAILURE);
4073 }
4074 return rv;
4075}
4076
4077/* The next two functions serve to append the handshake header.
4078 The first one additionally writes to seqNumberBuffer
4079 the sequence number of the message we are generating.
4080 This function is used when generating the keyUpdate message in dtls13_enqueueKeyUpdateMessage.
4081*/
4082SECStatus
4083ssl3_AppendHandshakeHeaderAndStashSeqNum(sslSocket *ss, SSLHandshakeType t, PRUint32 length, PRUint64 *sendMessageSeqOut)
4084{
4085 PORT_Assert(t != ssl_hs_client_hello)((t != ssl_hs_client_hello)?((void)0):PR_Assert("t != ssl_hs_client_hello"
,"ssl3con.c",4085))
;
4086 SECStatus rv;
4087
4088 /* If we already have a message in place, we need to enqueue it.
4089 * This empties the buffer. This is a convenient place to call
4090 * dtls_StageHandshakeMessage to mark the message boundary.
4091 */
4092 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
4093 rv = dtls_StageHandshakeMessage(ss);
4094 if (rv != SECSuccess) {
4095 return rv;
4096 }
4097 }
4098
4099 SSL_TRC(30, ("%d: SSL3[%d]: append handshake header: type %s",if (ssl_trace >= (30)) ssl_Trace ("%d: SSL3[%d]: append handshake header: type %s"
, getpid(), ss->fd, ssl3_DecodeHandshakeType(t))
4100 SSL_GETPID(), ss->fd, ssl3_DecodeHandshakeType(t)))if (ssl_trace >= (30)) ssl_Trace ("%d: SSL3[%d]: append handshake header: type %s"
, getpid(), ss->fd, ssl3_DecodeHandshakeType(t))
;
4101
4102 rv = ssl3_AppendHandshakeNumber(ss, t, 1);
4103 if (rv != SECSuccess) {
4104 return rv; /* error code set by AppendHandshake, if applicable. */
4105 }
4106 rv = ssl3_AppendHandshakeNumber(ss, length, 3);
4107 if (rv != SECSuccess) {
4108 return rv; /* error code set by AppendHandshake, if applicable. */
4109 }
4110
4111 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
4112 /* RFC 9147. 5.2. DTLS Handshake Message Format.
4113 * In DTLS 1.3, the message transcript is computed over the original TLS
4114 * 1.3-style Handshake messages without the message_seq,
4115 * fragment_offset, and fragment_length values. Note that this is a
4116 * change from DTLS 1.2 where those values were included in the transcript. */
4117 PRBool suppressHash = ss->version == SSL_LIBRARY_VERSION_TLS_1_30x0304 ? PR_TRUE1 : PR_FALSE0;
4118
4119 /* Note that we make an unfragmented message here. We fragment in the
4120 * transmission code, if necessary */
4121 rv = ssl3_AppendHandshakeNumberSuppressHash(ss, ss->ssl3.hs.sendMessageSeq, 2, suppressHash);
4122 if (rv != SECSuccess) {
4123 return rv; /* error code set by AppendHandshake, if applicable. */
4124 }
4125 /* In case if we provide a buffer for the sequence message,
4126 we write down sendMessageSeq to the buffer. */
4127 if (sendMessageSeqOut != NULL((void*)0)) {
4128 *sendMessageSeqOut = ss->ssl3.hs.sendMessageSeq;
4129 }
4130 ss->ssl3.hs.sendMessageSeq++;
4131
4132 /* 0 is the fragment offset, because it's not fragmented yet */
4133 rv = ssl3_AppendHandshakeNumberSuppressHash(ss, 0, 3, suppressHash);
4134 if (rv != SECSuccess) {
4135 return rv; /* error code set by AppendHandshake, if applicable. */
4136 }
4137
4138 /* Fragment length -- set to the packet length because not fragmented */
4139 rv = ssl3_AppendHandshakeNumberSuppressHash(ss, length, 3, suppressHash);
4140 if (rv != SECSuccess) {
4141 return rv; /* error code set by AppendHandshake, if applicable. */
4142 }
4143 }
4144
4145 return rv; /* error code set by AppendHandshake, if applicable. */
4146}
4147
4148/* The function calls the ssl3_AppendHandshakeHeaderAndStashSeqNum implemented above.
4149 As in the majority of the cases we do not need the last parameter,
4150 we separate out this function. */
4151SECStatus
4152ssl3_AppendHandshakeHeader(sslSocket *ss, SSLHandshakeType t, PRUint32 length)
4153{
4154 return ssl3_AppendHandshakeHeaderAndStashSeqNum(ss, t, length, NULL((void*)0));
4155}
4156
4157/**************************************************************************
4158 * Consume Handshake functions.
4159 *
4160 * All data used in these functions is protected by two locks,
4161 * the RecvBufLock and the SSL3HandshakeLock
4162 **************************************************************************/
4163
4164/* Read up the next "bytes" number of bytes from the (decrypted) input
4165 * stream "b" (which is *length bytes long). Copy them into buffer "v".
4166 * Reduces *length by bytes. Advances *b by bytes.
4167 *
4168 * If this function returns SECFailure, it has already sent an alert,
4169 * and has set a generic error code. The caller should probably
4170 * override the generic error code by setting another.
4171 */
4172SECStatus
4173ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRUint32 bytes, PRUint8 **b,
4174 PRUint32 *length)
4175{
4176 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->recvBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveRecvBufLock(ss)"
,"ssl3con.c",4176))
;
4177 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",4177))
;
4178
4179 if ((PRUint32)bytes > *length) {
4180 return ssl3_DecodeError(ss);
4181 }
4182 PORT_Memcpymemcpy(v, *b, bytes);
4183 PRINT_BUF(60, (ss, "consume bytes:", *b, bytes))if (ssl_trace >= (60)) ssl_PrintBuf (ss, "consume bytes:",
*b, bytes)
;
4184 *b += bytes;
4185 *length -= bytes;
4186 return SECSuccess;
4187}
4188
4189/* Read up the next "bytes" number of bytes from the (decrypted) input
4190 * stream "b" (which is *length bytes long), and interpret them as an
4191 * integer in network byte order. Sets *num to the received value.
4192 * Reduces *length by bytes. Advances *b by bytes.
4193 *
4194 * On error, an alert has been sent, and a generic error code has been set.
4195 */
4196SECStatus
4197ssl3_ConsumeHandshakeNumber64(sslSocket *ss, PRUint64 *num, PRUint32 bytes,
4198 PRUint8 **b, PRUint32 *length)
4199{
4200 PRUint8 *buf = *b;
4201 PRUint32 i;
4202
4203 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->recvBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveRecvBufLock(ss)"
,"ssl3con.c",4203))
;
4204 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",4204))
;
4205
4206 *num = 0;
4207 if (bytes > sizeof(*num)) {
4208 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
4209 return SECFailure;
4210 }
4211
4212 if (bytes > *length) {
4213 return ssl3_DecodeError(ss);
4214 }
4215 PRINT_BUF(60, (ss, "consume bytes:", *b, bytes))if (ssl_trace >= (60)) ssl_PrintBuf (ss, "consume bytes:",
*b, bytes)
;
4216
4217 for (i = 0; i < bytes; i++) {
4218 *num = (*num << 8) + buf[i];
4219 }
4220 *b += bytes;
4221 *length -= bytes;
4222 return SECSuccess;
4223}
4224
4225SECStatus
4226ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRUint32 *num, PRUint32 bytes,
4227 PRUint8 **b, PRUint32 *length)
4228{
4229 PRUint64 num64;
4230 SECStatus rv;
4231
4232 PORT_Assert(bytes <= sizeof(*num))((bytes <= sizeof(*num))?((void)0):PR_Assert("bytes <= sizeof(*num)"
,"ssl3con.c",4232))
;
4233 if (bytes > sizeof(*num)) {
4234 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
4235 return SECFailure;
4236 }
4237 rv = ssl3_ConsumeHandshakeNumber64(ss, &num64, bytes, b, length);
4238 if (rv != SECSuccess) {
4239 return SECFailure;
4240 }
4241 *num = num64 & 0xffffffff;
4242 return SECSuccess;
4243}
4244
4245/* Read in two values from the incoming decrypted byte stream "b", which is
4246 * *length bytes long. The first value is a number whose size is "bytes"
4247 * bytes long. The second value is a byte-string whose size is the value
4248 * of the first number received. The latter byte-string, and its length,
4249 * is returned in the SECItem i.
4250 *
4251 * Returns SECFailure (-1) on failure.
4252 * On error, an alert has been sent, and a generic error code has been set.
4253 *
4254 * RADICAL CHANGE for NSS 3.11. All callers of this function make copies
4255 * of the data returned in the SECItem *i, so making a copy of it here
4256 * is simply wasteful. So, This function now just sets SECItem *i to
4257 * point to the values in the buffer **b.
4258 */
4259SECStatus
4260ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i, PRUint32 bytes,
4261 PRUint8 **b, PRUint32 *length)
4262{
4263 PRUint32 count;
4264 SECStatus rv;
4265
4266 PORT_Assert(bytes <= 3)((bytes <= 3)?((void)0):PR_Assert("bytes <= 3","ssl3con.c"
,4266))
;
4267 i->len = 0;
4268 i->data = NULL((void*)0);
4269 i->type = siBuffer;
4270 rv = ssl3_ConsumeHandshakeNumber(ss, &count, bytes, b, length);
4271 if (rv != SECSuccess) {
4272 return SECFailure;
4273 }
4274 if (count > 0) {
4275 if (count > *length) {
4276 return ssl3_DecodeError(ss);
4277 }
4278 i->data = *b;
4279 i->len = count;
4280 *b += count;
4281 *length -= count;
4282 }
4283 return SECSuccess;
4284}
4285
4286/* ssl3_TLSHashAlgorithmToOID converts a TLS hash identifier into an OID value.
4287 * If the hash is not recognised, SEC_OID_UNKNOWN is returned.
4288 *
4289 * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
4290SECOidTag
4291ssl3_HashTypeToOID(SSLHashType hashType)
4292{
4293 switch (hashType) {
4294 case ssl_hash_sha1:
4295 return SEC_OID_SHA1;
4296 case ssl_hash_sha256:
4297 return SEC_OID_SHA256;
4298 case ssl_hash_sha384:
4299 return SEC_OID_SHA384;
4300 case ssl_hash_sha512:
4301 return SEC_OID_SHA512;
4302 default:
4303 break;
4304 }
4305 return SEC_OID_UNKNOWN;
4306}
4307
4308SECOidTag
4309ssl3_AuthTypeToOID(SSLAuthType authType)
4310{
4311 switch (authType) {
4312 case ssl_auth_rsa_sign:
4313 return SEC_OID_PKCS1_RSA_ENCRYPTION;
4314 case ssl_auth_rsa_pss:
4315 return SEC_OID_PKCS1_RSA_PSS_SIGNATURE;
4316 case ssl_auth_ecdsa:
4317 return SEC_OID_ANSIX962_EC_PUBLIC_KEY;
4318 case ssl_auth_dsa:
4319 return SEC_OID_ANSIX9_DSA_SIGNATURE;
4320 default:
4321 break;
4322 }
4323 /* shouldn't ever get there */
4324 PORT_Assert(0)((0)?((void)0):PR_Assert("0","ssl3con.c",4324));
4325 return SEC_OID_UNKNOWN;
4326}
4327
4328SSLHashType
4329ssl_SignatureSchemeToHashType(SSLSignatureScheme scheme)
4330{
4331 switch (scheme) {
4332 case ssl_sig_rsa_pkcs1_sha1:
4333 case ssl_sig_dsa_sha1:
4334 case ssl_sig_ecdsa_sha1:
4335 return ssl_hash_sha1;
4336 case ssl_sig_rsa_pkcs1_sha256:
4337 case ssl_sig_ecdsa_secp256r1_sha256:
4338 case ssl_sig_rsa_pss_rsae_sha256:
4339 case ssl_sig_rsa_pss_pss_sha256:
4340 case ssl_sig_dsa_sha256:
4341 return ssl_hash_sha256;
4342 case ssl_sig_rsa_pkcs1_sha384:
4343 case ssl_sig_ecdsa_secp384r1_sha384:
4344 case ssl_sig_rsa_pss_rsae_sha384:
4345 case ssl_sig_rsa_pss_pss_sha384:
4346 case ssl_sig_dsa_sha384:
4347 return ssl_hash_sha384;
4348 case ssl_sig_rsa_pkcs1_sha512:
4349 case ssl_sig_ecdsa_secp521r1_sha512:
4350 case ssl_sig_rsa_pss_rsae_sha512:
4351 case ssl_sig_rsa_pss_pss_sha512:
4352 case ssl_sig_dsa_sha512:
4353 return ssl_hash_sha512;
4354 case ssl_sig_rsa_pkcs1_sha1md5:
4355 return ssl_hash_none; /* Special for TLS 1.0/1.1. */
4356 case ssl_sig_none:
4357 case ssl_sig_ed25519:
4358 case ssl_sig_ed448:
4359 break;
4360 }
4361 PORT_Assert(0)((0)?((void)0):PR_Assert("0","ssl3con.c",4361));
4362 return ssl_hash_none;
4363}
4364
4365static PRBool
4366ssl_SignatureSchemeMatchesSpkiOid(SSLSignatureScheme scheme, SECOidTag spkiOid)
4367{
4368 SECOidTag authOid = ssl3_AuthTypeToOID(ssl_SignatureSchemeToAuthType(scheme));
4369
4370 if (spkiOid == authOid) {
4371 return PR_TRUE1;
4372 }
4373 if ((authOid == SEC_OID_PKCS1_RSA_ENCRYPTION) &&
4374 (spkiOid == SEC_OID_X500_RSA_ENCRYPTION)) {
4375 return PR_TRUE1;
4376 }
4377 return PR_FALSE0;
4378}
4379
4380/* Validate that the signature scheme works for the given key type. */
4381PRBool
4382ssl_SignatureSchemeValid(SSLSignatureScheme scheme, SECOidTag spkiOid,
4383 PRBool isTls13)
4384{
4385 if (!ssl_IsSupportedSignatureScheme(scheme)) {
4386 return PR_FALSE0;
4387 }
4388 /* if we are purposefully passed SEC_OID_UNKNOWN, it means
4389 * we not checking the scheme against a potential key, so skip
4390 * the call */
4391 if ((spkiOid != SEC_OID_UNKNOWN) &&
4392 !ssl_SignatureSchemeMatchesSpkiOid(scheme, spkiOid)) {
4393 return PR_FALSE0;
4394 }
4395 if (isTls13) {
4396 if (ssl_SignatureSchemeToHashType(scheme) == ssl_hash_sha1) {
4397 return PR_FALSE0;
4398 }
4399 if (ssl_IsRsaPkcs1SignatureScheme(scheme)) {
4400 return PR_FALSE0;
4401 }
4402 if (ssl_IsDsaSignatureScheme(scheme)) {
4403 return PR_FALSE0;
4404 }
4405 /* With TLS 1.3, EC keys should have been selected based on calling
4406 * ssl_SignatureSchemeFromSpki(), reject them otherwise. */
4407 return spkiOid != SEC_OID_ANSIX962_EC_PUBLIC_KEY;
4408 }
4409 return PR_TRUE1;
4410}
4411
4412static SECStatus
4413ssl_SignatureSchemeFromPssSpki(const CERTSubjectPublicKeyInfo *spki,
4414 SSLSignatureScheme *scheme)
4415{
4416 SECKEYRSAPSSParams pssParam = { 0 };
4417 PORTCheapArenaPool arena;
4418 SECStatus rv;
4419
4420 /* The key doesn't have parameters, boo. */
4421 if (!spki->algorithm.parameters.len) {
4422 *scheme = ssl_sig_none;
4423 return SECSuccess;
4424 }
4425
4426 PORT_InitCheapArena(&arena, DER_DEFAULT_CHUNKSIZE(2048));
4427 rv = SEC_QuickDERDecodeItemSEC_QuickDERDecodeItem_Util(&arena.arena, &pssParam,
4428 SEC_ASN1_GET(SECKEY_RSAPSSParamsTemplate)SECKEY_RSAPSSParamsTemplate,
4429 &spki->algorithm.parameters);
4430 if (rv != SECSuccess) {
4431 goto loser;
4432 }
4433 /* Not having hashAlg means SHA-1 and we don't accept that. */
4434 if (!pssParam.hashAlg) {
4435 goto loser;
4436 }
4437 switch (SECOID_GetAlgorithmTagSECOID_GetAlgorithmTag_Util(pssParam.hashAlg)) {
4438 case SEC_OID_SHA256:
4439 *scheme = ssl_sig_rsa_pss_pss_sha256;
4440 break;
4441 case SEC_OID_SHA384:
4442 *scheme = ssl_sig_rsa_pss_pss_sha384;
4443 break;
4444 case SEC_OID_SHA512:
4445 *scheme = ssl_sig_rsa_pss_pss_sha512;
4446 break;
4447 default:
4448 goto loser;
4449 }
4450
4451 PORT_DestroyCheapArena(&arena);
4452 return SECSuccess;
4453
4454loser:
4455 PORT_DestroyCheapArena(&arena);
4456 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_BAD_CERTIFICATE);
4457 return SECFailure;
4458}
4459
4460static SECStatus
4461ssl_SignatureSchemeFromEcSpki(const CERTSubjectPublicKeyInfo *spki,
4462 SSLSignatureScheme *scheme)
4463{
4464 const sslNamedGroupDef *group;
4465 SECKEYPublicKey *key;
4466
4467 key = SECKEY_ExtractPublicKey(spki);
4468 if (!key) {
4469 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_BAD_CERTIFICATE);
4470 return SECFailure;
4471 }
4472 group = ssl_ECPubKey2NamedGroup(key);
4473 SECKEY_DestroyPublicKey(key);
4474 if (!group) {
4475 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_BAD_CERTIFICATE);
4476 return SECFailure;
4477 }
4478 switch (group->name) {
4479 case ssl_grp_ec_secp256r1:
4480 *scheme = ssl_sig_ecdsa_secp256r1_sha256;
4481 return SECSuccess;
4482 case ssl_grp_ec_secp384r1:
4483 *scheme = ssl_sig_ecdsa_secp384r1_sha384;
4484 return SECSuccess;
4485 case ssl_grp_ec_secp521r1:
4486 *scheme = ssl_sig_ecdsa_secp521r1_sha512;
4487 return SECSuccess;
4488 default:
4489 break;
4490 }
4491 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_BAD_CERTIFICATE);
4492 return SECFailure;
4493}
4494
4495/* Newer signature schemes are designed so that a single SPKI can be used with
4496 * that scheme. This determines that scheme from the SPKI. If the SPKI doesn't
4497 * have a single scheme, |*scheme| is set to ssl_sig_none. */
4498SECStatus
4499ssl_SignatureSchemeFromSpki(const CERTSubjectPublicKeyInfo *spki,
4500 PRBool isTls13, SSLSignatureScheme *scheme)
4501{
4502 SECOidTag spkiOid = SECOID_GetAlgorithmTagSECOID_GetAlgorithmTag_Util(&spki->algorithm);
4503
4504 if (spkiOid == SEC_OID_PKCS1_RSA_PSS_SIGNATURE) {
4505 return ssl_SignatureSchemeFromPssSpki(spki, scheme);
4506 }
4507
4508 /* Only do this lookup for TLS 1.3, where the scheme can be determined from
4509 * the SPKI alone because the ECDSA key size determines the hash. Earlier
4510 * TLS versions allow the same EC key to be used with different hashes. */
4511 if (isTls13 && spkiOid == SEC_OID_ANSIX962_EC_PUBLIC_KEY) {
4512 return ssl_SignatureSchemeFromEcSpki(spki, scheme);
4513 }
4514
4515 *scheme = ssl_sig_none;
4516 return SECSuccess;
4517}
4518
4519/* Check that a signature scheme is enabled by configuration. */
4520PRBool
4521ssl_SignatureSchemeEnabled(const sslSocket *ss, SSLSignatureScheme scheme)
4522{
4523 unsigned int i;
4524 for (i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
4525 if (scheme == ss->ssl3.signatureSchemes[i]) {
4526 return PR_TRUE1;
4527 }
4528 }
4529 return PR_FALSE0;
4530}
4531
4532static PRBool
4533ssl_SignatureKeyMatchesSpkiOid(const ssl3KEADef *keaDef, SECOidTag spkiOid)
4534{
4535 switch (spkiOid) {
4536 case SEC_OID_X500_RSA_ENCRYPTION:
4537 case SEC_OID_PKCS1_RSA_ENCRYPTION:
4538 case SEC_OID_PKCS1_RSA_PSS_SIGNATURE:
4539 return keaDef->signKeyType == rsaKey;
4540 case SEC_OID_ANSIX9_DSA_SIGNATURE:
4541 return keaDef->signKeyType == dsaKey;
4542 case SEC_OID_ANSIX962_EC_PUBLIC_KEY:
4543 return keaDef->signKeyType == ecKey;
4544 default:
4545 break;
4546 }
4547 return PR_FALSE0;
4548}
4549
4550/* ssl3_CheckSignatureSchemeConsistency checks that the signature algorithm
4551 * identifier in |scheme| is consistent with the public key in |spki|. It also
4552 * checks the hash algorithm against the configured signature algorithms. If
4553 * all the tests pass, SECSuccess is returned. Otherwise, PORT_SetError is
4554 * called and SECFailure is returned. */
4555SECStatus
4556ssl_CheckSignatureSchemeConsistency(sslSocket *ss, SSLSignatureScheme scheme,
4557 CERTSubjectPublicKeyInfo *spki)
4558{
4559 SSLSignatureScheme spkiScheme;
4560 PRBool isTLS13 = ss->version == SSL_LIBRARY_VERSION_TLS_1_30x0304;
4561 SECOidTag spkiOid;
4562 SECStatus rv;
4563
4564 rv = ssl_SignatureSchemeFromSpki(spki, isTLS13, &spkiScheme);
4565 if (rv != SECSuccess) {
4566 return SECFailure;
4567 }
4568 if (spkiScheme != ssl_sig_none) {
4569 /* The SPKI in the certificate can only be used for a single scheme. */
4570 if (spkiScheme != scheme ||
4571 !ssl_SignatureSchemeEnabled(ss, scheme)) {
4572 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM);
4573 return SECFailure;
4574 }
4575 return SECSuccess;
4576 }
4577
4578 spkiOid = SECOID_GetAlgorithmTagSECOID_GetAlgorithmTag_Util(&spki->algorithm);
4579
4580 /* If we're a client, check that the signature algorithm matches the signing
4581 * key type of the cipher suite. */
4582 if (!isTLS13 && !ss->sec.isServer) {
4583 if (!ssl_SignatureKeyMatchesSpkiOid(ss->ssl3.hs.kea_def, spkiOid)) {
4584 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM);
4585 return SECFailure;
4586 }
4587 }
4588
4589 /* Verify that the signature scheme matches the signing key. */
4590 if ((spkiOid == SEC_OID_UNKNOWN) ||
4591 !ssl_SignatureSchemeValid(scheme, spkiOid, isTLS13)) {
4592 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM);
4593 return SECFailure;
4594 }
4595
4596 if (!ssl_SignatureSchemeEnabled(ss, scheme)) {
4597 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
4598 return SECFailure;
4599 }
4600
4601 return SECSuccess;
4602}
4603
4604PRBool
4605ssl_IsSupportedSignatureScheme(SSLSignatureScheme scheme)
4606{
4607 switch (scheme) {
4608 case ssl_sig_rsa_pkcs1_sha1:
4609 case ssl_sig_rsa_pkcs1_sha256:
4610 case ssl_sig_rsa_pkcs1_sha384:
4611 case ssl_sig_rsa_pkcs1_sha512:
4612 case ssl_sig_rsa_pss_rsae_sha256:
4613 case ssl_sig_rsa_pss_rsae_sha384:
4614 case ssl_sig_rsa_pss_rsae_sha512:
4615 case ssl_sig_rsa_pss_pss_sha256:
4616 case ssl_sig_rsa_pss_pss_sha384:
4617 case ssl_sig_rsa_pss_pss_sha512:
4618 case ssl_sig_ecdsa_secp256r1_sha256:
4619 case ssl_sig_ecdsa_secp384r1_sha384:
4620 case ssl_sig_ecdsa_secp521r1_sha512:
4621 case ssl_sig_dsa_sha1:
4622 case ssl_sig_dsa_sha256:
4623 case ssl_sig_dsa_sha384:
4624 case ssl_sig_dsa_sha512:
4625 case ssl_sig_ecdsa_sha1:
4626 return ssl_SchemePolicyOK(scheme, kSSLSigSchemePolicy);
4627 break;
4628
4629 case ssl_sig_rsa_pkcs1_sha1md5:
4630 case ssl_sig_none:
4631 case ssl_sig_ed25519:
4632 case ssl_sig_ed448:
4633 return PR_FALSE0;
4634 }
4635 return PR_FALSE0;
4636}
4637
4638PRBool
4639ssl_IsRsaPssSignatureScheme(SSLSignatureScheme scheme)
4640{
4641 switch (scheme) {
4642 case ssl_sig_rsa_pss_rsae_sha256:
4643 case ssl_sig_rsa_pss_rsae_sha384:
4644 case ssl_sig_rsa_pss_rsae_sha512:
4645 case ssl_sig_rsa_pss_pss_sha256:
4646 case ssl_sig_rsa_pss_pss_sha384:
4647 case ssl_sig_rsa_pss_pss_sha512:
4648 return PR_TRUE1;
4649
4650 default:
4651 return PR_FALSE0;
4652 }
4653 return PR_FALSE0;
4654}
4655
4656PRBool
4657ssl_IsRsaeSignatureScheme(SSLSignatureScheme scheme)
4658{
4659 switch (scheme) {
4660 case ssl_sig_rsa_pss_rsae_sha256:
4661 case ssl_sig_rsa_pss_rsae_sha384:
4662 case ssl_sig_rsa_pss_rsae_sha512:
4663 return PR_TRUE1;
4664
4665 default:
4666 return PR_FALSE0;
4667 }
4668 return PR_FALSE0;
4669}
4670
4671PRBool
4672ssl_IsRsaPkcs1SignatureScheme(SSLSignatureScheme scheme)
4673{
4674 switch (scheme) {
4675 case ssl_sig_rsa_pkcs1_sha256:
4676 case ssl_sig_rsa_pkcs1_sha384:
4677 case ssl_sig_rsa_pkcs1_sha512:
4678 case ssl_sig_rsa_pkcs1_sha1:
4679 return PR_TRUE1;
4680
4681 default:
4682 return PR_FALSE0;
4683 }
4684 return PR_FALSE0;
4685}
4686
4687PRBool
4688ssl_IsDsaSignatureScheme(SSLSignatureScheme scheme)
4689{
4690 switch (scheme) {
4691 case ssl_sig_dsa_sha256:
4692 case ssl_sig_dsa_sha384:
4693 case ssl_sig_dsa_sha512:
4694 case ssl_sig_dsa_sha1:
4695 return PR_TRUE1;
4696
4697 default:
4698 return PR_FALSE0;
4699 }
4700 return PR_FALSE0;
4701}
4702
4703SSLAuthType
4704ssl_SignatureSchemeToAuthType(SSLSignatureScheme scheme)
4705{
4706 switch (scheme) {
4707 case ssl_sig_rsa_pkcs1_sha1:
4708 case ssl_sig_rsa_pkcs1_sha1md5:
4709 case ssl_sig_rsa_pkcs1_sha256:
4710 case ssl_sig_rsa_pkcs1_sha384:
4711 case ssl_sig_rsa_pkcs1_sha512:
4712 /* We report based on the key type for PSS signatures. */
4713 case ssl_sig_rsa_pss_rsae_sha256:
4714 case ssl_sig_rsa_pss_rsae_sha384:
4715 case ssl_sig_rsa_pss_rsae_sha512:
4716 return ssl_auth_rsa_sign;
4717 case ssl_sig_rsa_pss_pss_sha256:
4718 case ssl_sig_rsa_pss_pss_sha384:
4719 case ssl_sig_rsa_pss_pss_sha512:
4720 return ssl_auth_rsa_pss;
4721 case ssl_sig_ecdsa_secp256r1_sha256:
4722 case ssl_sig_ecdsa_secp384r1_sha384:
4723 case ssl_sig_ecdsa_secp521r1_sha512:
4724 case ssl_sig_ecdsa_sha1:
4725 return ssl_auth_ecdsa;
4726 case ssl_sig_dsa_sha1:
4727 case ssl_sig_dsa_sha256:
4728 case ssl_sig_dsa_sha384:
4729 case ssl_sig_dsa_sha512:
4730 return ssl_auth_dsa;
4731
4732 default:
4733 PORT_Assert(0)((0)?((void)0):PR_Assert("0","ssl3con.c",4733));
4734 }
4735 return ssl_auth_null;
4736}
4737
4738/* ssl_ConsumeSignatureScheme reads a SSLSignatureScheme (formerly
4739 * SignatureAndHashAlgorithm) structure from |b| and puts the resulting value
4740 * into |out|. |b| and |length| are updated accordingly.
4741 *
4742 * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
4743SECStatus
4744ssl_ConsumeSignatureScheme(sslSocket *ss, PRUint8 **b,
4745 PRUint32 *length, SSLSignatureScheme *out)
4746{
4747 PRUint32 tmp;
4748 SECStatus rv;
4749
4750 rv = ssl3_ConsumeHandshakeNumber(ss, &tmp, 2, b, length);
4751 if (rv != SECSuccess) {
4752 return SECFailure; /* Alert sent, Error code set already. */
4753 }
4754 if (!ssl_IsSupportedSignatureScheme((SSLSignatureScheme)tmp)) {
4755 SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
4756 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
4757 return SECFailure;
4758 }
4759 *out = (SSLSignatureScheme)tmp;
4760 return SECSuccess;
4761}
4762
4763/**************************************************************************
4764 * end of Consume Handshake functions.
4765 **************************************************************************/
4766
4767static SECStatus
4768ssl3_ComputeHandshakeHash(unsigned char *buf, unsigned int len,
4769 SSLHashType hashAlg, SSL3Hashes *hashes)
4770{
4771 SECStatus rv = SECFailure;
4772 PK11Context *hashContext = PK11_CreateDigestContext(
4773 ssl3_HashTypeToOID(hashAlg));
4774
4775 if (!hashContext) {
4776 return rv;
4777 }
4778 rv = PK11_DigestBegin(hashContext);
4779 if (rv == SECSuccess) {
4780 rv = PK11_DigestOp(hashContext, buf, len);
4781 }
4782 if (rv == SECSuccess) {
4783 rv = PK11_DigestFinal(hashContext, hashes->u.raw, &hashes->len,
4784 sizeof(hashes->u.raw));
4785 }
4786 if (rv == SECSuccess) {
4787 hashes->hashAlg = hashAlg;
4788 }
4789 PK11_DestroyContext(hashContext, PR_TRUE1);
4790 return rv;
4791}
4792
4793/* Extract the hashes of handshake messages to this point.
4794 * Called from ssl3_SendCertificateVerify
4795 * ssl3_SendFinished
4796 * ssl3_HandleHandshakeMessage
4797 *
4798 * Caller must hold the SSL3HandshakeLock.
4799 * Caller must hold a read or write lock on the Spec R/W lock.
4800 * (There is presently no way to assert on a Read lock.)
4801 */
4802SECStatus
4803ssl3_ComputeHandshakeHashes(sslSocket *ss,
4804 ssl3CipherSpec *spec, /* uses ->master_secret */
4805 SSL3Hashes *hashes, /* output goes here. */
4806 PRUint32 sender)
4807{
4808 SECStatus rv = SECSuccess;
4809 PRBool isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_00x0300);
4810 unsigned int outLength;
4811 PRUint8 md5_inner[MAX_MAC_LENGTH64];
4812 PRUint8 sha_inner[MAX_MAC_LENGTH64];
4813
4814 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",4814))
;
4815 if (ss->ssl3.hs.hashType == handshake_hash_unknown) {
4816 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
4817 return SECFailure;
4818 }
4819
4820 hashes->hashAlg = ssl_hash_none;
4821
4822 if (ss->ssl3.hs.hashType == handshake_hash_single) {
4823 PK11Context *h;
4824 unsigned int stateLen;
4825 unsigned char stackBuf[1024];
4826 unsigned char *stateBuf = NULL((void*)0);
4827
4828 h = ss->ssl3.hs.sha;
4829 stateBuf = PK11_SaveContextAlloc(h, stackBuf,
4830 sizeof(stackBuf), &stateLen);
4831 if (stateBuf == NULL((void*)0)) {
4832 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4833 rv = SECFailure;
4834 goto tls12_loser;
4835 }
4836 rv |= PK11_DigestFinal(h, hashes->u.raw, &hashes->len,
4837 sizeof(hashes->u.raw));
4838 if (rv != SECSuccess) {
4839 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4840 rv = SECFailure;
4841 goto tls12_loser;
4842 }
4843
4844 hashes->hashAlg = ssl3_GetSuitePrfHash(ss);
4845
4846 tls12_loser:
4847 if (stateBuf) {
4848 if (PK11_RestoreContext(h, stateBuf, stateLen) != SECSuccess) {
4849 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4850 rv = SECFailure;
4851 }
4852 if (stateBuf != stackBuf) {
4853 PORT_ZFreePORT_ZFree_Util(stateBuf, stateLen);
4854 }
4855 }
4856 } else if (ss->ssl3.hs.hashType == handshake_hash_record) {
4857 rv = ssl3_ComputeHandshakeHash(ss->ssl3.hs.messages.buf,
4858 ss->ssl3.hs.messages.len,
4859 ssl3_GetSuitePrfHash(ss),
4860 hashes);
4861 } else {
4862 PK11Context *md5;
4863 PK11Context *sha = NULL((void*)0);
4864 unsigned char *md5StateBuf = NULL((void*)0);
4865 unsigned char *shaStateBuf = NULL((void*)0);
4866 unsigned int md5StateLen, shaStateLen;
4867 unsigned char md5StackBuf[256];
4868 unsigned char shaStackBuf[512];
4869 const int md5Pad = ssl_GetMacDefByAlg(ssl_mac_md5)->pad_size;
4870 const int shaPad = ssl_GetMacDefByAlg(ssl_mac_sha)->pad_size;
4871
4872 md5StateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.md5, md5StackBuf,
4873 sizeof md5StackBuf, &md5StateLen);
4874 if (md5StateBuf == NULL((void*)0)) {
4875 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4876 rv = SECFailure;
4877 goto loser;
4878 }
4879 md5 = ss->ssl3.hs.md5;
4880
4881 shaStateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.sha, shaStackBuf,
4882 sizeof shaStackBuf, &shaStateLen);
4883 if (shaStateBuf == NULL((void*)0)) {
4884 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4885 rv = SECFailure;
4886 goto loser;
4887 }
4888 sha = ss->ssl3.hs.sha;
4889
4890 if (!isTLS) {
4891 /* compute hashes for SSL3. */
4892 unsigned char s[4];
4893
4894 if (!spec->masterSecret) {
4895 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
4896 rv = SECFailure;
4897 goto loser;
4898 }
4899
4900 s[0] = (unsigned char)(sender >> 24);
4901 s[1] = (unsigned char)(sender >> 16);
4902 s[2] = (unsigned char)(sender >> 8);
4903 s[3] = (unsigned char)sender;
4904
4905 if (sender != 0) {
4906 rv |= PK11_DigestOp(md5, s, 4);
4907 PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4))if (ssl_trace >= (95)) ssl_PrintBuf (((void*)0), "MD5 inner: sender"
, s, 4)
;
4908 }
4909
4910 PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1, md5Pad))if (ssl_trace >= (95)) ssl_PrintBuf (((void*)0), "MD5 inner: MAC Pad 1"
, mac_pad_1, md5Pad)
;
4911
4912 rv |= PK11_DigestKey(md5, spec->masterSecret);
4913 rv |= PK11_DigestOp(md5, mac_pad_1, md5Pad);
4914 rv |= PK11_DigestFinal(md5, md5_inner, &outLength, MD5_LENGTH16);
4915 PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH)((rv != SECSuccess || outLength == 16)?((void)0):PR_Assert("rv != SECSuccess || outLength == MD5_LENGTH"
,"ssl3con.c",4915))
;
4916 if (rv != SECSuccess) {
4917 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4918 rv = SECFailure;
4919 goto loser;
4920 }
4921
4922 PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength))if (ssl_trace >= (95)) ssl_PrintBuf (((void*)0), "MD5 inner: result"
, md5_inner, outLength)
;
4923
4924 if (sender != 0) {
4925 rv |= PK11_DigestOp(sha, s, 4);
4926 PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4))if (ssl_trace >= (95)) ssl_PrintBuf (((void*)0), "SHA inner: sender"
, s, 4)
;
4927 }
4928
4929 PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1, shaPad))if (ssl_trace >= (95)) ssl_PrintBuf (((void*)0), "SHA inner: MAC Pad 1"
, mac_pad_1, shaPad)
;
4930
4931 rv |= PK11_DigestKey(sha, spec->masterSecret);
4932 rv |= PK11_DigestOp(sha, mac_pad_1, shaPad);
4933 rv |= PK11_DigestFinal(sha, sha_inner, &outLength, SHA1_LENGTH20);
4934 PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH)((rv != SECSuccess || outLength == 20)?((void)0):PR_Assert("rv != SECSuccess || outLength == SHA1_LENGTH"
,"ssl3con.c",4934))
;
4935 if (rv != SECSuccess) {
4936 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4937 rv = SECFailure;
4938 goto loser;
4939 }
4940
4941 PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength))if (ssl_trace >= (95)) ssl_PrintBuf (((void*)0), "SHA inner: result"
, sha_inner, outLength)
;
4942
4943 PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2, md5Pad))if (ssl_trace >= (95)) ssl_PrintBuf (((void*)0), "MD5 outer: MAC Pad 2"
, mac_pad_2, md5Pad)
;
4944 PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH))if (ssl_trace >= (95)) ssl_PrintBuf (((void*)0), "MD5 outer: MD5 inner"
, md5_inner, 16)
;
4945
4946 rv |= PK11_DigestBegin(md5);
4947 rv |= PK11_DigestKey(md5, spec->masterSecret);
4948 rv |= PK11_DigestOp(md5, mac_pad_2, md5Pad);
4949 rv |= PK11_DigestOp(md5, md5_inner, MD5_LENGTH16);
4950 }
4951 rv |= PK11_DigestFinal(md5, hashes->u.s.md5, &outLength, MD5_LENGTH16);
4952 PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH)((rv != SECSuccess || outLength == 16)?((void)0):PR_Assert("rv != SECSuccess || outLength == MD5_LENGTH"
,"ssl3con.c",4952))
;
4953 if (rv != SECSuccess) {
4954 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4955 rv = SECFailure;
4956 goto loser;
4957 }
4958
4959 PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH))if (ssl_trace >= (60)) ssl_PrintBuf (((void*)0), "MD5 outer: result"
, hashes->u.s.md5, 16)
;
4960
4961 if (!isTLS) {
4962 PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2, shaPad))if (ssl_trace >= (95)) ssl_PrintBuf (((void*)0), "SHA outer: MAC Pad 2"
, mac_pad_2, shaPad)
;
4963 PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH))if (ssl_trace >= (95)) ssl_PrintBuf (((void*)0), "SHA outer: SHA inner"
, sha_inner, 20)
;
4964
4965 rv |= PK11_DigestBegin(sha);
4966 rv |= PK11_DigestKey(sha, spec->masterSecret);
4967 rv |= PK11_DigestOp(sha, mac_pad_2, shaPad);
4968 rv |= PK11_DigestOp(sha, sha_inner, SHA1_LENGTH20);
4969 }
4970 rv |= PK11_DigestFinal(sha, hashes->u.s.sha, &outLength, SHA1_LENGTH20);
4971 PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH)((rv != SECSuccess || outLength == 20)?((void)0):PR_Assert("rv != SECSuccess || outLength == SHA1_LENGTH"
,"ssl3con.c",4971))
;
4972 if (rv != SECSuccess) {
4973 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4974 rv = SECFailure;
4975 goto loser;
4976 }
4977
4978 PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH))if (ssl_trace >= (60)) ssl_PrintBuf (((void*)0), "SHA outer: result"
, hashes->u.s.sha, 20)
;
4979
4980 hashes->len = MD5_LENGTH16 + SHA1_LENGTH20;
4981
4982 loser:
4983 if (md5StateBuf) {
4984 if (PK11_RestoreContext(ss->ssl3.hs.md5, md5StateBuf, md5StateLen) !=
4985 SECSuccess) {
4986 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
4987 rv = SECFailure;
4988 }
4989 if (md5StateBuf != md5StackBuf) {
4990 PORT_ZFreePORT_ZFree_Util(md5StateBuf, md5StateLen);
4991 }
4992 }
4993 if (shaStateBuf) {
4994 if (PK11_RestoreContext(ss->ssl3.hs.sha, shaStateBuf, shaStateLen) !=
4995 SECSuccess) {
4996 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4997 rv = SECFailure;
4998 }
4999 if (shaStateBuf != shaStackBuf) {
5000 PORT_ZFreePORT_ZFree_Util(shaStateBuf, shaStateLen);
5001 }
5002 }
5003 }
5004 return rv;
5005}
5006
5007/**************************************************************************
5008 * end of Handshake Hash functions.
5009 * Begin Send and Handle functions for handshakes.
5010 **************************************************************************/
5011
5012#ifdef TRACE
5013#define CHTYPE(t) \
5014 case client_hello_##t: \
5015 return #t;
5016
5017static const char *
5018ssl_ClientHelloTypeName(sslClientHelloType type)
5019{
5020 switch (type) {
5021 CHTYPE(initial);
5022 CHTYPE(retry);
5023 CHTYPE(retransmit); /* DTLS only */
5024 CHTYPE(renegotiation); /* TLS <= 1.2 only */
5025 }
5026 PORT_Assert(0)((0)?((void)0):PR_Assert("0","ssl3con.c",5026));
5027 return NULL((void*)0);
5028}
5029#undef CHTYPE
5030#endif
5031
5032PR_STATIC_ASSERT(SSL3_SESSIONID_BYTES == SSL3_RANDOM_LENGTH)extern void pr_static_assert(int arg[(32 == 32) ? 1 : -1]);
5033static void
5034ssl_MakeFakeSid(sslSocket *ss, PRUint8 *buf)
5035{
5036 PRUint8 x = 0x5a;
5037 int i;
5038 for (i = 0; i < SSL3_SESSIONID_BYTES32; ++i) {
5039 x += ss->ssl3.hs.client_random[i];
5040 buf[i] = x;
5041 }
5042}
5043
5044/* Set the version fields of the cipher spec for a ClientHello. */
5045static void
5046ssl_SetClientHelloSpecVersion(sslSocket *ss, ssl3CipherSpec *spec)
5047{
5048 ssl_GetSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_LockWrite_Util((ss)->
specLock); }
;
5049 PORT_Assert(spec->cipherDef->cipher == cipher_null)((spec->cipherDef->cipher == cipher_null)?((void)0):PR_Assert
("spec->cipherDef->cipher == cipher_null","ssl3con.c",5049
))
;
5050 /* This is - a best guess - but it doesn't matter here. */
5051 spec->version = ss->vrange.max;
5052 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
5053 spec->recordVersion = SSL_LIBRARY_VERSION_DTLS_1_0_WIRE((~0x0100) & 0xffff);
5054 } else {
5055 /* For new connections, cap the record layer version number of TLS
5056 * ClientHello to { 3, 1 } (TLS 1.0). Some TLS 1.0 servers (which seem
5057 * to use F5 BIG-IP) ignore ClientHello.client_version and use the
5058 * record layer version number (TLSPlaintext.version) instead when
5059 * negotiating protocol versions. In addition, if the record layer
5060 * version number of ClientHello is { 3, 2 } (TLS 1.1) or higher, these
5061 * servers reset the TCP connections. Lastly, some F5 BIG-IP servers
5062 * hang if a record containing a ClientHello has a version greater than
5063 * { 3, 1 } and a length greater than 255. Set this flag to work around
5064 * such servers.
5065 *
5066 * The final version is set when a version is negotiated.
5067 */
5068 spec->recordVersion = PR_MIN(SSL_LIBRARY_VERSION_TLS_1_0,((0x0301)<(ss->vrange.max)?(0x0301):(ss->vrange.max)
)
5069 ss->vrange.max)((0x0301)<(ss->vrange.max)?(0x0301):(ss->vrange.max)
)
;
5070 }
5071 ssl_ReleaseSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockWrite_Util((ss)->
specLock); }
;
5072}
5073
5074SECStatus
5075ssl3_InsertChHeaderSize(const sslSocket *ss, sslBuffer *preamble, const sslBuffer *extensions)
5076{
5077 SECStatus rv;
5078 unsigned int msgLen = preamble->len;
5079 msgLen += extensions->len ? (2 + extensions->len) : 0;
5080 unsigned int headerLen = IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram) ? 12 : 4;
5081
5082 /* Record the message length. */
5083 rv = sslBuffer_InsertNumber(preamble, 1, msgLen - headerLen, 3);
5084 if (rv != SECSuccess) {
5085 return SECFailure; /* code set */
5086 }
5087 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
5088 /* Record the (unfragmented) fragment length. */
5089 unsigned int offset = 1 /* ch */ + 3 /* len */ +
5090 2 /* seq */ + 3 /* fragment offset */;
5091 rv = sslBuffer_InsertNumber(preamble, offset, msgLen - headerLen, 3);
5092 if (rv != SECSuccess) {
5093 return SECFailure; /* code set */
5094 }
5095 }
5096
5097 return SECSuccess;
5098}
5099
5100static SECStatus
5101ssl3_AppendCipherSuites(sslSocket *ss, PRBool fallbackSCSV, sslBuffer *buf)
5102{
5103 SECStatus rv;
5104 unsigned int offset;
5105 unsigned int i;
5106 unsigned int saveLen;
5107
5108 rv = sslBuffer_Skip(buf, 2, &offset);
5109 if (rv != SECSuccess) {
5110 return SECFailure;
5111 }
5112
5113 if (ss->ssl3.hs.sendingSCSV) {
5114 /* Add the actual SCSV */
5115 rv = sslBuffer_AppendNumber(buf, TLS_EMPTY_RENEGOTIATION_INFO_SCSV0x00FF,
5116 sizeof(ssl3CipherSuite));
5117 if (rv != SECSuccess) {
5118 return SECFailure;
5119 }
5120 }
5121 if (fallbackSCSV) {
5122 rv = sslBuffer_AppendNumber(buf, TLS_FALLBACK_SCSV0x5600,
5123 sizeof(ssl3CipherSuite));
5124 if (rv != SECSuccess) {
5125 return SECFailure;
5126 }
5127 }
5128
5129 saveLen = SSL_BUFFER_LEN(buf)((buf)->len);
5130 /* CipherSuites are appended to Hello message here */
5131 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED71; i++) {
5132 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
5133 if (ssl3_config_match(suite, ss->ssl3.policy, &ss->vrange, ss)) {
5134 rv = sslBuffer_AppendNumber(buf, suite->cipher_suite,
5135 sizeof(ssl3CipherSuite));
5136 if (rv != SECSuccess) {
5137 return SECFailure;
5138 }
5139 }
5140 }
5141
5142 /* GREASE CipherSuites:
5143 * A client MAY select one or more GREASE cipher suite values and advertise
5144 * them in the "cipher_suites" field [RFC8701, Section 3.1]. */
5145 if (ss->opt.enableGrease && ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_30x0304) {
5146 rv = sslBuffer_AppendNumber(buf, ss->ssl3.hs.grease->idx[grease_cipher],
5147 sizeof(ssl3CipherSuite));
5148 if (rv != SECSuccess) {
5149 return SECFailure;
5150 }
5151 }
5152
5153 if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)((&ss->vrange)->min == 0) ||
5154 (SSL_BUFFER_LEN(buf)((buf)->len) - saveLen) == 0) {
5155 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_SSL_DISABLED);
5156 return SECFailure;
5157 }
5158
5159 return sslBuffer_InsertLength(buf, offset, 2);
5160}
5161
5162SECStatus
5163ssl3_CreateClientHelloPreamble(sslSocket *ss, const sslSessionID *sid,
5164 PRBool realSid, PRUint16 version, PRBool isEchInner,
5165 const sslBuffer *extensions, sslBuffer *preamble)
5166{
5167 SECStatus rv;
5168 sslBuffer constructed = SSL_BUFFER_EMPTY{ ((void*)0), 0, 0, 0 };
5169 const PRUint8 *client_random = isEchInner ? ss->ssl3.hs.client_inner_random : ss->ssl3.hs.client_random;
5170 PORT_Assert(sid)((sid)?((void)0):PR_Assert("sid","ssl3con.c",5170));
5171 PRBool fallbackSCSV = ss->opt.enableFallbackSCSV && !isEchInner &&
5172 (!realSid || version < sid->version);
5173
5174 rv = sslBuffer_AppendNumber(&constructed, ssl_hs_client_hello, 1);
5175 if (rv != SECSuccess) {
5176 goto loser;
5177 }
5178
5179 rv = sslBuffer_Skip(&constructed, 3, NULL((void*)0));
5180 if (rv != SECSuccess) {
5181 goto loser;
5182 }
5183
5184 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
5185 /* Note that we make an unfragmented message here. We fragment in the
5186 * transmission code, if necessary */
5187 rv = sslBuffer_AppendNumber(&constructed, ss->ssl3.hs.sendMessageSeq, 2);
5188 if (rv != SECSuccess) {
5189 goto loser;
5190 }
5191 ss->ssl3.hs.sendMessageSeq++;
5192
5193 /* 0 is the fragment offset, because it's not fragmented yet */
5194 rv = sslBuffer_AppendNumber(&constructed, 0, 3);
5195 if (rv != SECSuccess) {
5196 goto loser;
5197 }
5198
5199 /* Fragment length -- set to the packet length because not fragmented */
5200 rv = sslBuffer_Skip(&constructed, 3, NULL((void*)0));
5201 if (rv != SECSuccess) {
5202 goto loser;
5203 }
5204 }
5205
5206 if (ss->firstHsDone) {
5207 /* The client hello version must stay unchanged to work around
5208 * the Windows SChannel bug described in ssl3_SendClientHello. */
5209 PORT_Assert(version == ss->clientHelloVersion)((version == ss->clientHelloVersion)?((void)0):PR_Assert("version == ss->clientHelloVersion"
,"ssl3con.c",5209))
;
5210 }
5211
5212 ss->clientHelloVersion = PR_MIN(version, SSL_LIBRARY_VERSION_TLS_1_2)((version)<(0x0303)?(version):(0x0303));
5213 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
5214 PRUint16 dtlsVersion = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion);
5215 rv = sslBuffer_AppendNumber(&constructed, dtlsVersion, 2);
5216 } else {
5217 rv = sslBuffer_AppendNumber(&constructed, ss->clientHelloVersion, 2);
5218 }
5219 if (rv != SECSuccess) {
5220 goto loser;
5221 }
5222
5223 rv = sslBuffer_Append(&constructed, client_random, SSL3_RANDOM_LENGTH32);
5224 if (rv != SECSuccess) {
5225 goto loser;
5226 }
5227
5228 if (sid->version < SSL_LIBRARY_VERSION_TLS_1_30x0304 && !isEchInner) {
5229 rv = sslBuffer_AppendVariable(&constructed, sid->u.ssl3.sessionID,
5230 sid->u.ssl3.sessionIDLength, 1);
5231 } else if (ss->opt.enableTls13CompatMode && !IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
5232 /* We're faking session resumption, so rather than create new
5233 * randomness, just mix up the client random a little. */
5234 PRUint8 buf[SSL3_SESSIONID_BYTES32];
5235 ssl_MakeFakeSid(ss, buf);
5236 rv = sslBuffer_AppendVariable(&constructed, buf, SSL3_SESSIONID_BYTES32, 1);
5237 } else {
5238 rv = sslBuffer_AppendNumber(&constructed, 0, 1);
5239 }
5240 if (rv != SECSuccess) {
5241 goto loser;
5242 }
5243
5244 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
5245 /* This cookieLen applies to the cookie that appears in the DTLS
5246 * ClientHello, which isn't used in DTLS 1.3. */
5247 rv = sslBuffer_AppendVariable(&constructed, ss->ssl3.hs.cookie.data,
5248 ss->ssl3.hs.helloRetry ? 0 : ss->ssl3.hs.cookie.len,
5249 1);
5250 if (rv != SECSuccess) {
5251 goto loser;
5252 }
5253 }
5254
5255 rv = ssl3_AppendCipherSuites(ss, fallbackSCSV, &constructed);
5256 if (rv != SECSuccess) {
5257 goto loser;
5258 }
5259
5260 /* Compression methods: count is always 1, null compression. */
5261 rv = sslBuffer_AppendNumber(&constructed, 1, 1);
5262 if (rv != SECSuccess) {
5263 goto loser;
5264 }
5265 rv = sslBuffer_AppendNumber(&constructed, ssl_compression_null, 1);
5266 if (rv != SECSuccess) {
5267 goto loser;
5268 }
5269
5270 rv = ssl3_InsertChHeaderSize(ss, &constructed, extensions);
5271 if (rv != SECSuccess) {
5272 goto loser;
5273 }
5274
5275 *preamble = constructed;
5276 return SECSuccess;
5277loser:
5278 sslBuffer_Clear(&constructed);
5279 return SECFailure;
5280}
5281
5282/* Called from ssl3_HandleHelloRequest(),
5283 * ssl3_RedoHandshake()
5284 * ssl_BeginClientHandshake (when resuming ssl3 session)
5285 * dtls_HandleHelloVerifyRequest(with resending=PR_TRUE)
5286 *
5287 * The |type| argument indicates what is going on here:
5288 * - client_hello_initial is set for the very first ClientHello
5289 * - client_hello_retry indicates that this is a second attempt after receiving
5290 * a HelloRetryRequest (in TLS 1.3)
5291 * - client_hello_retransmit is used in DTLS when resending
5292 * - client_hello_renegotiation is used to renegotiate (in TLS <1.3)
5293 */
5294SECStatus
5295ssl3_SendClientHello(sslSocket *ss, sslClientHelloType type)
5296{
5297 sslSessionID *sid;
5298 SECStatus rv;
5299 PRBool isTLS = PR_FALSE0;
5300 PRBool requestingResume = PR_FALSE0;
5301 PRBool unlockNeeded = PR_FALSE0;
5302 sslBuffer extensionBuf = SSL_BUFFER_EMPTY{ ((void*)0), 0, 0, 0 };
5303 PRUint16 version = ss->vrange.max;
5304 PRInt32 flags;
5305 sslBuffer chBuf = SSL_BUFFER_EMPTY{ ((void*)0), 0, 0, 0 };
5306
5307 SSL_TRC(3, ("%d: SSL3[%d]: send %s ClientHello handshake", SSL_GETPID(),if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: send %s ClientHello handshake"
, getpid(), ss->fd, ssl_ClientHelloTypeName(type))
5308 ss->fd, ssl_ClientHelloTypeName(type)))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: send %s ClientHello handshake"
, getpid(), ss->fd, ssl_ClientHelloTypeName(type))
;
5309
5310 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",5310))
;
5311 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->xmitBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveXmitBufLock(ss)"
,"ssl3con.c",5311))
;
5312
5313 /* shouldn't get here if SSL3 is disabled, but ... */
5314 if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)((&ss->vrange)->min == 0)) {
5315 PR_NOT_REACHED("No versions of SSL 3.0 or later are enabled")PR_Assert("No versions of SSL 3.0 or later are enabled","ssl3con.c"
,5315)
;
5316 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_SSL_DISABLED);
5317 return SECFailure;
5318 }
5319
5320 /* If we are responding to a HelloRetryRequest, don't reinitialize. We need
5321 * to maintain the handshake hashes. */
5322 if (!ss->ssl3.hs.helloRetry) {
5323 ssl3_RestartHandshakeHashes(ss);
5324 }
5325 PORT_Assert(!ss->ssl3.hs.helloRetry || type == client_hello_retry)((!ss->ssl3.hs.helloRetry || type == client_hello_retry)?(
(void)0):PR_Assert("!ss->ssl3.hs.helloRetry || type == client_hello_retry"
,"ssl3con.c",5325))
;
5326
5327 if (type == client_hello_initial) {
5328 ssl_SetClientHelloSpecVersion(ss, ss->ssl3.cwSpec);
5329 }
5330 /* These must be reset every handshake. */
5331 ssl3_ResetExtensionData(&ss->xtnData, ss);
5332 ss->ssl3.hs.sendingSCSV = PR_FALSE0;
5333 ss->ssl3.hs.preliminaryInfo = 0;
5334 PORT_Assert(IS_DTLS(ss) || type != client_hello_retransmit)(((ss->protocolVariant == ssl_variant_datagram) || type !=
client_hello_retransmit)?((void)0):PR_Assert("IS_DTLS(ss) || type != client_hello_retransmit"
,"ssl3con.c",5334))
;
5335 SECITEM_FreeItemSECITEM_FreeItem_Util(&ss->ssl3.hs.newSessionTicket.ticket, PR_FALSE0);
5336 ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE0;
5337
5338 /* How many suites does our PKCS11 support (regardless of policy)? */
5339 if (ssl3_config_match_init(ss) == 0) {
5340 return SECFailure; /* ssl3_config_match_init has set error code. */
5341 }
5342
5343 /*
5344 * During a renegotiation, ss->clientHelloVersion will be used again to
5345 * work around a Windows SChannel bug. Ensure that it is still enabled.
5346 */
5347 if (ss->firstHsDone) {
5348 PORT_Assert(type != client_hello_initial)((type != client_hello_initial)?((void)0):PR_Assert("type != client_hello_initial"
,"ssl3con.c",5348))
;
5349 if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)((&ss->vrange)->min == 0)) {
5350 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_SSL_DISABLED);
5351 return SECFailure;
5352 }
5353
5354 if (ss->clientHelloVersion < ss->vrange.min ||
5355 ss->clientHelloVersion > ss->vrange.max) {
5356 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_NO_CYPHER_OVERLAP);
5357 return SECFailure;
5358 }
5359 }
5360
5361 /* Check if we have a ss->sec.ci.sid.
5362 * Check that it's not expired.
5363 * If we have an sid and it comes from an external cache, we use it. */
5364 if (ss->sec.ci.sid && ss->sec.ci.sid->cached == in_external_cache) {
5365 PORT_Assert(!ss->sec.isServer)((!ss->sec.isServer)?((void)0):PR_Assert("!ss->sec.isServer"
,"ssl3con.c",5365))
;
5366 sid = ssl_ReferenceSID(ss->sec.ci.sid);
5367 SSL_TRC(3, ("%d: SSL3[%d]: using external resumption token in ClientHello",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: using external resumption token in ClientHello"
, getpid(), ss->fd)
5368 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: using external resumption token in ClientHello"
, getpid(), ss->fd)
;
5369 } else if (ss->sec.ci.sid && ss->statelessResume && type == client_hello_retry) {
5370 /* If we are sending a second ClientHello, reuse the same SID
5371 * as the original one. */
5372 sid = ssl_ReferenceSID(ss->sec.ci.sid);
5373 } else if (!ss->opt.noCache) {
5374 /* We ignore ss->sec.ci.sid here, and use ssl_Lookup because Lookup
5375 * handles expired entries and other details.
5376 * XXX If we've been called from ssl_BeginClientHandshake, then
5377 * this lookup is duplicative and wasteful.
5378 */
5379 sid = ssl_LookupSID(ssl_Time(ss), &ss->sec.ci.peer,
5380 ss->sec.ci.port, ss->peerID, ss->url);
5381 } else {
5382 sid = NULL((void*)0);
5383 }
5384
5385 /* We can't resume based on a different token. If the sid exists,
5386 * make sure the token that holds the master secret still exists ...
5387 * If we previously did client-auth, make sure that the token that holds
5388 * the private key still exists, is logged in, hasn't been removed, etc.
5389 */
5390 if (sid) {
5391 PRBool sidOK = PR_TRUE1;
5392
5393 if (sid->version >= SSL_LIBRARY_VERSION_TLS_1_30x0304) {
5394 if (!tls13_ResumptionCompatible(ss, sid->u.ssl3.cipherSuite)) {
5395 sidOK = PR_FALSE0;
5396 }
5397 } else {
5398 /* Check that the cipher suite we need is enabled. */
5399 const ssl3CipherSuiteCfg *suite =
5400 ssl_LookupCipherSuiteCfg(sid->u.ssl3.cipherSuite,
5401 ss->cipherSuites);
5402 SSLVersionRange vrange = { sid->version, sid->version };
5403 if (!suite || !ssl3_config_match(suite, ss->ssl3.policy, &vrange, ss)) {
5404 sidOK = PR_FALSE0;
5405 }
5406
5407 /* Check that no (valid) ECHConfigs are setup in combination with a
5408 * (resumable) TLS < 1.3 session id. */
5409 if (!PR_CLIST_IS_EMPTY(&ss->echConfigs)((&ss->echConfigs)->next == (&ss->echConfigs
))
) {
5410 /* If there are ECH configs, the client must not resume but
5411 * offer ECH. */
5412 sidOK = PR_FALSE0;
5413 }
5414 }
5415
5416 /* Check that we can recover the master secret. */
5417 if (sidOK) {
5418 PK11SlotInfo *slot = NULL((void*)0);
5419 if (sid->u.ssl3.masterValid) {
5420 slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
5421 sid->u.ssl3.masterSlotID);
5422 }
5423 if (slot == NULL((void*)0)) {
5424 sidOK = PR_FALSE0;
5425 } else {
5426 PK11SymKey *wrapKey = NULL((void*)0);
5427 if (!PK11_IsPresent(slot) ||
5428 ((wrapKey = PK11_GetWrapKey(slot,
5429 sid->u.ssl3.masterWrapIndex,
5430 sid->u.ssl3.masterWrapMech,
5431 sid->u.ssl3.masterWrapSeries,
5432 ss->pkcs11PinArg)) == NULL((void*)0))) {
5433 sidOK = PR_FALSE0;
5434 }
5435 if (wrapKey)
5436 PK11_FreeSymKey(wrapKey);
5437 PK11_FreeSlot(slot);
5438 slot = NULL((void*)0);
5439 }
5440 }
5441 /* If we previously did client-auth, make sure that the token that
5442 ** holds the private key still exists, is logged in, hasn't been
5443 ** removed, etc.
5444 */
5445 if (sidOK && !ssl3_ClientAuthTokenPresent(sid)) {
5446 sidOK = PR_FALSE0;
5447 }
5448
5449 if (sidOK) {
5450 /* Set version based on the sid. */
5451 if (ss->firstHsDone) {
5452 /*
5453 * Windows SChannel compares the client_version inside the RSA
5454 * EncryptedPreMasterSecret of a renegotiation with the
5455 * client_version of the initial ClientHello rather than the
5456 * ClientHello in the renegotiation. To work around this bug, we
5457 * continue to use the client_version used in the initial
5458 * ClientHello when renegotiating.
5459 *
5460 * The client_version of the initial ClientHello is still
5461 * available in ss->clientHelloVersion. Ensure that
5462 * sid->version is bounded within
5463 * [ss->vrange.min, ss->clientHelloVersion], otherwise we
5464 * can't use sid.
5465 */
5466 if (sid->version >= ss->vrange.min &&
5467 sid->version <= ss->clientHelloVersion) {
5468 version = ss->clientHelloVersion;
5469 } else {
5470 sidOK = PR_FALSE0;
5471 }
5472 } else {
5473 /*
5474 * Check sid->version is OK first.
5475 * Previously, we would cap the version based on sid->version,
5476 * but that prevents negotiation of a higher version if the
5477 * previous session was reduced (e.g., with version fallback)
5478 */
5479 if (sid->version < ss->vrange.min ||
5480 sid->version > ss->vrange.max) {
5481 sidOK = PR_FALSE0;
5482 }
5483 }
5484 }
5485
5486 if (!sidOK) {
5487 SSL_AtomicIncrementLong(&ssl3stats.sch_sid_cache_not_ok);
5488 ssl_UncacheSessionID(ss);
5489 ssl_FreeSID(sid);
5490 sid = NULL((void*)0);
5491 }
5492 }
5493
5494 if (sid) {
5495 requestingResume = PR_TRUE1;
5496 SSL_AtomicIncrementLong(&ssl3stats.sch_sid_cache_hits);
5497
5498 PRINT_BUF(4, (ss, "client, found session-id:", sid->u.ssl3.sessionID,if (ssl_trace >= (4)) ssl_PrintBuf (ss, "client, found session-id:"
, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength)
5499 sid->u.ssl3.sessionIDLength))if (ssl_trace >= (4)) ssl_PrintBuf (ss, "client, found session-id:"
, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength)
;
5500
5501 ss->ssl3.policy = sid->u.ssl3.policy;
5502 } else {
5503 SSL_AtomicIncrementLong(&ssl3stats.sch_sid_cache_misses);
5504
5505 /*
5506 * Windows SChannel compares the client_version inside the RSA
5507 * EncryptedPreMasterSecret of a renegotiation with the
5508 * client_version of the initial ClientHello rather than the
5509 * ClientHello in the renegotiation. To work around this bug, we
5510 * continue to use the client_version used in the initial
5511 * ClientHello when renegotiating.
5512 */
5513 if (ss->firstHsDone) {
5514 version = ss->clientHelloVersion;
5515 }
5516
5517 sid = ssl3_NewSessionID(ss, PR_FALSE0);
5518 if (!sid) {
5519 return SECFailure; /* memory error is set */
5520 }
5521 /* ss->version isn't set yet, but the sid needs a sane value. */
5522 sid->version = version;
5523 }
5524
5525 isTLS = (version > SSL_LIBRARY_VERSION_3_00x0300);
5526 ssl_GetSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_LockWrite_Util((ss)->
specLock); }
;
5527 if (ss->ssl3.cwSpec->macDef->mac == ssl_mac_null) {
5528 /* SSL records are not being MACed. */
5529 ss->ssl3.cwSpec->version = version;
5530 }
5531 ssl_ReleaseSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockWrite_Util((ss)->
specLock); }
;
5532
5533 ssl_FreeSID(ss->sec.ci.sid); /* release the old sid */
5534 ss->sec.ci.sid = sid;
5535
5536 /* HACK for SCSV in SSL 3.0. On initial handshake, prepend SCSV,
5537 * only if TLS is disabled.
5538 */
5539 if (!ss->firstHsDone && !isTLS) {
5540 /* Must set this before calling Hello Extension Senders,
5541 * to suppress sending of empty RI extension.
5542 */
5543 ss->ssl3.hs.sendingSCSV = PR_TRUE1;
5544 }
5545
5546 /* When we attempt session resumption (only), we must lock the sid to
5547 * prevent races with other resumption connections that receive a
5548 * NewSessionTicket that will cause the ticket in the sid to be replaced.
5549 * Once we've copied the session ticket into our ClientHello message, it
5550 * is OK for the ticket to change, so we just need to make sure we hold
5551 * the lock across the calls to ssl_ConstructExtensions.
5552 */
5553 if (sid->u.ssl3.lock) {
5554 unlockNeeded = PR_TRUE1;
5555 PR_RWLock_Rlock(sid->u.ssl3.lock);
5556 }
5557
5558 /* Generate a new random if this is the first attempt or renegotiation. */
5559 if (type == client_hello_initial ||
5560 type == client_hello_renegotiation) {
5561 rv = ssl3_GetNewRandom(ss->ssl3.hs.client_random);
5562 if (rv != SECSuccess) {
5563 goto loser; /* err set by GetNewRandom. */
5564 }
5565 }
5566
5567 if (ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_30x0304) {
5568 rv = tls13_SetupClientHello(ss, type);
5569 if (rv != SECSuccess) {
5570 goto loser;
5571 }
5572 }
5573
5574 /* Setup TLS ClientHello Extension Permutation? */
5575 if (type == client_hello_initial &&
5576 ss->vrange.max > SSL_LIBRARY_VERSION_3_00x0300 &&
5577 ss->opt.enableChXtnPermutation) {
5578 rv = tls_ClientHelloExtensionPermutationSetup(ss);
5579 if (rv != SECSuccess) {
5580 goto loser;
5581 }
5582 }
5583
5584 if (isTLS || (ss->firstHsDone && ss->peerRequestedProtection)) {
5585 rv = ssl_ConstructExtensions(ss, &extensionBuf, ssl_hs_client_hello);
5586 if (rv != SECSuccess) {
5587 goto loser;
5588 }
5589 }
5590
5591 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
5592 ssl3_DisableNonDTLSSuites(ss);
5593 }
5594
5595 rv = ssl3_CreateClientHelloPreamble(ss, sid, requestingResume, version,
5596 PR_FALSE0, &extensionBuf, &chBuf);
5597 if (rv != SECSuccess) {
5598 goto loser; /* err set by ssl3_CreateClientHelloPreamble. */
5599 }
5600
5601 if (!ss->ssl3.hs.echHpkeCtx) {
5602 if (extensionBuf.len) {
5603 rv = tls13_MaybeGreaseEch(ss, &chBuf, &extensionBuf);
5604 if (rv != SECSuccess) {
5605 goto loser; /* err set by tls13_MaybeGreaseEch. */
5606 }
5607 rv = ssl_InsertPaddingExtension(ss, chBuf.len, &extensionBuf);
5608 if (rv != SECSuccess) {
5609 goto loser; /* err set by ssl_InsertPaddingExtension. */
5610 }
5611
5612 rv = ssl3_InsertChHeaderSize(ss, &chBuf, &extensionBuf);
5613 if (rv != SECSuccess) {
5614 goto loser; /* err set by ssl3_InsertChHeaderSize. */
5615 }
5616
5617 /* If we are sending a PSK binder, replace the dummy value. */
5618 if (ssl3_ExtensionAdvertised(ss, ssl_tls13_pre_shared_key_xtn)) {
5619 rv = tls13_WriteExtensionsWithBinder(ss, &extensionBuf, &chBuf);
5620 } else {
5621 rv = sslBuffer_AppendNumber(&chBuf, extensionBuf.len, 2);
5622 if (rv != SECSuccess) {
5623 goto loser;
5624 }
5625 rv = sslBuffer_AppendBuffer(&chBuf, &extensionBuf);
5626 }
5627 if (rv != SECSuccess) {
5628 goto loser; /* err set by sslBuffer_Append*. */
5629 }
5630 }
5631
5632 /* If we already have a message in place, we need to enqueue it.
5633 * This empties the buffer. This is a convenient place to call
5634 * dtls_StageHandshakeMessage to mark the message boundary. */
5635 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
5636 rv = dtls_StageHandshakeMessage(ss);
5637 if (rv != SECSuccess) {
5638 goto loser;
5639 }
5640 }
5641
5642 /* As here the function takes the full message and hashes it in one go,
5643 * For DTLS1.3, we skip hashing the unnecessary header fields.
5644 * See ssl3_AppendHandshakeHeader. */
5645 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram) && ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_30x0304) {
5646 rv = ssl3_AppendHandshakeSuppressHash(ss, chBuf.buf, chBuf.len);
5647 if (rv != SECSuccess) {
5648 goto loser; /* code set */
5649 }
5650 if (!ss->firstHsDone) {
5651 PORT_Assert(ss->ssl3.hs.dtls13ClientMessageBuffer.len == 0)((ss->ssl3.hs.dtls13ClientMessageBuffer.len == 0)?((void)0
):PR_Assert("ss->ssl3.hs.dtls13ClientMessageBuffer.len == 0"
,"ssl3con.c",5651))
;
5652 sslBuffer_Clear(&ss->ssl3.hs.dtls13ClientMessageBuffer);
5653 /* Here instead of computing the hash, we copy the data to a buffer.*/
5654 rv = sslBuffer_Append(&ss->ssl3.hs.dtls13ClientMessageBuffer, chBuf.buf, chBuf.len);
5655 }
5656 } else {
5657 rv = ssl3_AppendHandshake(ss, chBuf.buf, chBuf.len);
5658 }
5659
5660 } else {
5661 PORT_Assert(!IS_DTLS(ss))((!(ss->protocolVariant == ssl_variant_datagram))?((void)0
):PR_Assert("!IS_DTLS(ss)","ssl3con.c",5661))
;
5662 rv = tls13_ConstructClientHelloWithEch(ss, sid, !requestingResume, &chBuf, &extensionBuf);
5663 if (rv != SECSuccess) {
5664 goto loser; /* code set */
5665 }
5666 rv = ssl3_UpdateDefaultHandshakeHashes(ss, chBuf.buf, chBuf.len);
5667 if (rv != SECSuccess) {
5668 goto loser; /* code set */
5669 }
5670
5671 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
5672 rv = dtls_StageHandshakeMessage(ss);
5673 if (rv != SECSuccess) {
5674 goto loser;
5675 }
5676 }
5677 /* By default, all messagess are added to both the inner and
5678 * outer transcripts. For CH (or CH2 if HRR), that's problematic. */
5679 rv = ssl3_AppendHandshakeSuppressHash(ss, chBuf.buf, chBuf.len);
5680 }
5681 if (rv != SECSuccess) {
5682 goto loser;
5683 }
5684
5685 if (unlockNeeded) {
5686 /* Note: goto loser can't be used past this point. */
5687 PR_RWLock_Unlock(sid->u.ssl3.lock);
5688 }
5689
5690 if (ss->xtnData.sentSessionTicketInClientHello) {
5691 SSL_AtomicIncrementLong(&ssl3stats.sch_sid_stateless_resumes);
5692 }
5693
5694 if (ss->ssl3.hs.sendingSCSV) {
5695 /* Since we sent the SCSV, pretend we sent empty RI extension. */
5696 TLSExtensionData *xtnData = &ss->xtnData;
5697 xtnData->advertised[xtnData->numAdvertised++] =
5698 ssl_renegotiation_info_xtn;
5699 }
5700
5701 flags = 0;
5702 rv = ssl3_FlushHandshake(ss, flags);
5703 if (rv != SECSuccess) {
5704 return rv; /* error code set by ssl3_FlushHandshake */
5705 }
5706
5707 if (version >= SSL_LIBRARY_VERSION_TLS_1_30x0304) {
5708 rv = tls13_MaybeDo0RTTHandshake(ss);
5709 if (rv != SECSuccess) {
5710 return SECFailure; /* error code set already. */
5711 }
5712 }
5713
5714 ss->ssl3.hs.ws = wait_server_hello;
5715 sslBuffer_Clear(&chBuf);
5716 sslBuffer_Clear(&extensionBuf);
5717 return SECSuccess;
5718
5719loser:
5720 if (unlockNeeded) {
5721 PR_RWLock_Unlock(sid->u.ssl3.lock);
5722 }
5723 sslBuffer_Clear(&chBuf);
5724 sslBuffer_Clear(&extensionBuf);
5725 return SECFailure;
5726}
5727
5728/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered a
5729 * complete ssl3 Hello Request.
5730 * Caller must hold Handshake and RecvBuf locks.
5731 */
5732static SECStatus
5733ssl3_HandleHelloRequest(sslSocket *ss)
5734{
5735 sslSessionID *sid = ss->sec.ci.sid;
5736 SECStatus rv;
5737
5738 SSL_TRC(3, ("%d: SSL3[%d]: handle hello_request handshake",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: handle hello_request handshake"
, getpid(), ss->fd)
5739 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: handle hello_request handshake"
, getpid(), ss->fd)
;
5740
5741 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->recvBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveRecvBufLock(ss)"
,"ssl3con.c",5741))
;
5742 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",5742))
;
5743 PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3)((ss->version < 0x0304)?((void)0):PR_Assert("ss->version < SSL_LIBRARY_VERSION_TLS_1_3"
,"ssl3con.c",5743))
;
5744
5745 if (ss->ssl3.hs.ws == wait_server_hello)
5746 return SECSuccess;
5747 if (ss->ssl3.hs.ws != idle_handshake || ss->sec.isServer) {
5748 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
5749 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST);
5750 return SECFailure;
5751 }
5752 if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER((PRBool)0)) {
5753 (void)SSL3_SendAlert(ss, alert_warning, no_renegotiation);
5754 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
5755 return SECFailure;
5756 }
5757
5758 if (sid) {
5759 ssl_UncacheSessionID(ss);
5760 ssl_FreeSID(sid);
5761 ss->sec.ci.sid = NULL((void*)0);
5762 }
5763
5764 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
5765 dtls_RehandshakeCleanup(ss);
5766 }
5767
5768 ssl_GetXmitBufLock(ss){ if (!ss->opt.noLocks) PR_EnterMonitor(((ss)->xmitBufLock
)); }
;
5769 rv = ssl3_SendClientHello(ss, client_hello_renegotiation);
5770 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
;
5771
5772 return rv;
5773}
5774
5775static const CK_MECHANISM_TYPE wrapMechanismList[SSL_NUM_WRAP_MECHS15] = {
5776 CKM_DES3_ECB0x00000132UL,
5777 CKM_CAST5_ECB0x00000321UL,
5778 CKM_DES_ECB0x00000121UL,
5779 CKM_KEY_WRAP_LYNKS0x00000400UL,
5780 CKM_IDEA_ECB0x00000341UL,
5781 CKM_CAST3_ECB0x00000311UL,
5782 CKM_CAST_ECB0x00000301UL,
5783 CKM_RC5_ECB0x00000331UL,
5784 CKM_RC2_ECB0x00000101UL,
5785 CKM_CDMF_ECB0x00000141UL,
5786 CKM_SKIPJACK_WRAP0x00001008UL,
5787 CKM_SKIPJACK_CBC640x00001002UL,
5788 CKM_AES_ECB0x00001081UL,
5789 CKM_CAMELLIA_ECB0x00000551UL,
5790 CKM_SEED_ECB0x00000651UL
5791};
5792
5793static SECStatus
5794ssl_FindIndexByWrapMechanism(CK_MECHANISM_TYPE mech, unsigned int *wrapMechIndex)
5795{
5796 unsigned int i;
5797 for (i = 0; i < SSL_NUM_WRAP_MECHS15; ++i) {
5798 if (wrapMechanismList[i] == mech) {
5799 *wrapMechIndex = i;
5800 return SECSuccess;
5801 }
5802 }
5803 PORT_Assert(0)((0)?((void)0):PR_Assert("0","ssl3con.c",5803));
5804 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
5805 return SECFailure;
5806}
5807
5808/* Each process sharing the server session ID cache has its own array of SymKey
5809 * pointers for the symmetric wrapping keys that are used to wrap the master
5810 * secrets. There is one key for each authentication type. These Symkeys
5811 * correspond to the wrapped SymKeys kept in the server session cache.
5812 */
5813const SSLAuthType ssl_wrap_key_auth_type[SSL_NUM_WRAP_KEYS6] = {
5814 ssl_auth_rsa_decrypt,
5815 ssl_auth_rsa_sign,
5816 ssl_auth_rsa_pss,
5817 ssl_auth_ecdsa,
5818 ssl_auth_ecdh_rsa,
5819 ssl_auth_ecdh_ecdsa
5820};
5821
5822static SECStatus
5823ssl_FindIndexByWrapKey(const sslServerCert *serverCert, unsigned int *wrapKeyIndex)
5824{
5825 unsigned int i;
5826 for (i = 0; i < SSL_NUM_WRAP_KEYS6; ++i) {
5827 if (SSL_CERT_IS(serverCert, ssl_wrap_key_auth_type[i])((serverCert)->authTypes & (1 << (ssl_wrap_key_auth_type
[i])))
) {
5828 *wrapKeyIndex = i;
5829 return SECSuccess;
5830 }
5831 }
5832 /* Can't assert here because we still get people using DSA certificates. */
5833 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
5834 return SECFailure;
5835}
5836
5837static PK11SymKey *
5838ssl_UnwrapSymWrappingKey(
5839 SSLWrappedSymWrappingKey *pWswk,
5840 SECKEYPrivateKey *svrPrivKey,
5841 unsigned int wrapKeyIndex,
5842 CK_MECHANISM_TYPE masterWrapMech,
5843 void *pwArg)
5844{
5845 PK11SymKey *unwrappedWrappingKey = NULL((void*)0);
5846 SECItem wrappedKey;
5847 PK11SymKey *Ks;
5848 SECKEYPublicKey pubWrapKey;
5849 ECCWrappedKeyInfo *ecWrapped;
5850
5851 /* found the wrapping key on disk. */
5852 PORT_Assert(pWswk->symWrapMechanism == masterWrapMech)((pWswk->symWrapMechanism == masterWrapMech)?((void)0):PR_Assert
("pWswk->symWrapMechanism == masterWrapMech","ssl3con.c",5852
))
;
5853 PORT_Assert(pWswk->wrapKeyIndex == wrapKeyIndex)((pWswk->wrapKeyIndex == wrapKeyIndex)?((void)0):PR_Assert
("pWswk->wrapKeyIndex == wrapKeyIndex","ssl3con.c",5853))
;
5854 if (pWswk->symWrapMechanism != masterWrapMech ||
5855 pWswk->wrapKeyIndex != wrapKeyIndex) {
5856 goto loser;
5857 }
5858 wrappedKey.type = siBuffer;
5859 wrappedKey.data = pWswk->wrappedSymmetricWrappingkey;
5860 wrappedKey.len = pWswk->wrappedSymKeyLen;
5861 PORT_Assert(wrappedKey.len <= sizeof pWswk->wrappedSymmetricWrappingkey)((wrappedKey.len <= sizeof pWswk->wrappedSymmetricWrappingkey
)?((void)0):PR_Assert("wrappedKey.len <= sizeof pWswk->wrappedSymmetricWrappingkey"
,"ssl3con.c",5861))
;
5862
5863 switch (ssl_wrap_key_auth_type[wrapKeyIndex]) {
5864
5865 case ssl_auth_rsa_decrypt:
5866 case ssl_auth_rsa_sign: /* bad: see Bug 1248320 */
5867 unwrappedWrappingKey =
5868 PK11_PubUnwrapSymKey(svrPrivKey, &wrappedKey,
5869 masterWrapMech, CKA_UNWRAP0x00000107UL, 0);
5870 break;
5871
5872 case ssl_auth_ecdsa:
5873 case ssl_auth_ecdh_rsa:
5874 case ssl_auth_ecdh_ecdsa:
5875 /*
5876 * For ssl_auth_ecd*, we first create an EC public key based on
5877 * data stored with the wrappedSymmetricWrappingkey. Next,
5878 * we do an ECDH computation involving this public key and
5879 * the SSL server's (long-term) EC private key. The resulting
5880 * shared secret is treated the same way as Fortezza's Ks, i.e.,
5881 * it is used to recover the symmetric wrapping key.
5882 *
5883 * The data in wrappedSymmetricWrappingkey is laid out as defined
5884 * in the ECCWrappedKeyInfo structure.
5885 */
5886 ecWrapped = (ECCWrappedKeyInfo *)pWswk->wrappedSymmetricWrappingkey;
5887
5888 PORT_Assert(ecWrapped->encodedParamLen + ecWrapped->pubValueLen +((ecWrapped->encodedParamLen + ecWrapped->pubValueLen +
ecWrapped->wrappedKeyLen <= 504)?((void)0):PR_Assert("ecWrapped->encodedParamLen + ecWrapped->pubValueLen + ecWrapped->wrappedKeyLen <= MAX_EC_WRAPPED_KEY_BUFLEN"
,"ssl3con.c",5890))
5889 ecWrapped->wrappedKeyLen <=((ecWrapped->encodedParamLen + ecWrapped->pubValueLen +
ecWrapped->wrappedKeyLen <= 504)?((void)0):PR_Assert("ecWrapped->encodedParamLen + ecWrapped->pubValueLen + ecWrapped->wrappedKeyLen <= MAX_EC_WRAPPED_KEY_BUFLEN"
,"ssl3con.c",5890))
5890 MAX_EC_WRAPPED_KEY_BUFLEN)((ecWrapped->encodedParamLen + ecWrapped->pubValueLen +
ecWrapped->wrappedKeyLen <= 504)?((void)0):PR_Assert("ecWrapped->encodedParamLen + ecWrapped->pubValueLen + ecWrapped->wrappedKeyLen <= MAX_EC_WRAPPED_KEY_BUFLEN"
,"ssl3con.c",5890))
;
5891
5892 if (ecWrapped->encodedParamLen + ecWrapped->pubValueLen +
5893 ecWrapped->wrappedKeyLen >
5894 MAX_EC_WRAPPED_KEY_BUFLEN504) {
5895 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
5896 goto loser;
5897 }
5898
5899 pubWrapKey.keyType = ecKey;
5900 pubWrapKey.u.ec.size = ecWrapped->size;
5901 pubWrapKey.u.ec.DEREncodedParams.len = ecWrapped->encodedParamLen;
5902 pubWrapKey.u.ec.DEREncodedParams.data = ecWrapped->var;
5903 pubWrapKey.u.ec.publicValue.len = ecWrapped->pubValueLen;
5904 pubWrapKey.u.ec.publicValue.data = ecWrapped->var +
5905 ecWrapped->encodedParamLen;
5906
5907 wrappedKey.len = ecWrapped->wrappedKeyLen;
5908 wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen +
5909 ecWrapped->pubValueLen;
5910
5911 /* Derive Ks using ECDH */
5912 Ks = PK11_PubDeriveWithKDF(svrPrivKey, &pubWrapKey, PR_FALSE0, NULL((void*)0),
5913 NULL((void*)0), CKM_ECDH1_DERIVE0x00001050UL, masterWrapMech,
5914 CKA_DERIVE0x0000010CUL, 0, CKD_NULL0x00000001UL, NULL((void*)0), NULL((void*)0));
5915 if (Ks == NULL((void*)0)) {
5916 goto loser;
5917 }
5918
5919 /* Use Ks to unwrap the wrapping key */
5920 unwrappedWrappingKey = PK11_UnwrapSymKey(Ks, masterWrapMech, NULL((void*)0),
5921 &wrappedKey, masterWrapMech,
5922 CKA_UNWRAP0x00000107UL, 0);
5923 PK11_FreeSymKey(Ks);
5924
5925 break;
5926
5927 default:
5928 PORT_Assert(0)((0)?((void)0):PR_Assert("0","ssl3con.c",5928));
5929 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
5930 goto loser;
5931 }
5932loser:
5933 return unwrappedWrappingKey;
5934}
5935
5936typedef struct {
5937 PK11SymKey *symWrapKey[SSL_NUM_WRAP_KEYS6];
5938} ssl3SymWrapKey;
5939
5940static PZLockPRLock *symWrapKeysLock = NULL((void*)0);
5941static ssl3SymWrapKey symWrapKeys[SSL_NUM_WRAP_MECHS15];
5942
5943SECStatus
5944ssl_FreeSymWrapKeysLock(void)
5945{
5946 if (symWrapKeysLock) {
5947 PZ_DestroyLock(symWrapKeysLock)PR_DestroyLock((symWrapKeysLock));
5948 symWrapKeysLock = NULL((void*)0);
5949 return SECSuccess;
5950 }
5951 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_NOT_INITIALIZED);
5952 return SECFailure;
5953}
5954
5955SECStatus
5956SSL3_ShutdownServerCache(void)
5957{
5958 int i, j;
5959
5960 if (!symWrapKeysLock)
5961 return SECSuccess; /* lock was never initialized */
5962 PZ_Lock(symWrapKeysLock)PR_Lock((symWrapKeysLock));
5963 /* get rid of all symWrapKeys */
5964 for (i = 0; i < SSL_NUM_WRAP_MECHS15; ++i) {
5965 for (j = 0; j < SSL_NUM_WRAP_KEYS6; ++j) {
5966 PK11SymKey **pSymWrapKey;
5967 pSymWrapKey = &symWrapKeys[i].symWrapKey[j];
5968 if (*pSymWrapKey) {
5969 PK11_FreeSymKey(*pSymWrapKey);
5970 *pSymWrapKey = NULL((void*)0);
5971 }
5972 }
5973 }
5974
5975 PZ_Unlock(symWrapKeysLock)PR_Unlock((symWrapKeysLock));
5976 ssl_FreeSessionCacheLocks();
5977 return SECSuccess;
5978}
5979
5980SECStatus
5981ssl_InitSymWrapKeysLock(void)
5982{
5983 symWrapKeysLock = PZ_NewLock(nssILockOther)PR_NewLock();
5984 return symWrapKeysLock ? SECSuccess : SECFailure;
5985}
5986
5987/* Try to get wrapping key for mechanism from in-memory array.
5988 * If that fails, look for one on disk.
5989 * If that fails, generate a new one, put the new one on disk,
5990 * Put the new key in the in-memory array.
5991 *
5992 * Note that this function performs some fairly inadvisable functions with
5993 * certificate private keys. ECDSA keys are used with ECDH; similarly, RSA
5994 * signing keys are used to encrypt. Bug 1248320.
5995 */
5996PK11SymKey *
5997ssl3_GetWrappingKey(sslSocket *ss,
5998 PK11SlotInfo *masterSecretSlot,
5999 CK_MECHANISM_TYPE masterWrapMech,
6000 void *pwArg)
6001{
6002 SSLAuthType authType;
6003 SECKEYPrivateKey *svrPrivKey;
6004 SECKEYPublicKey *svrPubKey = NULL((void*)0);
6005 PK11SymKey *unwrappedWrappingKey = NULL((void*)0);
6006 PK11SymKey **pSymWrapKey;
6007 CK_MECHANISM_TYPE asymWrapMechanism = CKM_INVALID_MECHANISM0xffffffffUL;
6008 int length;
6009 unsigned int wrapMechIndex;
6010 unsigned int wrapKeyIndex;
6011 SECStatus rv;
6012 SECItem wrappedKey;
6013 SSLWrappedSymWrappingKey wswk;
6014 PK11SymKey *Ks = NULL((void*)0);
6015 SECKEYPublicKey *pubWrapKey = NULL((void*)0);
6016 SECKEYPrivateKey *privWrapKey = NULL((void*)0);
6017 ECCWrappedKeyInfo *ecWrapped;
6018 const sslServerCert *serverCert = ss->sec.serverCert;
6019
6020 PORT_Assert(serverCert)((serverCert)?((void)0):PR_Assert("serverCert","ssl3con.c",6020
))
;
6021 PORT_Assert(serverCert->serverKeyPair)((serverCert->serverKeyPair)?((void)0):PR_Assert("serverCert->serverKeyPair"
,"ssl3con.c",6021))
;
6022 PORT_Assert(serverCert->serverKeyPair->privKey)((serverCert->serverKeyPair->privKey)?((void)0):PR_Assert
("serverCert->serverKeyPair->privKey","ssl3con.c",6022)
)
;
6023 PORT_Assert(serverCert->serverKeyPair->pubKey)((serverCert->serverKeyPair->pubKey)?((void)0):PR_Assert
("serverCert->serverKeyPair->pubKey","ssl3con.c",6023))
;
6024 if (!serverCert || !serverCert->serverKeyPair ||
6025 !serverCert->serverKeyPair->privKey ||
6026 !serverCert->serverKeyPair->pubKey) {
6027 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
6028 return NULL((void*)0); /* hmm */
6029 }
6030
6031 rv = ssl_FindIndexByWrapKey(serverCert, &wrapKeyIndex);
6032 if (rv != SECSuccess)
6033 return NULL((void*)0); /* unusable wrapping key. */
6034
6035 rv = ssl_FindIndexByWrapMechanism(masterWrapMech, &wrapMechIndex);
6036 if (rv != SECSuccess)
6037 return NULL((void*)0); /* invalid masterWrapMech. */
6038
6039 authType = ssl_wrap_key_auth_type[wrapKeyIndex];
6040 svrPrivKey = serverCert->serverKeyPair->privKey;
6041 pSymWrapKey = &symWrapKeys[wrapMechIndex].symWrapKey[wrapKeyIndex];
6042
6043 ssl_InitSessionCacheLocks(PR_TRUE1);
6044
6045 PZ_Lock(symWrapKeysLock)PR_Lock((symWrapKeysLock));
6046
6047 unwrappedWrappingKey = *pSymWrapKey;
6048 if (unwrappedWrappingKey != NULL((void*)0)) {
6049 if (PK11_VerifyKeyOK(unwrappedWrappingKey)) {
6050 unwrappedWrappingKey = PK11_ReferenceSymKey(unwrappedWrappingKey);
6051 goto done;
6052 }
6053 /* slot series has changed, so this key is no good any more. */
6054 PK11_FreeSymKey(unwrappedWrappingKey);
6055 *pSymWrapKey = unwrappedWrappingKey = NULL((void*)0);
6056 }
6057
6058 /* Try to get wrapped SymWrapping key out of the (disk) cache. */
6059 /* Following call fills in wswk on success. */
6060 rv = ssl_GetWrappingKey(wrapMechIndex, wrapKeyIndex, &wswk);
6061 if (rv == SECSuccess) {
6062 /* found the wrapped sym wrapping key on disk. */
6063 unwrappedWrappingKey =
6064 ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, wrapKeyIndex,
6065 masterWrapMech, pwArg);
6066 if (unwrappedWrappingKey) {
6067 goto install;
6068 }
6069 }
6070
6071 if (!masterSecretSlot) /* caller doesn't want to create a new one. */
6072 goto loser;
6073
6074 length = PK11_GetBestKeyLength(masterSecretSlot, masterWrapMech);
6075 /* Zero length means fixed key length algorithm, or error.
6076 * It's ambiguous.
6077 */
6078 unwrappedWrappingKey = PK11_KeyGen(masterSecretSlot, masterWrapMech, NULL((void*)0),
6079 length, pwArg);
6080 if (!unwrappedWrappingKey) {
6081 goto loser;
6082 }
6083
6084 /* Prepare the buffer to receive the wrappedWrappingKey,
6085 * the symmetric wrapping key wrapped using the server's pub key.
6086 */
6087 PORT_Memsetmemset(&wswk, 0, sizeof wswk); /* eliminate UMRs. */
6088
6089 svrPubKey = serverCert->serverKeyPair->pubKey;
6090 wrappedKey.type = siBuffer;
6091 wrappedKey.len = SECKEY_PublicKeyStrength(svrPubKey);
6092 wrappedKey.data = wswk.wrappedSymmetricWrappingkey;
6093
6094 PORT_Assert(wrappedKey.len <= sizeof wswk.wrappedSymmetricWrappingkey)((wrappedKey.len <= sizeof wswk.wrappedSymmetricWrappingkey
)?((void)0):PR_Assert("wrappedKey.len <= sizeof wswk.wrappedSymmetricWrappingkey"
,"ssl3con.c",6094))
;
6095 if (wrappedKey.len > sizeof wswk.wrappedSymmetricWrappingkey)
6096 goto loser;
6097
6098 /* wrap symmetric wrapping key in server's public key. */
6099 switch (authType) {
6100 case ssl_auth_rsa_decrypt:
6101 case ssl_auth_rsa_sign: /* bad: see Bug 1248320 */
6102 case ssl_auth_rsa_pss:
6103 asymWrapMechanism = CKM_RSA_PKCS0x00000001UL;
6104 rv = PK11_PubWrapSymKey(asymWrapMechanism, svrPubKey,
6105 unwrappedWrappingKey, &wrappedKey);
6106 break;
6107
6108 case ssl_auth_ecdsa:
6109 case ssl_auth_ecdh_rsa:
6110 case ssl_auth_ecdh_ecdsa:
6111 /*
6112 * We generate an ephemeral EC key pair. Perform an ECDH
6113 * computation involving this ephemeral EC public key and
6114 * the SSL server's (long-term) EC private key. The resulting
6115 * shared secret is treated in the same way as Fortezza's Ks,
6116 * i.e., it is used to wrap the wrapping key. To facilitate
6117 * unwrapping in ssl_UnwrapWrappingKey, we also store all
6118 * relevant info about the ephemeral EC public key in
6119 * wswk.wrappedSymmetricWrappingkey and lay it out as
6120 * described in the ECCWrappedKeyInfo structure.
6121 */
6122 PORT_Assert(SECKEY_GetPublicKeyType(svrPubKey) == ecKey)((SECKEY_GetPublicKeyType(svrPubKey) == ecKey)?((void)0):PR_Assert
("SECKEY_GetPublicKeyType(svrPubKey) == ecKey","ssl3con.c",6122
))
;
6123 if (SECKEY_GetPublicKeyType(svrPubKey) != ecKey) {
6124 /* something is wrong in sslsecur.c if this isn't an ecKey */
6125 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
6126 rv = SECFailure;
6127 goto ec_cleanup;
6128 }
6129
6130 privWrapKey = SECKEY_CreateECPrivateKey(
6131 &svrPubKey->u.ec.DEREncodedParams, &pubWrapKey, NULL((void*)0));
6132 if ((privWrapKey == NULL((void*)0)) || (pubWrapKey == NULL((void*)0))) {
6133 rv = SECFailure;
6134 goto ec_cleanup;
6135 }
6136
6137 /* Set the key size in bits */
6138 if (pubWrapKey->u.ec.size == 0) {
6139 pubWrapKey->u.ec.size = SECKEY_PublicKeyStrengthInBits(svrPubKey);
6140 }
6141
6142 PORT_Assert(pubWrapKey->u.ec.DEREncodedParams.len +((pubWrapKey->u.ec.DEREncodedParams.len + pubWrapKey->u
.ec.publicValue.len < 504)?((void)0):PR_Assert("pubWrapKey->u.ec.DEREncodedParams.len + pubWrapKey->u.ec.publicValue.len < MAX_EC_WRAPPED_KEY_BUFLEN"
,"ssl3con.c",6144))
6143 pubWrapKey->u.ec.publicValue.len <((pubWrapKey->u.ec.DEREncodedParams.len + pubWrapKey->u
.ec.publicValue.len < 504)?((void)0):PR_Assert("pubWrapKey->u.ec.DEREncodedParams.len + pubWrapKey->u.ec.publicValue.len < MAX_EC_WRAPPED_KEY_BUFLEN"
,"ssl3con.c",6144))
6144 MAX_EC_WRAPPED_KEY_BUFLEN)((pubWrapKey->u.ec.DEREncodedParams.len + pubWrapKey->u
.ec.publicValue.len < 504)?((void)0):PR_Assert("pubWrapKey->u.ec.DEREncodedParams.len + pubWrapKey->u.ec.publicValue.len < MAX_EC_WRAPPED_KEY_BUFLEN"
,"ssl3con.c",6144))
;
6145 if (pubWrapKey->u.ec.DEREncodedParams.len +
6146 pubWrapKey->u.ec.publicValue.len >=
6147 MAX_EC_WRAPPED_KEY_BUFLEN504) {
6148 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_KEY);
6149 rv = SECFailure;
6150 goto ec_cleanup;
6151 }
6152
6153 /* Derive Ks using ECDH */
6154 Ks = PK11_PubDeriveWithKDF(svrPrivKey, pubWrapKey, PR_FALSE0, NULL((void*)0),
6155 NULL((void*)0), CKM_ECDH1_DERIVE0x00001050UL, masterWrapMech,
6156 CKA_DERIVE0x0000010CUL, 0, CKD_NULL0x00000001UL, NULL((void*)0), NULL((void*)0));
6157 if (Ks == NULL((void*)0)) {
6158 rv = SECFailure;
6159 goto ec_cleanup;
6160 }
6161
6162 ecWrapped = (ECCWrappedKeyInfo *)(wswk.wrappedSymmetricWrappingkey);
6163 ecWrapped->size = pubWrapKey->u.ec.size;
6164 ecWrapped->encodedParamLen = pubWrapKey->u.ec.DEREncodedParams.len;
6165 PORT_Memcpymemcpy(ecWrapped->var, pubWrapKey->u.ec.DEREncodedParams.data,
6166 pubWrapKey->u.ec.DEREncodedParams.len);
6167
6168 ecWrapped->pubValueLen = pubWrapKey->u.ec.publicValue.len;
6169 PORT_Memcpymemcpy(ecWrapped->var + ecWrapped->encodedParamLen,
6170 pubWrapKey->u.ec.publicValue.data,
6171 pubWrapKey->u.ec.publicValue.len);
6172
6173 wrappedKey.len = MAX_EC_WRAPPED_KEY_BUFLEN504 -
6174 (ecWrapped->encodedParamLen + ecWrapped->pubValueLen);
6175 wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen +
6176 ecWrapped->pubValueLen;
6177
6178 /* wrap symmetricWrapping key with the local Ks */
6179 rv = PK11_WrapSymKey(masterWrapMech, NULL((void*)0), Ks,
6180 unwrappedWrappingKey, &wrappedKey);
6181
6182 if (rv != SECSuccess) {
6183 goto ec_cleanup;
6184 }
6185
6186 /* Write down the length of wrapped key in the buffer
6187 * wswk.wrappedSymmetricWrappingkey at the appropriate offset
6188 */
6189 ecWrapped->wrappedKeyLen = wrappedKey.len;
6190
6191 ec_cleanup:
6192 if (privWrapKey)
6193 SECKEY_DestroyPrivateKey(privWrapKey);
6194 if (pubWrapKey)
6195 SECKEY_DestroyPublicKey(pubWrapKey);
6196 if (Ks)
6197 PK11_FreeSymKey(Ks);
6198 asymWrapMechanism = masterWrapMech;
6199 break;
6200
6201 default:
6202 rv = SECFailure;
6203 break;
6204 }
6205
6206 if (rv != SECSuccess) {
6207 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6208 goto loser;
6209 }
6210
6211 PORT_Assert(asymWrapMechanism != CKM_INVALID_MECHANISM)((asymWrapMechanism != 0xffffffffUL)?((void)0):PR_Assert("asymWrapMechanism != CKM_INVALID_MECHANISM"
,"ssl3con.c",6211))
;
6212
6213 wswk.symWrapMechanism = masterWrapMech;
6214 wswk.asymWrapMechanism = asymWrapMechanism;
6215 wswk.wrapMechIndex = wrapMechIndex;
6216 wswk.wrapKeyIndex = wrapKeyIndex;
6217 wswk.wrappedSymKeyLen = wrappedKey.len;
6218
6219 /* put it on disk. */
6220 /* If the wrapping key for this KEA type has already been set,
6221 * then abandon the value we just computed and
6222 * use the one we got from the disk.
6223 */
6224 rv = ssl_SetWrappingKey(&wswk);
6225 if (rv == SECSuccess) {
6226 /* somebody beat us to it. The original contents of our wswk
6227 * has been replaced with the content on disk. Now, discard
6228 * the key we just created and unwrap this new one.
6229 */
6230 PK11_FreeSymKey(unwrappedWrappingKey);
6231
6232 unwrappedWrappingKey =
6233 ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, wrapKeyIndex,
6234 masterWrapMech, pwArg);
6235 }
6236
6237install:
6238 if (unwrappedWrappingKey) {
6239 *pSymWrapKey = PK11_ReferenceSymKey(unwrappedWrappingKey);
6240 }
6241
6242loser:
6243done:
6244 PZ_Unlock(symWrapKeysLock)PR_Unlock((symWrapKeysLock));
6245 return unwrappedWrappingKey;
6246}
6247
6248#ifdef NSS_ALLOW_SSLKEYLOGFILE1
6249/* hexEncode hex encodes |length| bytes from |in| and writes it as |length*2|
6250 * bytes to |out|. */
6251static void
6252hexEncode(char *out, const unsigned char *in, unsigned int length)
6253{
6254 static const char hextable[] = "0123456789abcdef";
6255 unsigned int i;
6256
6257 for (i = 0; i < length; i++) {
6258 *(out++) = hextable[in[i] >> 4];
6259 *(out++) = hextable[in[i] & 15];
6260 }
6261}
6262#endif
6263
6264/* Called from ssl3_SendClientKeyExchange(). */
6265static SECStatus
6266ssl3_SendRSAClientKeyExchange(sslSocket *ss, SECKEYPublicKey *svrPubKey)
6267{
6268 PK11SymKey *pms = NULL((void*)0);
6269 SECStatus rv = SECFailure;
6270 SECItem enc_pms = { siBuffer, NULL((void*)0), 0 };
6271 PRBool isTLS;
6272
6273 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",6273))
;
6274 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->xmitBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveXmitBufLock(ss)"
,"ssl3con.c",6274))
;
6275
6276 /* Generate the pre-master secret ... */
6277 ssl_GetSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_LockWrite_Util((ss)->
specLock); }
;
6278 isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_00x0300);
6279
6280 pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.pwSpec, NULL((void*)0));
6281 ssl_ReleaseSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockWrite_Util((ss)->
specLock); }
;
6282 if (pms == NULL((void*)0)) {
6283 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6284 goto loser;
6285 }
6286
6287 /* Get the wrapped (encrypted) pre-master secret, enc_pms */
6288 unsigned int svrPubKeyBits = SECKEY_PublicKeyStrengthInBits(svrPubKey);
6289 enc_pms.len = (svrPubKeyBits + 7) / 8;
6290 /* Check that the RSA key isn't larger than 8k bit. */
6291 if (svrPubKeyBits > SSL_MAX_RSA_KEY_BITS8192) {
6292 (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
6293 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6294 goto loser;
6295 }
6296 enc_pms.data = (unsigned char *)PORT_AllocPORT_Alloc_Util(enc_pms.len);
6297 if (enc_pms.data == NULL((void*)0)) {
6298 goto loser; /* err set by PORT_Alloc */
6299 }
6300
6301 /* Wrap pre-master secret in server's public key. */
6302 rv = PK11_PubWrapSymKey(CKM_RSA_PKCS0x00000001UL, svrPubKey, pms, &enc_pms);
6303 if (rv != SECSuccess) {
6304 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6305 goto loser;
6306 }
6307
6308#ifdef TRACE
6309 if (ssl_trace >= 100) {
6310 SECStatus extractRV = PK11_ExtractKeyValue(pms);
6311 if (extractRV == SECSuccess) {
6312 SECItem *keyData = PK11_GetKeyData(pms);
6313 if (keyData && keyData->data && keyData->len) {
6314 ssl_PrintBuf(ss, "Pre-Master Secret",
6315 keyData->data, keyData->len);
6316 }
6317 }
6318 }
6319#endif
6320
6321 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_client_key_exchange,
6322 isTLS ? enc_pms.len + 2
6323 : enc_pms.len);
6324 if (rv != SECSuccess) {
6325 goto loser; /* err set by ssl3_AppendHandshake* */
6326 }
6327 if (isTLS) {
6328 rv = ssl3_AppendHandshakeVariable(ss, enc_pms.data, enc_pms.len, 2);
6329 } else {
6330 rv = ssl3_AppendHandshake(ss, enc_pms.data, enc_pms.len);
6331 }
6332 if (rv != SECSuccess) {
6333 goto loser; /* err set by ssl3_AppendHandshake* */
6334 }
6335
6336 rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE1);
6337 PK11_FreeSymKey(pms);
6338 pms = NULL((void*)0);
6339
6340 if (rv != SECSuccess) {
6341 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6342 goto loser;
6343 }
6344
6345 rv = SECSuccess;
6346
6347loser:
6348 if (enc_pms.data != NULL((void*)0)) {
6349 PORT_FreePORT_Free_Util(enc_pms.data);
6350 }
6351 if (pms != NULL((void*)0)) {
6352 PK11_FreeSymKey(pms);
6353 }
6354 return rv;
6355}
6356
6357/* DH shares need to be padded to the size of their prime. Some implementations
6358 * require this. TLS 1.3 also requires this. */
6359SECStatus
6360ssl_AppendPaddedDHKeyShare(sslBuffer *buf, const SECKEYPublicKey *pubKey,
6361 PRBool appendLength)
6362{
6363 SECStatus rv;
6364 unsigned int pad = pubKey->u.dh.prime.len - pubKey->u.dh.publicValue.len;
6365
6366 if (appendLength) {
6367 rv = sslBuffer_AppendNumber(buf, pubKey->u.dh.prime.len, 2);
6368 if (rv != SECSuccess) {
6369 return rv;
6370 }
6371 }
6372 while (pad) {
6373 rv = sslBuffer_AppendNumber(buf, 0, 1);
6374 if (rv != SECSuccess) {
6375 return rv;
6376 }
6377 --pad;
6378 }
6379 rv = sslBuffer_Append(buf, pubKey->u.dh.publicValue.data,
6380 pubKey->u.dh.publicValue.len);
6381 if (rv != SECSuccess) {
6382 return rv;
6383 }
6384 return SECSuccess;
6385}
6386
6387/* Called from ssl3_SendClientKeyExchange(). */
6388static SECStatus
6389ssl3_SendDHClientKeyExchange(sslSocket *ss, SECKEYPublicKey *svrPubKey)
6390{
6391 PK11SymKey *pms = NULL((void*)0);
6392 SECStatus rv;
6393 PRBool isTLS;
6394 CK_MECHANISM_TYPE target;
6395
6396 const ssl3DHParams *params;
6397 ssl3DHParams customParams;
6398 const sslNamedGroupDef *groupDef;
6399 static const sslNamedGroupDef customGroupDef = {
6400 ssl_grp_ffdhe_custom, 0, ssl_kea_dh, SEC_OID_TLS_DHE_CUSTOM, PR_FALSE0
6401 };
6402 sslEphemeralKeyPair *keyPair = NULL((void*)0);
6403 SECKEYPublicKey *pubKey;
6404 PRUint8 dhData[SSL_MAX_DH_KEY_BITS8192 / 8 + 2];
6405 sslBuffer dhBuf = SSL_BUFFER(dhData){ dhData, 0, sizeof(dhData), 1 };
6406
6407 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",6407))
;
6408 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->xmitBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveXmitBufLock(ss)"
,"ssl3con.c",6408))
;
6409
6410 isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_00x0300);
6411
6412 /* Copy DH parameters from server key */
6413
6414 if (SECKEY_GetPublicKeyType(svrPubKey) != dhKey) {
6415 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_BAD_KEY);
6416 return SECFailure;
6417 }
6418
6419 /* Work out the parameters. */
6420 rv = ssl_ValidateDHENamedGroup(ss, &svrPubKey->u.dh.prime,
6421 &svrPubKey->u.dh.base,
6422 &groupDef, &params);
6423 if (rv != SECSuccess) {
6424 /* If we require named groups, we will have already validated the group
6425 * in ssl_HandleDHServerKeyExchange() */
6426 PORT_Assert(!ss->opt.requireDHENamedGroups &&((!ss->opt.requireDHENamedGroups && !ss->xtnData
.peerSupportsFfdheGroups)?((void)0):PR_Assert("!ss->opt.requireDHENamedGroups && !ss->xtnData.peerSupportsFfdheGroups"
,"ssl3con.c",6427))
6427 !ss->xtnData.peerSupportsFfdheGroups)((!ss->opt.requireDHENamedGroups && !ss->xtnData
.peerSupportsFfdheGroups)?((void)0):PR_Assert("!ss->opt.requireDHENamedGroups && !ss->xtnData.peerSupportsFfdheGroups"
,"ssl3con.c",6427))
;
6428
6429 customParams.name = ssl_grp_ffdhe_custom;
6430 customParams.prime.data = svrPubKey->u.dh.prime.data;
6431 customParams.prime.len = svrPubKey->u.dh.prime.len;
6432 customParams.base.data = svrPubKey->u.dh.base.data;
6433 customParams.base.len = svrPubKey->u.dh.base.len;
6434 params = &customParams;
6435 groupDef = &customGroupDef;
6436 }
6437 ss->sec.keaGroup = groupDef;
6438
6439 rv = ssl_CreateDHEKeyPair(groupDef, params, &keyPair);
6440 if (rv != SECSuccess) {
6441 ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
6442 goto loser;
6443 }
6444 pubKey = keyPair->keys->pubKey;
6445 PRINT_BUF(50, (ss, "DH public value:",if (ssl_trace >= (50)) ssl_PrintBuf (ss, "DH public value:"
, pubKey->u.dh.publicValue.data, pubKey->u.dh.publicValue
.len)
6446 pubKey->u.dh.publicValue.data,if (ssl_trace >= (50)) ssl_PrintBuf (ss, "DH public value:"
, pubKey->u.dh.publicValue.data, pubKey->u.dh.publicValue
.len)
6447 pubKey->u.dh.publicValue.len))if (ssl_trace >= (50)) ssl_PrintBuf (ss, "DH public value:"
, pubKey->u.dh.publicValue.data, pubKey->u.dh.publicValue
.len)
;
6448
6449 if (isTLS)
6450 target = CKM_TLS_MASTER_KEY_DERIVE_DH0x00000377UL;
6451 else
6452 target = CKM_SSL3_MASTER_KEY_DERIVE_DH0x00000373UL;
6453
6454 /* Determine the PMS */
6455 pms = PK11_PubDerive(keyPair->keys->privKey, svrPubKey,
6456 PR_FALSE0, NULL((void*)0), NULL((void*)0), CKM_DH_PKCS_DERIVE0x00000021UL,
6457 target, CKA_DERIVE0x0000010CUL, 0, NULL((void*)0));
6458
6459 if (pms == NULL((void*)0)) {
6460 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6461 goto loser;
6462 }
6463
6464 /* Note: send the DH share padded to avoid triggering bugs. */
6465 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_client_key_exchange,
6466 params->prime.len + 2);
6467 if (rv != SECSuccess) {
6468 goto loser; /* err set by ssl3_AppendHandshake* */
6469 }
6470 rv = ssl_AppendPaddedDHKeyShare(&dhBuf, pubKey, PR_TRUE1);
6471 if (rv != SECSuccess) {
6472 goto loser; /* err set by ssl_AppendPaddedDHKeyShare */
6473 }
6474 rv = ssl3_AppendBufferToHandshake(ss, &dhBuf);
6475 if (rv != SECSuccess) {
6476 goto loser; /* err set by ssl3_AppendBufferToHandshake */
6477 }
6478
6479 rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE1);
6480 if (rv != SECSuccess) {
6481 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
6482 goto loser;
6483 }
6484
6485 sslBuffer_Clear(&dhBuf);
6486 PK11_FreeSymKey(pms);
6487 ssl_FreeEphemeralKeyPair(keyPair);
6488 return SECSuccess;
6489
6490loser:
6491 if (pms)
6492 PK11_FreeSymKey(pms);
6493 if (keyPair)
6494 ssl_FreeEphemeralKeyPair(keyPair);
6495 sslBuffer_Clear(&dhBuf);
6496 return SECFailure;
6497}
6498
6499/* Called from ssl3_HandleServerHelloDone(). */
6500static SECStatus
6501ssl3_SendClientKeyExchange(sslSocket *ss)
6502{
6503 SECKEYPublicKey *serverKey = NULL((void*)0);
6504 SECStatus rv = SECFailure;
6505
6506 SSL_TRC(3, ("%d: SSL3[%d]: send client_key_exchange handshake",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: send client_key_exchange handshake"
, getpid(), ss->fd)
6507 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: send client_key_exchange handshake"
, getpid(), ss->fd)
;
6508
6509 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->xmitBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveXmitBufLock(ss)"
,"ssl3con.c",6509))
;
6510 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",6510))
;
6511
6512 if (ss->sec.peerKey == NULL((void*)0)) {
6513 serverKey = CERT_ExtractPublicKey(ss->sec.peerCert);
6514 if (serverKey == NULL((void*)0)) {
6515 ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
6516 return SECFailure;
6517 }
6518 } else {
6519 serverKey = ss->sec.peerKey;
6520 ss->sec.peerKey = NULL((void*)0); /* we're done with it now */
6521 }
6522
6523 ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType;
6524 ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits(serverKey);
6525
6526 switch (ss->ssl3.hs.kea_def->exchKeyType) {
6527 case ssl_kea_rsa:
6528 rv = ssl3_SendRSAClientKeyExchange(ss, serverKey);
6529 break;
6530
6531 case ssl_kea_dh:
6532 rv = ssl3_SendDHClientKeyExchange(ss, serverKey);
6533 break;
6534
6535 case ssl_kea_ecdh:
6536 rv = ssl3_SendECDHClientKeyExchange(ss, serverKey);
6537 break;
6538
6539 default:
6540 PORT_Assert(0)((0)?((void)0):PR_Assert("0","ssl3con.c",6540));
6541 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
6542 break;
6543 }
6544
6545 SSL_TRC(3, ("%d: SSL3[%d]: DONE sending client_key_exchange",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: DONE sending client_key_exchange"
, getpid(), ss->fd)
6546 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: DONE sending client_key_exchange"
, getpid(), ss->fd)
;
6547
6548 SECKEY_DestroyPublicKey(serverKey);
6549 return rv; /* err code already set. */
6550}
6551
6552/* Used by ssl_PickSignatureScheme(). */
6553PRBool
6554ssl_CanUseSignatureScheme(SSLSignatureScheme scheme,
6555 const SSLSignatureScheme *peerSchemes,
6556 unsigned int peerSchemeCount,
6557 PRBool requireSha1,
6558 PRBool slotDoesPss)
6559{
6560 SSLHashType hashType;
6561 unsigned int i;
6562
6563 /* Skip RSA-PSS schemes when the certificate's private key slot does
6564 * not support this signature mechanism. */
6565 if (ssl_IsRsaPssSignatureScheme(scheme) && !slotDoesPss) {
6566 return PR_FALSE0;
6567 }
6568
6569 hashType = ssl_SignatureSchemeToHashType(scheme);
6570 if (requireSha1 && (hashType != ssl_hash_sha1)) {
6571 return PR_FALSE0;
6572 }
6573
6574 if (!ssl_SchemePolicyOK(scheme, kSSLSigSchemePolicy)) {
6575 return PR_FALSE0;
6576 }
6577
6578 for (i = 0; i < peerSchemeCount; i++) {
6579 if (peerSchemes[i] == scheme) {
6580 return PR_TRUE1;
6581 }
6582 }
6583 return PR_FALSE0;
6584}
6585
6586SECStatus
6587ssl_PrivateKeySupportsRsaPss(SECKEYPrivateKey *privKey, CERTCertificate *cert,
6588 void *pwarg, PRBool *supportsRsaPss)
6589{
6590 PK11SlotInfo *slot = NULL((void*)0);
6591 if (privKey) {
6592 slot = PK11_GetSlotFromPrivateKey(privKey);
6593 } else {
6594 CK_OBJECT_HANDLE certID = PK11_FindObjectForCert(cert, pwarg, &slot);
6595 if (certID == CK_INVALID_HANDLE0) {
6596 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
6597 return SECFailure;
6598 }
6599 }
6600 if (!slot) {
6601 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
6602 return SECFailure;
6603 }
6604 *supportsRsaPss = PK11_DoesMechanism(slot, auth_alg_defs[ssl_auth_rsa_pss]);
6605 PK11_FreeSlot(slot);
6606 return SECSuccess;
6607}
6608
6609SECStatus
6610ssl_PickSignatureScheme(sslSocket *ss,
6611 CERTCertificate *cert,
6612 SECKEYPublicKey *pubKey,
6613 SECKEYPrivateKey *privKey,
6614 const SSLSignatureScheme *peerSchemes,
6615 unsigned int peerSchemeCount,
6616 PRBool requireSha1,
6617 SSLSignatureScheme *schemePtr)
6618{
6619 unsigned int i;
6620 PRBool doesRsaPss;
6621 PRBool isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_30x0304;
6622 SECStatus rv;
6623 SSLSignatureScheme scheme;
6624 SECOidTag spkiOid;
6625
6626 /* We can't require SHA-1 in TLS 1.3. */
6627 PORT_Assert(!(requireSha1 && isTLS13))((!(requireSha1 && isTLS13))?((void)0):PR_Assert("!(requireSha1 && isTLS13)"
,"ssl3con.c",6627))
;
6628 if (!pubKey || !cert) {
6629 PORT_Assert(0)((0)?((void)0):PR_Assert("0","ssl3con.c",6629));
6630 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
6631 return SECFailure;
6632 }
6633 rv = ssl_PrivateKeySupportsRsaPss(privKey, cert, ss->pkcs11PinArg,
6634 &doesRsaPss);
6635 if (rv != SECSuccess) {
6636 return SECFailure;
6637 }
6638
6639 /* If the certificate SPKI indicates a single scheme, don't search. */
6640 rv = ssl_SignatureSchemeFromSpki(&cert->subjectPublicKeyInfo,
6641 isTLS13, &scheme);
6642 if (rv != SECSuccess) {
6643 return SECFailure;
6644 }
6645 if (scheme != ssl_sig_none) {
6646 if (!ssl_SignatureSchemeEnabled(ss, scheme) ||
6647 !ssl_CanUseSignatureScheme(scheme, peerSchemes, peerSchemeCount,
6648 requireSha1, doesRsaPss)) {
6649 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
6650 return SECFailure;
6651 }
6652 *schemePtr = scheme;
6653 return SECSuccess;
6654 }
6655
6656 spkiOid = SECOID_GetAlgorithmTagSECOID_GetAlgorithmTag_Util(&cert->subjectPublicKeyInfo.algorithm);
6657 if (spkiOid == SEC_OID_UNKNOWN) {
6658 return SECFailure;
6659 }
6660
6661 /* Now we have to search based on the key type. Go through our preferred
6662 * schemes in order and find the first that can be used. */
6663 for (i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
6664 scheme = ss->ssl3.signatureSchemes[i];
6665
6666 if (ssl_SignatureSchemeValid(scheme, spkiOid, isTLS13) &&
6667 ssl_CanUseSignatureScheme(scheme, peerSchemes, peerSchemeCount,
6668 requireSha1, doesRsaPss)) {
6669 *schemePtr = scheme;
6670 return SECSuccess;
6671 }
6672 }
6673
6674 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
6675 return SECFailure;
6676}
6677
6678static SECStatus
6679ssl_PickFallbackSignatureScheme(sslSocket *ss, SECKEYPublicKey *pubKey)
6680{
6681 PRBool isTLS12 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_20x0303;
6682
6683 switch (SECKEY_GetPublicKeyType(pubKey)) {
6684 case rsaKey:
6685 if (isTLS12) {
6686 ss->ssl3.hs.signatureScheme = ssl_sig_rsa_pkcs1_sha1;
6687 } else {
6688 ss->ssl3.hs.signatureScheme = ssl_sig_rsa_pkcs1_sha1md5;
6689 }
6690 break;
6691 case ecKey:
6692 ss->ssl3.hs.signatureScheme = ssl_sig_ecdsa_sha1;
6693 break;
6694 case dsaKey:
6695 ss->ssl3.hs.signatureScheme = ssl_sig_dsa_sha1;
6696 break;
6697 default:
6698 PORT_Assert(0)((0)?((void)0):PR_Assert("0","ssl3con.c",6698));
6699 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_KEY);
6700 return SECFailure;
6701 }
6702 return SECSuccess;
6703}
6704
6705/* ssl3_PickServerSignatureScheme selects a signature scheme for signing the
6706 * handshake. Most of this is determined by the key pair we are using.
6707 * Prior to TLS 1.2, the MD5/SHA1 combination is always used. With TLS 1.2, a
6708 * client may advertise its support for signature and hash combinations. */
6709static SECStatus
6710ssl3_PickServerSignatureScheme(sslSocket *ss)
6711{
6712 const sslServerCert *cert = ss->sec.serverCert;
6713 PRBool isTLS12 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_20x0303;
6714
6715 if (!isTLS12 || !ssl3_ExtensionNegotiated(ss, ssl_signature_algorithms_xtn)) {
6716 /* If the client didn't provide any signature_algorithms extension then
6717 * we can assume that they support SHA-1: RFC5246, Section 7.4.1.4.1. */
6718 return ssl_PickFallbackSignatureScheme(ss, cert->serverKeyPair->pubKey);
6719 }
6720
6721 /* Sets error code, if needed. */
6722 return ssl_PickSignatureScheme(ss, cert->serverCert,
6723 cert->serverKeyPair->pubKey,
6724 cert->serverKeyPair->privKey,
6725 ss->xtnData.sigSchemes,
6726 ss->xtnData.numSigSchemes,
6727 PR_FALSE0 /* requireSha1 */,
6728 &ss->ssl3.hs.signatureScheme);
6729}
6730
6731SECStatus
6732ssl_PickClientSignatureScheme(sslSocket *ss, CERTCertificate *clientCertificate,
6733 SECKEYPrivateKey *privKey,
6734 const SSLSignatureScheme *schemes,
6735 unsigned int numSchemes,
6736 SSLSignatureScheme *schemePtr)
6737{
6738 SECStatus rv;
6739 PRBool isTLS13 = (PRBool)ss->version >= SSL_LIBRARY_VERSION_TLS_1_30x0304;
6740 SECKEYPublicKey *pubKey = CERT_ExtractPublicKey(clientCertificate);
6741
6742 PORT_Assert(pubKey)((pubKey)?((void)0):PR_Assert("pubKey","ssl3con.c",6742));
6743
6744 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_20x0303) {
6745 /* We should have already checked that a signature scheme was
6746 * listed in the request. */
6747 PORT_Assert(schemes && numSchemes > 0)((schemes && numSchemes > 0)?((void)0):PR_Assert("schemes && numSchemes > 0"
,"ssl3con.c",6747))
;
6748 }
6749
6750 if (!isTLS13 &&
6751 (SECKEY_GetPublicKeyType(pubKey) == rsaKey ||
6752 SECKEY_GetPublicKeyType(pubKey) == dsaKey) &&
6753 SECKEY_PublicKeyStrengthInBits(pubKey) <= 1024) {
6754 /* If the key is a 1024-bit RSA or DSA key, assume conservatively that
6755 * it may be unable to sign SHA-256 hashes. This is the case for older
6756 * Estonian ID cards that have 1024-bit RSA keys. In FIPS 186-2 and
6757 * older, DSA key size is at most 1024 bits and the hash function must
6758 * be SHA-1.
6759 */
6760 rv = ssl_PickSignatureScheme(ss, clientCertificate,
6761 pubKey, privKey, schemes, numSchemes,
6762 PR_TRUE1 /* requireSha1 */, schemePtr);
6763 if (rv == SECSuccess) {
6764 SECKEY_DestroyPublicKey(pubKey);
6765 return SECSuccess;
6766 }
6767 /* If this fails, that's because the peer doesn't advertise SHA-1,
6768 * so fall back to the full negotiation. */
6769 }
6770 rv = ssl_PickSignatureScheme(ss, clientCertificate,
6771 pubKey, privKey, schemes, numSchemes,
6772 PR_FALSE0 /* requireSha1 */, schemePtr);
6773 SECKEY_DestroyPublicKey(pubKey);
6774 return rv;
6775}
6776
6777/* Called from ssl3_HandleServerHelloDone(). */
6778static SECStatus
6779ssl3_SendCertificateVerify(sslSocket *ss, SECKEYPrivateKey *privKey)
6780{
6781 SECStatus rv = SECFailure;
6782 PRBool isTLS12;
6783 SECItem buf = { siBuffer, NULL((void*)0), 0 };
6784 SSL3Hashes hashes;
6785 unsigned int len;
6786 SSLHashType hashAlg;
6787
6788 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->xmitBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveXmitBufLock(ss)"
,"ssl3con.c",6788))
;
6789 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",6789))
;
6790
6791 SSL_TRC(3, ("%d: SSL3[%d]: send certificate_verify handshake",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: send certificate_verify handshake"
, getpid(), ss->fd)
6792 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: send certificate_verify handshake"
, getpid(), ss->fd)
;
6793
6794 ssl_GetSpecReadLock(ss){ if (!ss->opt.noLocks) NSSRWLock_LockRead_Util((ss)->specLock
); }
;
6795
6796 if (ss->ssl3.hs.hashType == handshake_hash_record) {
6797 hashAlg = ssl_SignatureSchemeToHashType(ss->ssl3.hs.signatureScheme);
6798 } else {
6799 /* Use ssl_hash_none to represent the MD5+SHA1 combo. */
6800 hashAlg = ssl_hash_none;
6801 }
6802 if (ss->ssl3.hs.hashType == handshake_hash_record &&
6803 hashAlg != ssl3_GetSuitePrfHash(ss)) {
6804 rv = ssl3_ComputeHandshakeHash(ss->ssl3.hs.messages.buf,
6805 ss->ssl3.hs.messages.len,
6806 hashAlg, &hashes);
6807 if (rv != SECSuccess) {
6808 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
6809 }
6810 } else {
6811 rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.pwSpec, &hashes, 0);
6812 }
6813 ssl_ReleaseSpecReadLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockRead_Util((ss)->
specLock); }
;
6814 if (rv != SECSuccess) {
6815 goto done; /* err code was set by ssl3_ComputeHandshakeHash(es) */
6816 }
6817
6818 isTLS12 = (PRBool)(ss->version == SSL_LIBRARY_VERSION_TLS_1_20x0303);
6819 PORT_Assert(ss->version <= SSL_LIBRARY_VERSION_TLS_1_2)((ss->version <= 0x0303)?((void)0):PR_Assert("ss->version <= SSL_LIBRARY_VERSION_TLS_1_2"
,"ssl3con.c",6819))
;
6820
6821 rv = ssl3_SignHashes(ss, &hashes, privKey, &buf);
6822 if (rv == SECSuccess && !ss->sec.isServer) {
6823 /* Remember the info about the slot that did the signing.
6824 ** Later, when doing an SSL restart handshake, verify this.
6825 ** These calls are mere accessors, and can't fail.
6826 */
6827 PK11SlotInfo *slot;
6828 sslSessionID *sid = ss->sec.ci.sid;
6829
6830 slot = PK11_GetSlotFromPrivateKey(privKey);
6831 sid->u.ssl3.clAuthSeries = PK11_GetSlotSeries(slot);
6832 sid->u.ssl3.clAuthSlotID = PK11_GetSlotID(slot);
6833 sid->u.ssl3.clAuthModuleID = PK11_GetModuleID(slot);
6834 sid->u.ssl3.clAuthValid = PR_TRUE1;
6835 PK11_FreeSlot(slot);
6836 }
6837 if (rv != SECSuccess) {
6838 goto done; /* err code was set by ssl3_SignHashes */
6839 }
6840
6841 len = buf.len + 2 + (isTLS12 ? 2 : 0);
6842
6843 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_verify, len);
6844 if (rv != SECSuccess) {
6845 goto done; /* error code set by AppendHandshake */
6846 }
6847 if (isTLS12) {
6848 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.signatureScheme, 2);
6849 if (rv != SECSuccess) {
6850 goto done; /* err set by AppendHandshake. */
6851 }
6852 }
6853 rv = ssl3_AppendHandshakeVariable(ss, buf.data, buf.len, 2);
6854 if (rv != SECSuccess) {
6855 goto done; /* error code set by AppendHandshake */
6856 }
6857
6858done:
6859 if (buf.data)
6860 PORT_FreePORT_Free_Util(buf.data);
6861 return rv;
6862}
6863
6864/* Once a cipher suite has been selected, make sure that the necessary secondary
6865 * information is properly set. */
6866SECStatus
6867ssl3_SetupCipherSuite(sslSocket *ss, PRBool initHashes)
6868{
6869 ss->ssl3.hs.suite_def = ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite);
6870 if (!ss->ssl3.hs.suite_def) {
6871 PORT_Assert(0)((0)?((void)0):PR_Assert("0","ssl3con.c",6871));
6872 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
6873 return SECFailure;
6874 }
6875
6876 ss->ssl3.hs.kea_def = &kea_defs[ss->ssl3.hs.suite_def->key_exchange_alg];
6877 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_cipher_suite(1U << 1);
6878
6879 if (!initHashes) {
6880 return SECSuccess;
6881 }
6882 /* Now we have a cipher suite, initialize the handshake hashes. */
6883 return ssl3_InitHandshakeHashes(ss);
6884}
6885
6886SECStatus
6887ssl_ClientSetCipherSuite(sslSocket *ss, SSL3ProtocolVersion version,
6888 ssl3CipherSuite suite, PRBool initHashes)
6889{
6890 unsigned int i;
6891 if (ssl3_config_match_init(ss) == 0) {
6892 PORT_Assert(PR_FALSE)((0)?((void)0):PR_Assert("PR_FALSE","ssl3con.c",6892));
6893 return SECFailure;
6894 }
6895 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED71; i++) {
6896 ssl3CipherSuiteCfg *suiteCfg = &ss->cipherSuites[i];
6897 if (suite == suiteCfg->cipher_suite) {
6898 SSLVersionRange vrange = { version, version };
6899 if (!ssl3_config_match(suiteCfg, ss->ssl3.policy, &vrange, ss)) {
6900 /* config_match already checks whether the cipher suite is
6901 * acceptable for the version, but the check is repeated here
6902 * in order to give a more precise error code. */
6903 if (!ssl3_CipherSuiteAllowedForVersionRange(suite, &vrange)) {
6904 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_CIPHER_DISALLOWED_FOR_VERSION);
6905 } else {
6906 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_NO_CYPHER_OVERLAP);
6907 }
6908 return SECFailure;
6909 }
6910 break;
6911 }
6912 }
6913 if (i >= ssl_V3_SUITES_IMPLEMENTED71) {
6914 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_NO_CYPHER_OVERLAP);
6915 return SECFailure;
6916 }
6917
6918 /* Don't let the server change its mind. */
6919 if (ss->ssl3.hs.helloRetry && suite != ss->ssl3.hs.cipher_suite) {
6920 (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
6921 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_MALFORMED_SERVER_HELLO);
6922 return SECFailure;
6923 }
6924
6925 ss->ssl3.hs.cipher_suite = (ssl3CipherSuite)suite;
6926 return ssl3_SetupCipherSuite(ss, initHashes);
6927}
6928
6929/* Check that session ID we received from the server, if any, matches our
6930 * expectations, depending on whether we're in compat mode and whether we
6931 * negotiated TLS 1.3+ or TLS 1.2-.
6932 */
6933static PRBool
6934ssl_CheckServerSessionIdCorrectness(sslSocket *ss, SECItem *sidBytes)
6935{
6936 sslSessionID *sid = ss->sec.ci.sid;
6937 PRBool sidMatch = PR_FALSE0;
6938 PRBool sentFakeSid = PR_FALSE0;
6939 PRBool sentRealSid = sid && sid->version < SSL_LIBRARY_VERSION_TLS_1_30x0304;
6940
6941 /* If attempting to resume a TLS 1.2 connection, the session ID won't be a
6942 * fake. Check for the real value. */
6943 if (sentRealSid) {
6944 sidMatch = (sidBytes->len == sid->u.ssl3.sessionIDLength) &&
6945 (!sidBytes->len || PORT_Memcmpmemcmp(sid->u.ssl3.sessionID, sidBytes->data, sidBytes->len) == 0);
6946 } else {
6947 /* Otherwise, the session ID was a fake if TLS 1.3 compat mode is
6948 * enabled. If so, check for the fake value. */
6949 sentFakeSid = ss->opt.enableTls13CompatMode && !IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram);
6950 if (sentFakeSid && sidBytes->len == SSL3_SESSIONID_BYTES32) {
6951 PRUint8 buf[SSL3_SESSIONID_BYTES32];
6952 ssl_MakeFakeSid(ss, buf);
6953 sidMatch = PORT_Memcmpmemcmp(buf, sidBytes->data, sidBytes->len) == 0;
6954 }
6955 }
6956
6957 /* TLS 1.2: Session ID shouldn't match if we sent a fake. */
6958 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_30x0304) {
6959 if (sentFakeSid) {
6960 return !sidMatch;
6961 }
6962 return PR_TRUE1;
6963 }
6964
6965 /* TLS 1.3: We sent a session ID. The server's should match. */
6966 if (!IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram) && (sentRealSid || sentFakeSid)) {
6967 return sidMatch;
6968 }
6969
6970 /* TLS 1.3 (no SID)/DTLS 1.3: The server shouldn't send a session ID. */
6971 return sidBytes->len == 0;
6972}
6973
6974static SECStatus
6975ssl_CheckServerRandom(sslSocket *ss)
6976{
6977 /* Check the ServerHello.random per [RFC 8446 Section 4.1.3].
6978 *
6979 * TLS 1.3 clients receiving a ServerHello indicating TLS 1.2 or below
6980 * MUST check that the last 8 bytes are not equal to either of these
6981 * values. TLS 1.2 clients SHOULD also check that the last 8 bytes are
6982 * not equal to the second value if the ServerHello indicates TLS 1.1 or
6983 * below. If a match is found, the client MUST abort the handshake with
6984 * an "illegal_parameter" alert.
6985 */
6986 SSL3ProtocolVersion checkVersion =
6987 ss->ssl3.downgradeCheckVersion ? ss->ssl3.downgradeCheckVersion
6988 : ss->vrange.max;
6989
6990 if (checkVersion >= SSL_LIBRARY_VERSION_TLS_1_20x0303 &&
6991 checkVersion > ss->version) {
6992 /* Both sections use the same sentinel region. */
6993 PRUint8 *downgrade_sentinel =
6994 ss->ssl3.hs.server_random +
6995 SSL3_RANDOM_LENGTH32 - sizeof(tls12_downgrade_random);
6996
6997 if (!PORT_Memcmpmemcmp(downgrade_sentinel,
6998 tls12_downgrade_random,
6999 sizeof(tls12_downgrade_random)) ||
7000 !PORT_Memcmpmemcmp(downgrade_sentinel,
7001 tls1_downgrade_random,
7002 sizeof(tls1_downgrade_random))) {
7003 return SECFailure;
7004 }
7005 }
7006
7007 return SECSuccess;
7008}
7009
7010/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
7011 * ssl3 ServerHello message.
7012 * Caller must hold Handshake and RecvBuf locks.
7013 */
7014static SECStatus
7015ssl3_HandleServerHello(sslSocket *ss, PRUint8 *b, PRUint32 length)
7016{
7017 PRUint32 cipher;
7018 int errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
7019 PRUint32 compression;
7020 SECStatus rv;
7021 SECItem sidBytes = { siBuffer, NULL((void*)0), 0 };
7022 PRBool isHelloRetry;
7023 SSL3AlertDescription desc = illegal_parameter;
7024 const PRUint8 *savedMsg = b;
7025 const PRUint32 savedLength = length;
7026
7027 SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello handshake",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: handle server_hello handshake"
, getpid(), ss->fd)
7028 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: handle server_hello handshake"
, getpid(), ss->fd)
;
7029 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->recvBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveRecvBufLock(ss)"
,"ssl3con.c",7029))
;
7030 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",7030))
;
7031
7032 if (ss->ssl3.hs.ws != wait_server_hello) {
7033 errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO;
7034 desc = unexpected_message;
7035 goto alert_loser;
7036 }
7037
7038 /* clean up anything left from previous handshake. */
7039 if (ss->ssl3.clientCertChain != NULL((void*)0)) {
7040 CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
7041 ss->ssl3.clientCertChain = NULL((void*)0);
7042 }
7043 if (ss->ssl3.clientCertificate != NULL((void*)0)) {
7044 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
7045 ss->ssl3.clientCertificate = NULL((void*)0);
7046 }
7047 if (ss->ssl3.clientPrivateKey != NULL((void*)0)) {
7048 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
7049 ss->ssl3.clientPrivateKey = NULL((void*)0);
7050 }
7051 // TODO(djackson) - Bob removed this. Why?
7052 if (ss->ssl3.hs.clientAuthSignatureSchemes != NULL((void*)0)) {
7053 PR_Free(ss->ssl3.hs.clientAuthSignatureSchemes);
7054 ss->ssl3.hs.clientAuthSignatureSchemes = NULL((void*)0);
7055 ss->ssl3.hs.clientAuthSignatureSchemesLen = 0;
7056 }
7057
7058 /* Note that if the server selects TLS 1.3, this will set the version to TLS
7059 * 1.2. We will amend that once all other fields have been read. */
7060 rv = ssl_ClientReadVersion(ss, &b, &length, &ss->version);
7061 if (rv != SECSuccess) {
7062 goto loser; /* alert has been sent */
7063 }
7064
7065 rv = ssl3_ConsumeHandshake(
7066 ss, ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH32, &b, &length);
7067 if (rv != SECSuccess) {
7068 goto loser; /* alert has been sent */
7069 }
7070 isHelloRetry = !PORT_Memcmpmemcmp(ss->ssl3.hs.server_random,
7071 ssl_hello_retry_random, SSL3_RANDOM_LENGTH32);
7072
7073 rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length);
7074 if (rv != SECSuccess) {
7075 goto loser; /* alert has been sent */
7076 }
7077 if (sidBytes.len > SSL3_SESSIONID_BYTES32) {
7078 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_00x0301)
7079 desc = decode_error;
7080 goto alert_loser; /* malformed. */
7081 }
7082
7083 /* Read the cipher suite. */
7084 rv = ssl3_ConsumeHandshakeNumber(ss, &cipher, 2, &b, &length);
7085 if (rv != SECSuccess) {
7086 goto loser; /* alert has been sent */
7087 }
7088
7089 /* Compression method. */
7090 rv = ssl3_ConsumeHandshakeNumber(ss, &compression, 1, &b, &length);
7091 if (rv != SECSuccess) {
7092 goto loser; /* alert has been sent */
7093 }
7094 if (compression != ssl_compression_null) {
7095 desc = illegal_parameter;
7096 errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
7097 goto alert_loser;
7098 }
7099
7100 /* Parse extensions. */
7101 if (length != 0) {
7102 PRUint32 extensionLength;
7103 rv = ssl3_ConsumeHandshakeNumber(ss, &extensionLength, 2, &b, &length);
7104 if (rv != SECSuccess) {
7105 goto loser; /* alert already sent */
7106 }
7107 if (extensionLength != length) {
7108 desc = decode_error;
7109 goto alert_loser;
7110 }
7111 rv = ssl3_ParseExtensions(ss, &b, &length);
7112 if (rv != SECSuccess) {
7113 goto alert_loser; /* malformed */
7114 }
7115 }
7116
7117 /* Read supported_versions if present. */
7118 rv = tls13_ClientReadSupportedVersion(ss);
7119 if (rv != SECSuccess) {
7120 goto loser;
7121 }
7122
7123 /* RFC 9147. 5.2.
7124 * DTLS Handshake Message Format states the difference between the computation
7125 * of the transcript if the version is DTLS1.2 or DTLS1.3.
7126 *
7127 * At this moment we are sure which version
7128 * we are planning to use during the connection, so we can compute the hash. */
7129 rv = ssl3_MaybeUpdateHashWithSavedRecord(ss);
7130 if (rv != SECSuccess) {
7131 goto loser;
7132 }
7133
7134 PORT_Assert(!SSL_ALL_VERSIONS_DISABLED(&ss->vrange))((!((&ss->vrange)->min == 0))?((void)0):PR_Assert("!SSL_ALL_VERSIONS_DISABLED(&ss->vrange)"
,"ssl3con.c",7134))
;
7135 /* Check that the version is within the configured range. */
7136 if (ss->vrange.min > ss->version || ss->vrange.max < ss->version) {
7137 desc = (ss->version > SSL_LIBRARY_VERSION_3_00x0300)
7138 ? protocol_version
7139 : handshake_failure;
7140 errCode = SSL_ERROR_UNSUPPORTED_VERSION;
7141 goto alert_loser;
7142 }
7143
7144 if (isHelloRetry && ss->ssl3.hs.helloRetry) {
7145 SSL_TRC(3, ("%d: SSL3[%d]: received a second hello_retry_request",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: received a second hello_retry_request"
, getpid(), ss->fd)
7146 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: received a second hello_retry_request"
, getpid(), ss->fd)
;
7147 desc = unexpected_message;
7148 errCode = SSL_ERROR_RX_UNEXPECTED_HELLO_RETRY_REQUEST;
7149 goto alert_loser;
7150 }
7151
7152 /* There are three situations in which the server must pick
7153 * TLS 1.3.
7154 *
7155 * 1. We received HRR
7156 * 2. We sent early app data
7157 * 3. ECH was accepted (checked in MaybeHandleEchSignal)
7158 *
7159 * If we offered ECH and the server negotiated a lower version,
7160 * authenticate to the public name for secure disablement.
7161 *
7162 */
7163 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_30x0304) {
7164 if (isHelloRetry || ss->ssl3.hs.helloRetry) {
7165 /* SSL3_SendAlert() will uncache the SID. */
7166 desc = illegal_parameter;
7167 errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
7168 goto alert_loser;
7169 }
7170 if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent) {
7171 /* SSL3_SendAlert() will uncache the SID. */
7172 desc = illegal_parameter;
7173 errCode = SSL_ERROR_DOWNGRADE_WITH_EARLY_DATA;
7174 goto alert_loser;
7175 }
7176 }
7177
7178 /* Check that the server negotiated the same version as it did
7179 * in the first handshake. This isn't really the best place for
7180 * us to be getting this version number, but it's what we have.
7181 * (1294697). */
7182 if (ss->firstHsDone && (ss->version != ss->ssl3.crSpec->version)) {
7183 desc = protocol_version;
7184 errCode = SSL_ERROR_UNSUPPORTED_VERSION;
7185 goto alert_loser;
7186 }
7187
7188 if (ss->opt.enableHelloDowngradeCheck) {
7189 rv = ssl_CheckServerRandom(ss);
7190 if (rv != SECSuccess) {
7191 desc = illegal_parameter;
7192 errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
7193 goto alert_loser;
7194 }
7195 }
7196
7197 /* Finally, now all the version-related checks have passed. */
7198 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version(1U << 0);
7199 /* Update the write cipher spec to match the version. But not after
7200 * HelloRetryRequest, because cwSpec might be a 0-RTT cipher spec,
7201 * in which case this is a no-op. */
7202 if (!ss->firstHsDone && !isHelloRetry) {
7203 ssl_GetSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_LockWrite_Util((ss)->
specLock); }
;
7204 ssl_SetSpecVersions(ss, ss->ssl3.cwSpec);
7205 ssl_ReleaseSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockWrite_Util((ss)->
specLock); }
;
7206 }
7207
7208 /* Check that the session ID is as expected. */
7209 if (!ssl_CheckServerSessionIdCorrectness(ss, &sidBytes)) {
7210 desc = illegal_parameter;
7211 errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
7212 goto alert_loser;
7213 }
7214
7215 /* Only initialize hashes if this isn't a Hello Retry. */
7216 rv = ssl_ClientSetCipherSuite(ss, ss->version, cipher,
7217 !isHelloRetry);
7218 if (rv != SECSuccess) {
7219 desc = illegal_parameter;
7220 errCode = PORT_GetErrorPORT_GetError_Util();
7221 goto alert_loser;
7222 }
7223
7224 dtls_ReceivedFirstMessageInFlight(ss);
7225
7226 if (isHelloRetry) {
7227 rv = tls13_HandleHelloRetryRequest(ss, savedMsg, savedLength);
7228 if (rv != SECSuccess) {
7229 goto loser;
7230 }
7231 return SECSuccess;
7232 }
7233
7234 rv = ssl3_HandleParsedExtensions(ss, ssl_hs_server_hello);
7235 ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
7236 if (rv != SECSuccess) {
7237 goto alert_loser;
7238 }
7239
7240 rv = ssl_HashHandshakeMessage(ss, ssl_hs_server_hello,
7241 savedMsg, savedLength);
7242 if (rv != SECSuccess) {
7243 goto loser;
7244 }
7245
7246 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_30x0304) {
7247 rv = tls13_HandleServerHelloPart2(ss, savedMsg, savedLength);
7248 if (rv != SECSuccess) {
7249 errCode = PORT_GetErrorPORT_GetError_Util();
7250 goto loser;
7251 }
7252 } else {
7253 rv = ssl3_HandleServerHelloPart2(ss, &sidBytes, &errCode);
7254 if (rv != SECSuccess)
7255 goto loser;
7256 }
7257
7258 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_ech(1U << 4);
7259 return SECSuccess;
7260
7261alert_loser:
7262 (void)SSL3_SendAlert(ss, alert_fatal, desc);
7263
7264loser:
7265 /* Clean up the temporary pointer to the handshake buffer. */
7266 ss->xtnData.signedCertTimestamps.len = 0;
7267 ssl_MapLowLevelError(errCode);
7268 return SECFailure;
7269}
7270
7271static SECStatus
7272ssl3_UnwrapMasterSecretClient(sslSocket *ss, sslSessionID *sid, PK11SymKey **ms)
7273{
7274 PK11SlotInfo *slot;
7275 PK11SymKey *wrapKey;
7276 CK_FLAGS keyFlags = 0;
7277 SECItem wrappedMS = {
7278 siBuffer,
7279 sid->u.ssl3.keys.wrapped_master_secret,
7280 sid->u.ssl3.keys.wrapped_master_secret_len
7281 };
7282
7283 /* unwrap master secret */
7284 slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
7285 sid->u.ssl3.masterSlotID);
7286 if (slot == NULL((void*)0)) {
7287 return SECFailure;
7288 }
7289 if (!PK11_IsPresent(slot)) {
7290 PK11_FreeSlot(slot);
7291 return SECFailure;
7292 }
7293 wrapKey = PK11_GetWrapKey(slot, sid->u.ssl3.masterWrapIndex,
7294 sid->u.ssl3.masterWrapMech,
7295 sid->u.ssl3.masterWrapSeries,
7296 ss->pkcs11PinArg);
7297 PK11_FreeSlot(slot);
7298 if (wrapKey == NULL((void*)0)) {
7299 return SECFailure;
7300 }
7301
7302 if (ss->version > SSL_LIBRARY_VERSION_3_00x0300) { /* isTLS */
7303 keyFlags = CKF_SIGN0x00000800UL | CKF_VERIFY0x00002000;
7304 }
7305
7306 *ms = PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech,
7307 NULL((void*)0), &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE0x00000371UL,
7308 CKA_DERIVE0x0000010CUL, SSL3_MASTER_SECRET_LENGTH48, keyFlags);
7309 PK11_FreeSymKey(wrapKey);
7310 if (!*ms) {
7311 return SECFailure;
7312 }
7313 return SECSuccess;
7314}
7315
7316static SECStatus
7317ssl3_HandleServerHelloPart2(sslSocket *ss, const SECItem *sidBytes,
7318 int *retErrCode)
7319{
7320 SSL3AlertDescription desc = handshake_failure;
7321 int errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
7322 SECStatus rv;
7323 PRBool sid_match;
7324 sslSessionID *sid = ss->sec.ci.sid;
7325
7326 if ((ss->opt.requireSafeNegotiation ||
7327 (ss->firstHsDone && (ss->peerRequestedProtection ||
7328 ss->opt.enableRenegotiation ==
7329 SSL_RENEGOTIATE_REQUIRES_XTN((PRBool)2)))) &&
7330 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
7331 desc = handshake_failure;
7332 errCode = ss->firstHsDone ? SSL_ERROR_RENEGOTIATION_NOT_ALLOWED
7333 : SSL_ERROR_UNSAFE_NEGOTIATION;
7334 goto alert_loser;
7335 }
7336
7337 /* Any errors after this point are not "malformed" errors. */
7338 desc = handshake_failure;
7339
7340 /* we need to call ssl3_SetupPendingCipherSpec here so we can check the
7341 * key exchange algorithm. */
7342 rv = ssl3_SetupBothPendingCipherSpecs(ss);
7343 if (rv != SECSuccess) {
7344 goto alert_loser; /* error code is set. */
7345 }
7346
7347 /* We may or may not have sent a session id, we may get one back or
7348 * not and if so it may match the one we sent.
7349 * Attempt to restore the master secret to see if this is so...
7350 * Don't consider failure to find a matching SID an error.
7351 */
7352 sid_match = (PRBool)(sidBytes->len > 0 &&
7353 sidBytes->len ==
7354 sid->u.ssl3.sessionIDLength &&
7355 !PORT_Memcmpmemcmp(sid->u.ssl3.sessionID,
7356 sidBytes->data, sidBytes->len));
7357
7358 if (sid_match) {
7359 if (sid->version != ss->version ||
7360 sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite) {
7361 errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
7362 goto alert_loser;
7363 }
7364 do {
7365 PK11SymKey *masterSecret;
7366
7367 /* [draft-ietf-tls-session-hash-06; Section 5.3]
7368 *
7369 * o If the original session did not use the "extended_master_secret"
7370 * extension but the new ServerHello contains the extension, the
7371 * client MUST abort the handshake.
7372 */
7373 if (!sid->u.ssl3.keys.extendedMasterSecretUsed &&
7374 ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) {
7375 errCode = SSL_ERROR_UNEXPECTED_EXTENDED_MASTER_SECRET;
7376 goto alert_loser;
7377 }
7378
7379 /*
7380 * o If the original session used an extended master secret but the new
7381 * ServerHello does not contain the "extended_master_secret"
7382 * extension, the client SHOULD abort the handshake.
7383 *
7384 * TODO(ekr@rtfm.com): Add option to refuse to resume when EMS is not
7385 * used at all (bug 1176526).
7386 */
7387 if (sid->u.ssl3.keys.extendedMasterSecretUsed &&
7388 !ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) {
7389 errCode = SSL_ERROR_MISSING_EXTENDED_MASTER_SECRET;
7390 goto alert_loser;
7391 }
7392
7393 ss->sec.authType = sid->authType;
7394 ss->sec.authKeyBits = sid->authKeyBits;
7395 ss->sec.keaType = sid->keaType;
7396 ss->sec.keaKeyBits = sid->keaKeyBits;
7397 ss->sec.originalKeaGroup = ssl_LookupNamedGroup(sid->keaGroup);
7398 ss->sec.signatureScheme = sid->sigScheme;
7399
7400 rv = ssl3_UnwrapMasterSecretClient(ss, sid, &masterSecret);
7401 if (rv != SECSuccess) {
7402 break; /* not considered an error */
7403 }
7404
7405 /* Got a Match */
7406 SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_hits);
7407
7408 /* If we sent a session ticket, then this is a stateless resume. */
7409 if (ss->xtnData.sentSessionTicketInClientHello)
7410 SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_stateless_resumes);
7411
7412 if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn))
7413 ss->ssl3.hs.ws = wait_new_session_ticket;
7414 else
7415 ss->ssl3.hs.ws = wait_change_cipher;
7416
7417 ss->ssl3.hs.isResuming = PR_TRUE1;
7418
7419 /* copy the peer cert from the SID */
7420 if (sid->peerCert != NULL((void*)0)) {
7421 ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
7422 }
7423
7424 /* We are re-using the old MS, so no need to derive again. */
7425 rv = ssl3_InitPendingCipherSpecs(ss, masterSecret, PR_FALSE0);
7426 if (rv != SECSuccess) {
7427 goto alert_loser; /* err code was set */
7428 }
7429 return SECSuccess;
7430 } while (0);
7431 }
7432
7433 if (sid_match)
7434 SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_not_ok);
7435 else
7436 SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_misses);
7437
7438 /* We tried to resume a 1.3 session but the server negotiated 1.2. */
7439 if (ss->statelessResume) {
7440 PORT_Assert(sid->version == SSL_LIBRARY_VERSION_TLS_1_3)((sid->version == 0x0304)?((void)0):PR_Assert("sid->version == SSL_LIBRARY_VERSION_TLS_1_3"
,"ssl3con.c",7440))
;
7441 PORT_Assert(ss->ssl3.hs.currentSecret)((ss->ssl3.hs.currentSecret)?((void)0):PR_Assert("ss->ssl3.hs.currentSecret"
,"ssl3con.c",7441))
;
7442
7443 /* Reset resumption state, only used by 1.3 code. */
7444 ss->statelessResume = PR_FALSE0;
7445
7446 /* Clear TLS 1.3 early data traffic key. */
7447 PK11_FreeSymKey(ss->ssl3.hs.currentSecret);
7448 ss->ssl3.hs.currentSecret = NULL((void*)0);
7449 }
7450
7451 /* throw the old one away */
7452 sid->u.ssl3.keys.resumable = PR_FALSE0;
7453 ssl_UncacheSessionID(ss);
7454 ssl_FreeSID(sid);
7455
7456 /* get a new sid */
7457 ss->sec.ci.sid = sid = ssl3_NewSessionID(ss, PR_FALSE0);
7458 if (sid == NULL((void*)0)) {
7459 goto alert_loser; /* memory error is set. */
7460 }
7461
7462 sid->version = ss->version;
7463 sid->u.ssl3.sessionIDLength = sidBytes->len;
7464 if (sidBytes->len > 0) {
7465 PORT_Memcpymemcpy(sid->u.ssl3.sessionID, sidBytes->data, sidBytes->len);
7466 }
7467
7468 sid->u.ssl3.keys.extendedMasterSecretUsed =
7469 ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn);
7470
7471 /* Copy Signed Certificate Timestamps, if any. */
7472 if (ss->xtnData.signedCertTimestamps.len) {
7473 rv = SECITEM_CopyItemSECITEM_CopyItem_Util(NULL((void*)0), &sid->u.ssl3.signedCertTimestamps,
7474 &ss->xtnData.signedCertTimestamps);
7475 ss->xtnData.signedCertTimestamps.len = 0;
7476 if (rv != SECSuccess)
7477 goto loser;
7478 }
7479
7480 ss->ssl3.hs.isResuming = PR_FALSE0;
7481 if (ss->ssl3.hs.kea_def->authKeyType != ssl_auth_null) {
7482 /* All current cipher suites other than those with ssl_auth_null (i.e.,
7483 * (EC)DH_anon_* suites) require a certificate, so use that signal. */
7484 ss->ssl3.hs.ws = wait_server_cert;
7485 } else {
7486 /* All the remaining cipher suites must be (EC)DH_anon_* and so
7487 * must be ephemeral. Note, if we ever add PSK this might
7488 * change. */
7489 PORT_Assert(ss->ssl3.hs.kea_def->ephemeral)((ss->ssl3.hs.kea_def->ephemeral)?((void)0):PR_Assert("ss->ssl3.hs.kea_def->ephemeral"
,"ssl3con.c",7489))
;
7490 ss->ssl3.hs.ws = wait_server_key;
7491 }
7492 return SECSuccess;
7493
7494alert_loser:
7495 (void)SSL3_SendAlert(ss, alert_fatal, desc);
7496
7497loser:
7498 *retErrCode = errCode;
7499 return SECFailure;
7500}
7501
7502static SECStatus
7503ssl_HandleDHServerKeyExchange(sslSocket *ss, PRUint8 *b, PRUint32 length)
7504{
7505 SECStatus rv;
7506 int errCode = SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH;
7507 SSL3AlertDescription desc = illegal_parameter;
7508 SSLHashType hashAlg;
7509 PRBool isTLS = ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_00x0300;
7510 SSLSignatureScheme sigScheme;
7511
7512 SECItem dh_p = { siBuffer, NULL((void*)0), 0 };
7513 SECItem dh_g = { siBuffer, NULL((void*)0), 0 };
7514 SECItem dh_Ys = { siBuffer, NULL((void*)0), 0 };
7515 unsigned dh_p_bits;
7516 unsigned dh_g_bits;
7517 PRInt32 minDH = 0;
7518 PRInt32 optval;
7519
7520 SSL3Hashes hashes;
7521 SECItem signature = { siBuffer, NULL((void*)0), 0 };
7522 PLArenaPool *arena = NULL((void*)0);
7523 SECKEYPublicKey *peerKey = NULL((void*)0);
7524
7525 rv = ssl3_ConsumeHandshakeVariable(ss, &dh_p, 2, &b, &length);
7526 if (rv != SECSuccess) {
7527 goto loser; /* malformed. */
7528 }
7529 rv = NSS_OptionGet(NSS_KEY_SIZE_POLICY_FLAGS0x00e, &optval);
7530 if ((rv == SECSuccess) && (optval & NSS_KEY_SIZE_POLICY_SSL_FLAG1)) {
7531 (void)NSS_OptionGet(NSS_DH_MIN_KEY_SIZE0x002, &minDH);
7532 }
7533
7534 if (minDH <= 0) {
7535 minDH = SSL_DH_MIN_P_BITS1023;
7536 }
7537 dh_p_bits = SECKEY_BigIntegerBitLength(&dh_p);
7538 if (dh_p_bits < (unsigned)minDH) {
7539 errCode = SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY;
7540 goto alert_loser;
7541 }
7542 if (dh_p_bits > SSL_MAX_DH_KEY_BITS8192) {
7543 errCode = SSL_ERROR_DH_KEY_TOO_LONG;
7544 goto alert_loser;
7545 }
7546 rv = ssl3_ConsumeHandshakeVariable(ss, &dh_g, 2, &b, &length);
7547 if (rv != SECSuccess) {
7548 goto loser; /* malformed. */
7549 }
7550 /* Abort if dh_g is 0, 1, or obviously too big. */
7551 dh_g_bits = SECKEY_BigIntegerBitLength(&dh_g);
7552 if (dh_g_bits > dh_p_bits || dh_g_bits <= 1) {
7553 goto alert_loser;
7554 }
7555 if (ss->opt.requireDHENamedGroups) {
7556 /* If we're doing named groups, make sure it's good. */
7557 rv = ssl_ValidateDHENamedGroup(ss, &dh_p, &dh_g, NULL((void*)0), NULL((void*)0));
7558 if (rv != SECSuccess) {
7559 errCode = SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY;
7560 goto alert_loser;
7561 }
7562 }
7563
7564 rv = ssl3_ConsumeHandshakeVariable(ss, &dh_Ys, 2, &b, &length);
7565 if (rv != SECSuccess) {
7566 goto loser; /* malformed. */
7567 }
7568 if (!ssl_IsValidDHEShare(&dh_p, &dh_Ys)) {
7569 errCode = SSL_ERROR_RX_MALFORMED_DHE_KEY_SHARE;
7570 goto alert_loser;
7571 }
7572
7573 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_20x0303) {
7574 rv = ssl_ConsumeSignatureScheme(ss, &b, &length, &sigScheme);
7575 if (rv != SECSuccess) {
7576 goto loser; /* alert already sent */
7577 }
7578 rv = ssl_CheckSignatureSchemeConsistency(
7579 ss, sigScheme, &ss->sec.peerCert->subjectPublicKeyInfo);
7580 if (rv != SECSuccess) {
7581 goto alert_loser;
7582 }
7583 hashAlg = ssl_SignatureSchemeToHashType(sigScheme);
7584 } else {
7585 /* Use ssl_hash_none to represent the MD5+SHA1 combo. */
7586 hashAlg = ssl_hash_none;
7587 sigScheme = ssl_sig_none;
7588 }
7589 rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length);
7590 if (rv != SECSuccess) {
7591 goto loser; /* malformed. */
7592 }
7593 if (length != 0) {
7594 if (isTLS) {
7595 desc = decode_error;
7596 }
7597 goto alert_loser; /* malformed. */
7598 }
7599
7600 PRINT_BUF(60, (NULL, "Server DH p", dh_p.data, dh_p.len))if (ssl_trace >= (60)) ssl_PrintBuf (((void*)0), "Server DH p"
, dh_p.data, dh_p.len)
;
7601 PRINT_BUF(60, (NULL, "Server DH g", dh_g.data, dh_g.len))if (ssl_trace >= (60)) ssl_PrintBuf (((void*)0), "Server DH g"
, dh_g.data, dh_g.len)
;
7602 PRINT_BUF(60, (NULL, "Server DH Ys", dh_Ys.data, dh_Ys.len))if (ssl_trace >= (60)) ssl_PrintBuf (((void*)0), "Server DH Ys"
, dh_Ys.data, dh_Ys.len)
;
7603
7604 /* failures after this point are not malformed handshakes. */
7605 /* TLS: send decrypt_error if signature failed. */
7606 desc = isTLS ? decrypt_error : handshake_failure;
7607
7608 /*
7609 * Check to make sure the hash is signed by right guy.
7610 */
7611 rv = ssl3_ComputeDHKeyHash(ss, hashAlg, &hashes,
7612 dh_p, dh_g, dh_Ys, PR_FALSE0 /* padY */);
7613 if (rv != SECSuccess) {
7614 errCode =
7615 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
7616 goto alert_loser;
7617 }
7618 rv = ssl3_VerifySignedHashes(ss, sigScheme, &hashes, &signature);
7619 if (rv != SECSuccess) {
7620 errCode =
7621 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
7622 goto alert_loser;
7623 }
7624
7625 /*
7626 * we really need to build a new key here because we can no longer
7627 * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate
7628 * pkcs11 slots and ID's.
7629 */
7630 arena = PORT_NewArenaPORT_NewArena_Util(DER_DEFAULT_CHUNKSIZE(2048));
7631 if (arena == NULL((void*)0)) {
7632 errCode = SEC_ERROR_NO_MEMORY;
7633 goto loser;
7634 }
7635
7636 peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey)(SECKEYPublicKey *)PORT_ArenaZAlloc_Util(arena, sizeof(SECKEYPublicKey
))
;
7637 if (peerKey == NULL((void*)0)) {
7638 errCode = SEC_ERROR_NO_MEMORY;
7639 goto loser;
7640 }
7641
7642 peerKey->arena = arena;
7643 peerKey->keyType = dhKey;
7644 peerKey->pkcs11Slot = NULL((void*)0);
7645 peerKey->pkcs11ID = CK_INVALID_HANDLE0;
7646
7647 if (SECITEM_CopyItemSECITEM_CopyItem_Util(arena, &peerKey->u.dh.prime, &dh_p) ||
7648 SECITEM_CopyItemSECITEM_CopyItem_Util(arena, &peerKey->u.dh.base, &dh_g) ||
7649 SECITEM_CopyItemSECITEM_CopyItem_Util(arena, &peerKey->u.dh.publicValue, &dh_Ys)) {
7650 errCode = SEC_ERROR_NO_MEMORY;
7651 goto loser;
7652 }
7653 ss->sec.peerKey = peerKey;
7654 return SECSuccess;
7655
7656alert_loser:
7657 (void)SSL3_SendAlert(ss, alert_fatal, desc);
7658loser:
7659 if (arena) {
7660 PORT_FreeArenaPORT_FreeArena_Util(arena, PR_FALSE0);
7661 }
7662 PORT_SetErrorPORT_SetError_Util(ssl_MapLowLevelError(errCode));
7663 return SECFailure;
7664}
7665
7666/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered a
7667 * complete ssl3 ServerKeyExchange message.
7668 * Caller must hold Handshake and RecvBuf locks.
7669 */
7670static SECStatus
7671ssl3_HandleServerKeyExchange(sslSocket *ss, PRUint8 *b, PRUint32 length)
7672{
7673 SECStatus rv;
7674
7675 SSL_TRC(3, ("%d: SSL3[%d]: handle server_key_exchange handshake",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: handle server_key_exchange handshake"
, getpid(), ss->fd)
7676 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: handle server_key_exchange handshake"
, getpid(), ss->fd)
;
7677 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->recvBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveRecvBufLock(ss)"
,"ssl3con.c",7677))
;
7678 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",7678))
;
7679
7680 if (ss->ssl3.hs.ws != wait_server_key) {
7681 SSL3_SendAlert(ss, alert_fatal, unexpected_message);
7682 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH);
7683 return SECFailure;
7684 }
7685
7686 switch (ss->ssl3.hs.kea_def->exchKeyType) {
7687 case ssl_kea_dh:
7688 rv = ssl_HandleDHServerKeyExchange(ss, b, length);
7689 break;
7690
7691 case ssl_kea_ecdh:
7692 rv = ssl3_HandleECDHServerKeyExchange(ss, b, length);
7693 break;
7694
7695 default:
7696 SSL3_SendAlert(ss, alert_fatal, handshake_failure);
7697 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_UNSUPPORTED_KEYALG);
7698 rv = SECFailure;
7699 break;
7700 }
7701
7702 if (rv == SECSuccess) {
7703 ss->ssl3.hs.ws = wait_cert_request;
7704 }
7705 /* All Handle*ServerKeyExchange functions set the error code. */
7706 return rv;
7707}
7708
7709typedef struct dnameNode {
7710 struct dnameNode *next;
7711 SECItem name;
7712} dnameNode;
7713
7714/*
7715 * Parse the ca_list structure in a CertificateRequest.
7716 *
7717 * Called from:
7718 * ssl3_HandleCertificateRequest
7719 * tls13_HandleCertificateRequest
7720 */
7721SECStatus
7722ssl3_ParseCertificateRequestCAs(sslSocket *ss, PRUint8 **b, PRUint32 *length,
7723 CERTDistNames *ca_list)
7724{
7725 PRUint32 remaining;
7726 int nnames = 0;
7727 dnameNode *node;
7728 SECStatus rv;
7729 int i;
7730
7731 rv = ssl3_ConsumeHandshakeNumber(ss, &remaining, 2, b, length);
7732 if (rv != SECSuccess)
7733 return SECFailure; /* malformed, alert has been sent */
7734
7735 if (remaining > *length)
7736 goto alert_loser;
7737
7738 ca_list->head = node = PORT_ArenaZNew(ca_list->arena, dnameNode)(dnameNode *)PORT_ArenaZAlloc_Util(ca_list->arena, sizeof(
dnameNode))
;
7739 if (node == NULL((void*)0))
7740 goto no_mem;
7741
7742 while (remaining > 0) {
7743 PRUint32 len;
7744
7745 if (remaining < 2)
7746 goto alert_loser; /* malformed */
7747
7748 rv = ssl3_ConsumeHandshakeNumber(ss, &len, 2, b, length);
7749 if (rv != SECSuccess)
7750 return SECFailure; /* malformed, alert has been sent */
7751 if (len == 0 || remaining < len + 2)
7752 goto alert_loser; /* malformed */
7753
7754 remaining -= 2;
7755 if (SECITEM_MakeItem(ca_list->arena, &node->name, *b, len) != SECSuccess) {
7756 goto no_mem;
7757 }
7758 node->name.len = len;
7759 *b += len;
7760 *length -= len;
7761 remaining -= len;
7762 nnames++;
7763 if (remaining <= 0)
7764 break; /* success */
7765
7766 node->next = PORT_ArenaZNew(ca_list->arena, dnameNode)(dnameNode *)PORT_ArenaZAlloc_Util(ca_list->arena, sizeof(
dnameNode))
;
7767 node = node->next;
7768 if (node == NULL((void*)0))
7769 goto no_mem;
7770 }
7771
7772 ca_list->nnames = nnames;
7773 ca_list->names = PORT_ArenaNewArray(ca_list->arena, SECItem, nnames)(SECItem *)PORT_ArenaAlloc_Util(ca_list->arena, sizeof(SECItem
) * (nnames))
;
7774 if (nnames > 0 && ca_list->names == NULL((void*)0))
7775 goto no_mem;
7776
7777 for (i = 0, node = (dnameNode *)ca_list->head;
7778 i < nnames;
7779 i++, node = node->next) {
7780 ca_list->names[i] = node->name;
7781 }
7782
7783 return SECSuccess;
7784
7785no_mem:
7786 return SECFailure;
7787
7788alert_loser:
7789 (void)SSL3_SendAlert(ss, alert_fatal,
7790 ss->version < SSL_LIBRARY_VERSION_TLS_1_00x0301 ? illegal_parameter
7791 : decode_error);
7792 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CERT_REQUEST);
7793 return SECFailure;
7794}
7795
7796SECStatus
7797ssl_ParseSignatureSchemes(const sslSocket *ss, PLArenaPool *arena,
7798 SSLSignatureScheme **schemesOut,
7799 unsigned int *numSchemesOut,
7800 unsigned char **b, unsigned int *len)
7801{
7802 SECStatus rv;
7803 SECItem buf;
7804 SSLSignatureScheme *schemes = NULL((void*)0);
7805 unsigned int numSupported = 0;
7806 unsigned int numRemaining = 0;
7807 unsigned int max;
7808
7809 rv = ssl3_ExtConsumeHandshakeVariable(ss, &buf, 2, b, len);
7810 if (rv != SECSuccess) {
7811 return SECFailure;
7812 }
7813 /* An odd-length value is invalid. */
7814 if ((buf.len & 1) != 0) {
7815 ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
7816 return SECFailure;
7817 }
7818
7819 /* Let the caller decide whether to alert here. */
7820 if (buf.len == 0) {
7821 goto done;
7822 }
7823
7824 /* Limit the number of schemes we read. */
7825 numRemaining = buf.len / 2;
7826 max = PR_MIN(numRemaining, MAX_SIGNATURE_SCHEMES)((numRemaining)<(18)?(numRemaining):(18));
7827
7828 if (arena) {
7829 schemes = PORT_ArenaZNewArray(arena, SSLSignatureScheme, max)(SSLSignatureScheme *)PORT_ArenaZAlloc_Util(arena, sizeof(SSLSignatureScheme
) * (max))
;
7830 } else {
7831 schemes = PORT_ZNewArray(SSLSignatureScheme, max)(SSLSignatureScheme *)PORT_ZAlloc_Util(sizeof(SSLSignatureScheme
) * (max))
;
7832 }
7833 if (!schemes) {
7834 ssl3_ExtSendAlert(ss, alert_fatal, internal_error);
7835 return SECFailure;
7836 }
7837
7838 for (; numRemaining && numSupported < MAX_SIGNATURE_SCHEMES18; --numRemaining) {
7839 PRUint32 tmp;
7840 rv = ssl3_ExtConsumeHandshakeNumber(ss, &tmp, 2, &buf.data, &buf.len);
7841 if (rv != SECSuccess) {
7842 PORT_Assert(0)((0)?((void)0):PR_Assert("0","ssl3con.c",7842));
7843 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
7844 return SECFailure;
7845 }
7846 if (ssl_SignatureSchemeValid((SSLSignatureScheme)tmp, SEC_OID_UNKNOWN,
7847 (PRBool)ss->version >= SSL_LIBRARY_VERSION_TLS_1_30x0304)) {
7848 ;
7849 schemes[numSupported++] = (SSLSignatureScheme)tmp;
7850 }
7851 }
7852
7853 if (!numSupported) {
7854 if (!arena) {
7855 PORT_FreePORT_Free_Util(schemes);
7856 }
7857 schemes = NULL((void*)0);
7858 }
7859
7860done:
7861 *schemesOut = schemes;
7862 *numSchemesOut = numSupported;
7863 return SECSuccess;
7864}
7865
7866/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
7867 * a complete ssl3 Certificate Request message.
7868 * Caller must hold Handshake and RecvBuf locks.
7869 */
7870static SECStatus
7871ssl3_HandleCertificateRequest(sslSocket *ss, PRUint8 *b, PRUint32 length)
7872{
7873 PLArenaPool *arena = NULL((void*)0);
7874 PRBool isTLS = PR_FALSE0;
7875 PRBool isTLS12 = PR_FALSE0;
7876 int errCode = SSL_ERROR_RX_MALFORMED_CERT_REQUEST;
7877 SECStatus rv;
7878 SSL3AlertDescription desc = illegal_parameter;
7879 SECItem cert_types = { siBuffer, NULL((void*)0), 0 };
7880 SSLSignatureScheme *signatureSchemes = NULL((void*)0);
1
'signatureSchemes' initialized to a null pointer value
7881 unsigned int signatureSchemeCount = 0;
7882 CERTDistNames ca_list;
7883
7884 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_request handshake",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: handle certificate_request handshake"
, getpid(), ss->fd)
2
Assuming 'ssl_trace' is < 3
7885 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: handle certificate_request handshake"
, getpid(), ss->fd)
;
7886 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->recvBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveRecvBufLock(ss)"
,"ssl3con.c",7886))
;
3
Taking false branch
4
Assuming field 'noLocks' is not equal to 0
7887 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",7887))
;
7888
7889 if (ss->ssl3.hs.ws != wait_cert_request) {
5
Assuming field 'ws' is equal to wait_cert_request
7890 desc = unexpected_message;
7891 errCode = SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST;
7892 goto alert_loser;
7893 }
7894
7895 PORT_Assert(ss->ssl3.clientCertChain == NULL)((ss->ssl3.clientCertChain == ((void*)0))?((void)0):PR_Assert
("ss->ssl3.clientCertChain == NULL","ssl3con.c",7895))
;
6
Taking false branch
7
Assuming field 'clientCertChain' is equal to null
8
'?' condition is true
7896 PORT_Assert(ss->ssl3.clientCertificate == NULL)((ss->ssl3.clientCertificate == ((void*)0))?((void)0):PR_Assert
("ss->ssl3.clientCertificate == NULL","ssl3con.c",7896))
;
9
Assuming field 'clientCertificate' is equal to null
10
'?' condition is true
7897 PORT_Assert(ss->ssl3.clientPrivateKey == NULL)((ss->ssl3.clientPrivateKey == ((void*)0))?((void)0):PR_Assert
("ss->ssl3.clientPrivateKey == NULL","ssl3con.c",7897))
;
11
Assuming field 'clientPrivateKey' is equal to null
12
'?' condition is true
7898
7899 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_00x0300);
13
Assuming field 'version' is <= SSL_LIBRARY_VERSION_3_0
7900 isTLS12 = (PRBool)(ss->ssl3.prSpec->version
13.1
Field 'version' is < SSL_LIBRARY_VERSION_TLS_1_2
>= SSL_LIBRARY_VERSION_TLS_1_20x0303);
7901 rv = ssl3_ConsumeHandshakeVariable(ss, &cert_types, 1, &b, &length);
7902 if (rv
13.2
'rv' is equal to SECSuccess
!= SECSuccess)
14
Taking false branch
7903 goto loser; /* malformed, alert has been sent */
7904
7905 arena = ca_list.arena = PORT_NewArenaPORT_NewArena_Util(DER_DEFAULT_CHUNKSIZE(2048));
7906 if (arena == NULL((void*)0))
15
Assuming 'arena' is not equal to NULL
16
Taking false branch
7907 goto no_mem;
7908
7909 if (isTLS12
16.1
'isTLS12' is 0
) {
17
Taking false branch
7910 rv = ssl_ParseSignatureSchemes(ss, arena,
7911 &signatureSchemes,
7912 &signatureSchemeCount,
7913 &b, &length);
7914 if (rv != SECSuccess) {
7915 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CERT_REQUEST);
7916 goto loser; /* malformed, alert has been sent */
7917 }
7918 if (signatureSchemeCount == 0) {
7919 errCode = SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM;
7920 desc = handshake_failure;
7921 goto alert_loser;
7922 }
7923 }
7924
7925 rv = ssl3_ParseCertificateRequestCAs(ss, &b, &length, &ca_list);
7926 if (rv != SECSuccess)
18
Assuming 'rv' is equal to SECSuccess
19
Taking false branch
7927 goto done; /* alert sent in ssl3_ParseCertificateRequestCAs */
7928
7929 if (length != 0)
20
Assuming 'length' is equal to 0
21
Taking false branch
7930 goto alert_loser; /* malformed */
7931
7932 ss->ssl3.hs.ws = wait_hello_done;
7933
7934 rv = ssl3_BeginHandleCertificateRequest(ss, signatureSchemes,
22
Passing null pointer value via 2nd parameter 'signatureSchemes'
23
Calling 'ssl3_BeginHandleCertificateRequest'
7935 signatureSchemeCount, &ca_list);
7936 if (rv != SECSuccess) {
7937 PORT_Assert(0)((0)?((void)0):PR_Assert("0","ssl3con.c",7937));
7938 errCode = SEC_ERROR_LIBRARY_FAILURE;
7939 desc = internal_error;
7940 goto alert_loser;
7941 }
7942 goto done;
7943
7944no_mem:
7945 rv = SECFailure;
7946 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_NO_MEMORY);
7947 goto done;
7948
7949alert_loser:
7950 if (isTLS && desc == illegal_parameter)
7951 desc = decode_error;
7952 (void)SSL3_SendAlert(ss, alert_fatal, desc);
7953loser:
7954 PORT_SetErrorPORT_SetError_Util(errCode);
7955 rv = SECFailure;
7956done:
7957 if (arena != NULL((void*)0))
7958 PORT_FreeArenaPORT_FreeArena_Util(arena, PR_FALSE0);
7959 return rv;
7960}
7961
7962static void
7963ssl3_ClientAuthCallbackOutcome(sslSocket *ss, SECStatus outcome)
7964{
7965 SECStatus rv;
7966 switch (outcome) {
7967 case SECSuccess:
7968 /* check what the callback function returned */
7969 if ((!ss->ssl3.clientCertificate) || (!ss->ssl3.clientPrivateKey)) {
7970 /* we are missing either the key or cert */
7971 goto send_no_certificate;
7972 }
7973 /* Setting ssl3.clientCertChain non-NULL will cause
7974 * ssl3_HandleServerHelloDone to call SendCertificate.
7975 */
7976 ss->ssl3.clientCertChain = CERT_CertChainFromCert(
7977 ss->ssl3.clientCertificate,
7978 certUsageSSLClient, PR_FALSE0);
7979 if (ss->ssl3.clientCertChain == NULL((void*)0)) {
7980 goto send_no_certificate;
7981 }
7982 if (ss->ssl3.hs.hashType == handshake_hash_record ||
7983 ss->ssl3.hs.hashType == handshake_hash_single) {
7984 rv = ssl_PickClientSignatureScheme(ss,
7985 ss->ssl3.clientCertificate,
7986 ss->ssl3.clientPrivateKey,
7987 ss->ssl3.hs.clientAuthSignatureSchemes,
7988 ss->ssl3.hs.clientAuthSignatureSchemesLen,
7989 &ss->ssl3.hs.signatureScheme);
7990 if (rv != SECSuccess) {
7991 /* This should only happen if our schemes changed or
7992 * if an RSA-PSS cert was selected, but the token
7993 * does not support PSS schemes.
7994 */
7995 goto send_no_certificate;
7996 }
7997 }
7998 break;
7999
8000 case SECFailure:
8001 default:
8002 send_no_certificate:
8003 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
8004 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
8005 ss->ssl3.clientCertificate = NULL((void*)0);
8006 ss->ssl3.clientPrivateKey = NULL((void*)0);
8007 if (ss->ssl3.clientCertChain) {
8008 CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
8009 ss->ssl3.clientCertChain = NULL((void*)0);
8010 }
8011
8012 if (ss->version > SSL_LIBRARY_VERSION_3_00x0300) {
8013 ss->ssl3.sendEmptyCert = PR_TRUE1;
8014 } else {
8015 (void)SSL3_SendAlert(ss, alert_warning, no_certificate);
8016 }
8017 break;
8018 }
8019
8020 /* Release the cached parameters */
8021 PORT_FreePORT_Free_Util(ss->ssl3.hs.clientAuthSignatureSchemes);
8022 ss->ssl3.hs.clientAuthSignatureSchemes = NULL((void*)0);
8023 ss->ssl3.hs.clientAuthSignatureSchemesLen = 0;
8024}
8025
8026SECStatus
8027ssl3_BeginHandleCertificateRequest(sslSocket *ss,
8028 const SSLSignatureScheme *signatureSchemes,
8029 unsigned int signatureSchemeCount,
8030 CERTDistNames *ca_list)
8031{
8032 SECStatus rv;
8033
8034 PR_ASSERT(!ss->ssl3.hs.clientCertificatePending)((!ss->ssl3.hs.clientCertificatePending)?((void)0):PR_Assert
("!ss->ssl3.hs.clientCertificatePending","ssl3con.c",8034)
)
;
24
Assuming field 'clientCertificatePending' is 0
25
'?' condition is true
8035
8036 /* Should not send a client cert when (non-GREASE) ECH is rejected. */
8037 if (ss->ssl3.hs.echHpkeCtx && !ss->ssl3.hs.echAccepted) {
26
Assuming field 'echHpkeCtx' is null
8038 PORT_Assert(ssl3_ExtensionAdvertised(ss, ssl_tls13_encrypted_client_hello_xtn))((ssl3_ExtensionAdvertised(ss, ssl_tls13_encrypted_client_hello_xtn
))?((void)0):PR_Assert("ssl3_ExtensionAdvertised(ss, ssl_tls13_encrypted_client_hello_xtn)"
,"ssl3con.c",8038))
;
8039 rv = SECFailure;
8040 } else if (ss->getClientAuthData != NULL((void*)0)) {
27
Assuming field 'getClientAuthData' is not equal to NULL
8041 PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==(((ss->ssl3.hs.preliminaryInfo & ((1U << 0) | (1U
<< 1) | (1U << 4))) == ((1U << 0) | (1U <<
1) | (1U << 4)))?((void)0):PR_Assert("(ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) == ssl_preinfo_all"
,"ssl3con.c",8042))
28
Taking true branch
29
Assuming the condition is true
30
'?' condition is true
8042 ssl_preinfo_all)(((ss->ssl3.hs.preliminaryInfo & ((1U << 0) | (1U
<< 1) | (1U << 4))) == ((1U << 0) | (1U <<
1) | (1U << 4)))?((void)0):PR_Assert("(ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) == ssl_preinfo_all"
,"ssl3con.c",8042))
;
8043 PORT_Assert(ss->ssl3.clientPrivateKey == NULL)((ss->ssl3.clientPrivateKey == ((void*)0))?((void)0):PR_Assert
("ss->ssl3.clientPrivateKey == NULL","ssl3con.c",8043))
;
31
Assuming field 'clientPrivateKey' is equal to null
32
'?' condition is true
8044 PORT_Assert(ss->ssl3.clientCertificate == NULL)((ss->ssl3.clientCertificate == ((void*)0))?((void)0):PR_Assert
("ss->ssl3.clientCertificate == NULL","ssl3con.c",8044))
;
33
Assuming field 'clientCertificate' is equal to null
34
'?' condition is true
8045 PORT_Assert(ss->ssl3.clientCertChain == NULL)((ss->ssl3.clientCertChain == ((void*)0))?((void)0):PR_Assert
("ss->ssl3.clientCertChain == NULL","ssl3con.c",8045))
;
35
Assuming field 'clientCertChain' is equal to null
36
'?' condition is true
8046
8047 /* Previously cached parameters should be empty */
8048 PORT_Assert(ss->ssl3.hs.clientAuthSignatureSchemes == NULL)((ss->ssl3.hs.clientAuthSignatureSchemes == ((void*)0))?((
void)0):PR_Assert("ss->ssl3.hs.clientAuthSignatureSchemes == NULL"
,"ssl3con.c",8048))
;
37
Assuming field 'clientAuthSignatureSchemes' is equal to null
38
'?' condition is true
8049 PORT_Assert(ss->ssl3.hs.clientAuthSignatureSchemesLen == 0)((ss->ssl3.hs.clientAuthSignatureSchemesLen == 0)?((void)0
):PR_Assert("ss->ssl3.hs.clientAuthSignatureSchemesLen == 0"
,"ssl3con.c",8049))
;
39
Assuming field 'clientAuthSignatureSchemesLen' is equal to 0
40
'?' condition is true
8050 /*
8051 * Peer signatures are only available while in the context of
8052 * of a getClientAuthData callback. It is required for proper
8053 * functioning of SSL_CertIsUsable and SSL_FilterClientCertListBySocket
8054 * Calling these functions outside the context of a getClientAuthData
8055 * callback will result in no filtering.*/
8056
8057 ss->ssl3.hs.clientAuthSignatureSchemes = PORT_ZNewArray(SSLSignatureScheme, signatureSchemeCount)(SSLSignatureScheme *)PORT_ZAlloc_Util(sizeof(SSLSignatureScheme
) * (signatureSchemeCount))
;
8058 PORT_Memcpymemcpy(ss->ssl3.hs.clientAuthSignatureSchemes, signatureSchemes, signatureSchemeCount * sizeof(SSLSignatureScheme));
41
Null pointer passed to 2nd parameter expecting 'nonnull'
8059 ss->ssl3.hs.clientAuthSignatureSchemesLen = signatureSchemeCount;
8060
8061 rv = (SECStatus)(*ss->getClientAuthData)(ss->getClientAuthDataArg,
8062 ss->fd, ca_list,
8063 &ss->ssl3.clientCertificate,
8064 &ss->ssl3.clientPrivateKey);
8065 } else {
8066 rv = SECFailure; /* force it to send a no_certificate alert */
8067 }
8068
8069 if (rv == SECWouldBlock) {
8070 /* getClientAuthData needs more time (e.g. for user interaction) */
8071
8072 /* The out parameters should not have changed. */
8073 PORT_Assert(ss->ssl3.clientCertificate == NULL)((ss->ssl3.clientCertificate == ((void*)0))?((void)0):PR_Assert
("ss->ssl3.clientCertificate == NULL","ssl3con.c",8073))
;
8074 PORT_Assert(ss->ssl3.clientPrivateKey == NULL)((ss->ssl3.clientPrivateKey == ((void*)0))?((void)0):PR_Assert
("ss->ssl3.clientPrivateKey == NULL","ssl3con.c",8074))
;
8075
8076 /* Mark the handshake as blocked */
8077 ss->ssl3.hs.clientCertificatePending = PR_TRUE1;
8078
8079 rv = SECSuccess;
8080 } else {
8081 /* getClientAuthData returned SECSuccess or SECFailure immediately, handle accordingly */
8082 ssl3_ClientAuthCallbackOutcome(ss, rv);
8083 rv = SECSuccess;
8084 }
8085 return rv;
8086}
8087
8088/* Invoked by the application when client certificate selection is complete */
8089SECStatus
8090ssl3_ClientCertCallbackComplete(sslSocket *ss, SECStatus outcome, SECKEYPrivateKey *clientPrivateKey, CERTCertificate *clientCertificate)
8091{
8092 PORT_Assert(ss->ssl3.hs.clientCertificatePending)((ss->ssl3.hs.clientCertificatePending)?((void)0):PR_Assert
("ss->ssl3.hs.clientCertificatePending","ssl3con.c",8092))
;
8093 ss->ssl3.hs.clientCertificatePending = PR_FALSE0;
8094
8095 ss->ssl3.clientCertificate = clientCertificate;
8096 ss->ssl3.clientPrivateKey = clientPrivateKey;
8097
8098 ssl3_ClientAuthCallbackOutcome(ss, outcome);
8099
8100 /* Continue the handshake */
8101 PORT_Assert(ss->ssl3.hs.restartTarget)((ss->ssl3.hs.restartTarget)?((void)0):PR_Assert("ss->ssl3.hs.restartTarget"
,"ssl3con.c",8101))
;
8102 if (!ss->ssl3.hs.restartTarget) {
8103 FATAL_ERROR(ss, PR_INVALID_STATE_ERROR, internal_error)do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, (-5931L), __func__, "ssl3con.c", 8103)
; PORT_SetError_Util((-5931L)); } while (0); tls13_FatalError
(ss, (-5931L), internal_error); } while (0)
;
8104 return SECFailure;
8105 }
8106 sslRestartTarget target = ss->ssl3.hs.restartTarget;
8107 ss->ssl3.hs.restartTarget = NULL((void*)0);
8108 return target(ss);
8109}
8110
8111static SECStatus
8112ssl3_CheckFalseStart(sslSocket *ss)
8113{
8114 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",8114))
;
8115 PORT_Assert(!ss->ssl3.hs.authCertificatePending)((!ss->ssl3.hs.authCertificatePending)?((void)0):PR_Assert
("!ss->ssl3.hs.authCertificatePending","ssl3con.c",8115))
;
8116 PORT_Assert(!ss->ssl3.hs.canFalseStart)((!ss->ssl3.hs.canFalseStart)?((void)0):PR_Assert("!ss->ssl3.hs.canFalseStart"
,"ssl3con.c",8116))
;
8117
8118 if (!ss->canFalseStartCallback) {
8119 SSL_TRC(3, ("%d: SSL[%d]: no false start callback so no false start",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL[%d]: no false start callback so no false start"
, getpid(), ss->fd)
8120 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL[%d]: no false start callback so no false start"
, getpid(), ss->fd)
;
8121 } else {
8122 SECStatus rv;
8123
8124 rv = ssl_CheckServerRandom(ss);
8125 if (rv != SECSuccess) {
8126 SSL_TRC(3, ("%d: SSL[%d]: no false start due to possible downgrade",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL[%d]: no false start due to possible downgrade"
, getpid(), ss->fd)
8127 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL[%d]: no false start due to possible downgrade"
, getpid(), ss->fd)
;
8128 goto no_false_start;
8129 }
8130
8131 /* An attacker can control the selected ciphersuite so we only wish to
8132 * do False Start in the case that the selected ciphersuite is
8133 * sufficiently strong that the attack can gain no advantage.
8134 * Therefore we always require an 80-bit cipher. */
8135 ssl_GetSpecReadLock(ss){ if (!ss->opt.noLocks) NSSRWLock_LockRead_Util((ss)->specLock
); }
;
8136 PRBool weakCipher = ss->ssl3.cwSpec->cipherDef->secret_key_size < 10;
8137 ssl_ReleaseSpecReadLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockRead_Util((ss)->
specLock); }
;
8138 if (weakCipher) {
8139 SSL_TRC(3, ("%d: SSL[%d]: no false start due to weak cipher",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL[%d]: no false start due to weak cipher"
, getpid(), ss->fd)
8140 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL[%d]: no false start due to weak cipher"
, getpid(), ss->fd)
;
8141 goto no_false_start;
8142 }
8143
8144 if (ssl3_ExtensionAdvertised(ss, ssl_tls13_encrypted_client_hello_xtn)) {
8145 SSL_TRC(3, ("%d: SSL[%d]: no false start due to lower version after ECH",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL[%d]: no false start due to lower version after ECH"
, getpid(), ss->fd)
8146 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL[%d]: no false start due to lower version after ECH"
, getpid(), ss->fd)
;
8147 goto no_false_start;
8148 }
8149
8150 PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==(((ss->ssl3.hs.preliminaryInfo & ((1U << 0) | (1U
<< 1) | (1U << 4))) == ((1U << 0) | (1U <<
1) | (1U << 4)))?((void)0):PR_Assert("(ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) == ssl_preinfo_all"
,"ssl3con.c",8151))
8151 ssl_preinfo_all)(((ss->ssl3.hs.preliminaryInfo & ((1U << 0) | (1U
<< 1) | (1U << 4))) == ((1U << 0) | (1U <<
1) | (1U << 4)))?((void)0):PR_Assert("(ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) == ssl_preinfo_all"
,"ssl3con.c",8151))
;
8152 rv = (ss->canFalseStartCallback)(ss->fd,
8153 ss->canFalseStartCallbackData,
8154 &ss->ssl3.hs.canFalseStart);
8155 if (rv == SECSuccess) {
8156 SSL_TRC(3, ("%d: SSL[%d]: false start callback returned %s",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL[%d]: false start callback returned %s"
, getpid(), ss->fd, ss->ssl3.hs.canFalseStart ? "TRUE" :
"FALSE")
8157 SSL_GETPID(), ss->fd,if (ssl_trace >= (3)) ssl_Trace ("%d: SSL[%d]: false start callback returned %s"
, getpid(), ss->fd, ss->ssl3.hs.canFalseStart ? "TRUE" :
"FALSE")
8158 ss->ssl3.hs.canFalseStart ? "TRUE"if (ssl_trace >= (3)) ssl_Trace ("%d: SSL[%d]: false start callback returned %s"
, getpid(), ss->fd, ss->ssl3.hs.canFalseStart ? "TRUE" :
"FALSE")
8159 : "FALSE"))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL[%d]: false start callback returned %s"
, getpid(), ss->fd, ss->ssl3.hs.canFalseStart ? "TRUE" :
"FALSE")
;
8160 } else {
8161 SSL_TRC(3, ("%d: SSL[%d]: false start callback failed (%s)",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL[%d]: false start callback failed (%s)"
, getpid(), ss->fd, PR_ErrorToName(PR_GetError()))
8162 SSL_GETPID(), ss->fd,if (ssl_trace >= (3)) ssl_Trace ("%d: SSL[%d]: false start callback failed (%s)"
, getpid(), ss->fd, PR_ErrorToName(PR_GetError()))
8163 PR_ErrorToName(PR_GetError())))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL[%d]: false start callback failed (%s)"
, getpid(), ss->fd, PR_ErrorToName(PR_GetError()))
;
8164 }
8165 return rv;
8166 }
8167
8168no_false_start:
8169 ss->ssl3.hs.canFalseStart = PR_FALSE0;
8170 return SECSuccess;
8171}
8172
8173PRBool
8174ssl3_WaitingForServerSecondRound(sslSocket *ss)
8175{
8176 PRBool result;
8177
8178 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",8178))
;
8179
8180 switch (ss->ssl3.hs.ws) {
8181 case wait_new_session_ticket:
8182 case wait_change_cipher:
8183 case wait_finished:
8184 result = PR_TRUE1;
8185 break;
8186 default:
8187 result = PR_FALSE0;
8188 break;
8189 }
8190
8191 return result;
8192}
8193
8194static SECStatus ssl3_SendClientSecondRound(sslSocket *ss);
8195
8196/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
8197 * a complete ssl3 Server Hello Done message.
8198 * Caller must hold Handshake and RecvBuf locks.
8199 */
8200static SECStatus
8201ssl3_HandleServerHelloDone(sslSocket *ss)
8202{
8203 SECStatus rv;
8204 SSL3WaitState ws = ss->ssl3.hs.ws;
8205
8206 SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello_done handshake",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: handle server_hello_done handshake"
, getpid(), ss->fd)
8207 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: handle server_hello_done handshake"
, getpid(), ss->fd)
;
8208 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->recvBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveRecvBufLock(ss)"
,"ssl3con.c",8208))
;
8209 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",8209))
;
8210
8211 /* Skipping CertificateRequest is always permitted. */
8212 if (ws != wait_hello_done &&
8213 ws != wait_cert_request) {
8214 SSL3_SendAlert(ss, alert_fatal, unexpected_message);
8215 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
8216 return SECFailure;
8217 }
8218
8219 rv = ssl3_SendClientSecondRound(ss);
8220
8221 return rv;
8222}
8223
8224/* Called from ssl3_HandleServerHelloDone and ssl3_AuthCertificateComplete.
8225 *
8226 * Caller must hold Handshake and RecvBuf locks.
8227 */
8228static SECStatus
8229ssl3_SendClientSecondRound(sslSocket *ss)
8230{
8231 SECStatus rv;
8232 PRBool sendClientCert;
8233
8234 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->recvBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveRecvBufLock(ss)"
,"ssl3con.c",8234))
;
8235 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",8235))
;
8236
8237 sendClientCert = !ss->ssl3.sendEmptyCert &&
8238 ss->ssl3.clientCertChain != NULL((void*)0) &&
8239 ss->ssl3.clientPrivateKey != NULL((void*)0);
8240
8241 /* We must wait for the server's certificate to be authenticated before
8242 * sending the client certificate in order to disclosing the client
8243 * certificate to an attacker that does not have a valid cert for the
8244 * domain we are connecting to.
8245 *
8246 * During the initial handshake on a connection, we never send/receive
8247 * application data until we have authenticated the server's certificate;
8248 * i.e. we have fully authenticated the handshake before using the cipher
8249 * specs agreed upon for that handshake. During a renegotiation, we may
8250 * continue sending and receiving application data during the handshake
8251 * interleaved with the handshake records. If we were to send the client's
8252 * second round for a renegotiation before the server's certificate was
8253 * authenticated, then the application data sent/received after this point
8254 * would be using cipher spec that hadn't been authenticated. By waiting
8255 * until the server's certificate has been authenticated during
8256 * renegotiations, we ensure that renegotiations have the same property
8257 * as initial handshakes; i.e. we have fully authenticated the handshake
8258 * before using the cipher specs agreed upon for that handshake for
8259 * application data.
8260 */
8261 if (ss->ssl3.hs.restartTarget) {
8262 PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget")PR_Assert("unexpected ss->ssl3.hs.restartTarget","ssl3con.c"
,8262)
;
8263 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
8264 return SECFailure;
8265 }
8266 /* Check whether waiting for client certificate selection OR
8267 waiting on server certificate verification AND
8268 going to send client cert */
8269 if ((ss->ssl3.hs.clientCertificatePending) ||
8270 (ss->ssl3.hs.authCertificatePending && (sendClientCert || ss->ssl3.sendEmptyCert || ss->firstHsDone))) {
8271 SSL_TRC(3, ("%d: SSL3[%p]: deferring ssl3_SendClientSecondRound because"if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%p]: deferring ssl3_SendClientSecondRound because"
" certificate authentication is still pending.", getpid(), ss
->fd)
8272 " certificate authentication is still pending.",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%p]: deferring ssl3_SendClientSecondRound because"
" certificate authentication is still pending.", getpid(), ss
->fd)
8273 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%p]: deferring ssl3_SendClientSecondRound because"
" certificate authentication is still pending.", getpid(), ss
->fd)
;
8274 ss->ssl3.hs.restartTarget = ssl3_SendClientSecondRound;
8275 PORT_SetErrorPORT_SetError_Util(PR_WOULD_BLOCK_ERROR(-5998L));
8276 return SECFailure;
8277 }
8278
8279 ssl_GetXmitBufLock(ss){ if (!ss->opt.noLocks) PR_EnterMonitor(((ss)->xmitBufLock
)); }
; /*******************************/
8280
8281 if (ss->ssl3.sendEmptyCert) {
8282 ss->ssl3.sendEmptyCert = PR_FALSE0;
8283 rv = ssl3_SendEmptyCertificate(ss);
8284 /* Don't send verify */
8285 if (rv != SECSuccess) {
8286 goto loser; /* error code is set. */
8287 }
8288 } else if (sendClientCert) {
8289 rv = ssl3_SendCertificate(ss);
8290 if (rv != SECSuccess) {
8291 goto loser; /* error code is set. */
8292 }
8293 }
8294
8295 rv = ssl3_SendClientKeyExchange(ss);
8296 if (rv != SECSuccess) {
8297 goto loser; /* err is set. */
8298 }
8299
8300 if (sendClientCert) {
8301 rv = ssl3_SendCertificateVerify(ss, ss->ssl3.clientPrivateKey);
8302 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
8303 ss->ssl3.clientPrivateKey = NULL((void*)0);
8304 if (rv != SECSuccess) {
8305 goto loser; /* err is set. */
8306 }
8307 }
8308
8309 rv = ssl3_SendChangeCipherSpecs(ss);
8310 if (rv != SECSuccess) {
8311 goto loser; /* err code was set. */
8312 }
8313
8314 /* This must be done after we've set ss->ssl3.cwSpec in
8315 * ssl3_SendChangeCipherSpecs because SSL_GetChannelInfo uses information
8316 * from cwSpec. This must be done before we call ssl3_CheckFalseStart
8317 * because the false start callback (if any) may need the information from
8318 * the functions that depend on this being set.
8319 */
8320 ss->enoughFirstHsDone = PR_TRUE1;
8321
8322 if (!ss->firstHsDone) {
8323 if (ss->opt.enableFalseStart) {
8324 if (!ss->ssl3.hs.authCertificatePending) {
8325 /* When we fix bug 589047, we will need to know whether we are
8326 * false starting before we try to flush the client second
8327 * round to the network. With that in mind, we purposefully
8328 * call ssl3_CheckFalseStart before calling ssl3_SendFinished,
8329 * which includes a call to ssl3_FlushHandshake, so that
8330 * no application develops a reliance on such flushing being
8331 * done before its false start callback is called.
8332 */
8333 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
;
8334 rv = ssl3_CheckFalseStart(ss);
8335 ssl_GetXmitBufLock(ss){ if (!ss->opt.noLocks) PR_EnterMonitor(((ss)->xmitBufLock
)); }
;
8336 if (rv != SECSuccess) {
8337 goto loser;
8338 }
8339 } else {
8340 /* The certificate authentication and the server's Finished
8341 * message are racing each other. If the certificate
8342 * authentication wins, then we will try to false start in
8343 * ssl3_AuthCertificateComplete.
8344 */
8345 SSL_TRC(3, ("%d: SSL3[%p]: deferring false start check because"if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%p]: deferring false start check because"
" certificate authentication is still pending.", getpid(), ss
->fd)
8346 " certificate authentication is still pending.",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%p]: deferring false start check because"
" certificate authentication is still pending.", getpid(), ss
->fd)
8347 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%p]: deferring false start check because"
" certificate authentication is still pending.", getpid(), ss
->fd)
;
8348 }
8349 }
8350 }
8351
8352 rv = ssl3_SendFinished(ss, 0);
8353 if (rv != SECSuccess) {
8354 goto loser; /* err code was set. */
8355 }
8356
8357 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
; /*******************************/
8358
8359 if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn))
8360 ss->ssl3.hs.ws = wait_new_session_ticket;
8361 else
8362 ss->ssl3.hs.ws = wait_change_cipher;
8363
8364 PORT_Assert(ssl3_WaitingForServerSecondRound(ss))((ssl3_WaitingForServerSecondRound(ss))?((void)0):PR_Assert("ssl3_WaitingForServerSecondRound(ss)"
,"ssl3con.c",8364))
;
8365
8366 return SECSuccess;
8367
8368loser:
8369 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
;
8370 return rv;
8371}
8372
8373/*
8374 * Routines used by servers
8375 */
8376static SECStatus
8377ssl3_SendHelloRequest(sslSocket *ss)
8378{
8379 SECStatus rv;
8380
8381 SSL_TRC(3, ("%d: SSL3[%d]: send hello_request handshake", SSL_GETPID(),if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: send hello_request handshake"
, getpid(), ss->fd)
8382 ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: send hello_request handshake"
, getpid(), ss->fd)
;
8383
8384 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",8384))
;
8385 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->xmitBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveXmitBufLock(ss)"
,"ssl3con.c",8385))
;
8386
8387 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_hello_request, 0);
8388 if (rv != SECSuccess) {
8389 return rv; /* err set by AppendHandshake */
8390 }
8391 rv = ssl3_FlushHandshake(ss, 0);
8392 if (rv != SECSuccess) {
8393 return rv; /* error code set by ssl3_FlushHandshake */
8394 }
8395 ss->ssl3.hs.ws = wait_client_hello;
8396 return SECSuccess;
8397}
8398
8399/*
8400 * Called from:
8401 * ssl3_HandleClientHello()
8402 */
8403static SECComparison
8404ssl3_ServerNameCompare(const SECItem *name1, const SECItem *name2)
8405{
8406 if (!name1 != !name2) {
8407 return SECLessThan;
8408 }
8409 if (!name1) {
8410 return SECEqual;
8411 }
8412 if (name1->type != name2->type) {
8413 return SECLessThan;
8414 }
8415 return SECITEM_CompareItemSECITEM_CompareItem_Util(name1, name2);
8416}
8417
8418/* Sets memory error when returning NULL.
8419 * Called from:
8420 * ssl3_SendClientHello()
8421 * ssl3_HandleServerHello()
8422 * ssl3_HandleClientHello()
8423 * ssl3_HandleV2ClientHello()
8424 */
8425sslSessionID *
8426ssl3_NewSessionID(sslSocket *ss, PRBool is_server)
8427{
8428 sslSessionID *sid;
8429
8430 sid = PORT_ZNew(sslSessionID)(sslSessionID *)PORT_ZAlloc_Util(sizeof(sslSessionID));
8431 if (sid == NULL((void*)0))
8432 return sid;
8433
8434 if (is_server) {
8435 const SECItem *srvName;
8436 SECStatus rv = SECSuccess;
8437
8438 ssl_GetSpecReadLock(ss){ if (!ss->opt.noLocks) NSSRWLock_LockRead_Util((ss)->specLock
); }
; /********************************/
8439 srvName = &ss->ssl3.hs.srvVirtName;
8440 if (srvName->len && srvName->data) {
8441 rv = SECITEM_CopyItemSECITEM_CopyItem_Util(NULL((void*)0), &sid->u.ssl3.srvName, srvName);
8442 }
8443 ssl_ReleaseSpecReadLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockRead_Util((ss)->
specLock); }
; /************************************/
8444 if (rv != SECSuccess) {
8445 PORT_FreePORT_Free_Util(sid);
8446 return NULL((void*)0);
8447 }
8448 }
8449 sid->peerID = (ss->peerID == NULL((void*)0)) ? NULL((void*)0) : PORT_StrdupPORT_Strdup_Util(ss->peerID);
8450 sid->urlSvrName = (ss->url == NULL((void*)0)) ? NULL((void*)0) : PORT_StrdupPORT_Strdup_Util(ss->url);
8451 sid->addr = ss->sec.ci.peer;
8452 sid->port = ss->sec.ci.port;
8453 sid->references = 1;
8454 sid->cached = never_cached;
8455 sid->version = ss->version;
8456 sid->sigScheme = ssl_sig_none;
8457
8458 sid->u.ssl3.keys.resumable = PR_TRUE1;
8459 sid->u.ssl3.policy = SSL_ALLOWED1;
8460 sid->u.ssl3.keys.extendedMasterSecretUsed = PR_FALSE0;
8461
8462 if (is_server) {
8463 SECStatus rv;
8464 int pid = SSL_GETPIDgetpid();
8465
8466 sid->u.ssl3.sessionIDLength = SSL3_SESSIONID_BYTES32;
8467 sid->u.ssl3.sessionID[0] = (pid >> 8) & 0xff;
8468 sid->u.ssl3.sessionID[1] = pid & 0xff;
8469 rv = PK11_GenerateRandom(sid->u.ssl3.sessionID + 2,
8470 SSL3_SESSIONID_BYTES32 - 2);
8471 if (rv != SECSuccess) {
8472 ssl_FreeSID(sid);
8473 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
8474 return NULL((void*)0);
8475 }
8476 }
8477 return sid;
8478}
8479
8480/* Called from: ssl3_HandleClientHello, ssl3_HandleV2ClientHello */
8481static SECStatus
8482ssl3_SendServerHelloSequence(sslSocket *ss)
8483{
8484 const ssl3KEADef *kea_def;
8485 SECStatus rv;
8486
8487 SSL_TRC(3, ("%d: SSL3[%d]: begin send server_hello sequence",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: begin send server_hello sequence"
, getpid(), ss->fd)
8488 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: begin send server_hello sequence"
, getpid(), ss->fd)
;
8489
8490 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",8490))
;
8491 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->xmitBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveXmitBufLock(ss)"
,"ssl3con.c",8491))
;
8492
8493 rv = ssl3_SendServerHello(ss);
8494 if (rv != SECSuccess) {
8495 return rv; /* err code is set. */
8496 }
8497 rv = ssl3_SendCertificate(ss);
8498 if (rv != SECSuccess) {
8499 return rv; /* error code is set. */
8500 }
8501 rv = ssl3_SendCertificateStatus(ss);
8502 if (rv != SECSuccess) {
8503 return rv; /* error code is set. */
8504 }
8505 /* We have to do this after the call to ssl3_SendServerHello,
8506 * because kea_def is set up by ssl3_SendServerHello().
8507 */
8508 kea_def = ss->ssl3.hs.kea_def;
8509
8510 if (kea_def->ephemeral) {
8511 rv = ssl3_SendServerKeyExchange(ss);
8512 if (rv != SECSuccess) {
8513 return rv; /* err code was set. */
8514 }
8515 }
8516
8517 if (ss->opt.requestCertificate) {
8518 rv = ssl3_SendCertificateRequest(ss);
8519 if (rv != SECSuccess) {
8520 return rv; /* err code is set. */
8521 }
8522 }
8523 rv = ssl3_SendServerHelloDone(ss);
8524 if (rv != SECSuccess) {
8525 return rv; /* err code is set. */
8526 }
8527
8528 ss->ssl3.hs.ws = (ss->opt.requestCertificate) ? wait_client_cert
8529 : wait_client_key;
8530 return SECSuccess;
8531}
8532
8533/* An empty TLS Renegotiation Info (RI) extension */
8534static const PRUint8 emptyRIext[5] = { 0xff, 0x01, 0x00, 0x01, 0x00 };
8535
8536static PRBool
8537ssl3_KEASupportsTickets(const ssl3KEADef *kea_def)
8538{
8539 if (kea_def->signKeyType == dsaKey) {
8540 /* TODO: Fix session tickets for DSS. The server code rejects the
8541 * session ticket received from the client. Bug 1174677 */
8542 return PR_FALSE0;
8543 }
8544 return PR_TRUE1;
8545}
8546
8547static PRBool
8548ssl3_PeerSupportsCipherSuite(const SECItem *peerSuites, uint16_t suite)
8549{
8550 for (unsigned int i = 0; i + 1 < peerSuites->len; i += 2) {
8551 PRUint16 suite_i = (peerSuites->data[i] << 8) | peerSuites->data[i + 1];
8552 if (suite_i == suite) {
8553 return PR_TRUE1;
8554 }
8555 }
8556 return PR_FALSE0;
8557}
8558
8559SECStatus
8560ssl3_NegotiateCipherSuiteInner(sslSocket *ss, const SECItem *suites,
8561 PRUint16 version, PRUint16 *suitep)
8562{
8563 unsigned int i;
8564 SSLVersionRange vrange = { version, version };
8565
8566 /* If we negotiated an External PSK and that PSK has a ciphersuite
8567 * configured, we need to constrain our choice. If the client does
8568 * not support it, negotiate a certificate auth suite and fall back.
8569 */
8570 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_30x0304 &&
8571 ss->xtnData.selectedPsk &&
8572 ss->xtnData.selectedPsk->type == ssl_psk_external &&
8573 ss->xtnData.selectedPsk->zeroRttSuite != TLS_NULL_WITH_NULL_NULL0x0000) {
8574 PRUint16 pskSuite = ss->xtnData.selectedPsk->zeroRttSuite;
8575 ssl3CipherSuiteCfg *pskSuiteCfg = ssl_LookupCipherSuiteCfgMutable(pskSuite,
8576 ss->cipherSuites);
8577 if (ssl3_config_match(pskSuiteCfg, ss->ssl3.policy, &vrange, ss) &&
8578 ssl3_PeerSupportsCipherSuite(suites, pskSuite)) {
8579 *suitep = pskSuite;
8580 return SECSuccess;
8581 }
8582 }
8583
8584 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED71; i++) {
8585 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
8586 if (!ssl3_config_match(suite, ss->ssl3.policy, &vrange, ss)) {
8587 continue;
8588 }
8589 if (!ssl3_PeerSupportsCipherSuite(suites, suite->cipher_suite)) {
8590 continue;
8591 }
8592 *suitep = suite->cipher_suite;
8593 return SECSuccess;
8594 }
8595 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_NO_CYPHER_OVERLAP);
8596 return SECFailure;
8597}
8598
8599/* Select a cipher suite.
8600**
8601** NOTE: This suite selection algorithm should be the same as the one in
8602** ssl3_HandleV2ClientHello().
8603**
8604** If TLS 1.0 is enabled, we could handle the case where the client
8605** offered TLS 1.1 but offered only export cipher suites by choosing TLS
8606** 1.0 and selecting one of those export cipher suites. However, a secure
8607** TLS 1.1 client should not have export cipher suites enabled at all,
8608** and a TLS 1.1 client should definitely not be offering *only* export
8609** cipher suites. Therefore, we refuse to negotiate export cipher suites
8610** with any client that indicates support for TLS 1.1 or higher when we
8611** (the server) have TLS 1.1 support enabled.
8612*/
8613SECStatus
8614ssl3_NegotiateCipherSuite(sslSocket *ss, const SECItem *suites,
8615 PRBool initHashes)
8616{
8617 PRUint16 selected;
8618 SECStatus rv;
8619
8620 /* Ensure that only valid cipher suites are enabled. */
8621 if (ssl3_config_match_init(ss) == 0) {
8622 /* No configured cipher is both supported by PK11 and allowed.
8623 * This is a configuration error, so report handshake failure.*/
8624 FATAL_ERROR(ss, PORT_GetError(), handshake_failure)do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, PORT_GetError_Util(), __func__, "ssl3con.c"
, 8624); PORT_SetError_Util(PORT_GetError_Util()); } while (0
); tls13_FatalError(ss, PORT_GetError_Util(), handshake_failure
); } while (0)
;
8625 return SECFailure;
8626 }
8627
8628 rv = ssl3_NegotiateCipherSuiteInner(ss, suites, ss->version, &selected);
8629 if (rv != SECSuccess) {
8630 return SECFailure;
8631 }
8632
8633 ss->ssl3.hs.cipher_suite = selected;
8634 return ssl3_SetupCipherSuite(ss, initHashes);
8635}
8636
8637/*
8638 * Call the SNI config hook.
8639 *
8640 * Called from:
8641 * ssl3_HandleClientHello
8642 * tls13_HandleClientHelloPart2
8643 */
8644SECStatus
8645ssl3_ServerCallSNICallback(sslSocket *ss)
8646{
8647 int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
8648 SSL3AlertDescription desc = illegal_parameter;
8649 int ret = 0;
8650
8651#ifdef SSL_SNI_ALLOW_NAME_CHANGE_2HS
8652#error("No longer allowed to set SSL_SNI_ALLOW_NAME_CHANGE_2HS")
8653#endif
8654 if (!ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn)) {
8655 if (ss->firstHsDone) {
8656 /* Check that we don't have the name is current spec
8657 * if this extension was not negotiated on the 2d hs. */
8658 PRBool passed = PR_TRUE1;
8659 ssl_GetSpecReadLock(ss){ if (!ss->opt.noLocks) NSSRWLock_LockRead_Util((ss)->specLock
); }
; /*******************************/
8660 if (ss->ssl3.hs.srvVirtName.data) {
8661 passed = PR_FALSE0;
8662 }
8663 ssl_ReleaseSpecReadLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockRead_Util((ss)->
specLock); }
; /***************************/
8664 if (!passed) {
8665 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
8666 desc = handshake_failure;
8667 goto alert_loser;
8668 }
8669 }
8670 return SECSuccess;
8671 }
8672
8673 if (ss->sniSocketConfig)
8674 do { /* not a loop */
8675 PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==(((ss->ssl3.hs.preliminaryInfo & ((1U << 0) | (1U
<< 1) | (1U << 4))) == ((1U << 0) | (1U <<
1) | (1U << 4)))?((void)0):PR_Assert("(ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) == ssl_preinfo_all"
,"ssl3con.c",8676))
8676 ssl_preinfo_all)(((ss->ssl3.hs.preliminaryInfo & ((1U << 0) | (1U
<< 1) | (1U << 4))) == ((1U << 0) | (1U <<
1) | (1U << 4)))?((void)0):PR_Assert("(ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) == ssl_preinfo_all"
,"ssl3con.c",8676))
;
8677
8678 ret = SSL_SNI_SEND_ALERT-2;
8679 /* If extension is negotiated, the len of names should > 0. */
8680 if (ss->xtnData.sniNameArrSize) {
8681 /* Calling client callback to reconfigure the socket. */
8682 ret = (SECStatus)(*ss->sniSocketConfig)(ss->fd,
8683 ss->xtnData.sniNameArr,
8684 ss->xtnData.sniNameArrSize,
8685 ss->sniSocketConfigArg);
8686 }
8687 if (ret <= SSL_SNI_SEND_ALERT-2) {
8688 /* Application does not know the name or was not able to
8689 * properly reconfigure the socket. */
8690 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
8691 desc = unrecognized_name;
8692 break;
8693 } else if (ret == SSL_SNI_CURRENT_CONFIG_IS_USED-1) {
8694 SECStatus rv = SECSuccess;
8695 SECItem pwsNameBuf = { 0, NULL((void*)0), 0 };
8696 SECItem *pwsName = &pwsNameBuf;
8697 SECItem *cwsName;
8698
8699 ssl_GetSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_LockWrite_Util((ss)->
specLock); }
; /*******************************/
8700 cwsName = &ss->ssl3.hs.srvVirtName;
8701 /* not allow name change on the 2d HS */
8702 if (ss->firstHsDone) {
8703 if (ssl3_ServerNameCompare(pwsName, cwsName)) {
8704 ssl_ReleaseSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockWrite_Util((ss)->
specLock); }
; /******************/
8705 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
8706 desc = handshake_failure;
8707 ret = SSL_SNI_SEND_ALERT-2;
8708 break;
8709 }
8710 }
8711 if (pwsName->data) {
8712 SECITEM_FreeItemSECITEM_FreeItem_Util(pwsName, PR_FALSE0);
8713 }
8714 if (cwsName->data) {
8715 rv = SECITEM_CopyItemSECITEM_CopyItem_Util(NULL((void*)0), pwsName, cwsName);
8716 }
8717 ssl_ReleaseSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockWrite_Util((ss)->
specLock); }
; /**************************/
8718 if (rv != SECSuccess) {
8719 errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
8720 desc = internal_error;
8721 ret = SSL_SNI_SEND_ALERT-2;
8722 break;
8723 }
8724 } else if ((unsigned int)ret < ss->xtnData.sniNameArrSize) {
8725 /* Application has configured new socket info. Lets check it
8726 * and save the name. */
8727 SECStatus rv;
8728 SECItem *name = &ss->xtnData.sniNameArr[ret];
8729 SECItem *pwsName;
8730
8731 /* get rid of the old name and save the newly picked. */
8732 /* This code is protected by ssl3HandshakeLock. */
8733 ssl_GetSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_LockWrite_Util((ss)->
specLock); }
; /*******************************/
8734 /* not allow name change on the 2d HS */
8735 if (ss->firstHsDone) {
8736 SECItem *cwsName = &ss->ssl3.hs.srvVirtName;
8737 if (ssl3_ServerNameCompare(name, cwsName)) {
8738 ssl_ReleaseSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockWrite_Util((ss)->
specLock); }
; /******************/
8739 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
8740 desc = handshake_failure;
8741 ret = SSL_SNI_SEND_ALERT-2;
8742 break;
8743 }
8744 }
8745 pwsName = &ss->ssl3.hs.srvVirtName;
8746 if (pwsName->data) {
8747 SECITEM_FreeItemSECITEM_FreeItem_Util(pwsName, PR_FALSE0);
8748 }
8749 rv = SECITEM_CopyItemSECITEM_CopyItem_Util(NULL((void*)0), pwsName, name);
8750 ssl_ReleaseSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockWrite_Util((ss)->
specLock); }
; /***************************/
8751 if (rv != SECSuccess) {
8752 errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
8753 desc = internal_error;
8754 ret = SSL_SNI_SEND_ALERT-2;
8755 break;
8756 }
8757 /* Need to tell the client that application has picked
8758 * the name from the offered list and reconfigured the socket.
8759 */
8760 ssl3_RegisterExtensionSender(ss, &ss->xtnData, ssl_server_name_xtn,
8761 ssl_SendEmptyExtension);
8762 } else {
8763 /* Callback returned index outside of the boundary. */
8764 PORT_Assert((unsigned int)ret < ss->xtnData.sniNameArrSize)(((unsigned int)ret < ss->xtnData.sniNameArrSize)?((void
)0):PR_Assert("(unsigned int)ret < ss->xtnData.sniNameArrSize"
,"ssl3con.c",8764))
;
8765 errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
8766 desc = internal_error;
8767 ret = SSL_SNI_SEND_ALERT-2;
8768 break;
8769 }
8770 } while (0);
8771 ssl3_FreeSniNameArray(&ss->xtnData);
8772 if (ret <= SSL_SNI_SEND_ALERT-2) {
8773 /* desc and errCode should be set. */
8774 goto alert_loser;
8775 }
8776
8777 return SECSuccess;
8778
8779alert_loser:
8780 (void)SSL3_SendAlert(ss, alert_fatal, desc);
8781 PORT_SetErrorPORT_SetError_Util(errCode);
8782 return SECFailure;
8783}
8784
8785SECStatus
8786ssl3_SelectServerCert(sslSocket *ss)
8787{
8788 const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def;
8789 PRCList *cursor;
8790 SECStatus rv;
8791
8792 /* If the client didn't include the supported groups extension, assume just
8793 * P-256 support and disable all the other ECDHE groups. This also affects
8794 * ECDHE group selection, but this function is called first. */
8795 if (!ssl3_ExtensionNegotiated(ss, ssl_supported_groups_xtn)) {
8796 unsigned int i;
8797 for (i = 0; i < SSL_NAMED_GROUP_COUNT32; ++i) {
8798 if (ss->namedGroupPreferences[i] &&
8799 ss->namedGroupPreferences[i]->keaType == ssl_kea_ecdh &&
8800 ss->namedGroupPreferences[i]->name != ssl_grp_ec_secp256r1) {
8801 ss->namedGroupPreferences[i] = NULL((void*)0);
8802 }
8803 }
8804 }
8805
8806 /* This picks the first certificate that has:
8807 * a) the right authentication method, and
8808 * b) the right named curve (EC only)
8809 *
8810 * We might want to do some sort of ranking here later. For now, it's all
8811 * based on what order they are configured in. */
8812 for (cursor = PR_NEXT_LINK(&ss->serverCerts)((&ss->serverCerts)->next);
8813 cursor != &ss->serverCerts;
8814 cursor = PR_NEXT_LINK(cursor)((cursor)->next)) {
8815 sslServerCert *cert = (sslServerCert *)cursor;
8816 if (kea_def->authKeyType == ssl_auth_rsa_sign) {
8817 /* We consider PSS certificates here as well for TLS 1.2. */
8818 if (!SSL_CERT_IS(cert, ssl_auth_rsa_sign)((cert)->authTypes & (1 << (ssl_auth_rsa_sign))) &&
8819 (!SSL_CERT_IS(cert, ssl_auth_rsa_pss)((cert)->authTypes & (1 << (ssl_auth_rsa_pss))) ||
8820 ss->version < SSL_LIBRARY_VERSION_TLS_1_20x0303)) {
8821 continue;
8822 }
8823 } else {
8824 if (!SSL_CERT_IS(cert, kea_def->authKeyType)((cert)->authTypes & (1 << (kea_def->authKeyType
)))
) {
8825 continue;
8826 }
8827 if (SSL_CERT_IS_EC(cert)((cert)->authTypes & ((1 << ssl_auth_ecdsa) | (1
<< ssl_auth_ecdh_rsa) | (1 << ssl_auth_ecdh_ecdsa
)))
&&
8828 !ssl_NamedGroupEnabled(ss, cert->namedCurve)) {
8829 continue;
8830 }
8831 }
8832
8833 /* Found one. */
8834 ss->sec.serverCert = cert;
8835 ss->sec.authKeyBits = cert->serverKeyBits;
8836
8837 /* Don't pick a signature scheme if we aren't going to use it. */
8838 if (kea_def->signKeyType == nullKey) {
8839 ss->sec.authType = kea_def->authKeyType;
8840 return SECSuccess;
8841 }
8842
8843 rv = ssl3_PickServerSignatureScheme(ss);
8844 if (rv != SECSuccess) {
8845 return SECFailure;
8846 }
8847 ss->sec.authType =
8848 ssl_SignatureSchemeToAuthType(ss->ssl3.hs.signatureScheme);
8849 return SECSuccess;
8850 }
8851
8852 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_NO_CYPHER_OVERLAP);
8853 return SECFailure;
8854}
8855
8856static SECStatus
8857ssl_GenerateServerRandom(sslSocket *ss)
8858{
8859 SECStatus rv;
8860 PRUint8 *downgradeSentinel;
8861
8862 rv = ssl3_GetNewRandom(ss->ssl3.hs.server_random);
8863 if (rv != SECSuccess) {
8864 return SECFailure;
8865 }
8866
8867 if (ss->version == ss->vrange.max) {
8868 return SECSuccess;
8869 }
8870
8871 /*
8872 * [RFC 8446 Section 4.1.3].
8873 *
8874 * TLS 1.3 servers which negotiate TLS 1.2 or below in response to a
8875 * ClientHello MUST set the last 8 bytes of their Random value specially in
8876 * their ServerHello.
8877 *
8878 * If negotiating TLS 1.2, TLS 1.3 servers MUST set the last 8 bytes of
8879 * their Random value to the bytes:
8880 *
8881 * 44 4F 57 4E 47 52 44 01
8882 *
8883 * If negotiating TLS 1.1 or below, TLS 1.3 servers MUST, and TLS 1.2
8884 * servers SHOULD, set the last 8 bytes of their ServerHello.Random value to
8885 * the bytes:
8886 *
8887 * 44 4F 57 4E 47 52 44 00
8888 */
8889 downgradeSentinel =
8890 ss->ssl3.hs.server_random +
8891 SSL3_RANDOM_LENGTH32 - sizeof(tls12_downgrade_random);
8892 if (ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_20x0303) {
8893 switch (ss->version) {
8894 case SSL_LIBRARY_VERSION_TLS_1_20x0303:
8895 /* vrange.max > 1.2, since we didn't early exit above. */
8896 PORT_Memcpymemcpy(downgradeSentinel,
8897 tls12_downgrade_random, sizeof(tls12_downgrade_random));
8898 break;
8899 case SSL_LIBRARY_VERSION_TLS_1_10x0302:
8900 case SSL_LIBRARY_VERSION_TLS_1_00x0301:
8901 PORT_Memcpymemcpy(downgradeSentinel,
8902 tls1_downgrade_random, sizeof(tls1_downgrade_random));
8903 break;
8904 default:
8905 /* Do not change random. */
8906 break;
8907 }
8908 }
8909
8910 return SECSuccess;
8911}
8912
8913SECStatus
8914ssl3_HandleClientHelloPreamble(sslSocket *ss, PRUint8 **b, PRUint32 *length, SECItem *sidBytes,
8915 SECItem *cookieBytes, SECItem *suites, SECItem *comps)
8916{
8917 SECStatus rv;
8918 PRUint32 tmp;
8919 rv = ssl3_ConsumeHandshakeNumber(ss, &tmp, 2, b, length);
8920 if (rv != SECSuccess) {
8921 return SECFailure; /* malformed, alert already sent */
8922 }
8923
8924 /* Translate the version. */
8925 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
8926 ss->clientHelloVersion = dtls_DTLSVersionToTLSVersion((SSL3ProtocolVersion)tmp);
8927 } else {
8928 ss->clientHelloVersion = (SSL3ProtocolVersion)tmp;
8929 }
8930
8931 /* Grab the client random data. */
8932 rv = ssl3_ConsumeHandshake(
8933 ss, ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH32, b, length);
8934 if (rv != SECSuccess) {
8935 return SECFailure; /* malformed */
8936 }
8937
8938 /* Grab the client's SID, if present. */
8939 rv = ssl3_ConsumeHandshakeVariable(ss, sidBytes, 1, b, length);
8940 /* Check that the SID has the format: opaque legacy_session_id<0..32>, as
8941 * specified in RFC8446, Section 4.1.2. */
8942 if (rv != SECSuccess || sidBytes->len > SSL3_SESSIONID_BYTES32) {
8943 return SECFailure; /* malformed */
8944 }
8945
8946 /* Grab the client's cookie, if present. It is checked after version negotiation. */
8947 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
8948 rv = ssl3_ConsumeHandshakeVariable(ss, cookieBytes, 1, b, length);
8949 if (rv != SECSuccess) {
8950 return SECFailure; /* malformed */
8951 }
8952 }
8953
8954 /* Grab the list of cipher suites. */
8955 rv = ssl3_ConsumeHandshakeVariable(ss, suites, 2, b, length);
8956 if (rv != SECSuccess) {
8957 return SECFailure; /* malformed */
8958 }
8959
8960 /* Grab the list of compression methods. */
8961 rv = ssl3_ConsumeHandshakeVariable(ss, comps, 1, b, length);
8962 if (rv != SECSuccess) {
8963 return SECFailure; /* malformed */
8964 }
8965 return SECSuccess;
8966}
8967
8968static SECStatus
8969ssl3_ValidatePreambleWithVersion(sslSocket *ss, const SECItem *sidBytes, const SECItem *comps,
8970 const SECItem *cookieBytes)
8971{
8972 SECStatus rv;
8973 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_30x0304) {
8974 if (sidBytes->len > 0 && !IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
8975 SECITEM_FreeItemSECITEM_FreeItem_Util(&ss->ssl3.hs.fakeSid, PR_FALSE0);
8976 rv = SECITEM_CopyItemSECITEM_CopyItem_Util(NULL((void*)0), &ss->ssl3.hs.fakeSid, sidBytes);
8977 if (rv != SECSuccess) {
8978 FATAL_ERROR(ss, PORT_GetError(), internal_error)do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, PORT_GetError_Util(), __func__, "ssl3con.c"
, 8978); PORT_SetError_Util(PORT_GetError_Util()); } while (0
); tls13_FatalError(ss, PORT_GetError_Util(), internal_error)
; } while (0)
;
8979 return SECFailure;
8980 }
8981 }
8982
8983 /* TLS 1.3 requires that compression include only null. */
8984 if (comps->len != 1 || comps->data[0] != ssl_compression_null) {
8985 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter)do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, __func__
, "ssl3con.c", 8985); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO
, illegal_parameter); } while (0)
;
8986 return SECFailure;
8987 }
8988
8989 /* receivedCcs is only valid if we sent an HRR. */
8990 if (ss->ssl3.hs.receivedCcs && !ss->ssl3.hs.helloRetry) {
8991 FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER, unexpected_message)do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER,
__func__, "ssl3con.c", 8991); PORT_SetError_Util(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER
, unexpected_message); } while (0)
;
8992 return SECFailure;
8993 }
8994
8995 /* A DTLS 1.3-only client MUST set the legacy_cookie field to zero length.
8996 * If a DTLS 1.3 ClientHello is received with any other value in this field,
8997 * the server MUST abort the handshake with an "illegal_parameter" alert. */
8998 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram) && cookieBytes->len != 0) {
8999 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter)do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, __func__
, "ssl3con.c", 8999); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO
, illegal_parameter); } while (0)
;
9000 return SECFailure;
9001 }
9002 } else {
9003 /* ECH not possible here. */
9004 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_ech(1U << 4);
9005
9006 /* HRR and ECH are TLS1.3-only. We ignore the Cookie extension here. */
9007 if (ss->ssl3.hs.helloRetry) {
9008 FATAL_ERROR(ss, SSL_ERROR_UNSUPPORTED_VERSION, protocol_version)do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_UNSUPPORTED_VERSION, __func__
, "ssl3con.c", 9008); PORT_SetError_Util(SSL_ERROR_UNSUPPORTED_VERSION
); } while (0); tls13_FatalError(ss, SSL_ERROR_UNSUPPORTED_VERSION
, protocol_version); } while (0)
;
9009 return SECFailure;
9010 }
9011
9012 /* receivedCcs is only valid if we sent an HRR. */
9013 if (ss->ssl3.hs.receivedCcs) {
9014 FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER, unexpected_message)do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER,
__func__, "ssl3con.c", 9014); PORT_SetError_Util(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER
, unexpected_message); } while (0)
;
9015 return SECFailure;
9016 }
9017
9018 /* TLS versions prior to 1.3 must include null somewhere. */
9019 if (comps->len < 1 ||
9020 !memchr(comps->data, ssl_compression_null, comps->len)) {
9021 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter)do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, __func__
, "ssl3con.c", 9021); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO
, illegal_parameter); } while (0)
;
9022 return SECFailure;
9023 }
9024
9025 /* We never send cookies in DTLS 1.2. */
9026 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram) && cookieBytes->len != 0) {
9027 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter)do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, __func__
, "ssl3con.c", 9027); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO
, illegal_parameter); } while (0)
;
9028 return SECFailure;
9029 }
9030 }
9031
9032 return SECSuccess;
9033}
9034
9035/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
9036 * ssl3 Client Hello message.
9037 * Caller must hold Handshake and RecvBuf locks.
9038 */
9039static SECStatus
9040ssl3_HandleClientHello(sslSocket *ss, PRUint8 *b, PRUint32 length)
9041{
9042 sslSessionID *sid = NULL((void*)0);
9043 unsigned int i;
9044 SECStatus rv;
9045 PRUint32 extensionLength;
9046 int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
9047 SSL3AlertDescription desc = illegal_parameter;
9048 SSL3AlertLevel level = alert_fatal;
9049 TLSExtension *versionExtension;
9050 SECItem sidBytes = { siBuffer, NULL((void*)0), 0 };
9051 SECItem cookieBytes = { siBuffer, NULL((void*)0), 0 };
9052 SECItem suites = { siBuffer, NULL((void*)0), 0 };
9053 SECItem comps = { siBuffer, NULL((void*)0), 0 };
9054 SECItem *echInner = NULL((void*)0);
9055 PRBool isTLS13;
9056 const PRUint8 *savedMsg = b;
9057 const PRUint32 savedLen = length;
9058
9059 SSL_TRC(3, ("%d: SSL3[%d]: handle client_hello handshake",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: handle client_hello handshake"
, getpid(), ss->fd)
9060 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: handle client_hello handshake"
, getpid(), ss->fd)
;
9061
9062 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->recvBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveRecvBufLock(ss)"
,"ssl3con.c",9062))
;
9063 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",9063))
;
9064 ss->ssl3.hs.preliminaryInfo = 0;
9065
9066 if (!ss->sec.isServer ||
9067 (ss->ssl3.hs.ws != wait_client_hello &&
9068 ss->ssl3.hs.ws != idle_handshake)) {
9069 desc = unexpected_message;
9070 errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO;
9071 goto alert_loser;
9072 }
9073 if (ss->ssl3.hs.ws == idle_handshake) {
9074 /* Refuse re-handshake when we have already negotiated TLS 1.3. */
9075 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_30x0304) {
9076 desc = unexpected_message;
9077 errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
9078 goto alert_loser;
9079 }
9080 if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER((PRBool)0)) {
9081 desc = no_renegotiation;
9082 level = alert_warning;
9083 errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
9084 goto alert_loser;
9085 }
9086 }
9087
9088 /* We should always be in a fresh state. */
9089 SSL_ASSERT_HASHES_EMPTY(ss)do { ((ss->ssl3.hs.hashType == handshake_hash_unknown)?((void
)0):PR_Assert("ss->ssl3.hs.hashType == handshake_hash_unknown"
,"ssl3con.c",9089)); ((ss->ssl3.hs.messages.len == 0)?((void
)0):PR_Assert("ss->ssl3.hs.messages.len == 0","ssl3con.c",
9089)); ((ss->ssl3.hs.echInnerMessages.len == 0)?((void)0)
:PR_Assert("ss->ssl3.hs.echInnerMessages.len == 0","ssl3con.c"
,9089)); } while (0)
;
9090
9091 /* Get peer name of client */
9092 rv = ssl_GetPeerInfo(ss);
9093 if (rv != SECSuccess) {
9094 return rv; /* error code is set. */
9095 }
9096
9097 /* We might be starting session renegotiation in which case we should
9098 * clear previous state.
9099 */
9100 ssl3_ResetExtensionData(&ss->xtnData, ss);
9101 ss->statelessResume = PR_FALSE0;
9102
9103 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
9104 dtls_RehandshakeCleanup(ss);
9105 }
9106
9107 rv = ssl3_HandleClientHelloPreamble(ss, &b, &length, &sidBytes,
9108 &cookieBytes, &suites, &comps);
9109 if (rv != SECSuccess) {
9110 goto loser; /* malformed */
9111 }
9112
9113 /* Handle TLS hello extensions for SSL3 & TLS. We do not know if
9114 * we are restarting a previous session until extensions have been
9115 * parsed, since we might have received a SessionTicket extension.
9116 * Note: we allow extensions even when negotiating SSL3 for the sake
9117 * of interoperability (and backwards compatibility).
9118 */
9119 if (length) {
9120 /* Get length of hello extensions */
9121 rv = ssl3_ConsumeHandshakeNumber(ss, &extensionLength, 2, &b, &length);
9122 if (rv != SECSuccess) {
9123 goto loser; /* alert already sent */
9124 }
9125 if (extensionLength != length) {
9126 errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
9127 desc = decode_error;
9128 goto alert_loser;
9129 }
9130
9131 rv = ssl3_ParseExtensions(ss, &b, &length);
9132 if (rv != SECSuccess) {
9133 goto loser; /* malformed */
9134 }
9135 }
9136
9137 versionExtension = ssl3_FindExtension(ss, ssl_tls13_supported_versions_xtn);
9138 if (versionExtension) {
9139 rv = tls13_NegotiateVersion(ss, versionExtension);
9140 if (rv != SECSuccess) {
9141 errCode = PORT_GetErrorPORT_GetError_Util();
9142 desc = (errCode == SSL_ERROR_UNSUPPORTED_VERSION) ? protocol_version : illegal_parameter;
9143 goto alert_loser;
9144 }
9145 } else {
9146 /* The PR_MIN here ensures that we never negotiate 1.3 if the
9147 * peer didn't offer "supported_versions". */
9148 rv = ssl3_NegotiateVersion(ss,
9149 PR_MIN(ss->clientHelloVersion,((ss->clientHelloVersion)<(0x0303)?(ss->clientHelloVersion
):(0x0303))
9150 SSL_LIBRARY_VERSION_TLS_1_2)((ss->clientHelloVersion)<(0x0303)?(ss->clientHelloVersion
):(0x0303))
,
9151 PR_TRUE1);
9152 /* Send protocol version alert if the ClientHello.legacy_version is not
9153 * supported by the server.
9154 *
9155 * If the "supported_versions" extension is absent and the server only
9156 * supports versions greater than ClientHello.legacy_version, the
9157 * server MUST abort the handshake with a "protocol_version" alert
9158 * [RFC8446, Appendix D.2]. */
9159 if (rv != SECSuccess) {
9160 desc = protocol_version;
9161 errCode = SSL_ERROR_UNSUPPORTED_VERSION;
9162 goto alert_loser;
9163 }
9164 }
9165 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version(1U << 0);
9166
9167 /* Update the write spec to match the selected version. */
9168 if (!ss->firstHsDone) {
9169 ssl_GetSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_LockWrite_Util((ss)->
specLock); }
;
9170 ssl_SetSpecVersions(ss, ss->ssl3.cwSpec);
9171 ssl_ReleaseSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockWrite_Util((ss)->
specLock); }
;
9172 }
9173
9174 isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_30x0304;
9175 if (isTLS13) {
9176 if (ss->firstHsDone) {
9177 desc = unexpected_message;
9178 errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
9179 goto alert_loser;
9180 }
9181
9182 /* If there is a cookie, then this is a second ClientHello (TLS 1.3). */
9183 if (ssl3_FindExtension(ss, ssl_tls13_cookie_xtn)) {
9184 ss->ssl3.hs.helloRetry = PR_TRUE1;
9185 }
9186
9187 rv = tls13_MaybeHandleEch(ss, savedMsg, savedLen, &sidBytes,
9188 &comps, &cookieBytes, &suites, &echInner);
9189 if (rv != SECSuccess) {
9190 errCode = PORT_GetErrorPORT_GetError_Util();
9191 goto loser; /* code set, alert sent. */
9192 }
9193 }
9194
9195 rv = ssl3_ValidatePreambleWithVersion(ss, &sidBytes, &comps, &cookieBytes);
9196 if (rv != SECSuccess) {
9197 errCode = PORT_GetErrorPORT_GetError_Util();
9198 goto loser; /* code set, alert sent. */
9199 }
9200
9201 /* Now parse the rest of the extensions. */
9202 rv = ssl3_HandleParsedExtensions(ss, ssl_hs_client_hello);
9203 ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
9204 if (rv != SECSuccess) {
9205 if (PORT_GetErrorPORT_GetError_Util() == SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM) {
9206 errCode = SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM;
9207 }
9208 goto loser; /* malformed */
9209 }
9210
9211 /* If the ClientHello version is less than our maximum version, check for a
9212 * TLS_FALLBACK_SCSV and reject the connection if found. */
9213 if (ss->vrange.max > ss->version) {
9214 for (i = 0; i + 1 < suites.len; i += 2) {
9215 PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
9216 if (suite_i != TLS_FALLBACK_SCSV0x5600)
9217 continue;
9218 desc = inappropriate_fallback;
9219 errCode = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT;
9220 goto alert_loser;
9221 }
9222 }
9223
9224 if (!ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
9225 /* If we didn't receive an RI extension, look for the SCSV,
9226 * and if found, treat it just like an empty RI extension
9227 * by processing a local copy of an empty RI extension.
9228 */
9229 for (i = 0; i + 1 < suites.len; i += 2) {
9230 PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
9231 if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV0x00FF) {
9232 PRUint8 *b2 = (PRUint8 *)emptyRIext;
9233 PRUint32 L2 = sizeof emptyRIext;
9234 (void)ssl3_HandleExtensions(ss, &b2, &L2, ssl_hs_client_hello);
9235 break;
9236 }
9237 }
9238 }
9239
9240 /* The check for renegotiation in TLS 1.3 is earlier. */
9241 if (!isTLS13) {
9242 if (ss->firstHsDone &&
9243 (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_REQUIRES_XTN((PRBool)2) ||
9244 ss->opt.enableRenegotiation == SSL_RENEGOTIATE_TRANSITIONAL((PRBool)3)) &&
9245 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
9246 desc = no_renegotiation;
9247 level = alert_warning;
9248 errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
9249 goto alert_loser;
9250 }
9251 if ((ss->opt.requireSafeNegotiation ||
9252 (ss->firstHsDone && ss->peerRequestedProtection)) &&
9253 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
9254 desc = handshake_failure;
9255 errCode = SSL_ERROR_UNSAFE_NEGOTIATION;
9256 goto alert_loser;
9257 }
9258 }
9259
9260 /* We do stateful resumes only if we are in TLS < 1.3 and
9261 * either of the following conditions are satisfied:
9262 * (1) the client does not support the session ticket extension, or
9263 * (2) the client support the session ticket extension, but sent an
9264 * empty ticket.
9265 */
9266 if (!isTLS13 &&
9267 (!ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) ||
9268 ss->xtnData.emptySessionTicket)) {
9269 if (sidBytes.len > 0 && !ss->opt.noCache) {
9270 SSL_TRC(7, ("%d: SSL3[%d]: server, lookup client session-id for 0x%08x%08x%08x%08x",if (ssl_trace >= (7)) ssl_Trace ("%d: SSL3[%d]: server, lookup client session-id for 0x%08x%08x%08x%08x"
, getpid(), ss->fd, ss->sec.ci.peer._S6_un._S6_u32[0], ss
->sec.ci.peer._S6_un._S6_u32[1], ss->sec.ci.peer._S6_un
._S6_u32[2], ss->sec.ci.peer._S6_un._S6_u32[3])
9271 SSL_GETPID(), ss->fd, ss->sec.ci.peer.pr_s6_addr32[0],if (ssl_trace >= (7)) ssl_Trace ("%d: SSL3[%d]: server, lookup client session-id for 0x%08x%08x%08x%08x"
, getpid(), ss->fd, ss->sec.ci.peer._S6_un._S6_u32[0], ss
->sec.ci.peer._S6_un._S6_u32[1], ss->sec.ci.peer._S6_un
._S6_u32[2], ss->sec.ci.peer._S6_un._S6_u32[3])
9272 ss->sec.ci.peer.pr_s6_addr32[1],if (ssl_trace >= (7)) ssl_Trace ("%d: SSL3[%d]: server, lookup client session-id for 0x%08x%08x%08x%08x"
, getpid(), ss->fd, ss->sec.ci.peer._S6_un._S6_u32[0], ss
->sec.ci.peer._S6_un._S6_u32[1], ss->sec.ci.peer._S6_un
._S6_u32[2], ss->sec.ci.peer._S6_un._S6_u32[3])
9273 ss->sec.ci.peer.pr_s6_addr32[2],if (ssl_trace >= (7)) ssl_Trace ("%d: SSL3[%d]: server, lookup client session-id for 0x%08x%08x%08x%08x"
, getpid(), ss->fd, ss->sec.ci.peer._S6_un._S6_u32[0], ss
->sec.ci.peer._S6_un._S6_u32[1], ss->sec.ci.peer._S6_un
._S6_u32[2], ss->sec.ci.peer._S6_un._S6_u32[3])
9274 ss->sec.ci.peer.pr_s6_addr32[3]))if (ssl_trace >= (7)) ssl_Trace ("%d: SSL3[%d]: server, lookup client session-id for 0x%08x%08x%08x%08x"
, getpid(), ss->fd, ss->sec.ci.peer._S6_un._S6_u32[0], ss
->sec.ci.peer._S6_un._S6_u32[1], ss->sec.ci.peer._S6_un
._S6_u32[2], ss->sec.ci.peer._S6_un._S6_u32[3])
;
9275 if (ssl_sid_lookup) {
9276 sid = (*ssl_sid_lookup)(ssl_Time(ss), &ss->sec.ci.peer,
9277 sidBytes.data, sidBytes.len, ss->dbHandle);
9278 } else {
9279 errCode = SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED;
9280 goto loser;
9281 }
9282 }
9283 } else if (ss->statelessResume) {
9284 /* Fill in the client's session ID if doing a stateless resume.
9285 * (When doing stateless resumes, server echos client's SessionID.)
9286 * This branch also handles TLS 1.3 resumption-PSK.
9287 */
9288 sid = ss->sec.ci.sid;
9289 PORT_Assert(sid != NULL)((sid != ((void*)0))?((void)0):PR_Assert("sid != NULL","ssl3con.c"
,9289))
; /* Should have already been filled in.*/
9290
9291 if (sidBytes.len > 0 && sidBytes.len <= SSL3_SESSIONID_BYTES32) {
9292 sid->u.ssl3.sessionIDLength = sidBytes.len;
9293 PORT_Memcpymemcpy(sid->u.ssl3.sessionID, sidBytes.data,
9294 sidBytes.len);
9295 sid->u.ssl3.sessionIDLength = sidBytes.len;
9296 } else {
9297 sid->u.ssl3.sessionIDLength = 0;
9298 }
9299 ss->sec.ci.sid = NULL((void*)0);
9300 }
9301
9302 /* Free a potentially leftover session ID from a previous handshake. */
9303 if (ss->sec.ci.sid) {
9304 ssl_FreeSID(ss->sec.ci.sid);
9305 ss->sec.ci.sid = NULL((void*)0);
9306 }
9307
9308 if (sid != NULL((void*)0)) {
9309 /* We've found a session cache entry for this client.
9310 * Now, if we're going to require a client-auth cert,
9311 * and we don't already have this client's cert in the session cache,
9312 * and this is the first handshake on this connection (not a redo),
9313 * then drop this old cache entry and start a new session.
9314 */
9315 if ((sid->peerCert == NULL((void*)0)) && ss->opt.requestCertificate &&
9316 ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS((PRBool)1)) ||
9317 (ss->opt.requireCertificate == SSL_REQUIRE_NO_ERROR((PRBool)3)) ||
9318 ((ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE((PRBool)2)) &&
9319 !ss->firstHsDone))) {
9320
9321 SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_not_ok);
9322 ssl_FreeSID(sid);
9323 sid = NULL((void*)0);
9324 ss->statelessResume = PR_FALSE0;
9325 }
9326 }
9327
9328 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
9329 ssl3_DisableNonDTLSSuites(ss);
9330 dtls_ReceivedFirstMessageInFlight(ss);
9331 }
9332
9333 if (isTLS13) {
9334 rv = tls13_HandleClientHelloPart2(ss, &suites, sid,
9335 ss->ssl3.hs.echAccepted ? echInner->data : savedMsg,
9336 ss->ssl3.hs.echAccepted ? echInner->len : savedLen);
9337 SECITEM_FreeItemSECITEM_FreeItem_Util(echInner, PR_TRUE1);
9338 echInner = NULL((void*)0);
9339 } else {
9340 rv = ssl3_HandleClientHelloPart2(ss, &suites, sid,
9341 savedMsg, savedLen);
9342 }
9343 if (rv != SECSuccess) {
9344 errCode = PORT_GetErrorPORT_GetError_Util();
9345 goto loser;
9346 }
9347 return SECSuccess;
9348
9349alert_loser:
9350 (void)SSL3_SendAlert(ss, level, desc);
9351/* FALLTHRU */
9352loser:
9353 SECITEM_FreeItemSECITEM_FreeItem_Util(echInner, PR_TRUE1);
9354 PORT_SetErrorPORT_SetError_Util(errCode);
9355 return SECFailure;
9356}
9357
9358/* unwrap helper function to handle the case where the wrapKey doesn't wind
9359 * up in the correct token for the master secret */
9360PK11SymKey *
9361ssl_unwrapSymKey(PK11SymKey *wrapKey,
9362 CK_MECHANISM_TYPE wrapType, SECItem *param,
9363 SECItem *wrappedKey,
9364 CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
9365 int keySize, CK_FLAGS keyFlags, void *pinArg)
9366{
9367 PK11SymKey *unwrappedKey;
9368
9369 /* unwrap the master secret. */
9370 unwrappedKey = PK11_UnwrapSymKeyWithFlags(wrapKey, wrapType, param,
9371 wrappedKey, target, operation, keySize,
9372 keyFlags);
9373 if (!unwrappedKey) {
9374 PK11SlotInfo *targetSlot = PK11_GetBestSlot(target, pinArg);
9375 PK11SymKey *newWrapKey;
9376
9377 /* it's possible that we failed to unwrap because the wrapKey is in
9378 * a slot that can't handle target. Move the wrapKey to a slot that
9379 * can handle this mechanism and retry the operation */
9380 if (targetSlot == NULL((void*)0)) {
9381 return NULL((void*)0);
9382 }
9383 newWrapKey = PK11_MoveSymKey(targetSlot, CKA_UNWRAP0x00000107UL, 0,
9384 PR_FALSE0, wrapKey);
9385 PK11_FreeSlot(targetSlot);
9386 if (newWrapKey == NULL((void*)0)) {
9387 return NULL((void*)0);
9388 }
9389 unwrappedKey = PK11_UnwrapSymKeyWithFlags(newWrapKey, wrapType, param,
9390 wrappedKey, target, operation, keySize,
9391 keyFlags);
9392 PK11_FreeSymKey(newWrapKey);
9393 }
9394 return unwrappedKey;
9395}
9396
9397static SECStatus
9398ssl3_UnwrapMasterSecretServer(sslSocket *ss, sslSessionID *sid, PK11SymKey **ms)
9399{
9400 PK11SymKey *wrapKey;
9401 CK_FLAGS keyFlags = 0;
9402 SECItem wrappedMS = {
9403 siBuffer,
9404 sid->u.ssl3.keys.wrapped_master_secret,
9405 sid->u.ssl3.keys.wrapped_master_secret_len
9406 };
9407
9408 wrapKey = ssl3_GetWrappingKey(ss, NULL((void*)0), sid->u.ssl3.masterWrapMech,
9409 ss->pkcs11PinArg);
9410 if (!wrapKey) {
9411 return SECFailure;
9412 }
9413
9414 if (ss->version > SSL_LIBRARY_VERSION_3_00x0300) { /* isTLS */
9415 keyFlags = CKF_SIGN0x00000800UL | CKF_VERIFY0x00002000;
9416 }
9417
9418 *ms = ssl_unwrapSymKey(wrapKey, sid->u.ssl3.masterWrapMech, NULL((void*)0),
9419 &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE0x00000371UL,
9420 CKA_DERIVE0x0000010CUL, SSL3_MASTER_SECRET_LENGTH48,
9421 keyFlags, ss->pkcs11PinArg);
9422 PK11_FreeSymKey(wrapKey);
9423 if (!*ms) {
9424 SSL_TRC(10, ("%d: SSL3[%d]: server wrapping key found, but couldn't unwrap MasterSecret. wrapMech=0x%0lx",if (ssl_trace >= (10)) ssl_Trace ("%d: SSL3[%d]: server wrapping key found, but couldn't unwrap MasterSecret. wrapMech=0x%0lx"
, getpid(), ss->fd, sid->u.ssl3.masterWrapMech)
9425 SSL_GETPID(), ss->fd, sid->u.ssl3.masterWrapMech))if (ssl_trace >= (10)) ssl_Trace ("%d: SSL3[%d]: server wrapping key found, but couldn't unwrap MasterSecret. wrapMech=0x%0lx"
, getpid(), ss->fd, sid->u.ssl3.masterWrapMech)
;
9426 return SECFailure;
9427 }
9428 return SECSuccess;
9429}
9430
9431static SECStatus
9432ssl3_HandleClientHelloPart2(sslSocket *ss,
9433 SECItem *suites,
9434 sslSessionID *sid,
9435 const PRUint8 *msg,
9436 unsigned int len)
9437{
9438 PRBool haveXmitBufLock = PR_FALSE0;
9439 int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
9440 SSL3AlertDescription desc = illegal_parameter;
9441 SECStatus rv;
9442 unsigned int i;
9443 unsigned int j;
9444
9445 rv = ssl_HashHandshakeMessage(ss, ssl_hs_client_hello, msg, len);
9446 if (rv != SECSuccess) {
9447 errCode = SEC_ERROR_LIBRARY_FAILURE;
9448 desc = internal_error;
9449 goto alert_loser;
9450 }
9451
9452 /* If we already have a session for this client, be sure to pick the same
9453 ** cipher suite we picked before. This is not a loop, despite appearances.
9454 */
9455 if (sid)
9456 do {
9457 ssl3CipherSuiteCfg *suite;
9458 SSLVersionRange vrange = { ss->version, ss->version };
9459
9460 suite = ss->cipherSuites;
9461 /* Find the entry for the cipher suite used in the cached session. */
9462 for (j = ssl_V3_SUITES_IMPLEMENTED71; j > 0; --j, ++suite) {
9463 if (suite->cipher_suite == sid->u.ssl3.cipherSuite)
9464 break;
9465 }
9466 PORT_Assert(j > 0)((j > 0)?((void)0):PR_Assert("j > 0","ssl3con.c",9466));
9467 if (j == 0)
9468 break;
9469
9470 /* Double check that the cached cipher suite is still enabled,
9471 * implemented, and allowed by policy. Might have been disabled.
9472 */
9473 if (ssl3_config_match_init(ss) == 0) {
9474 desc = handshake_failure;
9475 errCode = PORT_GetErrorPORT_GetError_Util();
9476 goto alert_loser;
9477 }
9478 if (!ssl3_config_match(suite, ss->ssl3.policy, &vrange, ss))
9479 break;
9480
9481 /* Double check that the cached cipher suite is in the client's
9482 * list. If it isn't, fall through and start a new session. */
9483 for (i = 0; i + 1 < suites->len; i += 2) {
9484 PRUint16 suite_i = (suites->data[i] << 8) | suites->data[i + 1];
9485 if (suite_i == suite->cipher_suite) {
9486 ss->ssl3.hs.cipher_suite = suite_i;
9487 rv = ssl3_SetupCipherSuite(ss, PR_TRUE1);
9488 if (rv != SECSuccess) {
9489 desc = internal_error;
9490 errCode = PORT_GetErrorPORT_GetError_Util();
9491 goto alert_loser;
9492 }
9493
9494 goto cipher_found;
9495 }
9496 }
9497 } while (0);
9498 /* START A NEW SESSION */
9499
9500 rv = ssl3_NegotiateCipherSuite(ss, suites, PR_TRUE1);
9501 if (rv != SECSuccess) {
9502 desc = handshake_failure;
9503 errCode = PORT_GetErrorPORT_GetError_Util();
9504 goto alert_loser;
9505 }
9506
9507cipher_found:
9508 suites->data = NULL((void*)0);
9509
9510 /* If there are any failures while processing the old sid,
9511 * we don't consider them to be errors. Instead, We just behave
9512 * as if the client had sent us no sid to begin with, and make a new one.
9513 * The exception here is attempts to resume extended_master_secret
9514 * sessions without the extension, which causes an alert.
9515 */
9516 if (sid != NULL((void*)0))
9517 do {
9518 PK11SymKey *masterSecret;
9519
9520 if (sid->version != ss->version ||
9521 sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite) {
9522 break; /* not an error */
9523 }
9524
9525 /* server sids don't remember the server cert we previously sent,
9526 ** but they do remember the slot we originally used, so we
9527 ** can locate it again, provided that the current ssl socket
9528 ** has had its server certs configured the same as the previous one.
9529 */
9530 ss->sec.serverCert = ssl_FindServerCert(ss, sid->authType, sid->namedCurve);
9531 if (!ss->sec.serverCert || !ss->sec.serverCert->serverCert) {
9532 /* A compatible certificate must not have been configured. It
9533 * might not be the same certificate, but we only find that out
9534 * when the ticket fails to decrypt. */
9535 break;
9536 }
9537
9538 /* [draft-ietf-tls-session-hash-06; Section 5.3]
9539 * o If the original session did not use the "extended_master_secret"
9540 * extension but the new ClientHello contains the extension, then the
9541 * server MUST NOT perform the abbreviated handshake. Instead, it
9542 * SHOULD continue with a full handshake (as described in
9543 * Section 5.2) to negotiate a new session.
9544 *
9545 * o If the original session used the "extended_master_secret"
9546 * extension but the new ClientHello does not contain the extension,
9547 * the server MUST abort the abbreviated handshake.
9548 */
9549 if (ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) {
9550 if (!sid->u.ssl3.keys.extendedMasterSecretUsed) {
9551 break; /* not an error */
9552 }
9553 } else {
9554 if (sid->u.ssl3.keys.extendedMasterSecretUsed) {
9555 /* Note: we do not destroy the session */
9556 desc = handshake_failure;
9557 errCode = SSL_ERROR_MISSING_EXTENDED_MASTER_SECRET;
9558 goto alert_loser;
9559 }
9560 }
9561
9562 if (ss->sec.ci.sid) {
9563 ssl_UncacheSessionID(ss);
9564 PORT_Assert(ss->sec.ci.sid != sid)((ss->sec.ci.sid != sid)?((void)0):PR_Assert("ss->sec.ci.sid != sid"
,"ssl3con.c",9564))
; /* should be impossible, but ... */
9565 if (ss->sec.ci.sid != sid) {
9566 ssl_FreeSID(ss->sec.ci.sid);
9567 }
9568 ss->sec.ci.sid = NULL((void*)0);
9569 }
9570
9571 /* we need to resurrect the master secret.... */
9572 rv = ssl3_UnwrapMasterSecretServer(ss, sid, &masterSecret);
9573 if (rv != SECSuccess) {
9574 break; /* not an error */
9575 }
9576
9577 ss->sec.ci.sid = sid;
9578 if (sid->peerCert != NULL((void*)0)) {
9579 ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
9580 }
9581
9582 /*
9583 * Old SID passed all tests, so resume this old session.
9584 */
9585 SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_hits);
9586 if (ss->statelessResume)
9587 SSL_AtomicIncrementLong(&ssl3stats.hch_sid_stateless_resumes);
9588 ss->ssl3.hs.isResuming = PR_TRUE1;
9589
9590 ss->sec.authType = sid->authType;
9591 ss->sec.authKeyBits = sid->authKeyBits;
9592 ss->sec.keaType = sid->keaType;
9593 ss->sec.keaKeyBits = sid->keaKeyBits;
9594 ss->sec.originalKeaGroup = ssl_LookupNamedGroup(sid->keaGroup);
9595 ss->sec.signatureScheme = sid->sigScheme;
9596
9597 ss->sec.localCert =
9598 CERT_DupCertificate(ss->sec.serverCert->serverCert);
9599
9600 /* Copy cached name in to pending spec */
9601 if (sid != NULL((void*)0) &&
9602 sid->version > SSL_LIBRARY_VERSION_3_00x0300 &&
9603 sid->u.ssl3.srvName.len && sid->u.ssl3.srvName.data) {
9604 /* Set server name from sid */
9605 SECItem *sidName = &sid->u.ssl3.srvName;
9606 SECItem *pwsName = &ss->ssl3.hs.srvVirtName;
9607 if (pwsName->data) {
9608 SECITEM_FreeItemSECITEM_FreeItem_Util(pwsName, PR_FALSE0);
9609 }
9610 rv = SECITEM_CopyItemSECITEM_CopyItem_Util(NULL((void*)0), pwsName, sidName);
9611 if (rv != SECSuccess) {
9612 errCode = PORT_GetErrorPORT_GetError_Util();
9613 desc = internal_error;
9614 goto alert_loser;
9615 }
9616 }
9617
9618 /* Clean up sni name array */
9619 ssl3_FreeSniNameArray(&ss->xtnData);
9620
9621 ssl_GetXmitBufLock(ss){ if (!ss->opt.noLocks) PR_EnterMonitor(((ss)->xmitBufLock
)); }
;
9622 haveXmitBufLock = PR_TRUE1;
9623
9624 rv = ssl3_SendServerHello(ss);
9625 if (rv != SECSuccess) {
9626 errCode = PORT_GetErrorPORT_GetError_Util();
9627 goto loser;
9628 }
9629
9630 /* We are re-using the old MS, so no need to derive again. */
9631 rv = ssl3_InitPendingCipherSpecs(ss, masterSecret, PR_FALSE0);
9632 if (rv != SECSuccess) {
9633 errCode = PORT_GetErrorPORT_GetError_Util();
9634 goto loser;
9635 }
9636
9637 rv = ssl3_SendChangeCipherSpecs(ss);
9638 if (rv != SECSuccess) {
9639 errCode = PORT_GetErrorPORT_GetError_Util();
9640 goto loser;
9641 }
9642 rv = ssl3_SendFinished(ss, 0);
9643 ss->ssl3.hs.ws = wait_change_cipher;
9644 if (rv != SECSuccess) {
9645 errCode = PORT_GetErrorPORT_GetError_Util();
9646 goto loser;
9647 }
9648
9649 if (haveXmitBufLock) {
9650 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
;
9651 }
9652
9653 return SECSuccess;
9654 } while (0);
9655
9656 if (sid) { /* we had a sid, but it's no longer valid, free it */
9657 ss->statelessResume = PR_FALSE0;
9658 SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_not_ok);
9659 ssl_UncacheSessionID(ss);
9660 ssl_FreeSID(sid);
9661 sid = NULL((void*)0);
9662 }
9663 SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_misses);
9664
9665 /* We only send a session ticket extension if the client supports
9666 * the extension and we are unable to resume.
9667 *
9668 * TODO: send a session ticket if performing a stateful
9669 * resumption. (As per RFC4507, a server may issue a session
9670 * ticket while doing a (stateless or stateful) session resume,
9671 * but OpenSSL-0.9.8g does not accept session tickets while
9672 * resuming.)
9673 */
9674 if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) &&
9675 ssl3_KEASupportsTickets(ss->ssl3.hs.kea_def)) {
9676 ssl3_RegisterExtensionSender(ss, &ss->xtnData, ssl_session_ticket_xtn,
9677 ssl_SendEmptyExtension);
9678 }
9679
9680 rv = ssl3_ServerCallSNICallback(ss);
9681 if (rv != SECSuccess) {
9682 /* The alert has already been sent. */
9683 errCode = PORT_GetErrorPORT_GetError_Util();
9684 goto loser;
9685 }
9686
9687 rv = ssl3_SelectServerCert(ss);
9688 if (rv != SECSuccess) {
9689 errCode = PORT_GetErrorPORT_GetError_Util();
9690 desc = handshake_failure;
9691 goto alert_loser;
9692 }
9693
9694 sid = ssl3_NewSessionID(ss, PR_TRUE1);
9695 if (sid == NULL((void*)0)) {
9696 errCode = PORT_GetErrorPORT_GetError_Util();
9697 goto loser; /* memory error is set. */
9698 }
9699 ss->sec.ci.sid = sid;
9700
9701 sid->u.ssl3.keys.extendedMasterSecretUsed =
9702 ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn);
9703 ss->ssl3.hs.isResuming = PR_FALSE0;
9704
9705 ssl_GetXmitBufLock(ss){ if (!ss->opt.noLocks) PR_EnterMonitor(((ss)->xmitBufLock
)); }
;
9706 rv = ssl3_SendServerHelloSequence(ss);
9707 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
;
9708 if (rv != SECSuccess) {
9709 errCode = PORT_GetErrorPORT_GetError_Util();
9710 desc = handshake_failure;
9711 goto alert_loser;
9712 }
9713
9714 if (haveXmitBufLock) {
9715 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
;
9716 }
9717
9718 return SECSuccess;
9719
9720alert_loser:
9721 (void)SSL3_SendAlert(ss, alert_fatal, desc);
9722/* FALLTHRU */
9723loser:
9724 if (sid && sid != ss->sec.ci.sid) {
9725 ssl_UncacheSessionID(ss);
9726 ssl_FreeSID(sid);
9727 }
9728
9729 if (haveXmitBufLock) {
9730 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
;
9731 }
9732
9733 PORT_SetErrorPORT_SetError_Util(errCode);
9734 return SECFailure;
9735}
9736
9737/*
9738 * ssl3_HandleV2ClientHello is used when a V2 formatted hello comes
9739 * in asking to use the V3 handshake.
9740 */
9741SECStatus
9742ssl3_HandleV2ClientHello(sslSocket *ss, unsigned char *buffer, unsigned int length,
9743 PRUint8 padding)
9744{
9745 sslSessionID *sid = NULL((void*)0);
9746 unsigned char *suites;
9747 unsigned char *random;
9748 SSL3ProtocolVersion version;
9749 SECStatus rv;
9750 unsigned int i;
9751 unsigned int j;
9752 unsigned int sid_length;
9753 unsigned int suite_length;
9754 unsigned int rand_length;
9755 int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
9756 SSL3AlertDescription desc = handshake_failure;
9757 unsigned int total = SSL_HL_CLIENT_HELLO_HBYTES9;
9758
9759 SSL_TRC(3, ("%d: SSL3[%d]: handle v2 client_hello", SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: handle v2 client_hello"
, getpid(), ss->fd)
;
9760
9761 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->recvBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveRecvBufLock(ss)"
,"ssl3con.c",9761))
;
9762
9763 ssl_GetSSL3HandshakeLock(ss){ if (!ss->opt.noLocks) { ((!((PR_GetMonitorEntryCount(((ss
)->xmitBufLock)) > 0)))?((void)0):PR_Assert("!ssl_HaveXmitBufLock(ss)"
,"ssl3con.c",9763)); PR_EnterMonitor(((ss)->ssl3HandshakeLock
)); } }
;
9764
9765 version = (buffer[1] << 8) | buffer[2];
9766 if (version < SSL_LIBRARY_VERSION_3_00x0300) {
9767 goto loser;
9768 }
9769
9770 ssl3_RestartHandshakeHashes(ss);
9771
9772 if (ss->ssl3.hs.ws != wait_client_hello) {
9773 desc = unexpected_message;
9774 errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO;
9775 goto alert_loser;
9776 }
9777
9778 total += suite_length = (buffer[3] << 8) | buffer[4];
9779 total += sid_length = (buffer[5] << 8) | buffer[6];
9780 total += rand_length = (buffer[7] << 8) | buffer[8];
9781 total += padding;
9782 ss->clientHelloVersion = version;
9783
9784 if (version >= SSL_LIBRARY_VERSION_TLS_1_30x0304) {
9785 /* [draft-ietf-tls-tls-11; C.3] forbids sending a TLS 1.3
9786 * ClientHello using the backwards-compatible format. */
9787 desc = illegal_parameter;
9788 errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
9789 goto alert_loser;
9790 }
9791
9792 rv = ssl3_NegotiateVersion(ss, version, PR_TRUE1);
9793 if (rv != SECSuccess) {
9794 /* send back which ever alert client will understand. */
9795 desc = (version > SSL_LIBRARY_VERSION_3_00x0300) ? protocol_version
9796 : handshake_failure;
9797 errCode = SSL_ERROR_UNSUPPORTED_VERSION;
9798 goto alert_loser;
9799 }
9800 /* ECH not possible here. */
9801 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_ech(1U << 4);
9802 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version(1U << 0);
9803 if (!ss->firstHsDone) {
9804 ssl_GetSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_LockWrite_Util((ss)->
specLock); }
;
9805 ssl_SetSpecVersions(ss, ss->ssl3.cwSpec);
9806 ssl_ReleaseSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockWrite_Util((ss)->
specLock); }
;
9807 }
9808
9809 /* if we get a non-zero SID, just ignore it. */
9810 if (length != total) {
9811 SSL_DBG(("%d: SSL3[%d]: bad v2 client hello message, len=%d should=%d",if (ssl_debug) ssl_Trace ("%d: SSL3[%d]: bad v2 client hello message, len=%d should=%d"
, getpid(), ss->fd, length, total)
9812 SSL_GETPID(), ss->fd, length, total))if (ssl_debug) ssl_Trace ("%d: SSL3[%d]: bad v2 client hello message, len=%d should=%d"
, getpid(), ss->fd, length, total)
;
9813 desc = illegal_parameter;
9814 errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
9815 goto alert_loser;
9816 }
9817
9818 suites = buffer + SSL_HL_CLIENT_HELLO_HBYTES9;
9819 random = suites + suite_length + sid_length;
9820
9821 if (rand_length < SSL_MIN_CHALLENGE_BYTES16 ||
9822 rand_length > SSL_MAX_CHALLENGE_BYTES32) {
9823 desc = illegal_parameter;
9824 errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
9825 goto alert_loser;
9826 }
9827
9828 PORT_Assert(SSL_MAX_CHALLENGE_BYTES == SSL3_RANDOM_LENGTH)((32 == 32)?((void)0):PR_Assert("SSL_MAX_CHALLENGE_BYTES == SSL3_RANDOM_LENGTH"
,"ssl3con.c",9828))
;
9829
9830 PORT_Memsetmemset(ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH32);
9831 PORT_Memcpymemcpy(&ss->ssl3.hs.client_random[SSL3_RANDOM_LENGTH32 - rand_length],
9832 random, rand_length);
9833
9834 PRINT_BUF(60, (ss, "client random:", ss->ssl3.hs.client_random,if (ssl_trace >= (60)) ssl_PrintBuf (ss, "client random:",
ss->ssl3.hs.client_random, 32)
9835 SSL3_RANDOM_LENGTH))if (ssl_trace >= (60)) ssl_PrintBuf (ss, "client random:",
ss->ssl3.hs.client_random, 32)
;
9836
9837 if (ssl3_config_match_init(ss) == 0) {
9838 errCode = PORT_GetErrorPORT_GetError_Util(); /* error code is already set. */
9839 goto alert_loser;
9840 }
9841
9842 /* Select a cipher suite.
9843 **
9844 ** NOTE: This suite selection algorithm should be the same as the one in
9845 ** ssl3_HandleClientHello().
9846 */
9847 for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED71; j++) {
9848 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j];
9849 SSLVersionRange vrange = { ss->version, ss->version };
9850 if (!ssl3_config_match(suite, ss->ssl3.policy, &vrange, ss)) {
9851 continue;
9852 }
9853 for (i = 0; i + 2 < suite_length; i += 3) {
9854 PRUint32 suite_i = (suites[i] << 16) | (suites[i + 1] << 8) | suites[i + 2];
9855 if (suite_i == suite->cipher_suite) {
9856 ss->ssl3.hs.cipher_suite = suite_i;
9857 rv = ssl3_SetupCipherSuite(ss, PR_TRUE1);
9858 if (rv != SECSuccess) {
9859 desc = internal_error;
9860 errCode = PORT_GetErrorPORT_GetError_Util();
9861 goto alert_loser;
9862 }
9863 goto suite_found;
9864 }
9865 }
9866 }
9867 errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
9868 goto alert_loser;
9869
9870suite_found:
9871
9872 /* If the ClientHello version is less than our maximum version, check for a
9873 * TLS_FALLBACK_SCSV and reject the connection if found. */
9874 if (ss->vrange.max > ss->clientHelloVersion) {
9875 for (i = 0; i + 2 < suite_length; i += 3) {
9876 PRUint16 suite_i = (suites[i] << 16) | (suites[i + 1] << 8) | suites[i + 2];
9877 if (suite_i == TLS_FALLBACK_SCSV0x5600) {
9878 desc = inappropriate_fallback;
9879 errCode = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT;
9880 goto alert_loser;
9881 }
9882 }
9883 }
9884
9885 /* Look for the SCSV, and if found, treat it just like an empty RI
9886 * extension by processing a local copy of an empty RI extension.
9887 */
9888 for (i = 0; i + 2 < suite_length; i += 3) {
9889 PRUint32 suite_i = (suites[i] << 16) | (suites[i + 1] << 8) | suites[i + 2];
9890 if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV0x00FF) {
9891 PRUint8 *b2 = (PRUint8 *)emptyRIext;
9892 PRUint32 L2 = sizeof emptyRIext;
9893 (void)ssl3_HandleExtensions(ss, &b2, &L2, ssl_hs_client_hello);
9894 break;
9895 }
9896 }
9897
9898 if (ss->opt.requireSafeNegotiation &&
9899 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
9900 desc = handshake_failure;
9901 errCode = SSL_ERROR_UNSAFE_NEGOTIATION;
9902 goto alert_loser;
9903 }
9904
9905 rv = ssl3_SelectServerCert(ss);
9906 if (rv != SECSuccess) {
9907 errCode = PORT_GetErrorPORT_GetError_Util();
9908 desc = handshake_failure;
9909 goto alert_loser;
9910 }
9911
9912 /* we don't even search for a cache hit here. It's just a miss. */
9913 SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_misses);
9914 sid = ssl3_NewSessionID(ss, PR_TRUE1);
9915 if (sid == NULL((void*)0)) {
9916 errCode = PORT_GetErrorPORT_GetError_Util();
9917 goto loser; /* memory error is set. */
9918 }
9919 ss->sec.ci.sid = sid;
9920 /* do not worry about memory leak of sid since it now belongs to ci */
9921
9922 /* We have to update the handshake hashes before we can send stuff */
9923 rv = ssl3_UpdateHandshakeHashes(ss, buffer, length);
9924 if (rv != SECSuccess) {
9925 errCode = PORT_GetErrorPORT_GetError_Util();
9926 goto loser;
9927 }
9928
9929 ssl_GetXmitBufLock(ss){ if (!ss->opt.noLocks) PR_EnterMonitor(((ss)->xmitBufLock
)); }
;
9930 rv = ssl3_SendServerHelloSequence(ss);
9931 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
;
9932 if (rv != SECSuccess) {
9933 errCode = PORT_GetErrorPORT_GetError_Util();
9934 goto loser;
9935 }
9936
9937 ssl_ReleaseSSL3HandshakeLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->ssl3HandshakeLock
)); }
;
9938 return SECSuccess;
9939
9940alert_loser:
9941 SSL3_SendAlert(ss, alert_fatal, desc);
9942loser:
9943 ssl_ReleaseSSL3HandshakeLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->ssl3HandshakeLock
)); }
;
9944 PORT_SetErrorPORT_SetError_Util(errCode);
9945 return SECFailure;
9946}
9947
9948SECStatus
9949ssl_ConstructServerHello(sslSocket *ss, PRBool helloRetry,
9950 const sslBuffer *extensionBuf, sslBuffer *messageBuf)
9951{
9952 SECStatus rv;
9953 SSL3ProtocolVersion version;
9954 sslSessionID *sid = ss->sec.ci.sid;
9955 const PRUint8 *random;
9956
9957 version = PR_MIN(ss->version, SSL_LIBRARY_VERSION_TLS_1_2)((ss->version)<(0x0303)?(ss->version):(0x0303));
9958 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
9959 version = dtls_TLSVersionToDTLSVersion(version);
9960 }
9961 rv = sslBuffer_AppendNumber(messageBuf, version, 2);
9962 if (rv != SECSuccess) {
9963 return SECFailure;
9964 }
9965
9966 if (helloRetry) {
9967 random = ssl_hello_retry_random;
9968 } else {
9969 rv = ssl_GenerateServerRandom(ss);
9970 if (rv != SECSuccess) {
9971 return SECFailure;
9972 }
9973 random = ss->ssl3.hs.server_random;
9974 }
9975 rv = sslBuffer_Append(messageBuf, random, SSL3_RANDOM_LENGTH32);
9976 if (rv != SECSuccess) {
9977 return SECFailure;
9978 }
9979
9980 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_30x0304) {
9981 if (sid) {
9982 rv = sslBuffer_AppendVariable(messageBuf, sid->u.ssl3.sessionID,
9983 sid->u.ssl3.sessionIDLength, 1);
9984 } else {
9985 rv = sslBuffer_AppendNumber(messageBuf, 0, 1);
9986 }
9987 } else {
9988 rv = sslBuffer_AppendVariable(messageBuf, ss->ssl3.hs.fakeSid.data,
9989 ss->ssl3.hs.fakeSid.len, 1);
9990 }
9991 if (rv != SECSuccess) {
9992 return SECFailure;
9993 }
9994
9995 rv = sslBuffer_AppendNumber(messageBuf, ss->ssl3.hs.cipher_suite, 2);
9996 if (rv != SECSuccess) {
9997 return SECFailure;
9998 }
9999 rv = sslBuffer_AppendNumber(messageBuf, ssl_compression_null, 1);
10000 if (rv != SECSuccess) {
10001 return SECFailure;
10002 }
10003 if (SSL_BUFFER_LEN(extensionBuf)((extensionBuf)->len)) {
10004 /* Directly copy the extensions */
10005 rv = sslBuffer_AppendBufferVariable(messageBuf, extensionBuf, 2);
10006 if (rv != SECSuccess) {
10007 return SECFailure;
10008 }
10009 }
10010
10011 if (ss->xtnData.ech && ss->xtnData.ech->receivedInnerXtn) {
10012 /* Signal ECH acceptance if we handled handled both CHOuter/CHInner (i.e.
10013 * in shared mode), or if we received a CHInner in split/backend mode. */
10014 if (ss->ssl3.hs.echAccepted || ss->opt.enableTls13BackendEch) {
10015 if (helloRetry) {
10016 return tls13_WriteServerEchHrrSignal(ss, SSL_BUFFER_BASE(messageBuf)((messageBuf)->buf),
10017 SSL_BUFFER_LEN(messageBuf)((messageBuf)->len));
10018 } else {
10019 return tls13_WriteServerEchSignal(ss, SSL_BUFFER_BASE(messageBuf)((messageBuf)->buf),
10020 SSL_BUFFER_LEN(messageBuf)((messageBuf)->len));
10021 }
10022 }
10023 }
10024 return SECSuccess;
10025}
10026
10027/* The negotiated version number has been already placed in ss->version.
10028**
10029** Called from: ssl3_HandleClientHello (resuming session),
10030** ssl3_SendServerHelloSequence <- ssl3_HandleClientHello (new session),
10031** ssl3_SendServerHelloSequence <- ssl3_HandleV2ClientHello (new session)
10032*/
10033SECStatus
10034ssl3_SendServerHello(sslSocket *ss)
10035{
10036 SECStatus rv;
10037 sslBuffer extensionBuf = SSL_BUFFER_EMPTY{ ((void*)0), 0, 0, 0 };
10038 sslBuffer messageBuf = SSL_BUFFER_EMPTY{ ((void*)0), 0, 0, 0 };
10039
10040 SSL_TRC(3, ("%d: SSL3[%d]: send server_hello handshake", SSL_GETPID(),if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: send server_hello handshake"
, getpid(), ss->fd)
10041 ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: send server_hello handshake"
, getpid(), ss->fd)
;
10042
10043 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->xmitBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveXmitBufLock(ss)"
,"ssl3con.c",10043))
;
10044 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",10044))
;
10045
10046 PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_3_0))((((unsigned char)(((unsigned)(ss->version)) >> 8)) ==
((unsigned char)(((unsigned)(0x0300)) >> 8)))?((void)0
):PR_Assert("MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_3_0)"
,"ssl3con.c",10046))
;
10047 if (MSB(ss->version)((unsigned char)(((unsigned)(ss->version)) >> 8)) != MSB(SSL_LIBRARY_VERSION_3_0)((unsigned char)(((unsigned)(0x0300)) >> 8))) {
10048 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_NO_CYPHER_OVERLAP);
10049 return SECFailure;
10050 }
10051
10052 rv = ssl_ConstructExtensions(ss, &extensionBuf, ssl_hs_server_hello);
10053 if (rv != SECSuccess) {
10054 goto loser;
10055 }
10056
10057 rv = ssl_ConstructServerHello(ss, PR_FALSE0, &extensionBuf, &messageBuf);
10058 if (rv != SECSuccess) {
10059 goto loser;
10060 }
10061
10062 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_server_hello,
10063 SSL_BUFFER_LEN(&messageBuf)((&messageBuf)->len));
10064 if (rv != SECSuccess) {
10065 goto loser; /* err set by AppendHandshake. */
10066 }
10067
10068 rv = ssl3_AppendHandshake(ss, SSL_BUFFER_BASE(&messageBuf)((&messageBuf)->buf),
10069 SSL_BUFFER_LEN(&messageBuf)((&messageBuf)->len));
10070 if (rv != SECSuccess) {
10071 goto loser; /* err set by AppendHandshake. */
10072 }
10073
10074 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_30x0304) {
10075 rv = ssl3_SetupBothPendingCipherSpecs(ss);
10076 if (rv != SECSuccess) {
10077 goto loser; /* err set */
10078 }
10079 }
10080
10081 sslBuffer_Clear(&extensionBuf);
10082 sslBuffer_Clear(&messageBuf);
10083 return SECSuccess;
10084
10085loser:
10086 sslBuffer_Clear(&extensionBuf);
10087 sslBuffer_Clear(&messageBuf);
10088 return SECFailure;
10089}
10090
10091SECStatus
10092ssl_CreateDHEKeyPair(const sslNamedGroupDef *groupDef,
10093 const ssl3DHParams *params,
10094 sslEphemeralKeyPair **keyPair)
10095{
10096 SECKEYDHParams dhParam;
10097 SECKEYPublicKey *pubKey = NULL((void*)0); /* Ephemeral DH key */
10098 SECKEYPrivateKey *privKey = NULL((void*)0); /* Ephemeral DH key */
10099 sslEphemeralKeyPair *pair;
10100
10101 dhParam.prime.data = params->prime.data;
10102 dhParam.prime.len = params->prime.len;
10103 dhParam.base.data = params->base.data;
10104 dhParam.base.len = params->base.len;
10105
10106 PRINT_BUF(60, (NULL, "Server DH p", dhParam.prime.data,if (ssl_trace >= (60)) ssl_PrintBuf (((void*)0), "Server DH p"
, dhParam.prime.data, dhParam.prime.len)
10107 dhParam.prime.len))if (ssl_trace >= (60)) ssl_PrintBuf (((void*)0), "Server DH p"
, dhParam.prime.data, dhParam.prime.len)
;
10108 PRINT_BUF(60, (NULL, "Server DH g", dhParam.base.data,if (ssl_trace >= (60)) ssl_PrintBuf (((void*)0), "Server DH g"
, dhParam.base.data, dhParam.base.len)
10109 dhParam.base.len))if (ssl_trace >= (60)) ssl_PrintBuf (((void*)0), "Server DH g"
, dhParam.base.data, dhParam.base.len)
;
10110
10111 /* Generate ephemeral DH keypair */
10112 privKey = SECKEY_CreateDHPrivateKey(&dhParam, &pubKey, NULL((void*)0));
10113 if (!privKey || !pubKey) {
10114 ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
10115 return SECFailure;
10116 }
10117
10118 pair = ssl_NewEphemeralKeyPair(groupDef, privKey, pubKey);
10119 if (!pair) {
10120 SECKEY_DestroyPrivateKey(privKey);
10121 SECKEY_DestroyPublicKey(pubKey);
10122
10123 return SECFailure;
10124 }
10125
10126 *keyPair = pair;
10127 return SECSuccess;
10128}
10129
10130static SECStatus
10131ssl3_SendDHServerKeyExchange(sslSocket *ss)
10132{
10133 const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def;
10134 SECStatus rv = SECFailure;
10135 int length;
10136 SECItem signed_hash = { siBuffer, NULL((void*)0), 0 };
10137 SSL3Hashes hashes;
10138 SSLHashType hashAlg;
10139
10140 const ssl3DHParams *params;
10141 sslEphemeralKeyPair *keyPair;
10142 SECKEYPublicKey *pubKey;
10143 SECKEYPrivateKey *certPrivateKey;
10144 const sslNamedGroupDef *groupDef;
10145 /* Do this on the heap, this could be over 2k long. */
10146 sslBuffer dhBuf = SSL_BUFFER_EMPTY{ ((void*)0), 0, 0, 0 };
10147
10148 if (kea_def->kea != kea_dhe_dss && kea_def->kea != kea_dhe_rsa) {
10149 /* TODO: Support DH_anon. It might be sufficient to drop the signature.
10150 See bug 1170510. */
10151 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
10152 return SECFailure;
10153 }
10154
10155 rv = ssl_SelectDHEGroup(ss, &groupDef);
10156 if (rv == SECFailure) {
10157 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_NO_CYPHER_OVERLAP);
10158 return SECFailure;
10159 }
10160 ss->sec.keaGroup = groupDef;
10161
10162 params = ssl_GetDHEParams(groupDef);
10163 rv = ssl_CreateDHEKeyPair(groupDef, params, &keyPair);
10164 if (rv == SECFailure) {
10165 ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
10166 return SECFailure;
10167 }
10168 PR_APPEND_LINK(&keyPair->link, &ss->ephemeralKeyPairs)do { (&keyPair->link)->next = (&ss->ephemeralKeyPairs
); (&keyPair->link)->prev = (&ss->ephemeralKeyPairs
)->prev; (&ss->ephemeralKeyPairs)->prev->next
= (&keyPair->link); (&ss->ephemeralKeyPairs)->
prev = (&keyPair->link); } while (0)
;
10169
10170 if (ss->version == SSL_LIBRARY_VERSION_TLS_1_20x0303) {
10171 hashAlg = ssl_SignatureSchemeToHashType(ss->ssl3.hs.signatureScheme);
10172 } else {
10173 /* Use ssl_hash_none to represent the MD5+SHA1 combo. */
10174 hashAlg = ssl_hash_none;
10175 }
10176
10177 pubKey = keyPair->keys->pubKey;
10178 PRINT_BUF(50, (ss, "DH public value:",if (ssl_trace >= (50)) ssl_PrintBuf (ss, "DH public value:"
, pubKey->u.dh.publicValue.data, pubKey->u.dh.publicValue
.len)
10179 pubKey->u.dh.publicValue.data,if (ssl_trace >= (50)) ssl_PrintBuf (ss, "DH public value:"
, pubKey->u.dh.publicValue.data, pubKey->u.dh.publicValue
.len)
10180 pubKey->u.dh.publicValue.len))if (ssl_trace >= (50)) ssl_PrintBuf (ss, "DH public value:"
, pubKey->u.dh.publicValue.data, pubKey->u.dh.publicValue
.len)
;
10181 rv = ssl3_ComputeDHKeyHash(ss, hashAlg, &hashes,
10182 pubKey->u.dh.prime,
10183 pubKey->u.dh.base,
10184 pubKey->u.dh.publicValue,
10185 PR_TRUE1 /* padY */);
10186 if (rv != SECSuccess) {
10187 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
10188 goto loser;
10189 }
10190
10191 certPrivateKey = ss->sec.serverCert->serverKeyPair->privKey;
10192 rv = ssl3_SignHashes(ss, &hashes, certPrivateKey, &signed_hash);
10193 if (rv != SECSuccess) {
10194 goto loser; /* ssl3_SignHashes has set err. */
10195 }
10196
10197 length = 2 + pubKey->u.dh.prime.len +
10198 2 + pubKey->u.dh.base.len +
10199 2 + pubKey->u.dh.prime.len +
10200 2 + signed_hash.len;
10201
10202 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_20x0303) {
10203 length += 2;
10204 }
10205
10206 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_server_key_exchange, length);
10207 if (rv != SECSuccess) {
10208 goto loser; /* err set by AppendHandshake. */
10209 }
10210
10211 rv = ssl3_AppendHandshakeVariable(ss, pubKey->u.dh.prime.data,
10212 pubKey->u.dh.prime.len, 2);
10213 if (rv != SECSuccess) {
10214 goto loser; /* err set by AppendHandshake. */
10215 }
10216
10217 rv = ssl3_AppendHandshakeVariable(ss, pubKey->u.dh.base.data,
10218 pubKey->u.dh.base.len, 2);
10219 if (rv != SECSuccess) {
10220 goto loser; /* err set by AppendHandshake. */
10221 }
10222
10223 rv = ssl_AppendPaddedDHKeyShare(&dhBuf, pubKey, PR_TRUE1);
10224 if (rv != SECSuccess) {
10225 goto loser; /* err set by AppendPaddedDHKeyShare. */
10226 }
10227 rv = ssl3_AppendBufferToHandshake(ss, &dhBuf);
10228 if (rv != SECSuccess) {
10229 goto loser; /* err set by AppendHandshake. */
10230 }
10231
10232 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_20x0303) {
10233 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.signatureScheme, 2);
10234 if (rv != SECSuccess) {
10235 goto loser; /* err set by AppendHandshake. */
10236 }
10237 }
10238
10239 rv = ssl3_AppendHandshakeVariable(ss, signed_hash.data,
10240 signed_hash.len, 2);
10241 if (rv != SECSuccess) {
10242 goto loser; /* err set by AppendHandshake. */
10243 }
10244
10245 sslBuffer_Clear(&dhBuf);
10246 PORT_FreePORT_Free_Util(signed_hash.data);
10247 return SECSuccess;
10248
10249loser:
10250 if (signed_hash.data)
10251 PORT_FreePORT_Free_Util(signed_hash.data);
10252 sslBuffer_Clear(&dhBuf);
10253 return SECFailure;
10254}
10255
10256static SECStatus
10257ssl3_SendServerKeyExchange(sslSocket *ss)
10258{
10259 const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def;
10260
10261 SSL_TRC(3, ("%d: SSL3[%d]: send server_key_exchange handshake",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: send server_key_exchange handshake"
, getpid(), ss->fd)
10262 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: send server_key_exchange handshake"
, getpid(), ss->fd)
;
10263
10264 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->xmitBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveXmitBufLock(ss)"
,"ssl3con.c",10264))
;
10265 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",10265))
;
10266
10267 switch (kea_def->exchKeyType) {
10268 case ssl_kea_dh: {
10269 return ssl3_SendDHServerKeyExchange(ss);
10270 }
10271
10272 case ssl_kea_ecdh: {
10273 return ssl3_SendECDHServerKeyExchange(ss);
10274 }
10275
10276 case ssl_kea_rsa:
10277 case ssl_kea_null:
10278 default:
10279 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
10280 break;
10281 }
10282
10283 return SECFailure;
10284}
10285
10286SECStatus
10287ssl3_EncodeSigAlgs(const sslSocket *ss, PRUint16 minVersion, PRBool forCert,
10288 PRBool grease, sslBuffer *buf)
10289{
10290 SSLSignatureScheme filtered[MAX_SIGNATURE_SCHEMES18] = { 0 };
10291 unsigned int filteredCount = 0;
10292
10293 SECStatus rv = ssl3_FilterSigAlgs(ss, minVersion, PR_FALSE0, forCert,
10294 PR_ARRAY_SIZE(filtered)(sizeof(filtered)/sizeof((filtered)[0])),
10295 filtered, &filteredCount);
10296 if (rv != SECSuccess) {
10297 return SECFailure;
10298 }
10299 return ssl3_EncodeFilteredSigAlgs(ss, filtered, filteredCount, grease, buf);
10300}
10301
10302SECStatus
10303ssl3_EncodeFilteredSigAlgs(const sslSocket *ss, const SSLSignatureScheme *schemes,
10304 PRUint32 numSchemes, PRBool grease, sslBuffer *buf)
10305{
10306 if (!numSchemes) {
10307 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM);
10308 return SECFailure;
10309 }
10310
10311 unsigned int lengthOffset;
10312 SECStatus rv;
10313
10314 rv = sslBuffer_Skip(buf, 2, &lengthOffset);
10315 if (rv != SECSuccess) {
10316 return SECFailure;
10317 }
10318
10319 for (unsigned int i = 0; i < numSchemes; ++i) {
10320 rv = sslBuffer_AppendNumber(buf, schemes[i], 2);
10321 if (rv != SECSuccess) {
10322 return SECFailure;
10323 }
10324 }
10325
10326 /* GREASE SignatureAlgorithms:
10327 * A client MAY select one or more GREASE signature algorithm values and
10328 * advertise them in the "signature_algorithms" or
10329 * "signature_algorithms_cert" extensions, if sent [RFC8701, Section 3.1].
10330 *
10331 * When sending a CertificateRequest in TLS 1.3, a server MAY behave as
10332 * follows: [...] A server MAY select one or more GREASE signature
10333 * algorithm values and advertise them in the "signature_algorithms" or
10334 * "signature_algorithms_cert" extensions, if present
10335 * [RFC8701, Section 4.1]. */
10336 if (grease &&
10337 ((!ss->sec.isServer && ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_30x0304) ||
10338 (ss->sec.isServer && ss->version >= SSL_LIBRARY_VERSION_TLS_1_30x0304))) {
10339 PRUint16 value;
10340 if (ss->sec.isServer) {
10341 rv = tls13_RandomGreaseValue(&value);
10342 if (rv != SECSuccess) {
10343 return SECFailure;
10344 }
10345 } else {
10346 value = ss->ssl3.hs.grease->idx[grease_sigalg];
10347 }
10348 rv = sslBuffer_AppendNumber(buf, value, 2);
10349 if (rv != SECSuccess) {
10350 return SECFailure;
10351 }
10352 }
10353
10354 return sslBuffer_InsertLength(buf, lengthOffset, 2);
10355}
10356
10357/*
10358 * In TLS 1.3 we are permitted to advertise support for PKCS#1
10359 * schemes. This doesn't affect the signatures in TLS itself, just
10360 * those on certificates. Not advertising PKCS#1 signatures creates a
10361 * serious compatibility risk as it excludes many certificate chains
10362 * that include PKCS#1. Hence, forCert is used to enable advertising
10363 * PKCS#1 support. Note that we include these in signature_algorithms
10364 * because we don't yet support signature_algorithms_cert. TLS 1.3
10365 * requires that PKCS#1 schemes are placed last in the list if they
10366 * are present. This sorting can be removed once we support
10367 * signature_algorithms_cert.
10368 */
10369SECStatus
10370ssl3_FilterSigAlgs(const sslSocket *ss, PRUint16 minVersion, PRBool disableRsae,
10371 PRBool forCert,
10372 unsigned int maxSchemes, SSLSignatureScheme *filteredSchemes,
10373 unsigned int *numFilteredSchemes)
10374{
10375 PORT_Assert(filteredSchemes)((filteredSchemes)?((void)0):PR_Assert("filteredSchemes","ssl3con.c"
,10375))
;
10376 PORT_Assert(numFilteredSchemes)((numFilteredSchemes)?((void)0):PR_Assert("numFilteredSchemes"
,"ssl3con.c",10376))
;
10377 PORT_Assert(maxSchemes >= ss->ssl3.signatureSchemeCount)((maxSchemes >= ss->ssl3.signatureSchemeCount)?((void)0
):PR_Assert("maxSchemes >= ss->ssl3.signatureSchemeCount"
,"ssl3con.c",10377))
;
10378 if (maxSchemes < ss->ssl3.signatureSchemeCount) {
10379 return SECFailure;
10380 }
10381
10382 *numFilteredSchemes = 0;
10383 PRBool allowUnsortedPkcs1 = forCert && minVersion < SSL_LIBRARY_VERSION_TLS_1_30x0304;
10384 for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
10385 if (disableRsae && ssl_IsRsaeSignatureScheme(ss->ssl3.signatureSchemes[i])) {
10386 continue;
10387 }
10388 if (ssl_SignatureSchemeAccepted(minVersion,
10389 ss->ssl3.signatureSchemes[i],
10390 allowUnsortedPkcs1)) {
10391 filteredSchemes[(*numFilteredSchemes)++] = ss->ssl3.signatureSchemes[i];
10392 }
10393 }
10394 if (forCert && !allowUnsortedPkcs1) {
10395 for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
10396 if (disableRsae && ssl_IsRsaeSignatureScheme(ss->ssl3.signatureSchemes[i])) {
10397 continue;
10398 }
10399 if (!ssl_SignatureSchemeAccepted(minVersion,
10400 ss->ssl3.signatureSchemes[i],
10401 PR_FALSE0) &&
10402 ssl_SignatureSchemeAccepted(minVersion,
10403 ss->ssl3.signatureSchemes[i],
10404 PR_TRUE1)) {
10405 filteredSchemes[(*numFilteredSchemes)++] = ss->ssl3.signatureSchemes[i];
10406 }
10407 }
10408 }
10409 return SECSuccess;
10410}
10411
10412static SECStatus
10413ssl3_SendCertificateRequest(sslSocket *ss)
10414{
10415 PRBool isTLS12;
10416 const PRUint8 *certTypes;
10417 SECStatus rv;
10418 PRUint32 length;
10419 const SECItem *names;
10420 unsigned int calen;
10421 unsigned int nnames;
10422 const SECItem *name;
10423 unsigned int i;
10424 int certTypesLength;
10425 PRUint8 sigAlgs[2 + MAX_SIGNATURE_SCHEMES18 * 2];
10426 sslBuffer sigAlgsBuf = SSL_BUFFER(sigAlgs){ sigAlgs, 0, sizeof(sigAlgs), 1 };
10427
10428 SSL_TRC(3, ("%d: SSL3[%d]: send certificate_request handshake",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: send certificate_request handshake"
, getpid(), ss->fd)
10429 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: send certificate_request handshake"
, getpid(), ss->fd)
;
10430
10431 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->xmitBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveXmitBufLock(ss)"
,"ssl3con.c",10431))
;
10432 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",10432))
;
10433
10434 isTLS12 = (PRBool)(ss->version >= SSL_LIBRARY_VERSION_TLS_1_20x0303);
10435
10436 rv = ssl_GetCertificateRequestCAs(ss, &calen, &names, &nnames);
10437 if (rv != SECSuccess) {
10438 return rv;
10439 }
10440 certTypes = certificate_types;
10441 certTypesLength = sizeof certificate_types;
10442
10443 length = 1 + certTypesLength + 2 + calen;
10444 if (isTLS12) {
10445 rv = ssl3_EncodeSigAlgs(ss, ss->version, PR_TRUE1 /* forCert */,
10446 PR_FALSE0 /* GREASE */, &sigAlgsBuf);
10447 if (rv != SECSuccess) {
10448 return rv;
10449 }
10450 length += SSL_BUFFER_LEN(&sigAlgsBuf)((&sigAlgsBuf)->len);
10451 }
10452
10453 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_request, length);
10454 if (rv != SECSuccess) {
10455 return rv; /* err set by AppendHandshake. */
10456 }
10457 rv = ssl3_AppendHandshakeVariable(ss, certTypes, certTypesLength, 1);
10458 if (rv != SECSuccess) {
10459 return rv; /* err set by AppendHandshake. */
10460 }
10461 if (isTLS12) {
10462 rv = ssl3_AppendHandshake(ss, SSL_BUFFER_BASE(&sigAlgsBuf)((&sigAlgsBuf)->buf),
10463 SSL_BUFFER_LEN(&sigAlgsBuf)((&sigAlgsBuf)->len));
10464 if (rv != SECSuccess) {
10465 return rv; /* err set by AppendHandshake. */
10466 }
10467 }
10468 rv = ssl3_AppendHandshakeNumber(ss, calen, 2);
10469 if (rv != SECSuccess) {
10470 return rv; /* err set by AppendHandshake. */
10471 }
10472 for (i = 0, name = names; i < nnames; i++, name++) {
10473 rv = ssl3_AppendHandshakeVariable(ss, name->data, name->len, 2);
10474 if (rv != SECSuccess) {
10475 return rv; /* err set by AppendHandshake. */
10476 }
10477 }
10478
10479 return SECSuccess;
10480}
10481
10482static SECStatus
10483ssl3_SendServerHelloDone(sslSocket *ss)
10484{
10485 SECStatus rv;
10486
10487 SSL_TRC(3, ("%d: SSL3[%d]: send server_hello_done handshake",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: send server_hello_done handshake"
, getpid(), ss->fd)
10488 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: send server_hello_done handshake"
, getpid(), ss->fd)
;
10489
10490 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->xmitBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveXmitBufLock(ss)"
,"ssl3con.c",10490))
;
10491 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",10491))
;
10492
10493 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_server_hello_done, 0);
10494 if (rv != SECSuccess) {
10495 return rv; /* err set by AppendHandshake. */
10496 }
10497 rv = ssl3_FlushHandshake(ss, 0);
10498 if (rv != SECSuccess) {
10499 return rv; /* error code set by ssl3_FlushHandshake */
10500 }
10501 return SECSuccess;
10502}
10503
10504/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
10505 * a complete ssl3 Certificate Verify message
10506 * Caller must hold Handshake and RecvBuf locks.
10507 */
10508static SECStatus
10509ssl3_HandleCertificateVerify(sslSocket *ss, PRUint8 *b, PRUint32 length)
10510{
10511 SECItem signed_hash = { siBuffer, NULL((void*)0), 0 };
10512 SECStatus rv;
10513 int errCode = SSL_ERROR_RX_MALFORMED_CERT_VERIFY;
10514 SSL3AlertDescription desc = handshake_failure;
10515 PRBool isTLS;
10516 SSLSignatureScheme sigScheme;
10517 SSL3Hashes hashes;
10518 const PRUint8 *savedMsg = b;
10519 const PRUint32 savedLen = length;
10520
10521 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_verify handshake",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: handle certificate_verify handshake"
, getpid(), ss->fd)
10522 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: handle certificate_verify handshake"
, getpid(), ss->fd)
;
10523 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->recvBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveRecvBufLock(ss)"
,"ssl3con.c",10523))
;
10524 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",10524))
;
10525
10526 if (ss->ssl3.hs.ws != wait_cert_verify) {
10527 desc = unexpected_message;
10528 errCode = SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY;
10529 goto alert_loser;
10530 }
10531
10532 /* TLS 1.3 is handled by tls13_HandleCertificateVerify */
10533 PORT_Assert(ss->ssl3.prSpec->version <= SSL_LIBRARY_VERSION_TLS_1_2)((ss->ssl3.prSpec->version <= 0x0303)?((void)0):PR_Assert
("ss->ssl3.prSpec->version <= SSL_LIBRARY_VERSION_TLS_1_2"
,"ssl3con.c",10533))
;
10534
10535 if (ss->ssl3.prSpec->version == SSL_LIBRARY_VERSION_TLS_1_20x0303) {
10536 PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_record)((ss->ssl3.hs.hashType == handshake_hash_record)?((void)0)
:PR_Assert("ss->ssl3.hs.hashType == handshake_hash_record"
,"ssl3con.c",10536))
;
10537 rv = ssl_ConsumeSignatureScheme(ss, &b, &length, &sigScheme);
10538 if (rv != SECSuccess) {
10539 if (PORT_GetErrorPORT_GetError_Util() == SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM) {
10540 errCode = SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM;
10541 }
10542 goto loser; /* alert already sent */
10543 }
10544 rv = ssl_CheckSignatureSchemeConsistency(
10545 ss, sigScheme, &ss->sec.peerCert->subjectPublicKeyInfo);
10546 if (rv != SECSuccess) {
10547 errCode = PORT_GetErrorPORT_GetError_Util();
10548 desc = illegal_parameter;
10549 goto alert_loser;
10550 }
10551
10552 rv = ssl3_ComputeHandshakeHash(ss->ssl3.hs.messages.buf,
10553 ss->ssl3.hs.messages.len,
10554 ssl_SignatureSchemeToHashType(sigScheme),
10555 &hashes);
10556 } else {
10557 PORT_Assert(ss->ssl3.hs.hashType != handshake_hash_record)((ss->ssl3.hs.hashType != handshake_hash_record)?((void)0)
:PR_Assert("ss->ssl3.hs.hashType != handshake_hash_record"
,"ssl3con.c",10557))
;
10558 sigScheme = ssl_sig_none;
10559 rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.prSpec, &hashes, 0);
10560 }
10561
10562 if (rv != SECSuccess) {
10563 errCode = SSL_ERROR_DIGEST_FAILURE;
10564 desc = decrypt_error;
10565 goto alert_loser;
10566 }
10567
10568 rv = ssl3_ConsumeHandshakeVariable(ss, &signed_hash, 2, &b, &length);
10569 if (rv != SECSuccess) {
10570 goto loser; /* malformed. */
10571 }
10572
10573 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_00x0300);
10574
10575 /* XXX verify that the key & kea match */
10576 rv = ssl3_VerifySignedHashes(ss, sigScheme, &hashes, &signed_hash);
10577 if (rv != SECSuccess) {
10578 errCode = PORT_GetErrorPORT_GetError_Util();
10579 desc = isTLS ? decrypt_error : handshake_failure;
10580 goto alert_loser;
10581 }
10582
10583 signed_hash.data = NULL((void*)0);
10584
10585 if (length != 0) {
10586 desc = isTLS ? decode_error : illegal_parameter;
10587 goto alert_loser; /* malformed */
10588 }
10589
10590 rv = ssl_HashHandshakeMessage(ss, ssl_hs_certificate_verify,
10591 savedMsg, savedLen);
10592 if (rv != SECSuccess) {
10593 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
10594 return rv;
10595 }
10596
10597 ss->ssl3.hs.ws = wait_change_cipher;
10598 return SECSuccess;
10599
10600alert_loser:
10601 SSL3_SendAlert(ss, alert_fatal, desc);
10602loser:
10603 PORT_SetErrorPORT_SetError_Util(errCode);
10604 return SECFailure;
10605}
10606
10607/* find a slot that is able to generate a PMS and wrap it with RSA.
10608 * Then generate and return the PMS.
10609 * If the serverKeySlot parameter is non-null, this function will use
10610 * that slot to do the job, otherwise it will find a slot.
10611 *
10612 * Called from ssl3_DeriveConnectionKeys() (above)
10613 * ssl3_SendRSAClientKeyExchange() (above)
10614 * ssl3_HandleRSAClientKeyExchange() (below)
10615 * Caller must hold the SpecWriteLock, the SSL3HandshakeLock
10616 */
10617static PK11SymKey *
10618ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec,
10619 PK11SlotInfo *serverKeySlot)
10620{
10621 PK11SymKey *pms = NULL((void*)0);
10622 PK11SlotInfo *slot = serverKeySlot;
10623 void *pwArg = ss->pkcs11PinArg;
10624 SECItem param;
10625 CK_VERSION version;
10626 CK_MECHANISM_TYPE mechanism_array[3];
10627
10628 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",10628))
;
10629
10630 if (slot == NULL((void*)0)) {
10631 SSLCipherAlgorithm calg;
10632 /* The specReadLock would suffice here, but we cannot assert on
10633 ** read locks. Also, all the callers who call with a non-null
10634 ** slot already hold the SpecWriteLock.
10635 */
10636 PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss))((ss->opt.noLocks || (NSSRWLock_HaveWriteLock_Util((ss)->
specLock)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)"
,"ssl3con.c",10636))
;
10637 PORT_Assert(ss->ssl3.prSpec->epoch == ss->ssl3.pwSpec->epoch)((ss->ssl3.prSpec->epoch == ss->ssl3.pwSpec->epoch
)?((void)0):PR_Assert("ss->ssl3.prSpec->epoch == ss->ssl3.pwSpec->epoch"
,"ssl3con.c",10637))
;
10638
10639 calg = spec->cipherDef->calg;
10640
10641 /* First get an appropriate slot. */
10642 mechanism_array[0] = CKM_SSL3_PRE_MASTER_KEY_GEN0x00000370UL;
10643 mechanism_array[1] = CKM_RSA_PKCS0x00000001UL;
10644 mechanism_array[2] = ssl3_Alg2Mech(calg);
10645
10646 slot = PK11_GetBestSlotMultiple(mechanism_array, 3, pwArg);
10647 if (slot == NULL((void*)0)) {
10648 /* can't find a slot with all three, find a slot with the minimum */
10649 slot = PK11_GetBestSlotMultiple(mechanism_array, 2, pwArg);
10650 if (slot == NULL((void*)0)) {
10651 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_TOKEN_SLOT_NOT_FOUND);
10652 return pms; /* which is NULL */
10653 }
10654 }
10655 }
10656
10657 /* Generate the pre-master secret ... */
10658 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
10659 SSL3ProtocolVersion temp;
10660
10661 temp = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion);
10662 version.major = MSB(temp)((unsigned char)(((unsigned)(temp)) >> 8));
10663 version.minor = LSB(temp)((unsigned char)((temp)&0xff));
10664 } else {
10665 version.major = MSB(ss->clientHelloVersion)((unsigned char)(((unsigned)(ss->clientHelloVersion)) >>
8))
;
10666 version.minor = LSB(ss->clientHelloVersion)((unsigned char)((ss->clientHelloVersion)&0xff));
10667 }
10668
10669 param.data = (unsigned char *)&version;
10670 param.len = sizeof version;
10671
10672 pms = PK11_KeyGen(slot, CKM_SSL3_PRE_MASTER_KEY_GEN0x00000370UL, &param, 0, pwArg);
10673 if (!serverKeySlot)
10674 PK11_FreeSlot(slot);
10675 if (pms == NULL((void*)0)) {
10676 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
10677 }
10678 return pms;
10679}
10680
10681static void
10682ssl3_CSwapPK11SymKey(PK11SymKey **x, PK11SymKey **y, PRBool c)
10683{
10684 uintptr_t mask = (uintptr_t)c;
10685 unsigned int i;
10686 for (i = 1; i < sizeof(uintptr_t) * 8; i <<= 1) {
10687 mask |= mask << i;
10688 }
10689 uintptr_t x_ptr = (uintptr_t)*x;
10690 uintptr_t y_ptr = (uintptr_t)*y;
10691 uintptr_t tmp = (x_ptr ^ y_ptr) & mask;
10692 x_ptr = x_ptr ^ tmp;
10693 y_ptr = y_ptr ^ tmp;
10694 *x = (PK11SymKey *)x_ptr;
10695 *y = (PK11SymKey *)y_ptr;
10696}
10697
10698/* Note: The Bleichenbacher attack on PKCS#1 necessitates that we NEVER
10699 * return any indication of failure of the Client Key Exchange message,
10700 * where that failure is caused by the content of the client's message.
10701 * This function must not return SECFailure for any reason that is directly
10702 * or indirectly caused by the content of the client's encrypted PMS.
10703 * We must not send an alert and also not drop the connection.
10704 * Instead, we generate a random PMS. This will cause a failure
10705 * in the processing the finished message, which is exactly where
10706 * the failure must occur.
10707 *
10708 * Called from ssl3_HandleClientKeyExchange
10709 */
10710static SECStatus
10711ssl3_HandleRSAClientKeyExchange(sslSocket *ss,
10712 PRUint8 *b,
10713 PRUint32 length,
10714 sslKeyPair *serverKeyPair)
10715{
10716 SECStatus rv;
10717 SECItem enc_pms;
10718 PK11SymKey *pms = NULL((void*)0);
10719 PK11SymKey *fauxPms = NULL((void*)0);
10720 PK11SlotInfo *slot = NULL((void*)0);
10721
10722 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->recvBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveRecvBufLock(ss)"
,"ssl3con.c",10722))
;
10723 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",10723))
;
10724 PORT_Assert(ss->ssl3.prSpec->epoch == ss->ssl3.pwSpec->epoch)((ss->ssl3.prSpec->epoch == ss->ssl3.pwSpec->epoch
)?((void)0):PR_Assert("ss->ssl3.prSpec->epoch == ss->ssl3.pwSpec->epoch"
,"ssl3con.c",10724))
;
10725
10726 enc_pms.data = b;
10727 enc_pms.len = length;
10728
10729 if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_00x0300) { /* isTLS */
10730 PRUint32 kLen;
10731 rv = ssl3_ConsumeHandshakeNumber(ss, &kLen, 2, &enc_pms.data, &enc_pms.len);
10732 if (rv != SECSuccess) {
10733 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
10734 return SECFailure;
10735 }
10736 if ((unsigned)kLen < enc_pms.len) {
10737 enc_pms.len = kLen;
10738 }
10739 }
10740
10741 /*
10742 * Get as close to algorithm 2 from RFC 5246; Section 7.4.7.1
10743 * as we can within the constraints of the PKCS#11 interface.
10744 *
10745 * 1. Unconditionally generate a bogus PMS (what RFC 5246
10746 * calls R).
10747 * 2. Attempt the RSA decryption to recover the PMS (what
10748 * RFC 5246 calls M).
10749 * 3. Set PMS = (M == NULL) ? R : M
10750 * 4. Use ssl3_ComputeMasterSecret(PMS) to attempt to derive
10751 * the MS from PMS. This includes performing the version
10752 * check and length check.
10753 * 5. If either the initial RSA decryption failed or
10754 * ssl3_ComputeMasterSecret(PMS) failed, then discard
10755 * M and set PMS = R. Else, discard R and set PMS = M.
10756 *
10757 * We do two derivations here because we can't rely on having
10758 * a function that only performs the PMS version and length
10759 * check. The only redundant cost is that this runs the PRF,
10760 * which isn't necessary here.
10761 */
10762
10763 /* Generate the bogus PMS (R) */
10764 slot = PK11_GetSlotFromPrivateKey(serverKeyPair->privKey);
10765 if (!slot) {
10766 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
10767 return SECFailure;
10768 }
10769
10770 if (!PK11_DoesMechanism(slot, CKM_SSL3_MASTER_KEY_DERIVE0x00000371UL)) {
10771 PK11_FreeSlot(slot);
10772 slot = PK11_GetBestSlot(CKM_SSL3_MASTER_KEY_DERIVE0x00000371UL, NULL((void*)0));
10773 if (!slot) {
10774 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
10775 return SECFailure;
10776 }
10777 }
10778
10779 ssl_GetSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_LockWrite_Util((ss)->
specLock); }
;
10780 fauxPms = ssl3_GenerateRSAPMS(ss, ss->ssl3.prSpec, slot);
10781 ssl_ReleaseSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockWrite_Util((ss)->
specLock); }
;
10782 PK11_FreeSlot(slot);
10783
10784 if (fauxPms == NULL((void*)0)) {
10785 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
10786 return SECFailure;
10787 }
10788
10789 /*
10790 * unwrap pms out of the incoming buffer
10791 * Note: CKM_SSL3_MASTER_KEY_DERIVE is NOT the mechanism used to do
10792 * the unwrap. Rather, it is the mechanism with which the
10793 * unwrapped pms will be used.
10794 */
10795 pms = PK11_PubUnwrapSymKey(serverKeyPair->privKey, &enc_pms,
10796 CKM_SSL3_MASTER_KEY_DERIVE0x00000371UL, CKA_DERIVE0x0000010CUL, 0);
10797 /* Temporarily use the PMS if unwrapping the real PMS fails. */
10798 ssl3_CSwapPK11SymKey(&pms, &fauxPms, pms == NULL((void*)0));
10799
10800 /* Attempt to derive the MS from the PMS. This is the only way to
10801 * check the version field in the RSA PMS. If this fails, we
10802 * then use the faux PMS in place of the PMS. Note that this
10803 * operation should never fail if we are using the faux PMS
10804 * since it is correctly formatted. */
10805 rv = ssl3_ComputeMasterSecret(ss, pms, NULL((void*)0));
10806
10807 /* If we succeeded, then select the true PMS, else select the FPMS. */
10808 ssl3_CSwapPK11SymKey(&pms, &fauxPms, (rv != SECSuccess) & (fauxPms != NULL((void*)0)));
10809
10810 /* This step will derive the MS from the PMS, among other things. */
10811 rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE1);
10812
10813 /* Clear both PMS. */
10814 PK11_FreeSymKey(pms);
10815 PK11_FreeSymKey(fauxPms);
10816
10817 if (rv != SECSuccess) {
10818 (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
10819 return SECFailure; /* error code set by ssl3_InitPendingCipherSpec */
10820 }
10821
10822 return SECSuccess;
10823}
10824
10825static SECStatus
10826ssl3_HandleDHClientKeyExchange(sslSocket *ss,
10827 PRUint8 *b,
10828 PRUint32 length,
10829 sslKeyPair *serverKeyPair)
10830{
10831 PK11SymKey *pms;
10832 SECStatus rv;
10833 SECKEYPublicKey clntPubKey;
10834 CK_MECHANISM_TYPE target;
10835 PRBool isTLS;
10836
10837 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->recvBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveRecvBufLock(ss)"
,"ssl3con.c",10837))
;
10838 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",10838))
;
10839
10840 clntPubKey.keyType = dhKey;
10841 clntPubKey.u.dh.prime.len = serverKeyPair->pubKey->u.dh.prime.len;
10842 clntPubKey.u.dh.prime.data = serverKeyPair->pubKey->u.dh.prime.data;
10843 clntPubKey.u.dh.base.len = serverKeyPair->pubKey->u.dh.base.len;
10844 clntPubKey.u.dh.base.data = serverKeyPair->pubKey->u.dh.base.data;
10845
10846 rv = ssl3_ConsumeHandshakeVariable(ss, &clntPubKey.u.dh.publicValue,
10847 2, &b, &length);
10848 if (rv != SECSuccess) {
10849 return SECFailure;
10850 }
10851
10852 if (!ssl_IsValidDHEShare(&serverKeyPair->pubKey->u.dh.prime,
10853 &clntPubKey.u.dh.publicValue)) {
10854 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_MALFORMED_DHE_KEY_SHARE);
10855 return SECFailure;
10856 }
10857
10858 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_00x0300);
10859
10860 if (isTLS)
10861 target = CKM_TLS_MASTER_KEY_DERIVE_DH0x00000377UL;
10862 else
10863 target = CKM_SSL3_MASTER_KEY_DERIVE_DH0x00000373UL;
10864
10865 /* Determine the PMS */
10866 pms = PK11_PubDerive(serverKeyPair->privKey, &clntPubKey, PR_FALSE0, NULL((void*)0), NULL((void*)0),
10867 CKM_DH_PKCS_DERIVE0x00000021UL, target, CKA_DERIVE0x0000010CUL, 0, NULL((void*)0));
10868 if (pms == NULL((void*)0)) {
10869 ssl_FreeEphemeralKeyPairs(ss);
10870 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
10871 return SECFailure;
10872 }
10873
10874 rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE1);
10875 PK11_FreeSymKey(pms);
10876 ssl_FreeEphemeralKeyPairs(ss);
10877 return rv;
10878}
10879
10880/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
10881 * a complete ssl3 ClientKeyExchange message from the remote client
10882 * Caller must hold Handshake and RecvBuf locks.
10883 */
10884static SECStatus
10885ssl3_HandleClientKeyExchange(sslSocket *ss, PRUint8 *b, PRUint32 length)
10886{
10887 sslKeyPair *serverKeyPair = NULL((void*)0);
10888 SECStatus rv;
10889 const ssl3KEADef *kea_def;
10890
10891 SSL_TRC(3, ("%d: SSL3[%d]: handle client_key_exchange handshake",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: handle client_key_exchange handshake"
, getpid(), ss->fd)
10892 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: handle client_key_exchange handshake"
, getpid(), ss->fd)
;
10893
10894 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->recvBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveRecvBufLock(ss)"
,"ssl3con.c",10894))
;
10895 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",10895))
;
10896
10897 if (ss->ssl3.hs.ws != wait_client_key) {
10898 SSL3_SendAlert(ss, alert_fatal, unexpected_message);
10899 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
10900 return SECFailure;
10901 }
10902
10903 kea_def = ss->ssl3.hs.kea_def;
10904
10905 if (kea_def->ephemeral) {
10906 sslEphemeralKeyPair *keyPair;
10907 /* There should be exactly one pair. */
10908 PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ephemeralKeyPairs))((!((&ss->ephemeralKeyPairs)->next == (&ss->
ephemeralKeyPairs)))?((void)0):PR_Assert("!PR_CLIST_IS_EMPTY(&ss->ephemeralKeyPairs)"
,"ssl3con.c",10908))
;
10909 PORT_Assert(PR_PREV_LINK(&ss->ephemeralKeyPairs) ==((((&ss->ephemeralKeyPairs)->prev) == ((&ss->
ephemeralKeyPairs)->next))?((void)0):PR_Assert("PR_PREV_LINK(&ss->ephemeralKeyPairs) == PR_NEXT_LINK(&ss->ephemeralKeyPairs)"
,"ssl3con.c",10910))
10910 PR_NEXT_LINK(&ss->ephemeralKeyPairs))((((&ss->ephemeralKeyPairs)->prev) == ((&ss->
ephemeralKeyPairs)->next))?((void)0):PR_Assert("PR_PREV_LINK(&ss->ephemeralKeyPairs) == PR_NEXT_LINK(&ss->ephemeralKeyPairs)"
,"ssl3con.c",10910))
;
10911 keyPair = (sslEphemeralKeyPair *)PR_NEXT_LINK(&ss->ephemeralKeyPairs)((&ss->ephemeralKeyPairs)->next);
10912 serverKeyPair = keyPair->keys;
10913 ss->sec.keaKeyBits =
10914 SECKEY_PublicKeyStrengthInBits(serverKeyPair->pubKey);
10915 } else {
10916 serverKeyPair = ss->sec.serverCert->serverKeyPair;
10917 ss->sec.keaKeyBits = ss->sec.serverCert->serverKeyBits;
10918 }
10919
10920 if (!serverKeyPair) {
10921 SSL3_SendAlert(ss, alert_fatal, handshake_failure);
10922 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_NO_SERVER_KEY_FOR_ALG);
10923 return SECFailure;
10924 }
10925 PORT_Assert(serverKeyPair->pubKey)((serverKeyPair->pubKey)?((void)0):PR_Assert("serverKeyPair->pubKey"
,"ssl3con.c",10925))
;
10926 PORT_Assert(serverKeyPair->privKey)((serverKeyPair->privKey)?((void)0):PR_Assert("serverKeyPair->privKey"
,"ssl3con.c",10926))
;
10927
10928 ss->sec.keaType = kea_def->exchKeyType;
10929
10930 switch (kea_def->exchKeyType) {
10931 case ssl_kea_rsa:
10932 rv = ssl3_HandleRSAClientKeyExchange(ss, b, length, serverKeyPair);
10933 break;
10934
10935 case ssl_kea_dh:
10936 rv = ssl3_HandleDHClientKeyExchange(ss, b, length, serverKeyPair);
10937 break;
10938
10939 case ssl_kea_ecdh:
10940 rv = ssl3_HandleECDHClientKeyExchange(ss, b, length, serverKeyPair);
10941 break;
10942
10943 default:
10944 (void)ssl3_HandshakeFailure(ss);
10945 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_UNSUPPORTED_KEYALG);
10946 return SECFailure;
10947 }
10948 ssl_FreeEphemeralKeyPairs(ss);
10949 if (rv == SECSuccess) {
10950 ss->ssl3.hs.ws = ss->sec.peerCert ? wait_cert_verify : wait_change_cipher;
10951 } else {
10952 /* PORT_SetError has been called by all the Handle*ClientKeyExchange
10953 * functions above. However, not all error paths result in an alert, so
10954 * this ensures that the server knows about the error. Note that if an
10955 * alert was already sent, SSL3_SendAlert() is a noop. */
10956 PRErrorCode errCode = PORT_GetErrorPORT_GetError_Util();
10957 (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
10958 PORT_SetErrorPORT_SetError_Util(errCode);
10959 }
10960 return rv;
10961}
10962
10963/* This is TLS's equivalent of sending a no_certificate alert. */
10964SECStatus
10965ssl3_SendEmptyCertificate(sslSocket *ss)
10966{
10967 SECStatus rv;
10968 unsigned int len = 0;
10969 PRBool isTLS13 = PR_FALSE0;
10970 const SECItem *context;
10971
10972 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_30x0304) {
10973 PORT_Assert(ss->ssl3.hs.clientCertRequested)((ss->ssl3.hs.clientCertRequested)?((void)0):PR_Assert("ss->ssl3.hs.clientCertRequested"
,"ssl3con.c",10973))
;
10974 context = &ss->xtnData.certReqContext;
10975 len = context->len + 1;
10976 isTLS13 = PR_TRUE1;
10977 }
10978
10979 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate, len + 3);
10980 if (rv != SECSuccess) {
10981 return rv;
10982 }
10983
10984 if (isTLS13) {
10985 rv = ssl3_AppendHandshakeVariable(ss, context->data, context->len, 1);
10986 if (rv != SECSuccess) {
10987 return rv;
10988 }
10989 }
10990
10991 return ssl3_AppendHandshakeNumber(ss, 0, 3);
10992}
10993
10994/*
10995 * NewSessionTicket
10996 * Called from ssl3_HandleFinished
10997 */
10998static SECStatus
10999ssl3_SendNewSessionTicket(sslSocket *ss)
11000{
11001 SECItem ticket = { 0, NULL((void*)0), 0 };
11002 SECStatus rv;
11003 NewSessionTicket nticket = { 0 };
11004
11005 rv = ssl3_EncodeSessionTicket(ss, &nticket, NULL((void*)0), 0,
11006 ss->ssl3.pwSpec->masterSecret, &ticket);
11007 if (rv != SECSuccess)
11008 goto loser;
11009
11010 /* Serialize the handshake message. Length =
11011 * lifetime (4) + ticket length (2) + ticket. */
11012 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_new_session_ticket,
11013 4 + 2 + ticket.len);
11014 if (rv != SECSuccess)
11015 goto loser;
11016
11017 /* This is a fixed value. */
11018 rv = ssl3_AppendHandshakeNumber(ss, ssl_ticket_lifetime, 4);
11019 if (rv != SECSuccess)
11020 goto loser;
11021
11022 /* Encode the ticket. */
11023 rv = ssl3_AppendHandshakeVariable(ss, ticket.data, ticket.len, 2);
11024 if (rv != SECSuccess)
11025 goto loser;
11026
11027 rv = SECSuccess;
11028
11029loser:
11030 if (ticket.data) {
11031 SECITEM_FreeItemSECITEM_FreeItem_Util(&ticket, PR_FALSE0);
11032 }
11033 return rv;
11034}
11035
11036static SECStatus
11037ssl3_HandleNewSessionTicket(sslSocket *ss, PRUint8 *b, PRUint32 length)
11038{
11039 SECStatus rv;
11040 SECItem ticketData;
11041 PRUint32 temp;
11042
11043 SSL_TRC(3, ("%d: SSL3[%d]: handle session_ticket handshake",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: handle session_ticket handshake"
, getpid(), ss->fd)
11044 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: handle session_ticket handshake"
, getpid(), ss->fd)
;
11045
11046 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->recvBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveRecvBufLock(ss)"
,"ssl3con.c",11046))
;
11047 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",11047))
;
11048
11049 PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data)((!ss->ssl3.hs.newSessionTicket.ticket.data)?((void)0):PR_Assert
("!ss->ssl3.hs.newSessionTicket.ticket.data","ssl3con.c",11049
))
;
11050 PORT_Assert(!ss->ssl3.hs.receivedNewSessionTicket)((!ss->ssl3.hs.receivedNewSessionTicket)?((void)0):PR_Assert
("!ss->ssl3.hs.receivedNewSessionTicket","ssl3con.c",11050
))
;
11051
11052 if (ss->ssl3.hs.ws != wait_new_session_ticket) {
11053 SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11054 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
11055 return SECFailure;
11056 }
11057
11058 /* RFC5077 Section 3.3: "The client MUST NOT treat the ticket as valid
11059 * until it has verified the server's Finished message." See the comment in
11060 * ssl3_FinishHandshake for more details.
11061 */
11062 ss->ssl3.hs.newSessionTicket.received_timestamp = ssl_Time(ss);
11063 if (length < 4) {
11064 (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
11065 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
11066 return SECFailure;
11067 }
11068
11069 rv = ssl3_ConsumeHandshakeNumber(ss, &temp, 4, &b, &length);
11070 if (rv != SECSuccess) {
11071 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
11072 return SECFailure;
11073 }
11074 ss->ssl3.hs.newSessionTicket.ticket_lifetime_hint = temp;
11075
11076 rv = ssl3_ConsumeHandshakeVariable(ss, &ticketData, 2, &b, &length);
11077 if (rv != SECSuccess || length != 0) {
11078 (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
11079 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
11080 return SECFailure; /* malformed */
11081 }
11082 /* If the server sent a zero-length ticket, ignore it and keep the
11083 * existing ticket. */
11084 if (ticketData.len != 0) {
11085 rv = SECITEM_CopyItemSECITEM_CopyItem_Util(NULL((void*)0), &ss->ssl3.hs.newSessionTicket.ticket,
11086 &ticketData);
11087 if (rv != SECSuccess) {
11088 return rv;
11089 }
11090 ss->ssl3.hs.receivedNewSessionTicket = PR_TRUE1;
11091 }
11092
11093 ss->ssl3.hs.ws = wait_change_cipher;
11094 return SECSuccess;
11095}
11096
11097#ifdef NISCC_TEST
11098static PRInt32 connNum = 0;
11099
11100static SECStatus
11101get_fake_cert(SECItem *pCertItem, int *pIndex)
11102{
11103 PRFileDesc *cf;
11104 char *testdir;
11105 char *startat;
11106 char *stopat;
11107 const char *extension;
11108 int fileNum;
11109 PRInt32 numBytes = 0;
11110 PRStatus prStatus;
11111 PRFileInfo info;
11112 char cfn[100];
11113
11114 pCertItem->data = 0;
11115 if ((testdir = PR_GetEnvSecure("NISCC_TEST")) == NULL((void*)0)) {
11116 return SECSuccess;
11117 }
11118 *pIndex = (NULL((void*)0) != strstr(testdir, "root"));
11119 extension = (strstr(testdir, "simple") ? "" : ".der");
11120 fileNum = PR_ATOMIC_INCREMENT(&connNum)__sync_add_and_fetch(&connNum, 1) - 1;
11121 if ((startat = PR_GetEnvSecure("START_AT")) != NULL((void*)0)) {
11122 fileNum += atoi(startat);
11123 }
11124 if ((stopat = PR_GetEnvSecure("STOP_AT")) != NULL((void*)0) &&
11125 fileNum >= atoi(stopat)) {
11126 *pIndex = -1;
11127 return SECSuccess;
11128 }
11129 snprintf(cfn, sizeof(cfn), "%s/%08d%s", testdir, fileNum, extension);
11130 cf = PR_Open(cfn, PR_RDONLY0x01, 0);
11131 if (!cf) {
11132 goto loser;
11133 }
11134 prStatus = PR_GetOpenFileInfo(cf, &info);
11135 if (prStatus != PR_SUCCESS) {
11136 PR_Close(cf);
11137 goto loser;
11138 }
11139 pCertItem = SECITEM_AllocItemSECITEM_AllocItem_Util(NULL((void*)0), pCertItem, info.size);
11140 if (pCertItem) {
11141 numBytes = PR_Read(cf, pCertItem->data, info.size);
11142 }
11143 PR_Close(cf);
11144 if (numBytes != info.size) {
11145 SECITEM_FreeItemSECITEM_FreeItem_Util(pCertItem, PR_FALSE0);
11146 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_IO);
11147 goto loser;
11148 }
11149 fprintf(stderrstderr, "using %s\n", cfn);
11150 return SECSuccess;
11151
11152loser:
11153 fprintf(stderrstderr, "failed to use %s\n", cfn);
11154 *pIndex = -1;
11155 return SECFailure;
11156}
11157#endif
11158
11159/*
11160 * Used by both client and server.
11161 * Called from HandleServerHelloDone and from SendServerHelloSequence.
11162 */
11163static SECStatus
11164ssl3_SendCertificate(sslSocket *ss)
11165{
11166 SECStatus rv;
11167 CERTCertificateList *certChain;
11168 int certChainLen = 0;
11169 int i;
11170#ifdef NISCC_TEST
11171 SECItem fakeCert;
11172 int ndex = -1;
11173#endif
11174 PRBool isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_30x0304;
11175 SECItem context = { siBuffer, NULL((void*)0), 0 };
11176 unsigned int contextLen = 0;
11177
11178 SSL_TRC(3, ("%d: SSL3[%d]: send certificate handshake",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: send certificate handshake"
, getpid(), ss->fd)
11179 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: send certificate handshake"
, getpid(), ss->fd)
;
11180
11181 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->xmitBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveXmitBufLock(ss)"
,"ssl3con.c",11181))
;
11182 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",11182))
;
11183 PR_ASSERT(!ss->ssl3.hs.clientCertificatePending)((!ss->ssl3.hs.clientCertificatePending)?((void)0):PR_Assert
("!ss->ssl3.hs.clientCertificatePending","ssl3con.c",11183
))
;
11184
11185 if (ss->sec.localCert)
11186 CERT_DestroyCertificate(ss->sec.localCert);
11187 if (ss->sec.isServer) {
11188 /* A server certificate is selected in ssl3_HandleClientHello. */
11189 PORT_Assert(ss->sec.serverCert)((ss->sec.serverCert)?((void)0):PR_Assert("ss->sec.serverCert"
,"ssl3con.c",11189))
;
11190
11191 certChain = ss->sec.serverCert->serverCertChain;
11192 ss->sec.localCert = CERT_DupCertificate(ss->sec.serverCert->serverCert);
11193 } else {
11194 certChain = ss->ssl3.clientCertChain;
11195 ss->sec.localCert = CERT_DupCertificate(ss->ssl3.clientCertificate);
11196 }
11197
11198#ifdef NISCC_TEST
11199 rv = get_fake_cert(&fakeCert, &ndex);
11200#endif
11201
11202 if (isTLS13) {
11203 contextLen = 1; /* Size of the context length */
11204 if (!ss->sec.isServer) {
11205 PORT_Assert(ss->ssl3.hs.clientCertRequested)((ss->ssl3.hs.clientCertRequested)?((void)0):PR_Assert("ss->ssl3.hs.clientCertRequested"
,"ssl3con.c",11205))
;
11206 context = ss->xtnData.certReqContext;
11207 contextLen += context.len;
11208 }
11209 }
11210 if (certChain) {
11211 for (i = 0; i < certChain->len; i++) {
11212#ifdef NISCC_TEST
11213 if (fakeCert.len > 0 && i == ndex) {
11214 certChainLen += fakeCert.len + 3;
11215 } else {
11216 certChainLen += certChain->certs[i].len + 3;
11217 }
11218#else
11219 certChainLen += certChain->certs[i].len + 3;
11220#endif
11221 }
11222 }
11223
11224 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate,
11225 contextLen + certChainLen + 3);
11226 if (rv != SECSuccess) {
11227 return rv; /* err set by AppendHandshake. */
11228 }
11229
11230 if (isTLS13) {
11231 rv = ssl3_AppendHandshakeVariable(ss, context.data,
11232 context.len, 1);
11233 if (rv != SECSuccess) {
11234 return rv; /* err set by AppendHandshake. */
11235 }
11236 }
11237
11238 rv = ssl3_AppendHandshakeNumber(ss, certChainLen, 3);
11239 if (rv != SECSuccess) {
11240 return rv; /* err set by AppendHandshake. */
11241 }
11242 if (certChain) {
11243 for (i = 0; i < certChain->len; i++) {
11244#ifdef NISCC_TEST
11245 if (fakeCert.len > 0 && i == ndex) {
11246 rv = ssl3_AppendHandshakeVariable(ss, fakeCert.data,
11247 fakeCert.len, 3);
11248 SECITEM_FreeItemSECITEM_FreeItem_Util(&fakeCert, PR_FALSE0);
11249 } else {
11250 rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
11251 certChain->certs[i].len, 3);
11252 }
11253#else
11254 rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
11255 certChain->certs[i].len, 3);
11256#endif
11257 if (rv != SECSuccess) {
11258 return rv; /* err set by AppendHandshake. */
11259 }
11260 }
11261 }
11262
11263 return SECSuccess;
11264}
11265
11266/*
11267 * Used by server only.
11268 * single-stapling, send only a single cert status
11269 */
11270SECStatus
11271ssl3_SendCertificateStatus(sslSocket *ss)
11272{
11273 SECStatus rv;
11274 int len = 0;
11275 SECItemArray *statusToSend = NULL((void*)0);
11276 const sslServerCert *serverCert;
11277
11278 SSL_TRC(3, ("%d: SSL3[%d]: send certificate status handshake",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: send certificate status handshake"
, getpid(), ss->fd)
11279 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: send certificate status handshake"
, getpid(), ss->fd)
;
11280
11281 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->xmitBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveXmitBufLock(ss)"
,"ssl3con.c",11281))
;
11282 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",11282))
;
11283 PORT_Assert(ss->sec.isServer)((ss->sec.isServer)?((void)0):PR_Assert("ss->sec.isServer"
,"ssl3con.c",11283))
;
11284
11285 if (!ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn))
11286 return SECSuccess;
11287
11288 /* Use certStatus based on the cert being used. */
11289 serverCert = ss->sec.serverCert;
11290 if (serverCert->certStatusArray && serverCert->certStatusArray->len) {
11291 statusToSend = serverCert->certStatusArray;
11292 }
11293 if (!statusToSend)
11294 return SECSuccess;
11295
11296 /* Use the array's first item only (single stapling) */
11297 len = 1 + statusToSend->items[0].len + 3;
11298
11299 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_status, len);
11300 if (rv != SECSuccess) {
11301 return rv; /* err set by AppendHandshake. */
11302 }
11303 rv = ssl3_AppendHandshakeNumber(ss, 1 /*ocsp*/, 1);
11304 if (rv != SECSuccess)
11305 return rv; /* err set by AppendHandshake. */
11306
11307 rv = ssl3_AppendHandshakeVariable(ss,
11308 statusToSend->items[0].data,
11309 statusToSend->items[0].len,
11310 3);
11311 if (rv != SECSuccess)
11312 return rv; /* err set by AppendHandshake. */
11313
11314 return SECSuccess;
11315}
11316
11317/* This is used to delete the CA certificates in the peer certificate chain
11318 * from the cert database after they've been validated.
11319 */
11320void
11321ssl3_CleanupPeerCerts(sslSocket *ss)
11322{
11323 PLArenaPool *arena = ss->ssl3.peerCertArena;
11324 ssl3CertNode *certs = (ssl3CertNode *)ss->ssl3.peerCertChain;
11325
11326 for (; certs; certs = certs->next) {
11327 CERT_DestroyCertificate(certs->cert);
11328 }
11329 if (arena)
11330 PORT_FreeArenaPORT_FreeArena_Util(arena, PR_FALSE0);
11331 ss->ssl3.peerCertArena = NULL((void*)0);
11332 ss->ssl3.peerCertChain = NULL((void*)0);
11333
11334 if (ss->sec.peerCert != NULL((void*)0)) {
11335 if (ss->sec.peerKey) {
11336 SECKEY_DestroyPublicKey(ss->sec.peerKey);
11337 ss->sec.peerKey = NULL((void*)0);
11338 }
11339 CERT_DestroyCertificate(ss->sec.peerCert);
11340 ss->sec.peerCert = NULL((void*)0);
11341 }
11342}
11343
11344/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
11345 * a complete ssl3 CertificateStatus message.
11346 * Caller must hold Handshake and RecvBuf locks.
11347 */
11348static SECStatus
11349ssl3_HandleCertificateStatus(sslSocket *ss, PRUint8 *b, PRUint32 length)
11350{
11351 SECStatus rv;
11352
11353 if (ss->ssl3.hs.ws != wait_certificate_status) {
11354 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11355 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_UNEXPECTED_CERT_STATUS);
11356 return SECFailure;
11357 }
11358
11359 rv = ssl_ReadCertificateStatus(ss, b, length);
11360 if (rv != SECSuccess) {
11361 return SECFailure; /* code already set */
11362 }
11363
11364 return ssl3_AuthCertificate(ss);
11365}
11366
11367SECStatus
11368ssl_ReadCertificateStatus(sslSocket *ss, PRUint8 *b, PRUint32 length)
11369{
11370 PRUint32 status, len;
11371 SECStatus rv;
11372
11373 PORT_Assert(!ss->sec.isServer)((!ss->sec.isServer)?((void)0):PR_Assert("!ss->sec.isServer"
,"ssl3con.c",11373))
;
11374
11375 /* Consume the CertificateStatusType enum */
11376 rv = ssl3_ConsumeHandshakeNumber(ss, &status, 1, &b, &length);
11377 if (rv != SECSuccess || status != 1 /* ocsp */) {
11378 return ssl3_DecodeError(ss);
11379 }
11380
11381 rv = ssl3_ConsumeHandshakeNumber(ss, &len, 3, &b, &length);
11382 if (rv != SECSuccess || len != length) {
11383 return ssl3_DecodeError(ss);
11384 }
11385
11386#define MAX_CERTSTATUS_LEN 0x1ffff /* 128k - 1 */
11387 if (length > MAX_CERTSTATUS_LEN) {
11388 ssl3_DecodeError(ss); /* sets error code */
11389 return SECFailure;
11390 }
11391#undef MAX_CERTSTATUS_LEN
11392
11393 /* Array size 1, because we currently implement single-stapling only */
11394 SECITEM_AllocArray(NULL((void*)0), &ss->sec.ci.sid->peerCertStatus, 1);
11395 if (!ss->sec.ci.sid->peerCertStatus.items)
11396 return SECFailure; /* code already set */
11397
11398 ss->sec.ci.sid->peerCertStatus.items[0].data = PORT_AllocPORT_Alloc_Util(length);
11399
11400 if (!ss->sec.ci.sid->peerCertStatus.items[0].data) {
11401 SECITEM_FreeArray(&ss->sec.ci.sid->peerCertStatus, PR_FALSE0);
11402 return SECFailure; /* code already set */
11403 }
11404
11405 PORT_Memcpymemcpy(ss->sec.ci.sid->peerCertStatus.items[0].data, b, length);
11406 ss->sec.ci.sid->peerCertStatus.items[0].len = length;
11407 ss->sec.ci.sid->peerCertStatus.items[0].type = siBuffer;
11408 return SECSuccess;
11409}
11410
11411/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
11412 * a complete ssl3 Certificate message.
11413 * Caller must hold Handshake and RecvBuf locks.
11414 */
11415static SECStatus
11416ssl3_HandleCertificate(sslSocket *ss, PRUint8 *b, PRUint32 length)
11417{
11418 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate handshake",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: handle certificate handshake"
, getpid(), ss->fd)
11419 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: handle certificate handshake"
, getpid(), ss->fd)
;
11420 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->recvBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveRecvBufLock(ss)"
,"ssl3con.c",11420))
;
11421 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",11421))
;
11422
11423 if ((ss->sec.isServer && ss->ssl3.hs.ws != wait_client_cert) ||
11424 (!ss->sec.isServer && ss->ssl3.hs.ws != wait_server_cert)) {
11425 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
11426 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_UNEXPECTED_CERTIFICATE);
11427 return SECFailure;
11428 }
11429
11430 if (ss->sec.isServer) {
11431 dtls_ReceivedFirstMessageInFlight(ss);
11432 }
11433
11434 return ssl3_CompleteHandleCertificate(ss, b, length);
11435}
11436
11437/* Called from ssl3_HandleCertificate
11438 */
11439SECStatus
11440ssl3_CompleteHandleCertificate(sslSocket *ss, PRUint8 *b, PRUint32 length)
11441{
11442 ssl3CertNode *c;
11443 ssl3CertNode *lastCert = NULL((void*)0);
11444 PRUint32 remaining = 0;
11445 PRUint32 size;
11446 SECStatus rv;
11447 PRBool isServer = ss->sec.isServer;
11448 PRBool isTLS;
11449 SSL3AlertDescription desc;
11450 int errCode = SSL_ERROR_RX_MALFORMED_CERTIFICATE;
11451 SECItem certItem;
11452
11453 ssl3_CleanupPeerCerts(ss);
11454 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_00x0300);
11455
11456 /* It is reported that some TLS client sends a Certificate message
11457 ** with a zero-length message body. We'll treat that case like a
11458 ** normal no_certificates message to maximize interoperability.
11459 */
11460 if (length) {
11461 rv = ssl3_ConsumeHandshakeNumber(ss, &remaining, 3, &b, &length);
11462 if (rv != SECSuccess)
11463 goto loser; /* fatal alert already sent by ConsumeHandshake. */
11464 if (remaining > length)
11465 goto decode_loser;
11466 }
11467
11468 if (!remaining) {
11469 if (!(isTLS && isServer)) {
11470 desc = bad_certificate;
11471 goto alert_loser;
11472 }
11473 /* This is TLS's version of a no_certificate alert. */
11474 /* I'm a server. I've requested a client cert. He hasn't got one. */
11475 rv = ssl3_HandleNoCertificate(ss);
11476 if (rv != SECSuccess) {
11477 errCode = PORT_GetErrorPORT_GetError_Util();
11478 goto loser;
11479 }
11480
11481 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_30x0304) {
11482 ss->ssl3.hs.ws = wait_client_key;
11483 } else {
11484 TLS13_SET_HS_STATE(ss, wait_finished)tls13_SetHsState(ss, wait_finished, __func__, "ssl3con.c", 11484
)
;
11485 }
11486 return SECSuccess;
11487 }
11488
11489 ss->ssl3.peerCertArena = PORT_NewArenaPORT_NewArena_Util(DER_DEFAULT_CHUNKSIZE(2048));
11490 if (ss->ssl3.peerCertArena == NULL((void*)0)) {
11491 goto loser; /* don't send alerts on memory errors */
11492 }
11493
11494 /* First get the peer cert. */
11495 if (remaining < 3)
11496 goto decode_loser;
11497
11498 remaining -= 3;
11499 rv = ssl3_ConsumeHandshakeNumber(ss, &size, 3, &b, &length);
11500 if (rv != SECSuccess)
11501 goto loser; /* fatal alert already sent by ConsumeHandshake. */
11502 if (size == 0 || remaining < size)
11503 goto decode_loser;
11504
11505 certItem.data = b;
11506 certItem.len = size;
11507 b += size;
11508 length -= size;
11509 remaining -= size;
11510
11511 ss->sec.peerCert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL((void*)0),
11512 PR_FALSE0, PR_TRUE1);
11513 if (ss->sec.peerCert == NULL((void*)0)) {
11514 /* We should report an alert if the cert was bad, but not if the
11515 * problem was just some local problem, like memory error.
11516 */
11517 goto ambiguous_err;
11518 }
11519
11520 /* Now get all of the CA certs. */
11521 while (remaining > 0) {
11522 if (remaining < 3)
11523 goto decode_loser;
11524
11525 remaining -= 3;
11526 rv = ssl3_ConsumeHandshakeNumber(ss, &size, 3, &b, &length);
11527 if (rv != SECSuccess)
11528 goto loser; /* fatal alert already sent by ConsumeHandshake. */
11529 if (size == 0 || remaining < size)
11530 goto decode_loser;
11531
11532 certItem.data = b;
11533 certItem.len = size;
11534 b += size;
11535 length -= size;
11536 remaining -= size;
11537
11538 c = PORT_ArenaNew(ss->ssl3.peerCertArena, ssl3CertNode)(ssl3CertNode *)PORT_ArenaAlloc_Util(ss->ssl3.peerCertArena
, sizeof(ssl3CertNode))
;
11539 if (c == NULL((void*)0)) {
11540 goto loser; /* don't send alerts on memory errors */
11541 }
11542
11543 c->cert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL((void*)0),
11544 PR_FALSE0, PR_TRUE1);
11545 if (c->cert == NULL((void*)0)) {
11546 goto ambiguous_err;
11547 }
11548
11549 c->next = NULL((void*)0);
11550 if (lastCert) {
11551 lastCert->next = c;
11552 } else {
11553 ss->ssl3.peerCertChain = c;
11554 }
11555 lastCert = c;
11556 }
11557
11558 SECKEY_UpdateCertPQG(ss->sec.peerCert);
11559
11560 if (!isServer &&
11561 ss->version < SSL_LIBRARY_VERSION_TLS_1_30x0304 &&
11562 ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn)) {
11563 ss->ssl3.hs.ws = wait_certificate_status;
11564 rv = SECSuccess;
11565 } else {
11566 rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
11567 }
11568
11569 return rv;
11570
11571ambiguous_err:
11572 errCode = PORT_GetErrorPORT_GetError_Util();
11573 switch (errCode) {
11574 case PR_OUT_OF_MEMORY_ERROR(-6000L):
11575 case SEC_ERROR_BAD_DATABASE:
11576 case SEC_ERROR_NO_MEMORY:
11577 if (isTLS) {
11578 desc = internal_error;
11579 goto alert_loser;
11580 }
11581 goto loser;
11582 }
11583 ssl3_SendAlertForCertError(ss, errCode);
11584 goto loser;
11585
11586decode_loser:
11587 desc = isTLS ? decode_error : bad_certificate;
11588
11589alert_loser:
11590 (void)SSL3_SendAlert(ss, alert_fatal, desc);
11591
11592loser:
11593 (void)ssl_MapLowLevelError(errCode);
11594 return SECFailure;
11595}
11596
11597SECStatus
11598ssl_SetAuthKeyBits(sslSocket *ss, const SECKEYPublicKey *pubKey)
11599{
11600 SECStatus rv;
11601 PRUint32 minKey = 0;
11602 PRInt32 optval;
11603 PRBool usePolicyLength = PR_TRUE1;
11604
11605 rv = NSS_OptionGet(NSS_KEY_SIZE_POLICY_FLAGS0x00e, &optval);
11606 if (rv == SECSuccess) {
11607 usePolicyLength = (PRBool)((optval & NSS_KEY_SIZE_POLICY_SSL_FLAG1) == NSS_KEY_SIZE_POLICY_SSL_FLAG1);
11608 }
11609
11610 ss->sec.authKeyBits = SECKEY_PublicKeyStrengthInBits(pubKey);
11611 switch (SECKEY_GetPublicKeyType(pubKey)) {
11612 case rsaKey:
11613 case rsaPssKey:
11614 case rsaOaepKey:
11615 rv = usePolicyLength ? NSS_OptionGet(NSS_RSA_MIN_KEY_SIZE0x001, &optval)
11616 : SECFailure;
11617 if (rv == SECSuccess && optval > 0) {
11618 minKey = (PRUint32)optval;
11619 } else {
11620 minKey = SSL_RSA_MIN_MODULUS_BITS1023;
11621 }
11622 break;
11623
11624 case dsaKey:
11625 rv = usePolicyLength ? NSS_OptionGet(NSS_DSA_MIN_KEY_SIZE0x004, &optval)
11626 : SECFailure;
11627 if (rv == SECSuccess && optval > 0) {
11628 minKey = (PRUint32)optval;
11629 } else {
11630 minKey = SSL_DSA_MIN_P_BITS1023;
11631 }
11632 break;
11633
11634 case dhKey:
11635 rv = usePolicyLength ? NSS_OptionGet(NSS_DH_MIN_KEY_SIZE0x002, &optval)
11636 : SECFailure;
11637 if (rv == SECSuccess && optval > 0) {
11638 minKey = (PRUint32)optval;
11639 } else {
11640 minKey = SSL_DH_MIN_P_BITS1023;
11641 }
11642 break;
11643
11644 case ecKey:
11645 rv = usePolicyLength ? NSS_OptionGet(NSS_ECC_MIN_KEY_SIZE0x011, &optval)
11646 : SECFailure;
11647 if (rv == SECSuccess && optval > 0) {
11648 minKey = (PRUint32)optval;
11649 } else {
11650 /* Don't check EC strength here on the understanding that we
11651 * only support curves we like. */
11652 minKey = ss->sec.authKeyBits;
11653 }
11654 break;
11655
11656 default:
11657 FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error)do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SEC_ERROR_LIBRARY_FAILURE, __func__, "ssl3con.c"
, 11657); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0); tls13_FatalError(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error
); } while (0)
;
11658 return SECFailure;
11659 }
11660
11661 /* Too small: not good enough. Send a fatal alert. */
11662 if (ss->sec.authKeyBits < minKey) {
11663 FATAL_ERROR(ss, SSL_ERROR_WEAK_SERVER_CERT_KEY,do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_WEAK_SERVER_CERT_KEY, __func__
, "ssl3con.c", 11666); PORT_SetError_Util(SSL_ERROR_WEAK_SERVER_CERT_KEY
); } while (0); tls13_FatalError(ss, SSL_ERROR_WEAK_SERVER_CERT_KEY
, ss->version >= 0x0301 ? insufficient_security : illegal_parameter
); } while (0)
11664 ss->version >= SSL_LIBRARY_VERSION_TLS_1_0do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_WEAK_SERVER_CERT_KEY, __func__
, "ssl3con.c", 11666); PORT_SetError_Util(SSL_ERROR_WEAK_SERVER_CERT_KEY
); } while (0); tls13_FatalError(ss, SSL_ERROR_WEAK_SERVER_CERT_KEY
, ss->version >= 0x0301 ? insufficient_security : illegal_parameter
); } while (0)
11665 ? insufficient_securitydo { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_WEAK_SERVER_CERT_KEY, __func__
, "ssl3con.c", 11666); PORT_SetError_Util(SSL_ERROR_WEAK_SERVER_CERT_KEY
); } while (0); tls13_FatalError(ss, SSL_ERROR_WEAK_SERVER_CERT_KEY
, ss->version >= 0x0301 ? insufficient_security : illegal_parameter
); } while (0)
11666 : illegal_parameter)do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_WEAK_SERVER_CERT_KEY, __func__
, "ssl3con.c", 11666); PORT_SetError_Util(SSL_ERROR_WEAK_SERVER_CERT_KEY
); } while (0); tls13_FatalError(ss, SSL_ERROR_WEAK_SERVER_CERT_KEY
, ss->version >= 0x0301 ? insufficient_security : illegal_parameter
); } while (0)
;
11667 return SECFailure;
11668 }
11669
11670 /* PreliminaryChannelInfo.authKeyBits, scheme, and peerDelegCred are now valid. */
11671 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_peer_auth(1U << 3);
11672
11673 return SECSuccess;
11674}
11675
11676SECStatus
11677ssl3_HandleServerSpki(sslSocket *ss)
11678{
11679 PORT_Assert(!ss->sec.isServer)((!ss->sec.isServer)?((void)0):PR_Assert("!ss->sec.isServer"
,"ssl3con.c",11679))
;
11680 SECKEYPublicKey *pubKey;
11681
11682 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_30x0304 &&
11683 tls13_IsVerifyingWithDelegatedCredential(ss)) {
11684 sslDelegatedCredential *dc = ss->xtnData.peerDelegCred;
11685 pubKey = SECKEY_ExtractPublicKey(dc->spki);
11686 if (!pubKey) {
11687 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
11688 return SECFailure;
11689 }
11690
11691 /* Because we have only a single authType (ssl_auth_tls13_any)
11692 * for TLS 1.3 at this point, set the scheme so that the
11693 * callback can interpret |authKeyBits| correctly.
11694 */
11695 ss->sec.signatureScheme = dc->expectedCertVerifyAlg;
11696 } else {
11697 pubKey = CERT_ExtractPublicKey(ss->sec.peerCert);
11698 if (!pubKey) {
11699 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
11700 return SECFailure;
11701 }
11702 }
11703
11704 SECStatus rv = ssl_SetAuthKeyBits(ss, pubKey);
11705 SECKEY_DestroyPublicKey(pubKey);
11706 if (rv != SECSuccess) {
11707 return rv; /* Alert sent and code set. */
11708 }
11709
11710 return SECSuccess;
11711}
11712
11713SECStatus
11714ssl3_AuthCertificate(sslSocket *ss)
11715{
11716 SECStatus rv;
11717 PRBool isServer = ss->sec.isServer;
11718 int errCode;
11719
11720 ss->ssl3.hs.authCertificatePending = PR_FALSE0;
11721
11722 PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==(((ss->ssl3.hs.preliminaryInfo & ((1U << 0) | (1U
<< 1) | (1U << 4))) == ((1U << 0) | (1U <<
1) | (1U << 4)))?((void)0):PR_Assert("(ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) == ssl_preinfo_all"
,"ssl3con.c",11723))
11723 ssl_preinfo_all)(((ss->ssl3.hs.preliminaryInfo & ((1U << 0) | (1U
<< 1) | (1U << 4))) == ((1U << 0) | (1U <<
1) | (1U << 4)))?((void)0):PR_Assert("(ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) == ssl_preinfo_all"
,"ssl3con.c",11723))
;
11724
11725 if (!ss->sec.isServer) {
11726 /* Set the |spki| used to verify the handshake. When verifying with a
11727 * delegated credential (DC), this corresponds to the DC public key;
11728 * otherwise it correspond to the public key of the peer's end-entity
11729 * certificate. */
11730 rv = ssl3_HandleServerSpki(ss);
11731 if (rv != SECSuccess) {
11732 /* Alert sent and code set (if not SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE).
11733 * In either case, we're done here. */
11734 errCode = PORT_GetErrorPORT_GetError_Util();
11735 goto loser;
11736 }
11737
11738 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_30x0304) {
11739 ss->sec.authType = ss->ssl3.hs.kea_def->authKeyType;
11740 ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType;
11741 }
11742 }
11743
11744 /*
11745 * Ask caller-supplied callback function to validate cert chain.
11746 */
11747 rv = (SECStatus)(*ss->authCertificate)(ss->authCertificateArg, ss->fd,
11748 PR_TRUE1, isServer);
11749 if (rv != SECSuccess) {
11750 errCode = PORT_GetErrorPORT_GetError_Util();
11751 if (errCode == 0) {
11752 errCode = SSL_ERROR_BAD_CERTIFICATE;
11753 }
11754 if (rv != SECWouldBlock) {
11755 if (ss->handleBadCert) {
11756 rv = (*ss->handleBadCert)(ss->badCertArg, ss->fd);
11757 }
11758 }
11759
11760 if (rv == SECWouldBlock) {
11761 if (ss->sec.isServer) {
11762 errCode = SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS;
11763 goto loser;
11764 }
11765
11766 ss->ssl3.hs.authCertificatePending = PR_TRUE1;
11767 rv = SECSuccess;
11768 }
11769
11770 if (rv != SECSuccess) {
11771 ssl3_SendAlertForCertError(ss, errCode);
11772 goto loser;
11773 }
11774 }
11775
11776 if (ss->sec.ci.sid->peerCert) {
11777 CERT_DestroyCertificate(ss->sec.ci.sid->peerCert);
11778 }
11779 ss->sec.ci.sid->peerCert = CERT_DupCertificate(ss->sec.peerCert);
11780
11781 if (!ss->sec.isServer) {
11782 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_30x0304) {
11783 TLS13_SET_HS_STATE(ss, wait_cert_verify)tls13_SetHsState(ss, wait_cert_verify, __func__, "ssl3con.c",
11783)
;
11784 } else {
11785 /* Ephemeral suites require ServerKeyExchange. */
11786 if (ss->ssl3.hs.kea_def->ephemeral) {
11787 /* require server_key_exchange */
11788 ss->ssl3.hs.ws = wait_server_key;
11789 } else {
11790 /* disallow server_key_exchange */
11791 ss->ssl3.hs.ws = wait_cert_request;
11792 /* This is static RSA key exchange so set the key exchange
11793 * details to compensate for that. */
11794 ss->sec.keaKeyBits = ss->sec.authKeyBits;
11795 ss->sec.signatureScheme = ssl_sig_none;
11796 ss->sec.keaGroup = NULL((void*)0);
11797 }
11798 }
11799 } else {
11800 /* Server */
11801 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_30x0304) {
11802 ss->ssl3.hs.ws = wait_client_key;
11803 } else {
11804 TLS13_SET_HS_STATE(ss, wait_cert_verify)tls13_SetHsState(ss, wait_cert_verify, __func__, "ssl3con.c",
11804)
;
11805 }
11806 }
11807
11808 PORT_Assert(rv == SECSuccess)((rv == SECSuccess)?((void)0):PR_Assert("rv == SECSuccess","ssl3con.c"
,11808))
;
11809 if (rv != SECSuccess) {
11810 errCode = SEC_ERROR_LIBRARY_FAILURE;
11811 goto loser;
11812 }
11813
11814 return SECSuccess;
11815
11816loser:
11817 (void)ssl_MapLowLevelError(errCode);
11818 return SECFailure;
11819}
11820
11821static SECStatus ssl3_FinishHandshake(sslSocket *ss);
11822
11823static SECStatus
11824ssl3_AlwaysFail(sslSocket *ss)
11825{
11826 /* The caller should have cleared the callback. */
11827 ss->ssl3.hs.restartTarget = ssl3_AlwaysFail;
11828 PORT_SetErrorPORT_SetError_Util(PR_INVALID_STATE_ERROR(-5931L));
11829 return SECFailure;
11830}
11831
11832/* Caller must hold 1stHandshakeLock.
11833 */
11834SECStatus
11835ssl3_AuthCertificateComplete(sslSocket *ss, PRErrorCode error)
11836{
11837 SECStatus rv;
11838
11839 PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->firstHandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)"
,"ssl3con.c",11839))
;
11840
11841 if (ss->sec.isServer) {
11842 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS);
11843 return SECFailure;
11844 }
11845
11846 ssl_GetRecvBufLock(ss){ if (!ss->opt.noLocks) { ((!((PR_GetMonitorEntryCount(((ss
)->ssl3HandshakeLock)) > 0)))?((void)0):PR_Assert("!ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",11846)); ((!((PR_GetMonitorEntryCount(((ss)->
xmitBufLock)) > 0)))?((void)0):PR_Assert("!ssl_HaveXmitBufLock(ss)"
,"ssl3con.c",11846)); PR_EnterMonitor(((ss)->recvBufLock))
; } }
;
11847 ssl_GetSSL3HandshakeLock(ss){ if (!ss->opt.noLocks) { ((!((PR_GetMonitorEntryCount(((ss
)->xmitBufLock)) > 0)))?((void)0):PR_Assert("!ssl_HaveXmitBufLock(ss)"
,"ssl3con.c",11847)); PR_EnterMonitor(((ss)->ssl3HandshakeLock
)); } }
;
11848
11849 if (!ss->ssl3.hs.authCertificatePending) {
11850 PORT_SetErrorPORT_SetError_Util(PR_INVALID_STATE_ERROR(-5931L));
11851 rv = SECFailure;
11852 goto done;
11853 }
11854
11855 ss->ssl3.hs.authCertificatePending = PR_FALSE0;
11856
11857 if (error != 0) {
11858 ss->ssl3.hs.restartTarget = ssl3_AlwaysFail;
11859 ssl3_SendAlertForCertError(ss, error);
11860 rv = SECSuccess;
11861 } else if (ss->ssl3.hs.restartTarget != NULL((void*)0)) {
11862 sslRestartTarget target = ss->ssl3.hs.restartTarget;
11863 ss->ssl3.hs.restartTarget = NULL((void*)0);
11864
11865 if (target == ssl3_FinishHandshake) {
11866 SSL_TRC(3, ("%d: SSL3[%p]: certificate authentication lost the race"if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%p]: certificate authentication lost the race"
" with peer's finished message", getpid(), ss->fd)
11867 " with peer's finished message",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%p]: certificate authentication lost the race"
" with peer's finished message", getpid(), ss->fd)
11868 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%p]: certificate authentication lost the race"
" with peer's finished message", getpid(), ss->fd)
;
11869 }
11870
11871 rv = target(ss);
11872 } else {
11873 SSL_TRC(3, ("%d: SSL3[%p]: certificate authentication won the race with"if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%p]: certificate authentication won the race with"
" peer's finished message", getpid(), ss->fd)
11874 " peer's finished message",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%p]: certificate authentication won the race with"
" peer's finished message", getpid(), ss->fd)
11875 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%p]: certificate authentication won the race with"
" peer's finished message", getpid(), ss->fd)
;
11876
11877 PORT_Assert(!ss->ssl3.hs.isResuming)((!ss->ssl3.hs.isResuming)?((void)0):PR_Assert("!ss->ssl3.hs.isResuming"
,"ssl3con.c",11877))
;
11878 PORT_Assert(ss->ssl3.hs.ws != idle_handshake)((ss->ssl3.hs.ws != idle_handshake)?((void)0):PR_Assert("ss->ssl3.hs.ws != idle_handshake"
,"ssl3con.c",11878))
;
11879
11880 if (ss->opt.enableFalseStart &&
11881 !ss->firstHsDone &&
11882 !ss->ssl3.hs.isResuming &&
11883 ssl3_WaitingForServerSecondRound(ss)) {
11884 /* ssl3_SendClientSecondRound deferred the false start check because
11885 * certificate authentication was pending, so we do it now if we still
11886 * haven't received all of the server's second round yet.
11887 */
11888 rv = ssl3_CheckFalseStart(ss);
11889 } else {
11890 rv = SECSuccess;
11891 }
11892 }
11893
11894done:
11895 ssl_ReleaseSSL3HandshakeLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->ssl3HandshakeLock
)); }
;
11896 ssl_ReleaseRecvBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->recvBufLock
)); }
;
11897
11898 return rv;
11899}
11900
11901static SECStatus
11902ssl3_ComputeTLSFinished(sslSocket *ss, ssl3CipherSpec *spec,
11903 PRBool isServer,
11904 const SSL3Hashes *hashes,
11905 TLSFinished *tlsFinished)
11906{
11907 SECStatus rv;
11908 CK_TLS_MAC_PARAMS tls_mac_params;
11909 SECItem param = { siBuffer, NULL((void*)0), 0 };
11910 PK11Context *prf_context;
11911 unsigned int retLen;
11912
11913 PORT_Assert(spec->masterSecret)((spec->masterSecret)?((void)0):PR_Assert("spec->masterSecret"
,"ssl3con.c",11913))
;
11914 if (!spec->masterSecret) {
11915 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
11916 return SECFailure;
11917 }
11918
11919 if (spec->version < SSL_LIBRARY_VERSION_TLS_1_20x0303) {
11920 tls_mac_params.prfHashMechanism = CKM_TLS_PRF0x00000378UL;
11921 } else {
11922 tls_mac_params.prfHashMechanism = ssl3_GetPrfHashMechanism(ss);
11923 }
11924 tls_mac_params.ulMacLength = 12;
11925 tls_mac_params.ulServerOrClient = isServer ? 1 : 2;
11926 param.data = (unsigned char *)&tls_mac_params;
11927 param.len = sizeof(tls_mac_params);
11928 prf_context = PK11_CreateContextBySymKey(CKM_TLS_MAC0x000003E4UL, CKA_SIGN0x00000108UL,
11929 spec->masterSecret, &param);
11930 if (!prf_context)
11931 return SECFailure;
11932
11933 rv = PK11_DigestBegin(prf_context);
11934 rv |= PK11_DigestOp(prf_context, hashes->u.raw, hashes->len);
11935 rv |= PK11_DigestFinal(prf_context, tlsFinished->verify_data, &retLen,
11936 sizeof tlsFinished->verify_data);
11937 PORT_Assert(rv != SECSuccess || retLen == sizeof tlsFinished->verify_data)((rv != SECSuccess || retLen == sizeof tlsFinished->verify_data
)?((void)0):PR_Assert("rv != SECSuccess || retLen == sizeof tlsFinished->verify_data"
,"ssl3con.c",11937))
;
11938
11939 PK11_DestroyContext(prf_context, PR_TRUE1);
11940
11941 return rv;
11942}
11943
11944/* The calling function must acquire and release the appropriate
11945 * lock (e.g., ssl_GetSpecReadLock / ssl_ReleaseSpecReadLock for
11946 * ss->ssl3.crSpec).
11947 */
11948SECStatus
11949ssl3_TLSPRFWithMasterSecret(sslSocket *ss, ssl3CipherSpec *spec,
11950 const char *label, unsigned int labelLen,
11951 const unsigned char *val, unsigned int valLen,
11952 unsigned char *out, unsigned int outLen)
11953{
11954 SECItem param = { siBuffer, NULL((void*)0), 0 };
11955 CK_MECHANISM_TYPE mech = CKM_TLS_PRF_GENERAL0x80000373UL;
11956 PK11Context *prf_context;
11957 unsigned int retLen;
11958 SECStatus rv;
11959
11960 if (!spec->masterSecret) {
11961 PORT_Assert(spec->masterSecret)((spec->masterSecret)?((void)0):PR_Assert("spec->masterSecret"
,"ssl3con.c",11961))
;
11962 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
11963 return SECFailure;
11964 }
11965
11966 if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_20x0303) {
11967 /* Bug 1312976 non-SHA256 exporters are broken. */
11968 if (ssl3_GetPrfHashMechanism(ss) != CKM_SHA2560x00000250UL) {
11969 PORT_Assert(0)((0)?((void)0):PR_Assert("0","ssl3con.c",11969));
11970 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
11971 return SECFailure;
11972 }
11973 mech = CKM_NSS_TLS_PRF_GENERAL_SHA256((0x80000000UL | 0x4E534350) + 21);
11974 }
11975 prf_context = PK11_CreateContextBySymKey(mech, CKA_SIGN0x00000108UL,
11976 spec->masterSecret, &param);
11977 if (!prf_context)
11978 return SECFailure;
11979
11980 rv = PK11_DigestBegin(prf_context);
11981 rv |= PK11_DigestOp(prf_context, (unsigned char *)label, labelLen);
11982 rv |= PK11_DigestOp(prf_context, val, valLen);
11983 rv |= PK11_DigestFinal(prf_context, out, &retLen, outLen);
11984 PORT_Assert(rv != SECSuccess || retLen == outLen)((rv != SECSuccess || retLen == outLen)?((void)0):PR_Assert("rv != SECSuccess || retLen == outLen"
,"ssl3con.c",11984))
;
11985
11986 PK11_DestroyContext(prf_context, PR_TRUE1);
11987 return rv;
11988}
11989
11990/* called from ssl3_SendClientSecondRound
11991 * ssl3_HandleFinished
11992 */
11993static SECStatus
11994ssl3_SendNextProto(sslSocket *ss)
11995{
11996 SECStatus rv;
11997 int padding_len;
11998 static const unsigned char padding[32] = { 0 };
11999
12000 if (ss->xtnData.nextProto.len == 0 ||
12001 ss->xtnData.nextProtoState == SSL_NEXT_PROTO_SELECTED) {
12002 return SECSuccess;
12003 }
12004
12005 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->xmitBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveXmitBufLock(ss)"
,"ssl3con.c",12005))
;
12006 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",12006))
;
12007
12008 padding_len = 32 - ((ss->xtnData.nextProto.len + 2) % 32);
12009
12010 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_next_proto, ss->xtnData.nextProto.len + 2 + padding_len);
12011 if (rv != SECSuccess) {
12012 return rv; /* error code set by AppendHandshakeHeader */
12013 }
12014 rv = ssl3_AppendHandshakeVariable(ss, ss->xtnData.nextProto.data,
12015 ss->xtnData.nextProto.len, 1);
12016 if (rv != SECSuccess) {
12017 return rv; /* error code set by AppendHandshake */
12018 }
12019 rv = ssl3_AppendHandshakeVariable(ss, padding, padding_len, 1);
12020 if (rv != SECSuccess) {
12021 return rv; /* error code set by AppendHandshake */
12022 }
12023 return rv;
12024}
12025
12026/* called from ssl3_SendFinished and tls13_DeriveSecret.
12027 *
12028 * This function is simply a debugging aid and therefore does not return a
12029 * SECStatus. */
12030void
12031ssl3_RecordKeyLog(sslSocket *ss, const char *label, PK11SymKey *secret)
12032{
12033#ifdef NSS_ALLOW_SSLKEYLOGFILE1
12034 SECStatus rv;
12035 SECItem *keyData;
12036 /* Longest label is "CLIENT_HANDSHAKE_TRAFFIC_SECRET", master secret is 48
12037 * bytes which happens to be the largest in TLS 1.3 as well (SHA384).
12038 * Maximum line length: "CLIENT_HANDSHAKE_TRAFFIC_SECRET" (31) + " " (1) +
12039 * client_random (32*2) + " " (1) +
12040 * traffic_secret (48*2) + "\n" (1) = 194. */
12041 char buf[200];
12042 unsigned int offset, len;
12043
12044 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",12044))
;
12045
12046 if (!ssl_keylog_iob)
12047 return;
12048
12049 rv = PK11_ExtractKeyValue(secret);
12050 if (rv != SECSuccess)
12051 return;
12052
12053 /* keyData does not need to be freed. */
12054 keyData = PK11_GetKeyData(secret);
12055 if (!keyData || !keyData->data)
12056 return;
12057
12058 len = strlen(label) + 1 + /* label + space */
12059 SSL3_RANDOM_LENGTH32 * 2 + 1 + /* client random (hex) + space */
12060 keyData->len * 2 + 1; /* secret (hex) + newline */
12061 PORT_Assert(len <= sizeof(buf))((len <= sizeof(buf))?((void)0):PR_Assert("len <= sizeof(buf)"
,"ssl3con.c",12061))
;
12062 if (len > sizeof(buf))
12063 return;
12064
12065 /* https://developer.mozilla.org/en/NSS_Key_Log_Format */
12066
12067 /* There could be multiple, concurrent writers to the
12068 * keylog, so we have to do everything in a single call to
12069 * fwrite. */
12070
12071 strcpy(buf, label);
12072 offset = strlen(label);
12073 buf[offset++] += ' ';
12074 hexEncode(buf + offset, ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH32);
12075 offset += SSL3_RANDOM_LENGTH32 * 2;
12076 buf[offset++] = ' ';
12077 hexEncode(buf + offset, keyData->data, keyData->len);
12078 offset += keyData->len * 2;
12079 buf[offset++] = '\n';
12080
12081 PORT_Assert(offset == len)((offset == len)?((void)0):PR_Assert("offset == len","ssl3con.c"
,12081))
;
12082
12083 PZ_Lock(ssl_keylog_lock)PR_Lock((ssl_keylog_lock));
12084 if (fwrite(buf, len, 1, ssl_keylog_iob) == 1)
12085 fflush(ssl_keylog_iob);
12086 PZ_Unlock(ssl_keylog_lock)PR_Unlock((ssl_keylog_lock));
12087#endif
12088}
12089
12090/* called from ssl3_SendClientSecondRound
12091 * ssl3_HandleClientHello
12092 * ssl3_HandleFinished
12093 */
12094static SECStatus
12095ssl3_SendFinished(sslSocket *ss, PRInt32 flags)
12096{
12097 ssl3CipherSpec *cwSpec;
12098 PRBool isTLS;
12099 PRBool isServer = ss->sec.isServer;
12100 SECStatus rv;
12101 SSL3Sender sender = isServer ? sender_server : sender_client;
12102 SSL3Hashes hashes;
12103 TLSFinished tlsFinished;
12104
12105 SSL_TRC(3, ("%d: SSL3[%d]: send finished handshake", SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: send finished handshake"
, getpid(), ss->fd)
;
12106
12107 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->xmitBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveXmitBufLock(ss)"
,"ssl3con.c",12107))
;
12108 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",12108))
;
12109 PR_ASSERT(!ss->ssl3.hs.clientCertificatePending)((!ss->ssl3.hs.clientCertificatePending)?((void)0):PR_Assert
("!ss->ssl3.hs.clientCertificatePending","ssl3con.c",12109
))
;
12110
12111 ssl_GetSpecReadLock(ss){ if (!ss->opt.noLocks) NSSRWLock_LockRead_Util((ss)->specLock
); }
;
12112 cwSpec = ss->ssl3.cwSpec;
12113 isTLS = (PRBool)(cwSpec->version > SSL_LIBRARY_VERSION_3_00x0300);
12114 rv = ssl3_ComputeHandshakeHashes(ss, cwSpec, &hashes, sender);
12115 if (isTLS && rv == SECSuccess) {
12116 rv = ssl3_ComputeTLSFinished(ss, cwSpec, isServer, &hashes, &tlsFinished);
12117 }
12118 ssl_ReleaseSpecReadLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockRead_Util((ss)->
specLock); }
;
12119 if (rv != SECSuccess) {
12120 goto fail; /* err code was set by ssl3_ComputeHandshakeHashes */
12121 }
12122
12123 if (isTLS) {
12124 if (isServer)
12125 ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished;
12126 else
12127 ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished;
12128 ss->ssl3.hs.finishedBytes = sizeof tlsFinished;
12129 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_finished, sizeof tlsFinished);
12130 if (rv != SECSuccess)
12131 goto fail; /* err set by AppendHandshake. */
12132 rv = ssl3_AppendHandshake(ss, &tlsFinished, sizeof tlsFinished);
12133 if (rv != SECSuccess)
12134 goto fail; /* err set by AppendHandshake. */
12135 } else {
12136 if (isServer)
12137 ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes.u.s;
12138 else
12139 ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes.u.s;
12140 PORT_Assert(hashes.len == sizeof hashes.u.s)((hashes.len == sizeof hashes.u.s)?((void)0):PR_Assert("hashes.len == sizeof hashes.u.s"
,"ssl3con.c",12140))
;
12141 ss->ssl3.hs.finishedBytes = sizeof hashes.u.s;
12142 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_finished, sizeof hashes.u.s);
12143 if (rv != SECSuccess)
12144 goto fail; /* err set by AppendHandshake. */
12145 rv = ssl3_AppendHandshake(ss, &hashes.u.s, sizeof hashes.u.s);
12146 if (rv != SECSuccess)
12147 goto fail; /* err set by AppendHandshake. */
12148 }
12149 rv = ssl3_FlushHandshake(ss, flags);
12150 if (rv != SECSuccess) {
12151 goto fail; /* error code set by ssl3_FlushHandshake */
12152 }
12153
12154 ssl3_RecordKeyLog(ss, "CLIENT_RANDOM", ss->ssl3.cwSpec->masterSecret);
12155
12156 return SECSuccess;
12157
12158fail:
12159 return rv;
12160}
12161
12162/* wrap the master secret, and put it into the SID.
12163 * Caller holds the Spec read lock.
12164 */
12165SECStatus
12166ssl3_CacheWrappedSecret(sslSocket *ss, sslSessionID *sid,
12167 PK11SymKey *secret)
12168{
12169 PK11SymKey *wrappingKey = NULL((void*)0);
12170 PK11SlotInfo *symKeySlot;
12171 void *pwArg = ss->pkcs11PinArg;
12172 SECStatus rv = SECFailure;
12173 PRBool isServer = ss->sec.isServer;
12174 CK_MECHANISM_TYPE mechanism = CKM_INVALID_MECHANISM0xffffffffUL;
12175
12176 symKeySlot = PK11_GetSlotFromKey(secret);
12177 if (!isServer) {
12178 int wrapKeyIndex;
12179 int incarnation;
12180
12181 /* these next few functions are mere accessors and don't fail. */
12182 sid->u.ssl3.masterWrapIndex = wrapKeyIndex =
12183 PK11_GetCurrentWrapIndex(symKeySlot);
12184 PORT_Assert(wrapKeyIndex == 0)((wrapKeyIndex == 0)?((void)0):PR_Assert("wrapKeyIndex == 0",
"ssl3con.c",12184))
; /* array has only one entry! */
12185
12186 sid->u.ssl3.masterWrapSeries = incarnation =
12187 PK11_GetSlotSeries(symKeySlot);
12188 sid->u.ssl3.masterSlotID = PK11_GetSlotID(symKeySlot);
12189 sid->u.ssl3.masterModuleID = PK11_GetModuleID(symKeySlot);
12190 sid->u.ssl3.masterValid = PR_TRUE1;
12191 /* Get the default wrapping key, for wrapping the master secret before
12192 * placing it in the SID cache entry. */
12193 wrappingKey = PK11_GetWrapKey(symKeySlot, wrapKeyIndex,
12194 CKM_INVALID_MECHANISM0xffffffffUL, incarnation,
12195 pwArg);
12196 if (wrappingKey) {
12197 mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
12198 } else {
12199 int keyLength;
12200 /* if the wrappingKey doesn't exist, attempt to create it.
12201 * Note: we intentionally ignore errors here. If we cannot
12202 * generate a wrapping key, it is not fatal to this SSL connection,
12203 * but we will not be able to restart this session.
12204 */
12205 mechanism = PK11_GetBestWrapMechanism(symKeySlot);
12206 keyLength = PK11_GetBestKeyLength(symKeySlot, mechanism);
12207 /* Zero length means fixed key length algorithm, or error.
12208 * It's ambiguous.
12209 */
12210 wrappingKey = PK11_KeyGen(symKeySlot, mechanism, NULL((void*)0),
12211 keyLength, pwArg);
12212 if (wrappingKey) {
12213 /* The thread safety characteristics of PK11_[SG]etWrapKey is
12214 * abominable. This protects against races in calling
12215 * PK11_SetWrapKey by dropping and re-acquiring the canonical
12216 * value once it is set. The mutex in PK11_[SG]etWrapKey will
12217 * ensure that races produce the same value in the end. */
12218 PK11_SetWrapKey(symKeySlot, wrapKeyIndex, wrappingKey);
12219 PK11_FreeSymKey(wrappingKey);
12220 wrappingKey = PK11_GetWrapKey(symKeySlot, wrapKeyIndex,
12221 CKM_INVALID_MECHANISM0xffffffffUL, incarnation, pwArg);
12222 if (!wrappingKey) {
12223 PK11_FreeSlot(symKeySlot);
12224 return SECFailure;
12225 }
12226 }
12227 }
12228 } else {
12229 /* server socket using session cache. */
12230 mechanism = PK11_GetBestWrapMechanism(symKeySlot);
12231 if (mechanism != CKM_INVALID_MECHANISM0xffffffffUL) {
12232 wrappingKey =
12233 ssl3_GetWrappingKey(ss, symKeySlot, mechanism, pwArg);
12234 if (wrappingKey) {
12235 mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
12236 }
12237 }
12238 }
12239
12240 sid->u.ssl3.masterWrapMech = mechanism;
12241 PK11_FreeSlot(symKeySlot);
12242
12243 if (wrappingKey) {
12244 SECItem wmsItem;
12245
12246 wmsItem.data = sid->u.ssl3.keys.wrapped_master_secret;
12247 wmsItem.len = sizeof sid->u.ssl3.keys.wrapped_master_secret;
12248 rv = PK11_WrapSymKey(mechanism, NULL((void*)0), wrappingKey,
12249 secret, &wmsItem);
12250 /* rv is examined below. */
12251 sid->u.ssl3.keys.wrapped_master_secret_len = wmsItem.len;
12252 PK11_FreeSymKey(wrappingKey);
12253 }
12254 return rv;
12255}
12256
12257/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
12258 * a complete ssl3 Finished message from the peer.
12259 * Caller must hold Handshake and RecvBuf locks.
12260 */
12261static SECStatus
12262ssl3_HandleFinished(sslSocket *ss, PRUint8 *b, PRUint32 length)
12263{
12264 SECStatus rv = SECSuccess;
12265 PRBool isServer = ss->sec.isServer;
12266 PRBool isTLS;
12267 SSL3Hashes hashes;
12268
12269 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->recvBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveRecvBufLock(ss)"
,"ssl3con.c",12269))
;
12270 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",12270))
;
12271
12272 SSL_TRC(3, ("%d: SSL3[%d]: handle finished handshake",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: handle finished handshake"
, getpid(), ss->fd)
12273 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL3[%d]: handle finished handshake"
, getpid(), ss->fd)
;
12274
12275 if (ss->ssl3.hs.ws != wait_finished) {
12276 SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12277 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_UNEXPECTED_FINISHED);
12278 return SECFailure;
12279 }
12280
12281 if (!ss->sec.isServer || !ss->opt.requestCertificate) {
12282 dtls_ReceivedFirstMessageInFlight(ss);
12283 }
12284
12285 rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.crSpec, &hashes,
12286 isServer ? sender_client : sender_server);
12287 if (rv != SECSuccess) {
12288 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
12289 return SECFailure;
12290 }
12291
12292 rv = ssl_HashHandshakeMessage(ss, ssl_hs_finished, b, length);
12293 if (rv != SECSuccess) {
12294 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
12295 return rv;
12296 }
12297
12298 isTLS = (PRBool)(ss->ssl3.crSpec->version > SSL_LIBRARY_VERSION_3_00x0300);
12299 if (isTLS) {
12300 TLSFinished tlsFinished;
12301
12302 if (length != sizeof(tlsFinished)) {
12303#ifndef UNSAFE_FUZZER_MODE
12304 (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
12305 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_MALFORMED_FINISHED);
12306 return SECFailure;
12307#endif
12308 }
12309 rv = ssl3_ComputeTLSFinished(ss, ss->ssl3.crSpec, !isServer,
12310 &hashes, &tlsFinished);
12311 if (!isServer)
12312 ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished;
12313 else
12314 ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished;
12315 ss->ssl3.hs.finishedBytes = sizeof(tlsFinished);
12316 if (rv != SECSuccess ||
12317 0 != NSS_SecureMemcmp(&tlsFinished, b,
12318 PR_MIN(length, ss->ssl3.hs.finishedBytes)((length)<(ss->ssl3.hs.finishedBytes)?(length):(ss->
ssl3.hs.finishedBytes))
)) {
12319#ifndef UNSAFE_FUZZER_MODE
12320 (void)SSL3_SendAlert(ss, alert_fatal, decrypt_error);
12321 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
12322 return SECFailure;
12323#endif
12324 }
12325 } else {
12326 if (length != sizeof(SSL3Finished)) {
12327 (void)ssl3_IllegalParameter(ss);
12328 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_MALFORMED_FINISHED);
12329 return SECFailure;
12330 }
12331
12332 if (!isServer)
12333 ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes.u.s;
12334 else
12335 ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes.u.s;
12336 PORT_Assert(hashes.len == sizeof hashes.u.s)((hashes.len == sizeof hashes.u.s)?((void)0):PR_Assert("hashes.len == sizeof hashes.u.s"
,"ssl3con.c",12336))
;
12337 ss->ssl3.hs.finishedBytes = sizeof hashes.u.s;
12338 if (0 != NSS_SecureMemcmp(&hashes.u.s, b, length)) {
12339 (void)ssl3_HandshakeFailure(ss);
12340 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
12341 return SECFailure;
12342 }
12343 }
12344
12345 ssl_GetXmitBufLock(ss){ if (!ss->opt.noLocks) PR_EnterMonitor(((ss)->xmitBufLock
)); }
; /*************************************/
12346
12347 if ((isServer && !ss->ssl3.hs.isResuming) ||
12348 (!isServer && ss->ssl3.hs.isResuming)) {
12349 PRInt32 flags = 0;
12350
12351 /* Send a NewSessionTicket message if the client sent us
12352 * either an empty session ticket, or one that did not verify.
12353 * (Note that if either of these conditions was met, then the
12354 * server has sent a SessionTicket extension in the
12355 * ServerHello message.)
12356 */
12357 if (isServer && !ss->ssl3.hs.isResuming &&
12358 ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) &&
12359 ssl3_KEASupportsTickets(ss->ssl3.hs.kea_def)) {
12360 /* RFC 5077 Section 3.3: "In the case of a full handshake, the
12361 * server MUST verify the client's Finished message before sending
12362 * the ticket." Presumably, this also means that the client's
12363 * certificate, if any, must be verified beforehand too.
12364 */
12365 rv = ssl3_SendNewSessionTicket(ss);
12366 if (rv != SECSuccess) {
12367 goto xmit_loser;
12368 }
12369 }
12370
12371 rv = ssl3_SendChangeCipherSpecs(ss);
12372 if (rv != SECSuccess) {
12373 goto xmit_loser; /* err is set. */
12374 }
12375 /* If this thread is in SSL_SecureSend (trying to write some data)
12376 ** then set the ssl_SEND_FLAG_FORCE_INTO_BUFFER flag, so that the
12377 ** last two handshake messages (change cipher spec and finished)
12378 ** will be sent in the same send/write call as the application data.
12379 */
12380 if (ss->writerThread == PR_GetCurrentThread()) {
12381 flags = ssl_SEND_FLAG_FORCE_INTO_BUFFER0x40000000;
12382 }
12383
12384 if (!isServer && !ss->firstHsDone) {
12385 rv = ssl3_SendNextProto(ss);
12386 if (rv != SECSuccess) {
12387 goto xmit_loser; /* err code was set. */
12388 }
12389 }
12390
12391 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
12392 flags |= ssl_SEND_FLAG_NO_RETRANSMIT0x08000000;
12393 }
12394
12395 rv = ssl3_SendFinished(ss, flags);
12396 if (rv != SECSuccess) {
12397 goto xmit_loser; /* err is set. */
12398 }
12399 }
12400
12401xmit_loser:
12402 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
; /*************************************/
12403 if (rv != SECSuccess) {
12404 return rv;
12405 }
12406
12407 if (ss->ssl3.hs.authCertificatePending) {
12408 if (ss->ssl3.hs.restartTarget) {
12409 PR_NOT_REACHED("ssl3_HandleFinished: unexpected restartTarget")PR_Assert("ssl3_HandleFinished: unexpected restartTarget","ssl3con.c"
,12409)
;
12410 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
12411 return SECFailure;
12412 }
12413
12414 ss->ssl3.hs.restartTarget = ssl3_FinishHandshake;
12415 PORT_SetErrorPORT_SetError_Util(PR_WOULD_BLOCK_ERROR(-5998L));
12416 return SECFailure;
12417 }
12418
12419 rv = ssl3_FinishHandshake(ss);
12420 return rv;
12421}
12422
12423SECStatus
12424ssl3_FillInCachedSID(sslSocket *ss, sslSessionID *sid, PK11SymKey *secret)
12425{
12426 PORT_Assert(secret)((secret)?((void)0):PR_Assert("secret","ssl3con.c",12426));
12427
12428 /* fill in the sid */
12429 sid->u.ssl3.cipherSuite = ss->ssl3.hs.cipher_suite;
12430 sid->u.ssl3.policy = ss->ssl3.policy;
12431 sid->version = ss->version;
12432 sid->authType = ss->sec.authType;
12433 sid->authKeyBits = ss->sec.authKeyBits;
12434 sid->keaType = ss->sec.keaType;
12435 sid->keaKeyBits = ss->sec.keaKeyBits;
12436 if (ss->sec.keaGroup) {
12437 sid->keaGroup = ss->sec.keaGroup->name;
12438 } else {
12439 sid->keaGroup = ssl_grp_none;
12440 }
12441 sid->sigScheme = ss->sec.signatureScheme;
12442 sid->lastAccessTime = sid->creationTime = ssl_Time(ss);
12443 sid->expirationTime = sid->creationTime + (ssl_ticket_lifetime * PR_USEC_PER_SEC1000000L);
12444 sid->localCert = CERT_DupCertificate(ss->sec.localCert);
12445 if (ss->sec.isServer) {
12446 sid->namedCurve = ss->sec.serverCert->namedCurve;
12447 }
12448
12449 if (ss->xtnData.nextProtoState != SSL_NEXT_PROTO_NO_SUPPORT &&
12450 ss->xtnData.nextProto.data) {
12451 SECITEM_FreeItemSECITEM_FreeItem_Util(&sid->u.ssl3.alpnSelection, PR_FALSE0);
12452 if (SECITEM_CopyItemSECITEM_CopyItem_Util(
12453 NULL((void*)0), &sid->u.ssl3.alpnSelection, &ss->xtnData.nextProto) != SECSuccess) {
12454 return SECFailure; /* error already set. */
12455 }
12456 }
12457
12458 /* Copy the master secret (wrapped or unwrapped) into the sid */
12459 return ssl3_CacheWrappedSecret(ss, ss->sec.ci.sid, secret);
12460}
12461
12462/* The return type is SECStatus instead of void because this function needs
12463 * to have type sslRestartTarget.
12464 */
12465SECStatus
12466ssl3_FinishHandshake(sslSocket *ss)
12467{
12468 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->recvBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveRecvBufLock(ss)"
,"ssl3con.c",12468))
;
12469 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",12469))
;
12470 PORT_Assert(ss->ssl3.hs.restartTarget == NULL)((ss->ssl3.hs.restartTarget == ((void*)0))?((void)0):PR_Assert
("ss->ssl3.hs.restartTarget == NULL","ssl3con.c",12470))
;
12471 sslSessionID *sid = ss->sec.ci.sid;
12472 SECStatus sidRv = SECFailure;
12473
12474 /* The first handshake is now completed. */
12475 ss->handshake = NULL((void*)0);
12476
12477 if (sid->cached == never_cached && !ss->opt.noCache) {
12478 /* If the wrap fails, don't cache the sid. The connection proceeds
12479 * normally, so the rv is only used to determine whether we cache. */
12480 sidRv = ssl3_FillInCachedSID(ss, sid, ss->ssl3.crSpec->masterSecret);
12481 }
12482
12483 /* RFC 5077 Section 3.3: "The client MUST NOT treat the ticket as valid
12484 * until it has verified the server's Finished message." When the server
12485 * sends a NewSessionTicket in a resumption handshake, we must wait until
12486 * the handshake is finished (we have verified the server's Finished
12487 * AND the server's certificate) before we update the ticket in the sid.
12488 *
12489 * This must be done before we call ssl_CacheSessionID(ss)
12490 * because CacheSID requires the session ticket to already be set, and also
12491 * because of the lazy lock creation scheme used by CacheSID and
12492 * ssl3_SetSIDSessionTicket. */
12493 if (ss->ssl3.hs.receivedNewSessionTicket) {
12494 PORT_Assert(!ss->sec.isServer)((!ss->sec.isServer)?((void)0):PR_Assert("!ss->sec.isServer"
,"ssl3con.c",12494))
;
12495 if (sidRv == SECSuccess) {
12496 /* The sid takes over the ticket data */
12497 ssl3_SetSIDSessionTicket(ss->sec.ci.sid,
12498 &ss->ssl3.hs.newSessionTicket);
12499 } else {
12500 PORT_Assert(ss->ssl3.hs.newSessionTicket.ticket.data)((ss->ssl3.hs.newSessionTicket.ticket.data)?((void)0):PR_Assert
("ss->ssl3.hs.newSessionTicket.ticket.data","ssl3con.c",12500
))
;
12501 SECITEM_FreeItemSECITEM_FreeItem_Util(&ss->ssl3.hs.newSessionTicket.ticket,
12502 PR_FALSE0);
12503 }
12504 PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data)((!ss->ssl3.hs.newSessionTicket.ticket.data)?((void)0):PR_Assert
("!ss->ssl3.hs.newSessionTicket.ticket.data","ssl3con.c",12504
))
;
12505 ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE0;
12506 }
12507 if (sidRv == SECSuccess) {
12508 PORT_Assert(ss->sec.ci.sid->cached == never_cached)((ss->sec.ci.sid->cached == never_cached)?((void)0):PR_Assert
("ss->sec.ci.sid->cached == never_cached","ssl3con.c",12508
))
;
12509 ssl_CacheSessionID(ss);
12510 }
12511
12512 ss->ssl3.hs.canFalseStart = PR_FALSE0; /* False Start phase is complete */
12513 ss->ssl3.hs.ws = idle_handshake;
12514
12515 return ssl_FinishHandshake(ss);
12516}
12517
12518SECStatus
12519ssl_HashHandshakeMessageInt(sslSocket *ss, SSLHandshakeType ct,
12520 PRUint32 dtlsSeq,
12521 const PRUint8 *b, PRUint32 length,
12522 sslUpdateHandshakeHashes updateHashes)
12523{
12524 PRUint8 hdr[4];
12525 PRUint8 dtlsData[8];
12526 SECStatus rv;
12527
12528 PRINT_BUF(50, (ss, "Hash handshake message:", b, length))if (ssl_trace >= (50)) ssl_PrintBuf (ss, "Hash handshake message:"
, b, length)
;
12529
12530 hdr[0] = (PRUint8)ct;
12531 hdr[1] = (PRUint8)(length >> 16);
12532 hdr[2] = (PRUint8)(length >> 8);
12533 hdr[3] = (PRUint8)(length);
12534
12535 rv = updateHashes(ss, (unsigned char *)hdr, 4);
12536 if (rv != SECSuccess)
12537 return rv; /* err code already set. */
12538
12539 /* Extra data to simulate a complete DTLS handshake fragment */
12540 if (IS_DTLS_1_OR_12(ss)((ss->protocolVariant == ssl_variant_datagram) && ss
->version < 0x0304)
) {
12541 /* Sequence number */
12542 dtlsData[0] = MSB(dtlsSeq)((unsigned char)(((unsigned)(dtlsSeq)) >> 8));
12543 dtlsData[1] = LSB(dtlsSeq)((unsigned char)((dtlsSeq)&0xff));
12544
12545 /* Fragment offset */
12546 dtlsData[2] = 0;
12547 dtlsData[3] = 0;
12548 dtlsData[4] = 0;
12549
12550 /* Fragment length */
12551 dtlsData[5] = (PRUint8)(length >> 16);
12552 dtlsData[6] = (PRUint8)(length >> 8);
12553 dtlsData[7] = (PRUint8)(length);
12554
12555 rv = updateHashes(ss, (unsigned char *)dtlsData, sizeof(dtlsData));
12556 if (rv != SECSuccess)
12557 return rv; /* err code already set. */
12558 }
12559
12560 /* The message body */
12561 rv = updateHashes(ss, b, length);
12562 if (rv != SECSuccess)
12563 return rv; /* err code already set. */
12564
12565 return SECSuccess;
12566}
12567
12568SECStatus
12569ssl_HashHandshakeMessage(sslSocket *ss, SSLHandshakeType ct,
12570 const PRUint8 *b, PRUint32 length)
12571{
12572 return ssl_HashHandshakeMessageInt(ss, ct, ss->ssl3.hs.recvMessageSeq,
12573 b, length, ssl3_UpdateHandshakeHashes);
12574}
12575
12576SECStatus
12577ssl_HashHandshakeMessageDefault(sslSocket *ss, SSLHandshakeType ct,
12578 const PRUint8 *b, PRUint32 length)
12579{
12580 return ssl_HashHandshakeMessageInt(ss, ct, ss->ssl3.hs.recvMessageSeq,
12581 b, length, ssl3_UpdateDefaultHandshakeHashes);
12582}
12583SECStatus
12584ssl_HashHandshakeMessageEchInner(sslSocket *ss, SSLHandshakeType ct,
12585 const PRUint8 *b, PRUint32 length)
12586{
12587 return ssl_HashHandshakeMessageInt(ss, ct, ss->ssl3.hs.recvMessageSeq,
12588 b, length, ssl3_UpdateInnerHandshakeHashes);
12589}
12590
12591SECStatus
12592ssl_HashPostHandshakeMessage(sslSocket *ss, SSLHandshakeType ct,
12593 const PRUint8 *b, PRUint32 length)
12594{
12595 return ssl_HashHandshakeMessageInt(ss, ct, ss->ssl3.hs.recvMessageSeq,
12596 b, length, ssl3_UpdatePostHandshakeHashes);
12597}
12598
12599/* Called from ssl3_HandleHandshake() when it has gathered a complete ssl3
12600 * handshake message.
12601 * Caller must hold Handshake and RecvBuf locks.
12602 */
12603SECStatus
12604ssl3_HandleHandshakeMessage(sslSocket *ss, PRUint8 *b, PRUint32 length,
12605 PRBool endOfRecord)
12606{
12607 SECStatus rv = SECSuccess;
12608 PRUint16 epoch;
12609
12610 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->recvBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveRecvBufLock(ss)"
,"ssl3con.c",12610))
;
12611 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",12611))
;
12612
12613 SSL_TRC(30, ("%d: SSL3[%d]: handle handshake message: %s", SSL_GETPID(),if (ssl_trace >= (30)) ssl_Trace ("%d: SSL3[%d]: handle handshake message: %s"
, getpid(), ss->fd, ssl3_DecodeHandshakeType(ss->ssl3.hs
.msg_type))
12614 ss->fd, ssl3_DecodeHandshakeType(ss->ssl3.hs.msg_type)))if (ssl_trace >= (30)) ssl_Trace ("%d: SSL3[%d]: handle handshake message: %s"
, getpid(), ss->fd, ssl3_DecodeHandshakeType(ss->ssl3.hs
.msg_type))
;
12615
12616 /* Start new handshake hashes when we start a new handshake. */
12617 if (ss->ssl3.hs.msg_type == ssl_hs_client_hello) {
12618 ssl3_RestartHandshakeHashes(ss);
12619 }
12620 switch (ss->ssl3.hs.msg_type) {
12621 case ssl_hs_hello_request:
12622 case ssl_hs_hello_verify_request:
12623 /* We don't include hello_request and hello_verify_request messages
12624 * in the handshake hashes */
12625 break;
12626
12627 /* Defer hashing of these messages until the message handlers. */
12628 case ssl_hs_client_hello:
12629 case ssl_hs_server_hello:
12630 case ssl_hs_certificate_verify:
12631 case ssl_hs_finished:
12632 break;
12633
12634 default:
12635 if (!tls13_IsPostHandshake(ss)) {
12636 rv = ssl_HashHandshakeMessage(ss, ss->ssl3.hs.msg_type, b, length);
12637 if (rv != SECSuccess) {
12638 return SECFailure;
12639 }
12640 }
12641 }
12642
12643 PORT_SetErrorPORT_SetError_Util(0); /* each message starts with no error. */
12644
12645 if (ss->ssl3.hs.ws == wait_certificate_status &&
12646 ss->ssl3.hs.msg_type != ssl_hs_certificate_status) {
12647 /* If we negotiated the certificate_status extension then we deferred
12648 * certificate validation until we get the CertificateStatus messsage.
12649 * But the CertificateStatus message is optional. If the server did
12650 * not send it then we need to validate the certificate now. If the
12651 * server does send the CertificateStatus message then we will
12652 * authenticate the certificate in ssl3_HandleCertificateStatus.
12653 */
12654 rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
12655 if (rv != SECSuccess) {
12656 /* This can't block. */
12657 PORT_Assert(PORT_GetError() != PR_WOULD_BLOCK_ERROR)((PORT_GetError_Util() != (-5998L))?((void)0):PR_Assert("PORT_GetError() != PR_WOULD_BLOCK_ERROR"
,"ssl3con.c",12657))
;
12658 return SECFailure;
12659 }
12660 }
12661
12662 epoch = ss->ssl3.crSpec->epoch;
12663 switch (ss->ssl3.hs.msg_type) {
12664 case ssl_hs_client_hello:
12665 if (!ss->sec.isServer) {
12666 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12667 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO);
12668 return SECFailure;
12669 }
12670 rv = ssl3_HandleClientHello(ss, b, length);
12671 break;
12672 case ssl_hs_server_hello:
12673 if (ss->sec.isServer) {
12674 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12675 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO);
12676 return SECFailure;
12677 }
12678 rv = ssl3_HandleServerHello(ss, b, length);
12679 break;
12680 default:
12681 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_30x0304) {
12682 rv = ssl3_HandlePostHelloHandshakeMessage(ss, b, length);
12683 } else {
12684 rv = tls13_HandlePostHelloHandshakeMessage(ss, b, length);
12685 }
12686 break;
12687 }
12688 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_30x0304 &&
12689 (epoch != ss->ssl3.crSpec->epoch) && !endOfRecord) {
12690 /* If we changed read cipher states, there must not be any
12691 * data in the input queue. */
12692 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12693 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
12694 return SECFailure;
12695 }
12696 /* We consider the record to have been handled if SECSuccess or else WOULD_BLOCK is set
12697 * Whoever set WOULD_BLOCK must handle any remaining actions required to finsih processing the record.
12698 * e.g. by setting restartTarget.
12699 */
12700 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram) && (rv == SECSuccess || (rv == SECFailure && PR_GetError() == PR_WOULD_BLOCK_ERROR(-5998L)))) {
12701 /* Increment the expected sequence number */
12702 ss->ssl3.hs.recvMessageSeq++;
12703 }
12704
12705 /* Taint the message so that it's easier to detect UAFs. */
12706 PORT_Memsetmemset(b, 'N', length);
12707
12708 return rv;
12709}
12710
12711static SECStatus
12712ssl3_HandlePostHelloHandshakeMessage(sslSocket *ss, PRUint8 *b,
12713 PRUint32 length)
12714{
12715 SECStatus rv;
12716 PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3)((ss->version < 0x0304)?((void)0):PR_Assert("ss->version < SSL_LIBRARY_VERSION_TLS_1_3"
,"ssl3con.c",12716))
;
12717
12718 switch (ss->ssl3.hs.msg_type) {
12719 case ssl_hs_hello_request:
12720 if (length != 0) {
12721 (void)ssl3_DecodeError(ss);
12722 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_MALFORMED_HELLO_REQUEST);
12723 return SECFailure;
12724 }
12725 if (ss->sec.isServer) {
12726 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12727 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST);
12728 return SECFailure;
12729 }
12730 rv = ssl3_HandleHelloRequest(ss);
12731 break;
12732
12733 case ssl_hs_hello_verify_request:
12734 if (!IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram) || ss->sec.isServer) {
12735 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12736 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_UNEXPECTED_HELLO_VERIFY_REQUEST);
12737 return SECFailure;
12738 }
12739 rv = dtls_HandleHelloVerifyRequest(ss, b, length);
12740 break;
12741 case ssl_hs_certificate:
12742 rv = ssl3_HandleCertificate(ss, b, length);
12743 break;
12744 case ssl_hs_certificate_status:
12745 rv = ssl3_HandleCertificateStatus(ss, b, length);
12746 break;
12747 case ssl_hs_server_key_exchange:
12748 if (ss->sec.isServer) {
12749 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12750 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH);
12751 return SECFailure;
12752 }
12753 rv = ssl3_HandleServerKeyExchange(ss, b, length);
12754 break;
12755 case ssl_hs_certificate_request:
12756 if (ss->sec.isServer) {
12757 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12758 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST);
12759 return SECFailure;
12760 }
12761 rv = ssl3_HandleCertificateRequest(ss, b, length);
12762 break;
12763 case ssl_hs_server_hello_done:
12764 if (length != 0) {
12765 (void)ssl3_DecodeError(ss);
12766 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_MALFORMED_HELLO_DONE);
12767 return SECFailure;
12768 }
12769 if (ss->sec.isServer) {
12770 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12771 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
12772 return SECFailure;
12773 }
12774 rv = ssl3_HandleServerHelloDone(ss);
12775 break;
12776 case ssl_hs_certificate_verify:
12777 if (!ss->sec.isServer) {
12778 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12779 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY);
12780 return SECFailure;
12781 }
12782 rv = ssl3_HandleCertificateVerify(ss, b, length);
12783 break;
12784 case ssl_hs_client_key_exchange:
12785 if (!ss->sec.isServer) {
12786 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12787 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
12788 return SECFailure;
12789 }
12790 rv = ssl3_HandleClientKeyExchange(ss, b, length);
12791 break;
12792 case ssl_hs_new_session_ticket:
12793 if (ss->sec.isServer) {
12794 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12795 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
12796 return SECFailure;
12797 }
12798 rv = ssl3_HandleNewSessionTicket(ss, b, length);
12799 break;
12800 case ssl_hs_finished:
12801 rv = ssl3_HandleFinished(ss, b, length);
12802 break;
12803 default:
12804 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
12805 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_UNKNOWN_HANDSHAKE);
12806 rv = SECFailure;
12807 }
12808
12809 return rv;
12810}
12811
12812/* Called only from ssl3_HandleRecord, for each (deciphered) ssl3 record.
12813 * origBuf is the decrypted ssl record content.
12814 * Caller must hold the handshake and RecvBuf locks.
12815 */
12816static SECStatus
12817ssl3_HandleHandshake(sslSocket *ss, sslBuffer *origBuf)
12818{
12819 sslBuffer buf = *origBuf; /* Work from a copy. */
12820 SECStatus rv;
12821
12822 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->recvBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveRecvBufLock(ss)"
,"ssl3con.c",12822))
;
12823 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",12823))
;
12824
12825 while (buf.len > 0) {
12826 if (ss->ssl3.hs.header_bytes < 4) {
12827 PRUint8 t;
12828 t = *(buf.buf++);
12829 buf.len--;
12830 if (ss->ssl3.hs.header_bytes++ == 0)
12831 ss->ssl3.hs.msg_type = (SSLHandshakeType)t;
12832 else
12833 ss->ssl3.hs.msg_len = (ss->ssl3.hs.msg_len << 8) + t;
12834 if (ss->ssl3.hs.header_bytes < 4)
12835 continue;
12836
12837#define MAX_HANDSHAKE_MSG_LEN 0x1ffff /* 128k - 1 */
12838 if (ss->ssl3.hs.msg_len > MAX_HANDSHAKE_MSG_LEN) {
12839 (void)ssl3_DecodeError(ss);
12840 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_MALFORMED_HANDSHAKE);
12841 goto loser;
12842 }
12843#undef MAX_HANDSHAKE_MSG_LEN
12844
12845 /* If msg_len is zero, be sure we fall through,
12846 ** even if buf.len is zero.
12847 */
12848 if (ss->ssl3.hs.msg_len > 0)
12849 continue;
12850 }
12851
12852 /*
12853 * Header has been gathered and there is at least one byte of new
12854 * data available for this message. If it can be done right out
12855 * of the original buffer, then use it from there.
12856 */
12857 if (ss->ssl3.hs.msg_body.len == 0 && buf.len >= ss->ssl3.hs.msg_len) {
12858 /* handle it from input buffer */
12859 rv = ssl3_HandleHandshakeMessage(ss, buf.buf, ss->ssl3.hs.msg_len,
12860 buf.len == ss->ssl3.hs.msg_len);
12861 buf.buf += ss->ssl3.hs.msg_len;
12862 buf.len -= ss->ssl3.hs.msg_len;
12863 ss->ssl3.hs.msg_len = 0;
12864 ss->ssl3.hs.header_bytes = 0;
12865 if (rv != SECSuccess) {
12866 goto loser;
12867 }
12868 } else {
12869 /* must be copied to msg_body and dealt with from there */
12870 unsigned int bytes;
12871
12872 PORT_Assert(ss->ssl3.hs.msg_body.len < ss->ssl3.hs.msg_len)((ss->ssl3.hs.msg_body.len < ss->ssl3.hs.msg_len)?((
void)0):PR_Assert("ss->ssl3.hs.msg_body.len < ss->ssl3.hs.msg_len"
,"ssl3con.c",12872))
;
12873 bytes = PR_MIN(buf.len, ss->ssl3.hs.msg_len - ss->ssl3.hs.msg_body.len)((buf.len)<(ss->ssl3.hs.msg_len - ss->ssl3.hs.msg_body
.len)?(buf.len):(ss->ssl3.hs.msg_len - ss->ssl3.hs.msg_body
.len))
;
12874
12875 /* Grow the buffer if needed */
12876 rv = sslBuffer_Grow(&ss->ssl3.hs.msg_body, ss->ssl3.hs.msg_len);
12877 if (rv != SECSuccess) {
12878 /* sslBuffer_Grow has set a memory error code. */
12879 goto loser;
12880 }
12881
12882 PORT_Memcpymemcpy(ss->ssl3.hs.msg_body.buf + ss->ssl3.hs.msg_body.len,
12883 buf.buf, bytes);
12884 ss->ssl3.hs.msg_body.len += bytes;
12885 buf.buf += bytes;
12886 buf.len -= bytes;
12887
12888 PORT_Assert(ss->ssl3.hs.msg_body.len <= ss->ssl3.hs.msg_len)((ss->ssl3.hs.msg_body.len <= ss->ssl3.hs.msg_len)?(
(void)0):PR_Assert("ss->ssl3.hs.msg_body.len <= ss->ssl3.hs.msg_len"
,"ssl3con.c",12888))
;
12889
12890 /* if we have a whole message, do it */
12891 if (ss->ssl3.hs.msg_body.len == ss->ssl3.hs.msg_len) {
12892 rv = ssl3_HandleHandshakeMessage(
12893 ss, ss->ssl3.hs.msg_body.buf, ss->ssl3.hs.msg_len,
12894 buf.len == 0);
12895 ss->ssl3.hs.msg_body.len = 0;
12896 ss->ssl3.hs.msg_len = 0;
12897 ss->ssl3.hs.header_bytes = 0;
12898 if (rv != SECSuccess) {
12899 goto loser;
12900 }
12901 } else {
12902 PORT_Assert(buf.len == 0)((buf.len == 0)?((void)0):PR_Assert("buf.len == 0","ssl3con.c"
,12902))
;
12903 break;
12904 }
12905 }
12906 } /* end loop */
12907
12908 origBuf->len = 0; /* So ssl3_GatherAppDataRecord will keep looping. */
12909 return SECSuccess;
12910
12911loser : {
12912 /* Make sure to remove any data that was consumed. */
12913 unsigned int consumed = origBuf->len - buf.len;
12914 PORT_Assert(consumed == buf.buf - origBuf->buf)((consumed == buf.buf - origBuf->buf)?((void)0):PR_Assert(
"consumed == buf.buf - origBuf->buf","ssl3con.c",12914))
;
12915 if (consumed > 0) {
12916 memmove(origBuf->buf, origBuf->buf + consumed, buf.len);
12917 origBuf->len = buf.len;
12918 }
12919}
12920 return SECFailure;
12921}
12922
12923/* SECStatusToMask returns, in constant time, a mask value of all ones if
12924 * rv == SECSuccess. Otherwise it returns zero. */
12925static unsigned int
12926SECStatusToMask(SECStatus rv)
12927{
12928 return PORT_CT_EQ(rv, SECSuccess)(~((PRUint32)((PRInt32)(((((rv) - (SECSuccess))) | (0 - (((rv
) - (SECSuccess)))))) >> (sizeof(PRInt32) * 8 - 1))))
;
12929}
12930
12931/* ssl_ConstantTimeGE returns 0xffffffff if a>=b and 0x00 otherwise. */
12932static unsigned char
12933ssl_ConstantTimeGE(unsigned int a, unsigned int b)
12934{
12935 return PORT_CT_GE(a, b)(~((PRUint32)((PRInt32)((a) - (b)) >> (sizeof(PRInt32) *
8 - 1))))
;
12936}
12937
12938/* ssl_ConstantTimeEQ returns 0xffffffff if a==b and 0x00 otherwise. */
12939static unsigned char
12940ssl_ConstantTimeEQ(unsigned char a, unsigned char b)
12941{
12942 return PORT_CT_EQ(a, b)(~((PRUint32)((PRInt32)(((((a) - (b))) | (0 - (((a) - (b)))))
) >> (sizeof(PRInt32) * 8 - 1))))
;
12943}
12944
12945/* ssl_constantTimeSelect return a if mask is 0xFF and b if mask is 0x00 */
12946static unsigned char
12947ssl_constantTimeSelect(unsigned char mask, unsigned char a, unsigned char b)
12948{
12949 return (mask & a) | (~mask & b);
12950}
12951
12952static SECStatus
12953ssl_RemoveSSLv3CBCPadding(sslBuffer *plaintext,
12954 unsigned int blockSize,
12955 unsigned int macSize)
12956{
12957 unsigned int paddingLength, good;
12958 const unsigned int overhead = 1 /* padding length byte */ + macSize;
12959
12960 /* These lengths are all public so we can test them in non-constant
12961 * time. */
12962 if (overhead > plaintext->len) {
12963 return SECFailure;
12964 }
12965
12966 paddingLength = plaintext->buf[plaintext->len - 1];
12967 /* SSLv3 padding bytes are random and cannot be checked. */
12968 good = PORT_CT_GE(plaintext->len, paddingLength + overhead)(~((PRUint32)((PRInt32)((plaintext->len) - (paddingLength +
overhead)) >> (sizeof(PRInt32) * 8 - 1))))
;
12969 /* SSLv3 requires that the padding is minimal. */
12970 good &= PORT_CT_GE(blockSize, paddingLength + 1)(~((PRUint32)((PRInt32)((blockSize) - (paddingLength + 1)) >>
(sizeof(PRInt32) * 8 - 1))))
;
12971 plaintext->len -= good & (paddingLength + 1);
12972 return (good & SECSuccess) | (~good & SECFailure);
12973}
12974
12975SECStatus
12976ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize)
12977{
12978 unsigned int paddingLength, good, toCheck, i;
12979 const unsigned int overhead = 1 /* padding length byte */ + macSize;
12980
12981 /* These lengths are all public so we can test them in non-constant
12982 * time. */
12983 if (overhead > plaintext->len) {
12984 return SECFailure;
12985 }
12986
12987 paddingLength = plaintext->buf[plaintext->len - 1];
12988 good = PORT_CT_GE(plaintext->len, paddingLength + overhead)(~((PRUint32)((PRInt32)((plaintext->len) - (paddingLength +
overhead)) >> (sizeof(PRInt32) * 8 - 1))))
;
12989
12990 /* The padding consists of a length byte at the end of the record and then
12991 * that many bytes of padding, all with the same value as the length byte.
12992 * Thus, with the length byte included, there are paddingLength+1 bytes of
12993 * padding.
12994 *
12995 * We can't check just |paddingLength+1| bytes because that leaks
12996 * decrypted information. Therefore we always have to check the maximum
12997 * amount of padding possible. (Again, the length of the record is
12998 * public information so we can use it.) */
12999 toCheck = 256; /* maximum amount of padding + 1. */
13000 if (toCheck > plaintext->len) {
13001 toCheck = plaintext->len;
13002 }
13003
13004 for (i = 0; i < toCheck; i++) {
13005 /* If i <= paddingLength then the MSB of t is zero and mask is
13006 * 0xff. Otherwise, mask is 0. */
13007 unsigned char mask = PORT_CT_LE(i, paddingLength)(~((PRUint32)((PRInt32)((paddingLength) - (i)) >> (sizeof
(PRInt32) * 8 - 1))))
;
13008 unsigned char b = plaintext->buf[plaintext->len - 1 - i];
13009 /* The final |paddingLength+1| bytes should all have the value
13010 * |paddingLength|. Therefore the XOR should be zero. */
13011 good &= ~(mask & (paddingLength ^ b));
13012 }
13013
13014 /* If any of the final |paddingLength+1| bytes had the wrong value,
13015 * one or more of the lower eight bits of |good| will be cleared. We
13016 * AND the bottom 8 bits together and duplicate the result to all the
13017 * bits. */
13018 good &= good >> 4;
13019 good &= good >> 2;
13020 good &= good >> 1;
13021 good <<= sizeof(good) * 8 - 1;
13022 good = PORT_CT_DUPLICATE_MSB_TO_ALL(good)((PRUint32)((PRInt32)(good) >> (sizeof(PRInt32) * 8 - 1
)))
;
13023
13024 plaintext->len -= good & (paddingLength + 1);
13025 return (good & SECSuccess) | (~good & SECFailure);
13026}
13027
13028/* On entry:
13029 * originalLength >= macSize
13030 * macSize <= MAX_MAC_LENGTH
13031 * plaintext->len >= macSize
13032 */
13033static void
13034ssl_CBCExtractMAC(sslBuffer *plaintext,
13035 unsigned int originalLength,
13036 PRUint8 *out,
13037 unsigned int macSize)
13038{
13039 unsigned char rotatedMac[MAX_MAC_LENGTH64];
13040 /* macEnd is the index of |plaintext->buf| just after the end of the
13041 * MAC. */
13042 unsigned macEnd = plaintext->len;
13043 unsigned macStart = macEnd - macSize;
13044 /* scanStart contains the number of bytes that we can ignore because
13045 * the MAC's position can only vary by 255 bytes. */
13046 unsigned scanStart = 0;
13047 unsigned i, j;
13048 unsigned char rotateOffset;
13049
13050 if (originalLength > macSize + 255 + 1) {
13051 scanStart = originalLength - (macSize + 255 + 1);
13052 }
13053
13054 /* We want to compute
13055 * rotateOffset = (macStart - scanStart) % macSize
13056 * But the time to compute this varies based on the amount of padding. Thus
13057 * we explicitely handle all mac sizes with (hopefully) constant time modulo
13058 * using Barrett reduction:
13059 * q := (rotateOffset * m) >> k
13060 * rotateOffset -= q * n
13061 * if (n <= rotateOffset) rotateOffset -= n
13062 */
13063 rotateOffset = macStart - scanStart;
13064 /* rotateOffset < 255 + 1 + 48 = 304 */
13065 if (macSize == 16) {
13066 rotateOffset &= 15;
13067 } else if (macSize == 20) {
13068 /*
13069 * Correctness: rotateOffset * ( 1/20 - 25/2^9 ) < 1
13070 * with rotateOffset <= 853
13071 */
13072 unsigned q = (rotateOffset * 25) >> 9;
13073 rotateOffset -= q * 20;
13074 rotateOffset -= ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, 20),
13075 20, 0);
13076 } else if (macSize == 32) {
13077 rotateOffset &= 31;
13078 } else if (macSize == 48) {
13079 /*
13080 * Correctness: rotateOffset * ( 1/48 - 10/2^9 ) < 1
13081 * with rotateOffset < 768
13082 */
13083 unsigned q = (rotateOffset * 10) >> 9;
13084 rotateOffset -= q * 48;
13085 rotateOffset -= ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, 48),
13086 48, 0);
13087 } else {
13088 /*
13089 * SHA384 (macSize == 48) is the largest we support. We should never
13090 * get here.
13091 */
13092 PORT_Assert(0)((0)?((void)0):PR_Assert("0","ssl3con.c",13092));
13093 rotateOffset = rotateOffset % macSize;
13094 }
13095
13096 memset(rotatedMac, 0, macSize);
13097 for (i = scanStart; i < originalLength;) {
13098 for (j = 0; j < macSize && i < originalLength; i++, j++) {
13099 unsigned char macStarted = ssl_ConstantTimeGE(i, macStart);
13100 unsigned char macEnded = ssl_ConstantTimeGE(i, macEnd);
13101 unsigned char b = 0;
13102 b = plaintext->buf[i];
13103 rotatedMac[j] |= b & macStarted & ~macEnded;
13104 }
13105 }
13106
13107 /* Now rotate the MAC. If we knew that the MAC fit into a CPU cache line
13108 * we could line-align |rotatedMac| and rotate in place. */
13109 memset(out, 0, macSize);
13110 rotateOffset = macSize - rotateOffset;
13111 rotateOffset = ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, macSize),
13112 0, rotateOffset);
13113 for (i = 0; i < macSize; i++) {
13114 for (j = 0; j < macSize; j++) {
13115 out[j] |= rotatedMac[i] & ssl_ConstantTimeEQ(j, rotateOffset);
13116 }
13117 rotateOffset++;
13118 rotateOffset = ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, macSize),
13119 0, rotateOffset);
13120 }
13121}
13122
13123/* MAX_EXPANSION is the amount by which a record might plausibly be expanded
13124 * when protected. It's the worst case estimate, so the sum of block cipher
13125 * padding (up to 256 octets), HMAC (48 octets for SHA-384), and IV (16
13126 * octets for AES). */
13127#define MAX_EXPANSION(256 + 48 + 16) (256 + 48 + 16)
13128
13129/* Unprotect an SSL3 record and leave the result in plaintext.
13130 *
13131 * If SECFailure is returned, we:
13132 * 1. Set |*alert| to the alert to be sent.
13133 * 2. Call PORT_SetError() with an appropriate code.
13134 *
13135 * Called by ssl3_HandleRecord. Caller must hold the spec read lock.
13136 * Therefore, we MUST not call SSL3_SendAlert().
13137 *
13138 */
13139static SECStatus
13140ssl3_UnprotectRecord(sslSocket *ss,
13141 ssl3CipherSpec *spec,
13142 SSL3Ciphertext *cText, sslBuffer *plaintext,
13143 SSL3AlertDescription *alert)
13144{
13145 const ssl3BulkCipherDef *cipher_def = spec->cipherDef;
13146 PRBool isTLS;
13147 unsigned int good;
13148 unsigned int ivLen = 0;
13149 SSLContentType rType;
13150 SSL3ProtocolVersion rVersion;
13151 unsigned int minLength;
13152 unsigned int originalLen = 0;
13153 PRUint8 headerBuf[13];
13154 sslBuffer header = SSL_BUFFER(headerBuf){ headerBuf, 0, sizeof(headerBuf), 1 };
13155 PRUint8 hash[MAX_MAC_LENGTH64];
13156 PRUint8 givenHashBuf[MAX_MAC_LENGTH64];
13157 PRUint8 *givenHash;
13158 unsigned int hashBytes = MAX_MAC_LENGTH64 + 1;
13159 SECStatus rv;
13160
13161 PORT_Assert(spec->direction == ssl_secret_read)((spec->direction == ssl_secret_read)?((void)0):PR_Assert(
"spec->direction == ssl_secret_read","ssl3con.c",13161))
;
13162
13163 good = ~0U;
13164 minLength = spec->macDef->mac_size;
13165 if (cipher_def->type == type_block) {
13166 /* CBC records have a padding length byte at the end. */
13167 minLength++;
13168 if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_10x0302) {
13169 /* With >= TLS 1.1, CBC records have an explicit IV. */
13170 minLength += cipher_def->iv_size;
13171 }
13172 } else if (cipher_def->type == type_aead) {
13173 minLength = cipher_def->explicit_nonce_size + cipher_def->tag_size;
13174 }
13175
13176 /* We can perform this test in variable time because the record's total
13177 * length and the ciphersuite are both public knowledge. */
13178 if (cText->buf->len < minLength) {
13179 goto decrypt_loser;
13180 }
13181
13182 if (cipher_def->type == type_block &&
13183 spec->version >= SSL_LIBRARY_VERSION_TLS_1_10x0302) {
13184 /* Consume the per-record explicit IV. RFC 4346 Section 6.2.3.2 states
13185 * "The receiver decrypts the entire GenericBlockCipher structure and
13186 * then discards the first cipher block corresponding to the IV
13187 * component." Instead, we decrypt the first cipher block and then
13188 * discard it before decrypting the rest.
13189 */
13190 PRUint8 iv[MAX_IV_LENGTH24];
13191 unsigned int decoded;
13192
13193 ivLen = cipher_def->iv_size;
13194 if (ivLen < 8 || ivLen > sizeof(iv)) {
13195 *alert = internal_error;
13196 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
13197 return SECFailure;
13198 }
13199
13200 PRINT_BUF(80, (ss, "IV (ciphertext):", cText->buf->buf, ivLen))if (ssl_trace >= (80)) ssl_PrintBuf (ss, "IV (ciphertext):"
, cText->buf->buf, ivLen)
;
13201
13202 /* The decryption result is garbage, but since we just throw away
13203 * the block it doesn't matter. The decryption of the next block
13204 * depends only on the ciphertext of the IV block.
13205 */
13206 rv = spec->cipher(spec->cipherContext, iv, &decoded,
13207 sizeof(iv), cText->buf->buf, ivLen);
13208
13209 good &= SECStatusToMask(rv);
13210 }
13211
13212 PRINT_BUF(80, (ss, "ciphertext:", cText->buf->buf + ivLen,if (ssl_trace >= (80)) ssl_PrintBuf (ss, "ciphertext:", cText
->buf->buf + ivLen, cText->buf->len - ivLen)
13213 cText->buf->len - ivLen))if (ssl_trace >= (80)) ssl_PrintBuf (ss, "ciphertext:", cText
->buf->buf + ivLen, cText->buf->len - ivLen)
;
13214
13215 /* Check if the ciphertext can be valid if we assume maximum plaintext and
13216 * add the maximum possible ciphersuite expansion.
13217 * This way we detect overlong plaintexts/padding before decryption.
13218 * This check enforces size limitations more strict than the RFC.
13219 * [RFC5246, Section 6.2.3] */
13220 if (cText->buf->len > (spec->recordSizeLimit + MAX_EXPANSION(256 + 48 + 16))) {
13221 *alert = record_overflow;
13222 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_RECORD_TOO_LONG);
13223 return SECFailure;
13224 }
13225
13226 isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_00x0300);
13227 rType = (SSLContentType)cText->hdr[0];
13228 rVersion = ((SSL3ProtocolVersion)cText->hdr[1] << 8) |
13229 (SSL3ProtocolVersion)cText->hdr[2];
13230 if (cipher_def->type == type_aead) {
13231 /* XXX For many AEAD ciphers, the plaintext is shorter than the
13232 * ciphertext by a fixed byte count, but it is not true in general.
13233 * Each AEAD cipher should provide a function that returns the
13234 * plaintext length for a given ciphertext. */
13235 const unsigned int explicitNonceLen = cipher_def->explicit_nonce_size;
13236 const unsigned int tagLen = cipher_def->tag_size;
13237 unsigned int nonceLen = explicitNonceLen;
13238 unsigned int decryptedLen = cText->buf->len - nonceLen - tagLen;
13239 /* even though read doesn't return and IV, we still need a space to put
13240 * the combined iv/nonce n the gcm 1.2 case*/
13241 unsigned char ivOut[MAX_IV_LENGTH24];
13242 unsigned char *iv = NULL((void*)0);
13243 unsigned char *nonce = NULL((void*)0);
13244
13245 ivLen = cipher_def->iv_size;
13246
13247 rv = ssl3_BuildRecordPseudoHeader(
13248 spec->epoch, cText->seqNum,
13249 rType, isTLS, rVersion, IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram), decryptedLen, &header, spec->version);
13250 PORT_Assert(rv == SECSuccess)((rv == SECSuccess)?((void)0):PR_Assert("rv == SECSuccess","ssl3con.c"
,13250))
;
13251
13252 /* build the iv */
13253 if (explicitNonceLen == 0) {
13254 nonceLen = sizeof(cText->seqNum);
13255 iv = spec->keyMaterial.iv;
13256 nonce = SSL_BUFFER_BASE(&header)((&header)->buf);
13257 } else {
13258 PORT_Memcpymemcpy(ivOut, spec->keyMaterial.iv, ivLen);
13259 PORT_Memsetmemset(ivOut + ivLen, 0, explicitNonceLen);
13260 iv = ivOut;
13261 nonce = cText->buf->buf;
13262 nonceLen = explicitNonceLen;
13263 }
13264 rv = tls13_AEAD(spec->cipherContext, PR_TRUE1,
13265 CKG_NO_GENERATE0x00000000UL, 0, /* iv generator params
13266 * (not used in decrypt)*/
13267 iv, /* iv in */
13268 NULL((void*)0), /* iv out */
13269 ivLen + explicitNonceLen, /* full iv length */
13270 nonce, nonceLen, /* nonce in */
13271 SSL_BUFFER_BASE(&header)((&header)->buf), /* aad */
13272 SSL_BUFFER_LEN(&header)((&header)->len), /* aadlen */
13273 plaintext->buf, /* output */
13274 &plaintext->len, /* out len */
13275 plaintext->space, /* max out */
13276 tagLen,
13277 cText->buf->buf + explicitNonceLen, /* input */
13278 cText->buf->len - explicitNonceLen); /* input len */
13279 if (rv != SECSuccess) {
13280 good = 0;
13281 }
13282 } else {
13283 if (cipher_def->type == type_block &&
13284 ((cText->buf->len - ivLen) % cipher_def->block_size) != 0) {
13285 goto decrypt_loser;
13286 }
13287
13288 /* decrypt from cText buf to plaintext. */
13289 rv = spec->cipher(
13290 spec->cipherContext, plaintext->buf, &plaintext->len,
13291 plaintext->space, cText->buf->buf + ivLen, cText->buf->len - ivLen);
13292 if (rv != SECSuccess) {
13293 goto decrypt_loser;
13294 }
13295
13296 PRINT_BUF(80, (ss, "cleartext:", plaintext->buf, plaintext->len))if (ssl_trace >= (80)) ssl_PrintBuf (ss, "cleartext:", plaintext
->buf, plaintext->len)
;
13297
13298 originalLen = plaintext->len;
13299
13300 /* If it's a block cipher, check and strip the padding. */
13301 if (cipher_def->type == type_block) {
13302 const unsigned int blockSize = cipher_def->block_size;
13303 const unsigned int macSize = spec->macDef->mac_size;
13304
13305 if (!isTLS) {
13306 good &= SECStatusToMask(ssl_RemoveSSLv3CBCPadding(
13307 plaintext, blockSize, macSize));
13308 } else {
13309 good &= SECStatusToMask(ssl_RemoveTLSCBCPadding(
13310 plaintext, macSize));
13311 }
13312 }
13313
13314 /* compute the MAC */
13315 rv = ssl3_BuildRecordPseudoHeader(
13316 spec->epoch, cText->seqNum,
13317 rType, isTLS, rVersion, IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram),
13318 plaintext->len - spec->macDef->mac_size, &header, spec->version);
13319 PORT_Assert(rv == SECSuccess)((rv == SECSuccess)?((void)0):PR_Assert("rv == SECSuccess","ssl3con.c"
,13319))
;
13320 if (cipher_def->type == type_block) {
13321 rv = ssl3_ComputeRecordMACConstantTime(
13322 spec, SSL_BUFFER_BASE(&header)((&header)->buf), SSL_BUFFER_LEN(&header)((&header)->len),
13323 plaintext->buf, plaintext->len, originalLen,
13324 hash, &hashBytes);
13325
13326 ssl_CBCExtractMAC(plaintext, originalLen, givenHashBuf,
13327 spec->macDef->mac_size);
13328 givenHash = givenHashBuf;
13329
13330 /* plaintext->len will always have enough space to remove the MAC
13331 * because in ssl_Remove{SSLv3|TLS}CBCPadding we only adjust
13332 * plaintext->len if the result has enough space for the MAC and we
13333 * tested the unadjusted size against minLength, above. */
13334 plaintext->len -= spec->macDef->mac_size;
13335 } else {
13336 /* This is safe because we checked the minLength above. */
13337 plaintext->len -= spec->macDef->mac_size;
13338
13339 rv = ssl3_ComputeRecordMAC(
13340 spec, SSL_BUFFER_BASE(&header)((&header)->buf), SSL_BUFFER_LEN(&header)((&header)->len),
13341 plaintext->buf, plaintext->len, hash, &hashBytes);
13342
13343 /* We can read the MAC directly from the record because its location
13344 * is public when a stream cipher is used. */
13345 givenHash = plaintext->buf + plaintext->len;
13346 }
13347
13348 good &= SECStatusToMask(rv);
13349
13350 if (hashBytes != (unsigned)spec->macDef->mac_size ||
13351 NSS_SecureMemcmp(givenHash, hash, spec->macDef->mac_size) != 0) {
13352 /* We're allowed to leak whether or not the MAC check was correct */
13353 good = 0;
13354 }
13355 }
13356
13357 if (good == 0) {
13358 decrypt_loser:
13359 /* always log mac error, in case attacker can read server logs. */
13360 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_BAD_MAC_READ);
13361 *alert = bad_record_mac;
13362 return SECFailure;
13363 }
13364 return SECSuccess;
13365}
13366
13367SECStatus
13368ssl3_HandleNonApplicationData(sslSocket *ss, SSLContentType rType,
13369 DTLSEpoch epoch, sslSequenceNumber seqNum,
13370 sslBuffer *databuf)
13371{
13372 SECStatus rv;
13373
13374 /* check for Token Presence */
13375 if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
13376 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
13377 return SECFailure;
13378 }
13379
13380 ssl_GetSSL3HandshakeLock(ss){ if (!ss->opt.noLocks) { ((!((PR_GetMonitorEntryCount(((ss
)->xmitBufLock)) > 0)))?((void)0):PR_Assert("!ssl_HaveXmitBufLock(ss)"
,"ssl3con.c",13380)); PR_EnterMonitor(((ss)->ssl3HandshakeLock
)); } }
;
13381
13382 /* All the functions called in this switch MUST set error code if
13383 ** they return SECFailure.
13384 */
13385 switch (rType) {
13386 case ssl_ct_change_cipher_spec:
13387 rv = ssl3_HandleChangeCipherSpecs(ss, databuf);
13388 break;
13389 case ssl_ct_alert:
13390 rv = ssl3_HandleAlert(ss, databuf);
13391 break;
13392 case ssl_ct_handshake:
13393 if (!IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
13394 rv = ssl3_HandleHandshake(ss, databuf);
13395 } else {
13396 rv = dtls_HandleHandshake(ss, epoch, seqNum, databuf);
13397 }
13398 break;
13399 case ssl_ct_ack:
13400 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram) && tls13_MaybeTls13(ss)) {
13401 rv = dtls13_HandleAck(ss, databuf);
13402 break;
13403 }
13404 /* Fall through. */
13405 default:
13406 /* If a TLS implementation receives an unexpected record type,
13407 * it MUST terminate the connection with an "unexpected_message"
13408 * alert [RFC8446, Section 5].
13409 *
13410 * For TLS 1.3 the outer content type is checked before in
13411 * tls13con.c/tls13_UnprotectRecord(),
13412 * For DTLS 1.3 the outer content type is checked before in
13413 * ssl3gthr.c/dtls_GatherData.
13414 * The inner content types will be checked here.
13415 *
13416 * In DTLS generally invalid records SHOULD be silently discarded,
13417 * no alert is sent [RFC6347, Section 4.1.2.7].
13418 */
13419 if (!IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
13420 SSL3_SendAlert(ss, alert_fatal, unexpected_message);
13421 }
13422 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE);
13423 SSL_DBG(("%d: SSL3[%d]: bogus content type=%d",if (ssl_debug) ssl_Trace ("%d: SSL3[%d]: bogus content type=%d"
, getpid(), ss->fd, rType)
13424 SSL_GETPID(), ss->fd, rType))if (ssl_debug) ssl_Trace ("%d: SSL3[%d]: bogus content type=%d"
, getpid(), ss->fd, rType)
;
13425 rv = SECFailure;
13426 break;
13427 }
13428
13429 ssl_ReleaseSSL3HandshakeLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->ssl3HandshakeLock
)); }
;
13430 return rv;
13431}
13432
13433/* Find the cipher spec to use for a given record. For TLS, this
13434 * is the current cipherspec. For DTLS, we look up by epoch.
13435 * In DTLS < 1.3 this just means the current epoch or nothing,
13436 * but in DTLS >= 1.3, we keep multiple reading cipherspecs.
13437 * Returns NULL if no appropriate cipher spec is found.
13438 */
13439static ssl3CipherSpec *
13440ssl3_GetCipherSpec(sslSocket *ss, SSL3Ciphertext *cText)
13441{
13442 ssl3CipherSpec *crSpec = ss->ssl3.crSpec;
13443 ssl3CipherSpec *newSpec = NULL((void*)0);
13444 DTLSEpoch epoch;
13445
13446 if (!IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
13447 return crSpec;
13448 }
13449 epoch = dtls_ReadEpoch(crSpec->version, crSpec->epoch, cText->hdr);
13450 if (crSpec->epoch == epoch) {
13451 return crSpec;
13452 }
13453 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_30x0304) {
13454 /* Try to find the cipher spec. */
13455 newSpec = ssl_FindCipherSpecByEpoch(ss, ssl_secret_read,
13456 epoch);
13457 if (newSpec != NULL((void*)0)) {
13458 return newSpec;
13459 }
13460 }
13461 SSL_TRC(10, ("%d: DTLS[%d]: %s couldn't find cipherspec from epoch %d",if (ssl_trace >= (10)) ssl_Trace ("%d: DTLS[%d]: %s couldn't find cipherspec from epoch %d"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
), epoch)
13462 SSL_GETPID(), ss->fd, SSL_ROLE(ss), epoch))if (ssl_trace >= (10)) ssl_Trace ("%d: DTLS[%d]: %s couldn't find cipherspec from epoch %d"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
), epoch)
;
13463 return NULL((void*)0);
13464}
13465
13466/* if cText is non-null, then decipher and check the MAC of the
13467 * SSL record from cText->buf (typically gs->inbuf)
13468 * into databuf (typically gs->buf), and any previous contents of databuf
13469 * is lost. Then handle databuf according to its SSL record type,
13470 * unless it's an application record.
13471 *
13472 * If cText is NULL, then the ciphertext has previously been deciphered and
13473 * checked, and is already sitting in databuf. It is processed as an SSL
13474 * Handshake message.
13475 *
13476 * DOES NOT process the decrypted application data.
13477 * On return, databuf contains the decrypted record.
13478 *
13479 * Called from ssl3_GatherCompleteHandshake
13480 * ssl3_RestartHandshakeAfterCertReq
13481 *
13482 * Caller must hold the RecvBufLock.
13483 *
13484 * This function aquires and releases the SSL3Handshake Lock, holding the
13485 * lock around any calls to functions that handle records other than
13486 * Application Data records.
13487 */
13488SECStatus
13489ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText)
13490{
13491 SECStatus rv = SECFailure;
13492 PRBool isTLS, isTLS13;
13493 DTLSEpoch epoch;
13494 ssl3CipherSpec *spec = NULL((void*)0);
13495 PRUint16 recordSizeLimit, cTextSizeLimit;
13496 PRBool outOfOrderSpec = PR_FALSE0;
13497 SSLContentType rType;
13498 sslBuffer *plaintext = &ss->gs.buf;
13499 SSL3AlertDescription alert = internal_error;
13500 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->recvBufLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveRecvBufLock(ss)"
,"ssl3con.c",13500))
;
13501
13502 /* check for Token Presence */
13503 if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
13504 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
13505 return SECFailure;
13506 }
13507
13508 /* Clear out the buffer in case this exits early. Any data then won't be
13509 * processed twice. */
13510 plaintext->len = 0;
13511
13512 /* We're waiting for another ClientHello, which will appear unencrypted.
13513 * Use the content type to tell whether this should be discarded. */
13514 if (ss->ssl3.hs.zeroRttIgnore == ssl_0rtt_ignore_hrr &&
13515 cText->hdr[0] == ssl_ct_application_data) {
13516 PORT_Assert(ss->ssl3.hs.ws == wait_client_hello)((ss->ssl3.hs.ws == wait_client_hello)?((void)0):PR_Assert
("ss->ssl3.hs.ws == wait_client_hello","ssl3con.c",13516))
;
13517 return SECSuccess;
13518 }
13519
13520 ssl_GetSpecReadLock(ss){ if (!ss->opt.noLocks) NSSRWLock_LockRead_Util((ss)->specLock
); }
; /******************************************/
13521 spec = ssl3_GetCipherSpec(ss, cText);
13522 if (!spec) {
13523 PORT_Assert(IS_DTLS(ss))(((ss->protocolVariant == ssl_variant_datagram))?((void)0)
:PR_Assert("IS_DTLS(ss)","ssl3con.c",13523))
;
13524 ssl_ReleaseSpecReadLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockRead_Util((ss)->
specLock); }
; /*****************************/
13525 return SECSuccess;
13526 }
13527 if (spec != ss->ssl3.crSpec) {
13528 PORT_Assert(IS_DTLS(ss))(((ss->protocolVariant == ssl_variant_datagram))?((void)0)
:PR_Assert("IS_DTLS(ss)","ssl3con.c",13528))
;
13529 SSL_TRC(3, ("%d: DTLS[%d]: Handling out-of-epoch record from epoch=%d",if (ssl_trace >= (3)) ssl_Trace ("%d: DTLS[%d]: Handling out-of-epoch record from epoch=%d"
, getpid(), ss->fd, spec->epoch)
13530 SSL_GETPID(), ss->fd, spec->epoch))if (ssl_trace >= (3)) ssl_Trace ("%d: DTLS[%d]: Handling out-of-epoch record from epoch=%d"
, getpid(), ss->fd, spec->epoch)
;
13531 outOfOrderSpec = PR_TRUE1;
13532 }
13533 isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_00x0300);
13534 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
13535 if (dtls13_MaskSequenceNumber(ss, spec, cText->hdr,
13536 SSL_BUFFER_BASE(cText->buf)((cText->buf)->buf), SSL_BUFFER_LEN(cText->buf)((cText->buf)->len)) != SECSuccess) {
13537 ssl_ReleaseSpecReadLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockRead_Util((ss)->
specLock); }
; /*****************************/
13538 /* code already set. */
13539 return SECFailure;
13540 }
13541 if (!dtls_IsRelevant(ss, spec, cText, &cText->seqNum)) {
13542 ssl_ReleaseSpecReadLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockRead_Util((ss)->
specLock); }
; /*****************************/
13543 return SECSuccess;
13544 }
13545 } else {
13546 cText->seqNum = spec->nextSeqNum;
13547 }
13548 if (cText->seqNum >= spec->cipherDef->max_records) {
13549 ssl_ReleaseSpecReadLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockRead_Util((ss)->
specLock); }
; /*****************************/
13550 SSL_TRC(3, ("%d: SSL[%d]: read sequence number at limit 0x%0llx",if (ssl_trace >= (3)) ssl_Trace ("%d: SSL[%d]: read sequence number at limit 0x%0llx"
, getpid(), ss->fd, cText->seqNum)
13551 SSL_GETPID(), ss->fd, cText->seqNum))if (ssl_trace >= (3)) ssl_Trace ("%d: SSL[%d]: read sequence number at limit 0x%0llx"
, getpid(), ss->fd, cText->seqNum)
;
13552 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_TOO_MANY_RECORDS);
13553 return SECFailure;
13554 }
13555
13556 isTLS13 = (PRBool)(ss->version >= SSL_LIBRARY_VERSION_TLS_1_30x0304);
13557 recordSizeLimit = spec->recordSizeLimit;
13558 cTextSizeLimit = recordSizeLimit;
13559 cTextSizeLimit += (isTLS13) ? TLS_1_3_MAX_EXPANSION(255 + 1) : TLS_1_2_MAX_EXPANSION2048;
13560
13561 /* Check if the specified recordSizeLimit and the RFC8446 specified max
13562 * expansion are respected. recordSizeLimit is probably at the default for
13563 * the first (hello) handshake message and then set to a smaller size by
13564 * the Record Size Limit Extension.
13565 * Stricter expansion size checks dependent on implemented cipher suites
13566 * are performed in ssl3con.c/ssl3_UnprotectRecord() OR
13567 * tls13con.c/tls13_UnprotextRecord().
13568 * After Decryption the plaintext size is checked (l. 13424). This also
13569 * applies to unencrypted records. */
13570 if (cText->buf->len > cTextSizeLimit) {
13571 ssl_ReleaseSpecReadLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockRead_Util((ss)->
specLock); }
; /*****************************/
13572 /* Drop DTLS Record Errors silently [RFC6347, Section 4.1.2.7] */
13573 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
13574 return SECSuccess;
13575 }
13576 SSL3_SendAlert(ss, alert_fatal, record_overflow);
13577 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_RECORD_TOO_LONG);
13578 return SECFailure;
13579 }
13580
13581#ifdef DEBUG1
13582 /* In debug builds the gather buffers are freed after the handling of each
13583 * record for advanced ASAN coverage. Allocate the buffer again to the
13584 * maximum possibly needed size as on gather initialization in
13585 * ssl3gthr.c/ssl3_InitGather(). */
13586 PR_ASSERT(sslBuffer_Grow(plaintext, TLS_1_2_MAX_CTEXT_LENGTH) == SECSuccess)((sslBuffer_Grow(plaintext, ((16384) + (2048))) == SECSuccess
)?((void)0):PR_Assert("sslBuffer_Grow(plaintext, TLS_1_2_MAX_CTEXT_LENGTH) == SECSuccess"
,"ssl3con.c",13586))
;
13587#endif
13588 /* This replaces a dynamic plaintext buffer size check, since the buffer is
13589 * allocated to the maximum size in ssl3gthr.c/ssl3_InitGather(). The buffer
13590 * was always grown to the maximum size at first record gathering before. */
13591 PR_ASSERT(plaintext->space >= cTextSizeLimit)((plaintext->space >= cTextSizeLimit)?((void)0):PR_Assert
("plaintext->space >= cTextSizeLimit","ssl3con.c",13591
))
;
13592
13593 /* Most record types aside from protected TLS 1.3 records carry the content
13594 * type in the first octet. TLS 1.3 will override this value later. */
13595 rType = cText->hdr[0];
13596 /* Encrypted application data records could arrive before the handshake
13597 * completes in DTLS 1.3. These can look like valid TLS 1.2 application_data
13598 * records in epoch 0, which is never valid. Pretend they didn't decrypt. */
13599 if (spec->epoch == 0 && ((IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram) &&
13600 dtls_IsDtls13Ciphertext(0, rType)) ||
13601 rType == ssl_ct_application_data)) {
13602 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA);
13603 alert = unexpected_message;
13604 rv = SECFailure;
13605 } else {
13606#ifdef UNSAFE_FUZZER_MODE
13607 rv = Null_Cipher(NULL((void*)0), plaintext->buf, &plaintext->len,
13608 plaintext->space, cText->buf->buf, cText->buf->len);
13609#else
13610 /* IMPORTANT:
13611 * Unprotect functions MUST NOT send alerts
13612 * because we still hold the spec read lock. Instead, if they
13613 * return SECFailure, they set *alert to the alert to be sent.
13614 * Additionaly, this is used to silently drop DTLS encryption/record
13615 * errors/alerts using the error handling below as suggested in the
13616 * DTLS specification [RFC6347, Section 4.1.2.7]. */
13617 if (spec->cipherDef->cipher == cipher_null && cText->buf->len == 0) {
13618 /* Handle a zero-length unprotected record
13619 * In this case, we treat it as a no-op and let later functions decide
13620 * whether to ignore or alert accordingly. */
13621 PR_ASSERT(plaintext->len == 0)((plaintext->len == 0)?((void)0):PR_Assert("plaintext->len == 0"
,"ssl3con.c",13621))
;
13622 rv = SECSuccess;
13623 } else if (spec->version < SSL_LIBRARY_VERSION_TLS_1_30x0304 || spec->epoch == 0) {
13624 rv = ssl3_UnprotectRecord(ss, spec, cText, plaintext, &alert);
13625 } else {
13626 rv = tls13_UnprotectRecord(ss, spec, cText, plaintext, &rType,
13627 &alert);
13628 }
13629#endif
13630 }
13631
13632 /* Error/Alert handling for ssl3/tls13_UnprotectRecord */
13633 if (rv != SECSuccess) {
13634 ssl_ReleaseSpecReadLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockRead_Util((ss)->
specLock); }
; /***************************/
13635
13636 SSL_DBG(("%d: SSL3[%d]: decryption failed", SSL_GETPID(), ss->fd))if (ssl_debug) ssl_Trace ("%d: SSL3[%d]: decryption failed", getpid
(), ss->fd)
;
13637
13638 /* Ensure that we don't process this data again. */
13639 plaintext->len = 0;
13640
13641 /* Ignore a CCS if compatibility mode is negotiated. Note that this
13642 * will fail if the server fails to negotiate compatibility mode in a
13643 * 0-RTT session that is resumed from a session that did negotiate it.
13644 * We don't care about that corner case right now. */
13645 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_30x0304 &&
13646 cText->hdr[0] == ssl_ct_change_cipher_spec &&
13647 ss->ssl3.hs.ws != idle_handshake &&
13648 cText->buf->len == 1 &&
13649 cText->buf->buf[0] == change_cipher_spec_choice) {
13650 if (!ss->ssl3.hs.rejectCcs) {
13651 /* Allow only the first CCS. */
13652 ss->ssl3.hs.rejectCcs = PR_TRUE1;
13653 return SECSuccess;
13654 } else {
13655 alert = unexpected_message;
13656 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
13657 }
13658 }
13659
13660 /* All errors/alerts that might occur during unprotection are related
13661 * to invalid records (e.g. invalid formatting, length, MAC, ...).
13662 * Following the DTLS specification such errors/alerts SHOULD be
13663 * dropped silently [RFC9147, Section 4.5.2].
13664 * This is done below. */
13665
13666 if ((IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram) && !dtls13_AeadLimitReached(spec)) ||
13667 (!IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram) && ss->sec.isServer &&
13668 ss->ssl3.hs.zeroRttIgnore == ssl_0rtt_ignore_trial)) {
13669 /* Silently drop the packet unless we set ss->ssl3.fatalAlertSent.
13670 * (Manually or by using functions like
13671 * SSL3_SendAlert(.., alert_fatal,..))
13672 * This is not currently used in the unprotection functions since
13673 * all TLS and DTLS errors are propagated to this handler. */
13674 if (ss->ssl3.fatalAlertSent) {
13675 return SECFailure;
13676 }
13677 return SECSuccess;
13678 }
13679
13680 int errCode = PORT_GetErrorPORT_GetError_Util();
13681 SSL3_SendAlert(ss, alert_fatal, alert);
13682 /* Reset the error code in case SSL3_SendAlert called
13683 * PORT_SetError(). */
13684 PORT_SetErrorPORT_SetError_Util(errCode);
13685 return SECFailure;
13686 }
13687
13688 /* SECSuccess */
13689 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
13690 dtls_RecordSetRecvd(&spec->recvdRecords, cText->seqNum);
13691 spec->nextSeqNum = PR_MAX(spec->nextSeqNum, cText->seqNum + 1)((spec->nextSeqNum)>(cText->seqNum + 1)?(spec->nextSeqNum
):(cText->seqNum + 1))
;
13692 } else {
13693 ++spec->nextSeqNum;
13694 }
13695 epoch = spec->epoch;
13696
13697 ssl_ReleaseSpecReadLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockRead_Util((ss)->
specLock); }
; /*****************************************/
13698
13699 /*
13700 * The decrypted data is now in plaintext.
13701 */
13702
13703 /* IMPORTANT: We are in DTLS 1.3 mode and we have processed something
13704 * from the wrong epoch. Divert to a divert processing function to make
13705 * sure we don't accidentally use the data unsafely. */
13706
13707 /* We temporary allowed reading the records from the previous epoch n-1
13708 until the moment we get a message from the new epoch n. */
13709
13710 if (outOfOrderSpec) {
13711 PORT_Assert(IS_DTLS(ss) && ss->version >= SSL_LIBRARY_VERSION_TLS_1_3)(((ss->protocolVariant == ssl_variant_datagram) &&
ss->version >= 0x0304)?((void)0):PR_Assert("IS_DTLS(ss) && ss->version >= SSL_LIBRARY_VERSION_TLS_1_3"
,"ssl3con.c",13711))
;
13712 ssl_GetSSL3HandshakeLock(ss){ if (!ss->opt.noLocks) { ((!((PR_GetMonitorEntryCount(((ss
)->xmitBufLock)) > 0)))?((void)0):PR_Assert("!ssl_HaveXmitBufLock(ss)"
,"ssl3con.c",13712)); PR_EnterMonitor(((ss)->ssl3HandshakeLock
)); } }
;
13713 if (ss->ssl3.hs.allowPreviousEpoch && spec->epoch == ss->ssl3.crSpec->epoch - 1) {
13714 SSL_TRC(30, ("%d: DTLS13[%d]: Out of order message %d is accepted",if (ssl_trace >= (30)) ssl_Trace ("%d: DTLS13[%d]: Out of order message %d is accepted"
, getpid(), ss->fd, spec->epoch)
13715 SSL_GETPID(), ss->fd, spec->epoch))if (ssl_trace >= (30)) ssl_Trace ("%d: DTLS13[%d]: Out of order message %d is accepted"
, getpid(), ss->fd, spec->epoch)
;
13716 ssl_ReleaseSSL3HandshakeLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->ssl3HandshakeLock
)); }
;
13717 } else {
13718 ssl_ReleaseSSL3HandshakeLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->ssl3HandshakeLock
)); }
;
13719 return dtls13_HandleOutOfEpochRecord(ss, spec, rType, plaintext);
13720 }
13721 } else {
13722 ssl_GetSSL3HandshakeLock(ss){ if (!ss->opt.noLocks) { ((!((PR_GetMonitorEntryCount(((ss
)->xmitBufLock)) > 0)))?((void)0):PR_Assert("!ssl_HaveXmitBufLock(ss)"
,"ssl3con.c",13722)); PR_EnterMonitor(((ss)->ssl3HandshakeLock
)); } }
;
13723 /* Forbid (application) messages from the previous epoch.
13724 From now, messages that arrive out of order will be discarded. */
13725 ss->ssl3.hs.allowPreviousEpoch = PR_FALSE0;
13726 ssl_ReleaseSSL3HandshakeLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->ssl3HandshakeLock
)); }
;
13727 }
13728
13729 /* Check the length of the plaintext. */
13730 if (isTLS && plaintext->len > recordSizeLimit) {
13731 plaintext->len = 0;
13732 /* Drop DTLS Record Errors silently [RFC6347, Section 4.1.2.7] */
13733 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
13734 return SECSuccess;
13735 }
13736 SSL3_SendAlert(ss, alert_fatal, record_overflow);
13737 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_RECORD_TOO_LONG);
13738 return SECFailure;
13739 }
13740
13741 /* Application data records are processed by the caller of this
13742 ** function, not by this function.
13743 */
13744 if (rType == ssl_ct_application_data) {
13745 if (ss->firstHsDone)
13746 return SECSuccess;
13747 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_30x0304 &&
13748 ss->sec.isServer &&
13749 ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) {
13750 return tls13_HandleEarlyApplicationData(ss, plaintext);
13751 }
13752 plaintext->len = 0;
13753 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
13754 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA);
13755 return SECFailure;
13756 }
13757
13758 rv = ssl3_HandleNonApplicationData(ss, rType, epoch, cText->seqNum,
13759 plaintext);
13760
13761#ifdef DEBUG1
13762 /* In Debug builds free and zero gather plaintext buffer after its content
13763 * has been used/copied for advanced ASAN coverage/utilization.
13764 * This frees buffer for non application data records, for application data
13765 * records it is freed in sslsecur.c/DoRecv(). */
13766 sslBuffer_Clear(&ss->gs.buf);
13767#endif
13768
13769 return rv;
13770}
13771
13772/*
13773 * Initialization functions
13774 */
13775
13776void
13777ssl_InitSecState(sslSecurityInfo *sec)
13778{
13779 sec->authType = ssl_auth_null;
13780 sec->authKeyBits = 0;
13781 sec->signatureScheme = ssl_sig_none;
13782 sec->keaType = ssl_kea_null;
13783 sec->keaKeyBits = 0;
13784 sec->keaGroup = NULL((void*)0);
13785}
13786
13787SECStatus
13788ssl3_InitState(sslSocket *ss)
13789{
13790 SECStatus rv;
13791
13792 ss->ssl3.policy = SSL_ALLOWED1;
13793
13794 ssl_InitSecState(&ss->sec);
13795
13796 ssl_GetSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_LockWrite_Util((ss)->
specLock); }
;
13797 PR_INIT_CLIST(&ss->ssl3.hs.cipherSpecs)do { (&ss->ssl3.hs.cipherSpecs)->next = (&ss->
ssl3.hs.cipherSpecs); (&ss->ssl3.hs.cipherSpecs)->prev
= (&ss->ssl3.hs.cipherSpecs); } while (0)
;
13798 rv = ssl_SetupNullCipherSpec(ss, ssl_secret_read);
13799 rv |= ssl_SetupNullCipherSpec(ss, ssl_secret_write);
13800 ss->ssl3.pwSpec = ss->ssl3.prSpec = NULL((void*)0);
13801 ssl_ReleaseSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockWrite_Util((ss)->
specLock); }
;
13802 if (rv != SECSuccess) {
13803 /* Rely on ssl_CreateNullCipherSpec() to set error code. */
13804 return SECFailure;
13805 }
13806
13807 ss->ssl3.hs.sendingSCSV = PR_FALSE0;
13808 ss->ssl3.hs.preliminaryInfo = 0;
13809 ss->ssl3.hs.ws = (ss->sec.isServer) ? wait_client_hello : idle_handshake;
13810
13811 ssl3_ResetExtensionData(&ss->xtnData, ss);
13812 PR_INIT_CLIST(&ss->ssl3.hs.remoteExtensions)do { (&ss->ssl3.hs.remoteExtensions)->next = (&
ss->ssl3.hs.remoteExtensions); (&ss->ssl3.hs.remoteExtensions
)->prev = (&ss->ssl3.hs.remoteExtensions); } while (
0)
;
13813 PR_INIT_CLIST(&ss->ssl3.hs.echOuterExtensions)do { (&ss->ssl3.hs.echOuterExtensions)->next = (&
ss->ssl3.hs.echOuterExtensions); (&ss->ssl3.hs.echOuterExtensions
)->prev = (&ss->ssl3.hs.echOuterExtensions); } while
(0)
;
13814 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
13815 ss->ssl3.hs.sendMessageSeq = 0;
13816 ss->ssl3.hs.recvMessageSeq = 0;
13817 ss->ssl3.hs.rtTimer->timeout = DTLS_RETRANSMIT_INITIAL_MS50;
13818 ss->ssl3.hs.rtRetries = 0;
13819 ss->ssl3.hs.recvdHighWater = -1;
13820 PR_INIT_CLIST(&ss->ssl3.hs.lastMessageFlight)do { (&ss->ssl3.hs.lastMessageFlight)->next = (&
ss->ssl3.hs.lastMessageFlight); (&ss->ssl3.hs.lastMessageFlight
)->prev = (&ss->ssl3.hs.lastMessageFlight); } while
(0)
;
13821 dtls_SetMTU(ss, 0); /* Set the MTU to the highest plateau */
13822 }
13823
13824 ss->ssl3.hs.currentSecret = NULL((void*)0);
13825 ss->ssl3.hs.resumptionMasterSecret = NULL((void*)0);
13826 ss->ssl3.hs.dheSecret = NULL((void*)0);
13827 ss->ssl3.hs.clientEarlyTrafficSecret = NULL((void*)0);
13828 ss->ssl3.hs.clientHsTrafficSecret = NULL((void*)0);
13829 ss->ssl3.hs.serverHsTrafficSecret = NULL((void*)0);
13830 ss->ssl3.hs.clientTrafficSecret = NULL((void*)0);
13831 ss->ssl3.hs.serverTrafficSecret = NULL((void*)0);
13832 ss->ssl3.hs.echHpkeCtx = NULL((void*)0);
13833 ss->ssl3.hs.greaseEchSize = 100;
13834 ss->ssl3.hs.echAccepted = PR_FALSE0;
13835 ss->ssl3.hs.echDecided = PR_FALSE0;
13836
13837 ss->ssl3.hs.clientAuthSignatureSchemes = NULL((void*)0);
13838 ss->ssl3.hs.clientAuthSignatureSchemesLen = 0;
13839
13840 PORT_Assert(!ss->ssl3.hs.messages.buf && !ss->ssl3.hs.messages.space)((!ss->ssl3.hs.messages.buf && !ss->ssl3.hs.messages
.space)?((void)0):PR_Assert("!ss->ssl3.hs.messages.buf && !ss->ssl3.hs.messages.space"
,"ssl3con.c",13840))
;
13841 ss->ssl3.hs.messages.buf = NULL((void*)0);
13842 ss->ssl3.hs.messages.space = 0;
13843
13844 ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE0;
13845 PORT_Memsetmemset(&ss->ssl3.hs.newSessionTicket, 0,
13846 sizeof(ss->ssl3.hs.newSessionTicket));
13847
13848 ss->ssl3.hs.zeroRttState = ssl_0rtt_none;
13849 return SECSuccess;
13850}
13851
13852/* record the export policy for this cipher suite */
13853SECStatus
13854ssl3_SetPolicy(ssl3CipherSuite which, int policy)
13855{
13856 ssl3CipherSuiteCfg *suite;
13857
13858 suite = ssl_LookupCipherSuiteCfgMutable(which, cipherSuites);
13859 if (suite == NULL((void*)0)) {
13860 return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
13861 }
13862 suite->policy = policy;
13863
13864 return SECSuccess;
13865}
13866
13867SECStatus
13868ssl3_GetPolicy(ssl3CipherSuite which, PRInt32 *oPolicy)
13869{
13870 const ssl3CipherSuiteCfg *suite;
13871 PRInt32 policy;
13872 SECStatus rv;
13873
13874 suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
13875 if (suite) {
13876 policy = suite->policy;
13877 rv = SECSuccess;
13878 } else {
13879 policy = SSL_NOT_ALLOWED0;
13880 rv = SECFailure; /* err code was set by Lookup. */
13881 }
13882 *oPolicy = policy;
13883 return rv;
13884}
13885
13886/* record the user preference for this suite */
13887SECStatus
13888ssl3_CipherPrefSetDefault(ssl3CipherSuite which, PRBool enabled)
13889{
13890 ssl3CipherSuiteCfg *suite;
13891
13892 suite = ssl_LookupCipherSuiteCfgMutable(which, cipherSuites);
13893 if (suite == NULL((void*)0)) {
13894 return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
13895 }
13896 suite->enabled = enabled;
13897 return SECSuccess;
13898}
13899
13900/* return the user preference for this suite */
13901SECStatus
13902ssl3_CipherPrefGetDefault(ssl3CipherSuite which, PRBool *enabled)
13903{
13904 const ssl3CipherSuiteCfg *suite;
13905 PRBool pref;
13906 SECStatus rv;
13907
13908 suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
13909 if (suite) {
13910 pref = suite->enabled;
13911 rv = SECSuccess;
13912 } else {
13913 pref = SSL_NOT_ALLOWED0;
13914 rv = SECFailure; /* err code was set by Lookup. */
13915 }
13916 *enabled = pref;
13917 return rv;
13918}
13919
13920SECStatus
13921ssl3_CipherPrefSet(sslSocket *ss, ssl3CipherSuite which, PRBool enabled)
13922{
13923 ssl3CipherSuiteCfg *suite;
13924
13925 suite = ssl_LookupCipherSuiteCfgMutable(which, ss->cipherSuites);
13926 if (suite == NULL((void*)0)) {
13927 return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
13928 }
13929 suite->enabled = enabled;
13930 return SECSuccess;
13931}
13932
13933SECStatus
13934ssl3_CipherPrefGet(const sslSocket *ss, ssl3CipherSuite which, PRBool *enabled)
13935{
13936 const ssl3CipherSuiteCfg *suite;
13937 PRBool pref;
13938 SECStatus rv;
13939
13940 suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites);
13941 if (suite) {
13942 pref = suite->enabled;
13943 rv = SECSuccess;
13944 } else {
13945 pref = SSL_NOT_ALLOWED0;
13946 rv = SECFailure; /* err code was set by Lookup. */
13947 }
13948 *enabled = pref;
13949 return rv;
13950}
13951
13952SECStatus
13953SSL_SignatureSchemePrefSet(PRFileDesc *fd, const SSLSignatureScheme *schemes,
13954 unsigned int count)
13955{
13956 sslSocket *ss;
13957 unsigned int i;
13958 unsigned int supported = 0;
13959
13960 ss = ssl_FindSocket(fd);
13961 if (!ss) {
13962 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SignatureSchemePrefSet",if (ssl_debug) ssl_Trace ("%d: SSL[%d]: bad socket in SSL_SignatureSchemePrefSet"
, getpid(), fd)
13963 SSL_GETPID(), fd))if (ssl_debug) ssl_Trace ("%d: SSL[%d]: bad socket in SSL_SignatureSchemePrefSet"
, getpid(), fd)
;
13964 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
13965 return SECFailure;
13966 }
13967
13968 if (!count) {
13969 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
13970 return SECFailure;
13971 }
13972
13973 for (i = 0; i < count; ++i) {
13974 if (ssl_IsSupportedSignatureScheme(schemes[i])) {
13975 ++supported;
13976 }
13977 }
13978 /* We don't check for duplicates, so it's possible to get too many. */
13979 if (supported > MAX_SIGNATURE_SCHEMES18) {
13980 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
13981 return SECFailure;
13982 }
13983
13984 ss->ssl3.signatureSchemeCount = 0;
13985 for (i = 0; i < count; ++i) {
13986 if (!ssl_IsSupportedSignatureScheme(schemes[i])) {
13987 SSL_DBG(("%d: SSL[%d]: invalid signature scheme %d ignored",if (ssl_debug) ssl_Trace ("%d: SSL[%d]: invalid signature scheme %d ignored"
, getpid(), fd, schemes[i])
13988 SSL_GETPID(), fd, schemes[i]))if (ssl_debug) ssl_Trace ("%d: SSL[%d]: invalid signature scheme %d ignored"
, getpid(), fd, schemes[i])
;
13989 continue;
13990 }
13991
13992 ss->ssl3.signatureSchemes[ss->ssl3.signatureSchemeCount++] = schemes[i];
13993 }
13994
13995 if (ss->ssl3.signatureSchemeCount == 0) {
13996 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM);
13997 return SECFailure;
13998 }
13999 return SECSuccess;
14000}
14001
14002SECStatus
14003SSL_SignaturePrefSet(PRFileDesc *fd, const SSLSignatureAndHashAlg *algorithms,
14004 unsigned int count)
14005{
14006 SSLSignatureScheme schemes[MAX_SIGNATURE_SCHEMES18];
14007 unsigned int i;
14008
14009 count = PR_MIN(PR_ARRAY_SIZE(schemes), count)(((sizeof(schemes)/sizeof((schemes)[0])))<(count)?((sizeof
(schemes)/sizeof((schemes)[0]))):(count))
;
14010 for (i = 0; i < count; ++i) {
14011 schemes[i] = (algorithms[i].hashAlg << 8) | algorithms[i].sigAlg;
14012 }
14013 return SSL_SignatureSchemePrefSet(fd, schemes, count);
14014}
14015
14016SECStatus
14017SSL_SignatureSchemePrefGet(PRFileDesc *fd, SSLSignatureScheme *schemes,
14018 unsigned int *count, unsigned int maxCount)
14019{
14020 sslSocket *ss;
14021
14022 ss = ssl_FindSocket(fd);
14023 if (!ss) {
14024 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SignatureSchemePrefGet",if (ssl_debug) ssl_Trace ("%d: SSL[%d]: bad socket in SSL_SignatureSchemePrefGet"
, getpid(), fd)
14025 SSL_GETPID(), fd))if (ssl_debug) ssl_Trace ("%d: SSL[%d]: bad socket in SSL_SignatureSchemePrefGet"
, getpid(), fd)
;
14026 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
14027 return SECFailure;
14028 }
14029
14030 if (!schemes || !count ||
14031 maxCount < ss->ssl3.signatureSchemeCount) {
14032 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
14033 return SECFailure;
14034 }
14035
14036 PORT_Memcpymemcpy(schemes, ss->ssl3.signatureSchemes,
14037 ss->ssl3.signatureSchemeCount * sizeof(SSLSignatureScheme));
14038 *count = ss->ssl3.signatureSchemeCount;
14039 return SECSuccess;
14040}
14041
14042SECStatus
14043SSL_SignaturePrefGet(PRFileDesc *fd, SSLSignatureAndHashAlg *algorithms,
14044 unsigned int *count, unsigned int maxCount)
14045{
14046 sslSocket *ss;
14047 unsigned int i;
14048
14049 ss = ssl_FindSocket(fd);
14050 if (!ss) {
14051 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SignaturePrefGet",if (ssl_debug) ssl_Trace ("%d: SSL[%d]: bad socket in SSL_SignaturePrefGet"
, getpid(), fd)
14052 SSL_GETPID(), fd))if (ssl_debug) ssl_Trace ("%d: SSL[%d]: bad socket in SSL_SignaturePrefGet"
, getpid(), fd)
;
14053 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
14054 return SECFailure;
14055 }
14056
14057 if (!algorithms || !count ||
14058 maxCount < ss->ssl3.signatureSchemeCount) {
14059 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
14060 return SECFailure;
14061 }
14062
14063 for (i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
14064 algorithms[i].hashAlg = (ss->ssl3.signatureSchemes[i] >> 8) & 0xff;
14065 algorithms[i].sigAlg = ss->ssl3.signatureSchemes[i] & 0xff;
14066 }
14067 *count = ss->ssl3.signatureSchemeCount;
14068 return SECSuccess;
14069}
14070
14071unsigned int
14072SSL_SignatureMaxCount(void)
14073{
14074 return MAX_SIGNATURE_SCHEMES18;
14075}
14076
14077/* copy global default policy into socket. */
14078void
14079ssl3_InitSocketPolicy(sslSocket *ss)
14080{
14081 PORT_Memcpymemcpy(ss->cipherSuites, cipherSuites, sizeof(cipherSuites));
14082 PORT_Memcpymemcpy(ss->ssl3.signatureSchemes, defaultSignatureSchemes,
14083 sizeof(defaultSignatureSchemes));
14084 ss->ssl3.signatureSchemeCount = PR_ARRAY_SIZE(defaultSignatureSchemes)(sizeof(defaultSignatureSchemes)/sizeof((defaultSignatureSchemes
)[0]))
;
14085}
14086
14087/*
14088** If ssl3 socket has completed the first handshake, and is in idle state,
14089** then start a new handshake.
14090** If flushCache is true, the SID cache will be flushed first, forcing a
14091** "Full" handshake (not a session restart handshake), to be done.
14092**
14093** called from SSL_RedoHandshake(), which already holds the handshake locks.
14094*/
14095SECStatus
14096ssl3_RedoHandshake(sslSocket *ss, PRBool flushCache)
14097{
14098 sslSessionID *sid = ss->sec.ci.sid;
14099 SECStatus rv;
14100
14101 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss))((ss->opt.noLocks || ((PR_GetMonitorEntryCount(((ss)->ssl3HandshakeLock
)) > 0)))?((void)0):PR_Assert("ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)"
,"ssl3con.c",14101))
;
14102
14103 if (!ss->firstHsDone || (ss->ssl3.hs.ws != idle_handshake)) {
14104 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_HANDSHAKE_NOT_COMPLETED);
14105 return SECFailure;
14106 }
14107
14108 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
14109 dtls_RehandshakeCleanup(ss);
14110 }
14111
14112 if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER((PRBool)0) ||
14113 ss->version >= SSL_LIBRARY_VERSION_TLS_1_30x0304) {
14114 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
14115 return SECFailure;
14116 }
14117 if (ss->version > ss->vrange.max || ss->version < ss->vrange.min) {
14118 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_UNSUPPORTED_VERSION);
14119 return SECFailure;
14120 }
14121
14122 if (sid && flushCache) {
14123 ssl_UncacheSessionID(ss); /* remove it from whichever cache it's in. */
14124 ssl_FreeSID(sid); /* dec ref count and free if zero. */
14125 ss->sec.ci.sid = NULL((void*)0);
14126 }
14127
14128 ssl_GetXmitBufLock(ss){ if (!ss->opt.noLocks) PR_EnterMonitor(((ss)->xmitBufLock
)); }
; /**************************************/
14129
14130 /* start off a new handshake. */
14131 if (ss->sec.isServer) {
14132 rv = ssl3_SendHelloRequest(ss);
14133 } else {
14134 rv = ssl3_SendClientHello(ss, client_hello_renegotiation);
14135 }
14136
14137 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
; /**************************************/
14138 return rv;
14139}
14140
14141/* Called from ssl_DestroySocketContents() in sslsock.c */
14142void
14143ssl3_DestroySSL3Info(sslSocket *ss)
14144{
14145
14146 if (ss->ssl3.clientCertificate != NULL((void*)0))
14147 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
14148
14149 if (ss->ssl3.clientPrivateKey != NULL((void*)0))
14150 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
14151
14152 if (ss->ssl3.hs.clientAuthSignatureSchemes != NULL((void*)0)) {
14153 PORT_FreePORT_Free_Util(ss->ssl3.hs.clientAuthSignatureSchemes);
14154 ss->ssl3.hs.clientAuthSignatureSchemes = NULL((void*)0);
14155 ss->ssl3.hs.clientAuthSignatureSchemesLen = 0;
14156 }
14157
14158 if (ss->ssl3.peerCertArena != NULL((void*)0))
14159 ssl3_CleanupPeerCerts(ss);
14160
14161 if (ss->ssl3.clientCertChain != NULL((void*)0)) {
14162 CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
14163 ss->ssl3.clientCertChain = NULL((void*)0);
14164 }
14165 if (ss->ssl3.ca_list) {
14166 CERT_FreeDistNames(ss->ssl3.ca_list);
14167 }
14168
14169 /* clean up handshake */
14170 if (ss->ssl3.hs.md5) {
14171 PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE1);
14172 }
14173 if (ss->ssl3.hs.sha) {
14174 PK11_DestroyContext(ss->ssl3.hs.sha, PR_TRUE1);
14175 }
14176 if (ss->ssl3.hs.shaEchInner) {
14177 PK11_DestroyContext(ss->ssl3.hs.shaEchInner, PR_TRUE1);
14178 }
14179 if (ss->ssl3.hs.shaPostHandshake) {
14180 PK11_DestroyContext(ss->ssl3.hs.shaPostHandshake, PR_TRUE1);
14181 }
14182 if (ss->ssl3.hs.messages.buf) {
14183 sslBuffer_Clear(&ss->ssl3.hs.messages);
14184 }
14185 if (ss->ssl3.hs.echInnerMessages.buf) {
14186 sslBuffer_Clear(&ss->ssl3.hs.echInnerMessages);
14187 }
14188 if (ss->ssl3.hs.dtls13ClientMessageBuffer.buf) {
14189 sslBuffer_Clear(&ss->ssl3.hs.dtls13ClientMessageBuffer);
14190 }
14191
14192 /* free the SSL3Buffer (msg_body) */
14193 PORT_FreePORT_Free_Util(ss->ssl3.hs.msg_body.buf);
14194
14195 SECITEM_FreeItemSECITEM_FreeItem_Util(&ss->ssl3.hs.newSessionTicket.ticket, PR_FALSE0);
14196 SECITEM_FreeItemSECITEM_FreeItem_Util(&ss->ssl3.hs.srvVirtName, PR_FALSE0);
14197 SECITEM_FreeItemSECITEM_FreeItem_Util(&ss->ssl3.hs.fakeSid, PR_FALSE0);
14198
14199 /* Destroy the DTLS data */
14200 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
14201 dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight);
14202 if (ss->ssl3.hs.recvdFragments.buf) {
14203 PORT_FreePORT_Free_Util(ss->ssl3.hs.recvdFragments.buf);
14204 }
14205 }
14206
14207 /* Destroy remote extensions */
14208 ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
14209 ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.echOuterExtensions);
14210 ssl3_DestroyExtensionData(&ss->xtnData);
14211
14212 /* Destroy cipher specs */
14213 ssl_DestroyCipherSpecs(&ss->ssl3.hs.cipherSpecs);
14214
14215 /* Destroy TLS 1.3 keys */
14216 if (ss->ssl3.hs.currentSecret)
14217 PK11_FreeSymKey(ss->ssl3.hs.currentSecret);
14218 if (ss->ssl3.hs.resumptionMasterSecret)
14219 PK11_FreeSymKey(ss->ssl3.hs.resumptionMasterSecret);
14220 if (ss->ssl3.hs.dheSecret)
14221 PK11_FreeSymKey(ss->ssl3.hs.dheSecret);
14222 if (ss->ssl3.hs.clientEarlyTrafficSecret)
14223 PK11_FreeSymKey(ss->ssl3.hs.clientEarlyTrafficSecret);
14224 if (ss->ssl3.hs.clientHsTrafficSecret)
14225 PK11_FreeSymKey(ss->ssl3.hs.clientHsTrafficSecret);
14226 if (ss->ssl3.hs.serverHsTrafficSecret)
14227 PK11_FreeSymKey(ss->ssl3.hs.serverHsTrafficSecret);
14228 if (ss->ssl3.hs.clientTrafficSecret)
14229 PK11_FreeSymKey(ss->ssl3.hs.clientTrafficSecret);
14230 if (ss->ssl3.hs.serverTrafficSecret)
14231 PK11_FreeSymKey(ss->ssl3.hs.serverTrafficSecret);
14232 if (ss->ssl3.hs.earlyExporterSecret)
14233 PK11_FreeSymKey(ss->ssl3.hs.earlyExporterSecret);
14234 if (ss->ssl3.hs.exporterSecret)
14235 PK11_FreeSymKey(ss->ssl3.hs.exporterSecret);
14236
14237 ss->ssl3.hs.zeroRttState = ssl_0rtt_none;
14238 /* Destroy TLS 1.3 buffered early data. */
14239 tls13_DestroyEarlyData(&ss->ssl3.hs.bufferedEarlyData);
14240
14241 /* Destroy TLS 1.3 PSKs. */
14242 tls13_DestroyPskList(&ss->ssl3.hs.psks);
14243
14244 /* TLS 1.3 ECH state. */
14245 PK11_HPKE_DestroyContext(ss->ssl3.hs.echHpkeCtx, PR_TRUE1);
14246 PORT_FreePORT_Free_Util((void *)ss->ssl3.hs.echPublicName); /* CONST */
14247 sslBuffer_Clear(&ss->ssl3.hs.greaseEchBuf);
14248
14249 /* TLS 1.3 GREASE (client) state. */
14250 tls13_ClientGreaseDestroy(ss);
14251
14252 /* TLS ClientHello Extension Permutation state. */
14253 tls_ClientHelloExtensionPermutationDestroy(ss);
14254}
14255
14256/* check if the current cipher spec is FIPS. We only need to
14257 * check the contexts here, if the kea, prf or keys were not FIPS,
14258 * that status would have been rolled up in the create context
14259 * call */
14260static PRBool
14261ssl_cipherSpecIsFips(ssl3CipherSpec *spec)
14262{
14263 if (!spec || !spec->cipherDef) {
14264 return PR_FALSE0;
14265 }
14266
14267 if (spec->cipherDef->type != type_aead) {
14268 if (spec->keyMaterial.macContext == NULL((void*)0)) {
14269 return PR_FALSE0;
14270 }
14271 if (!PK11_ContextGetFIPSStatus(spec->keyMaterial.macContext)) {
14272 return PR_FALSE0;
14273 }
14274 }
14275 if (!spec->cipherContext) {
14276 return PR_FALSE0;
14277 }
14278 return PK11_ContextGetFIPSStatus(spec->cipherContext);
14279}
14280
14281/* return true if the current operation is running in FIPS mode */
14282PRBool
14283ssl_isFIPS(sslSocket *ss)
14284{
14285 if (!ssl_cipherSpecIsFips(ss->ssl3.crSpec)) {
14286 return PR_FALSE0;
14287 }
14288 return ssl_cipherSpecIsFips(ss->ssl3.cwSpec);
14289}
14290
14291/*
14292 * parse the policy value for a single algorithm in a cipher_suite,
14293 * return TRUE if we disallow by the cipher suite by policy
14294 * (we don't have to parse any more algorithm policies on this cipher suite),
14295 * otherwise return FALSE.
14296 * 1. If we don't have the required policy, disable by default, disallow by
14297 * policy and return TRUE (no more processing needed).
14298 * 2. If we have the required policy, and we are disabled, return FALSE,
14299 * (if we are disabled, we only need to parse policy, not default).
14300 * 3. If we have the required policy, and we aren't adjusting the defaults
14301 * return FALSE. (only parsing the policy, not default).
14302 * 4. We have the required policy and we are adjusting the defaults.
14303 * If we are setting default = FALSE, set isDisabled to true so that
14304 * we don't try to re-enable the cipher suite based on a different
14305 * algorithm.
14306 */
14307PRBool
14308ssl_HandlePolicy(int cipher_suite, SECOidTag policyOid,
14309 PRUint32 requiredPolicy, PRBool *isDisabled)
14310{
14311 PRUint32 policy;
14312 SECStatus rv;
14313
14314 /* first fetch the policy for this algorithm */
14315 rv = NSS_GetAlgorithmPolicy(policyOid, &policy);
14316 if (rv != SECSuccess) {
14317 return PR_FALSE0; /* no policy value, continue to the next algorithm */
14318 }
14319 /* first, are we allowed by policy, if not turn off allow and disable */
14320 if (!(policy & requiredPolicy)) {
14321 ssl_CipherPrefSetDefault(cipher_suite, PR_FALSE0);
14322 ssl_CipherPolicySet(cipher_suite, SSL_NOT_ALLOWED0);
14323 return PR_TRUE1;
14324 }
14325 /* If we are already disabled, or the policy isn't setting a default
14326 * we are done processing this algorithm */
14327 if (*isDisabled || (policy & NSS_USE_DEFAULT_NOT_VALID0x80000000)) {
14328 return PR_FALSE0;
14329 }
14330 /* set the default value for the cipher suite. If we disable the cipher
14331 * suite, remember that so we don't process the next default. This has
14332 * the effect of disabling the whole cipher suite if any of the
14333 * algorithms it uses are disabled by default. We still have to
14334 * process the upper level because the cipher suite is still allowed
14335 * by policy, and we may still have to disallow it based on other
14336 * algorithms in the cipher suite. */
14337 if (policy & NSS_USE_DEFAULT_SSL_ENABLE0x40000000) {
14338 ssl_CipherPrefSetDefault(cipher_suite, PR_TRUE1);
14339 } else {
14340 *isDisabled = PR_TRUE1;
14341 ssl_CipherPrefSetDefault(cipher_suite, PR_FALSE0);
14342 }
14343 return PR_FALSE0;
14344}
14345
14346#define MAP_NULL(x)(((x) != 0) ? (x) : SEC_OID_NULL_CIPHER) (((x) != 0) ? (x) : SEC_OID_NULL_CIPHER)
14347
14348SECStatus
14349ssl3_ApplyNSSPolicy(void)
14350{
14351 unsigned i;
14352 SECStatus rv;
14353 PRUint32 policy = 0;
14354
14355 rv = NSS_GetAlgorithmPolicy(SEC_OID_APPLY_SSL_POLICY, &policy);
14356 if (rv != SECSuccess || !(policy & NSS_USE_POLICY_IN_SSL0x00000010)) {
14357 return SECSuccess; /* do nothing */
14358 }
14359
14360 /* disable every ciphersuite */
14361 for (i = 1; i < PR_ARRAY_SIZE(cipher_suite_defs)(sizeof(cipher_suite_defs)/sizeof((cipher_suite_defs)[0])); ++i) {
14362 const ssl3CipherSuiteDef *suite = &cipher_suite_defs[i];
14363 SECOidTag policyOid;
14364 PRBool isDisabled = PR_FALSE0;
14365
14366 /* if we haven't explicitly disabled it below enable by policy */
14367 ssl_CipherPolicySet(suite->cipher_suite, SSL_ALLOWED1);
14368
14369 /* now check the various key exchange, ciphers and macs and
14370 * if we ever disallow by policy, we are done, go to the next cipher
14371 */
14372 policyOid = MAP_NULL(kea_defs[suite->key_exchange_alg].oid)(((kea_defs[suite->key_exchange_alg].oid) != 0) ? (kea_defs
[suite->key_exchange_alg].oid) : SEC_OID_NULL_CIPHER)
;
14373 if (ssl_HandlePolicy(suite->cipher_suite, policyOid,
14374 NSS_USE_ALG_IN_SSL_KX0x00000004, &isDisabled)) {
14375 continue;
14376 }
14377
14378 policyOid = MAP_NULL(ssl_GetBulkCipherDef(suite)->oid)(((ssl_GetBulkCipherDef(suite)->oid) != 0) ? (ssl_GetBulkCipherDef
(suite)->oid) : SEC_OID_NULL_CIPHER)
;
14379 if (ssl_HandlePolicy(suite->cipher_suite, policyOid,
14380 NSS_USE_ALG_IN_SSL0x00000008, &isDisabled)) {
14381 continue;
14382 }
14383
14384 if (ssl_GetBulkCipherDef(suite)->type != type_aead) {
14385 policyOid = MAP_NULL(ssl_GetMacDefByAlg(suite->mac_alg)->oid)(((ssl_GetMacDefByAlg(suite->mac_alg)->oid) != 0) ? (ssl_GetMacDefByAlg
(suite->mac_alg)->oid) : SEC_OID_NULL_CIPHER)
;
14386 if (ssl_HandlePolicy(suite->cipher_suite, policyOid,
14387 NSS_USE_ALG_IN_SSL0x00000008, &isDisabled)) {
14388 continue;
14389 }
14390 }
14391 }
14392
14393 rv = ssl3_ConstrainRangeByPolicy();
14394
14395 return rv;
14396}
14397
14398/* End of ssl3con.c */