Bug Summary

File:s/lib/ssl/tls13con.c
Warning:line 750, column 5
Value stored to 'rv' is never read

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 tls13con.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 tls13con.c
1/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2/*
3 * TLS 1.3 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#include "sslt.h"
10#include "stdarg.h"
11#include "cert.h"
12#include "ssl.h"
13#include "keyhi.h"
14#include "pk11func.h"
15#include "prerr.h"
16#include "secitem.h"
17#include "secmod.h"
18#include "sslimpl.h"
19#include "sslproto.h"
20#include "sslerr.h"
21#include "ssl3exthandle.h"
22#include "tls13hkdf.h"
23#include "tls13con.h"
24#include "tls13err.h"
25#include "tls13ech.h"
26#include "tls13exthandle.h"
27#include "tls13hashstate.h"
28#include "tls13subcerts.h"
29#include "tls13psk.h"
30
31static SECStatus tls13_SetCipherSpec(sslSocket *ss, PRUint16 epoch,
32 SSLSecretDirection install,
33 PRBool deleteSecret);
34static SECStatus tls13_SendServerHelloSequence(sslSocket *ss);
35static SECStatus tls13_SendEncryptedExtensions(sslSocket *ss);
36static void tls13_SetKeyExchangeType(sslSocket *ss, const sslNamedGroupDef *group);
37static SECStatus tls13_HandleClientKeyShare(sslSocket *ss,
38 TLS13KeyShareEntry *peerShare);
39static SECStatus tls13_SendHelloRetryRequest(
40 sslSocket *ss, const sslNamedGroupDef *selectedGroup,
41 const PRUint8 *token, unsigned int tokenLen);
42
43static SECStatus tls13_HandleServerKeyShare(sslSocket *ss);
44static SECStatus tls13_HandleEncryptedExtensions(sslSocket *ss, PRUint8 *b,
45 PRUint32 length);
46static SECStatus tls13_SendCertificate(sslSocket *ss);
47static SECStatus tls13_HandleCertificateDecode(
48 sslSocket *ss, PRUint8 *b, PRUint32 length);
49static SECStatus tls13_HandleCertificate(
50 sslSocket *ss, PRUint8 *b, PRUint32 length, PRBool alreadyHashed);
51static SECStatus tls13_ReinjectHandshakeTranscript(sslSocket *ss);
52static SECStatus tls13_SendCertificateRequest(sslSocket *ss);
53static SECStatus tls13_HandleCertificateRequest(sslSocket *ss, PRUint8 *b,
54 PRUint32 length);
55static SECStatus
56tls13_SendCertificateVerify(sslSocket *ss, SECKEYPrivateKey *privKey);
57static SECStatus tls13_HandleCertificateVerify(
58 sslSocket *ss, PRUint8 *b, PRUint32 length);
59static SECStatus tls13_RecoverWrappedSharedSecret(sslSocket *ss,
60 sslSessionID *sid);
61static SECStatus
62tls13_DeriveSecretWrap(sslSocket *ss, PK11SymKey *key,
63 const char *prefix,
64 const char *suffix,
65 const char *keylogLabel,
66 PK11SymKey **dest);
67SECStatus
68tls13_DeriveSecret(sslSocket *ss, PK11SymKey *key,
69 const char *label,
70 unsigned int labelLen,
71 const SSL3Hashes *hashes,
72 PK11SymKey **dest,
73 SSLHashType hash);
74static SECStatus tls13_SendEndOfEarlyData(sslSocket *ss);
75static SECStatus tls13_HandleEndOfEarlyData(sslSocket *ss, const PRUint8 *b,
76 PRUint32 length);
77static SECStatus tls13_MaybeHandleSuppressedEndOfEarlyData(sslSocket *ss);
78static SECStatus tls13_SendFinished(sslSocket *ss, PK11SymKey *baseKey);
79static SECStatus tls13_ComputePskBinderHash(sslSocket *ss, PRUint8 *b, size_t length,
80 SSL3Hashes *hashes, SSLHashType type);
81static SECStatus tls13_VerifyFinished(sslSocket *ss, SSLHandshakeType message,
82 PK11SymKey *secret,
83 PRUint8 *b, PRUint32 length,
84 const SSL3Hashes *hashes);
85static SECStatus tls13_ClientHandleFinished(sslSocket *ss,
86 PRUint8 *b, PRUint32 length);
87static SECStatus tls13_ServerHandleFinished(sslSocket *ss,
88 PRUint8 *b, PRUint32 length);
89static SECStatus tls13_SendNewSessionTicket(sslSocket *ss,
90 const PRUint8 *appToken,
91 unsigned int appTokenLen);
92static SECStatus tls13_HandleNewSessionTicket(sslSocket *ss, PRUint8 *b,
93 PRUint32 length);
94static SECStatus tls13_ComputeEarlySecretsWithPsk(sslSocket *ss);
95static SECStatus tls13_ComputeHandshakeSecrets(sslSocket *ss);
96static SECStatus tls13_ComputeApplicationSecrets(sslSocket *ss);
97static SECStatus tls13_ComputeFinalSecrets(sslSocket *ss);
98static SECStatus tls13_ComputeFinished(
99 sslSocket *ss, PK11SymKey *baseKey, SSLHashType hashType,
100 const SSL3Hashes *hashes, PRBool sending, PRUint8 *output,
101 unsigned int *outputLen, unsigned int maxOutputLen);
102static SECStatus tls13_SendClientSecondRound(sslSocket *ss);
103static SECStatus tls13_SendClientSecondFlight(sslSocket *ss);
104static SECStatus tls13_FinishHandshake(sslSocket *ss);
105
106const char kHkdfLabelClient[] = "c";
107const char kHkdfLabelServer[] = "s";
108const char kHkdfLabelDerivedSecret[] = "derived";
109const char kHkdfLabelResPskBinderKey[] = "res binder";
110const char kHkdfLabelExtPskBinderKey[] = "ext binder";
111const char kHkdfLabelEarlyTrafficSecret[] = "e traffic";
112const char kHkdfLabelEarlyExporterSecret[] = "e exp master";
113const char kHkdfLabelHandshakeTrafficSecret[] = "hs traffic";
114const char kHkdfLabelApplicationTrafficSecret[] = "ap traffic";
115const char kHkdfLabelFinishedSecret[] = "finished";
116const char kHkdfLabelResumptionMasterSecret[] = "res master";
117const char kHkdfLabelExporterMasterSecret[] = "exp master";
118const char kHkdfLabelResumption[] = "resumption";
119const char kHkdfLabelTrafficUpdate[] = "traffic upd";
120const char kHkdfPurposeKey[] = "key";
121const char kHkdfPurposeSn[] = "sn";
122const char kHkdfPurposeIv[] = "iv";
123
124const char keylogLabelClientEarlyTrafficSecret[] = "CLIENT_EARLY_TRAFFIC_SECRET";
125const char keylogLabelClientHsTrafficSecret[] = "CLIENT_HANDSHAKE_TRAFFIC_SECRET";
126const char keylogLabelServerHsTrafficSecret[] = "SERVER_HANDSHAKE_TRAFFIC_SECRET";
127const char keylogLabelClientTrafficSecret[] = "CLIENT_TRAFFIC_SECRET_0";
128const char keylogLabelServerTrafficSecret[] = "SERVER_TRAFFIC_SECRET_0";
129const char keylogLabelEarlyExporterSecret[] = "EARLY_EXPORTER_SECRET";
130const char keylogLabelExporterSecret[] = "EXPORTER_SECRET";
131
132/* Belt and suspenders in case we ever add a TLS 1.4. */
133PR_STATIC_ASSERT(SSL_LIBRARY_VERSION_MAX_SUPPORTED <=extern void pr_static_assert(int arg[(0x0304 <= 0x0304) ? 1
: -1])
134 SSL_LIBRARY_VERSION_TLS_1_3)extern void pr_static_assert(int arg[(0x0304 <= 0x0304) ? 1
: -1])
;
135
136void
137tls13_FatalError(sslSocket *ss, PRErrorCode prError, SSL3AlertDescription desc)
138{
139 PORT_Assert(desc != internal_error)((desc != internal_error)?((void)0):PR_Assert("desc != internal_error"
,"tls13con.c",139))
; /* These should never happen */
140 (void)SSL3_SendAlert(ss, alert_fatal, desc);
141 PORT_SetErrorPORT_SetError_Util(prError);
142}
143
144#ifdef TRACE
145#define STATE_CASE(a)case a: return "a" \
146 case a: \
147 return #a
148static char *
149tls13_HandshakeState(SSL3WaitState st)
150{
151 switch (st) {
152 STATE_CASE(idle_handshake)case idle_handshake: return "idle_handshake";
153 STATE_CASE(wait_client_hello)case wait_client_hello: return "wait_client_hello";
154 STATE_CASE(wait_end_of_early_data)case wait_end_of_early_data: return "wait_end_of_early_data";
155 STATE_CASE(wait_client_cert)case wait_client_cert: return "wait_client_cert";
156 STATE_CASE(wait_client_key)case wait_client_key: return "wait_client_key";
157 STATE_CASE(wait_cert_verify)case wait_cert_verify: return "wait_cert_verify";
158 STATE_CASE(wait_change_cipher)case wait_change_cipher: return "wait_change_cipher";
159 STATE_CASE(wait_finished)case wait_finished: return "wait_finished";
160 STATE_CASE(wait_server_hello)case wait_server_hello: return "wait_server_hello";
161 STATE_CASE(wait_certificate_status)case wait_certificate_status: return "wait_certificate_status";
162 STATE_CASE(wait_server_cert)case wait_server_cert: return "wait_server_cert";
163 STATE_CASE(wait_server_key)case wait_server_key: return "wait_server_key";
164 STATE_CASE(wait_cert_request)case wait_cert_request: return "wait_cert_request";
165 STATE_CASE(wait_hello_done)case wait_hello_done: return "wait_hello_done";
166 STATE_CASE(wait_new_session_ticket)case wait_new_session_ticket: return "wait_new_session_ticket";
167 STATE_CASE(wait_encrypted_extensions)case wait_encrypted_extensions: return "wait_encrypted_extensions";
168 default:
169 break;
170 }
171 PORT_Assert(0)((0)?((void)0):PR_Assert("0","tls13con.c",171));
172 return "unknown";
173}
174#endif
175
176#define TLS13_WAIT_STATE_MASK0x80 0x80
177
178#define TLS13_BASE_WAIT_STATE(ws)(ws & ~0x80) (ws & ~TLS13_WAIT_STATE_MASK0x80)
179/* We don't mask idle_handshake because other parts of the code use it*/
180#define TLS13_WAIT_STATE(ws)(((ws == idle_handshake) || (ws == wait_server_hello)) ? ws :
ws | 0x80)
(((ws == idle_handshake) || (ws == wait_server_hello)) ? ws : ws | TLS13_WAIT_STATE_MASK0x80)
181#define TLS13_CHECK_HS_STATE(ss, err, ...)tls13_CheckHsState(ss, err, "err", __func__, "tls13con.c", 181
, ..., wait_invalid)
\
182 tls13_CheckHsState(ss, err, #err, __func__, __FILE__"tls13con.c", __LINE__182, \
183 __VA_ARGS__, \
184 wait_invalid)
185void
186tls13_SetHsState(sslSocket *ss, SSL3WaitState ws,
187 const char *func, const char *file, int line)
188{
189#ifdef TRACE
190 const char *new_state_name =
191 tls13_HandshakeState(ws);
192
193 SSL_TRC(3, ("%d: TLS13[%d]: %s state change from %s->%s in %s (%s:%d)",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: %s state change from %s->%s in %s (%s:%d)"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
), tls13_HandshakeState((ss->ssl3.hs.ws & ~0x80)), new_state_name
, func, file, line)
194 SSL_GETPID(), ss->fd, SSL_ROLE(ss),if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: %s state change from %s->%s in %s (%s:%d)"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
), tls13_HandshakeState((ss->ssl3.hs.ws & ~0x80)), new_state_name
, func, file, line)
195 tls13_HandshakeState(TLS13_BASE_WAIT_STATE(ss->ssl3.hs.ws)),if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: %s state change from %s->%s in %s (%s:%d)"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
), tls13_HandshakeState((ss->ssl3.hs.ws & ~0x80)), new_state_name
, func, file, line)
196 new_state_name,if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: %s state change from %s->%s in %s (%s:%d)"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
), tls13_HandshakeState((ss->ssl3.hs.ws & ~0x80)), new_state_name
, func, file, line)
197 func, file, line))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: %s state change from %s->%s in %s (%s:%d)"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
), tls13_HandshakeState((ss->ssl3.hs.ws & ~0x80)), new_state_name
, func, file, line)
;
198#endif
199
200 ss->ssl3.hs.ws = TLS13_WAIT_STATE(ws)(((ws == idle_handshake) || (ws == wait_server_hello)) ? ws :
ws | 0x80)
;
201}
202
203static PRBool
204tls13_InHsStateV(sslSocket *ss, va_list ap)
205{
206 SSL3WaitState ws;
207
208 while ((ws = va_arg(ap, SSL3WaitState)__builtin_va_arg(ap, SSL3WaitState)) != wait_invalid) {
209 if (TLS13_WAIT_STATE(ws)(((ws == idle_handshake) || (ws == wait_server_hello)) ? ws :
ws | 0x80)
== ss->ssl3.hs.ws) {
210 return PR_TRUE1;
211 }
212 }
213 return PR_FALSE0;
214}
215
216PRBool
217tls13_InHsState(sslSocket *ss, ...)
218{
219 PRBool found;
220 va_list ap;
221
222 va_start(ap, ss)__builtin_va_start(ap, ss);
223 found = tls13_InHsStateV(ss, ap);
224 va_end(ap)__builtin_va_end(ap);
225
226 return found;
227}
228
229static SECStatus
230tls13_CheckHsState(sslSocket *ss, int err, const char *error_name,
231 const char *func, const char *file, int line,
232 ...)
233{
234 va_list ap;
235 va_start(ap, line)__builtin_va_start(ap, line);
236 if (tls13_InHsStateV(ss, ap)) {
237 va_end(ap)__builtin_va_end(ap);
238 return SECSuccess;
239 }
240 va_end(ap)__builtin_va_end(ap);
241
242 SSL_TRC(3, ("%d: TLS13[%d]: error %s state is (%s) at %s (%s:%d)",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: error %s state is (%s) at %s (%s:%d)"
, getpid(), ss->fd, error_name, tls13_HandshakeState((ss->
ssl3.hs.ws & ~0x80)), func, file, line)
243 SSL_GETPID(), ss->fd,if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: error %s state is (%s) at %s (%s:%d)"
, getpid(), ss->fd, error_name, tls13_HandshakeState((ss->
ssl3.hs.ws & ~0x80)), func, file, line)
244 error_name,if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: error %s state is (%s) at %s (%s:%d)"
, getpid(), ss->fd, error_name, tls13_HandshakeState((ss->
ssl3.hs.ws & ~0x80)), func, file, line)
245 tls13_HandshakeState(TLS13_BASE_WAIT_STATE(ss->ssl3.hs.ws)),if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: error %s state is (%s) at %s (%s:%d)"
, getpid(), ss->fd, error_name, tls13_HandshakeState((ss->
ssl3.hs.ws & ~0x80)), func, file, line)
246 func, file, line))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: error %s state is (%s) at %s (%s:%d)"
, getpid(), ss->fd, error_name, tls13_HandshakeState((ss->
ssl3.hs.ws & ~0x80)), func, file, line)
;
247 tls13_FatalError(ss, err, unexpected_message);
248 return SECFailure;
249}
250
251PRBool
252tls13_IsPostHandshake(const sslSocket *ss)
253{
254 return ss->version >= SSL_LIBRARY_VERSION_TLS_1_30x0304 && ss->firstHsDone;
255}
256
257SSLHashType
258tls13_GetHashForCipherSuite(ssl3CipherSuite suite)
259{
260 const ssl3CipherSuiteDef *cipherDef =
261 ssl_LookupCipherSuiteDef(suite);
262 PORT_Assert(cipherDef)((cipherDef)?((void)0):PR_Assert("cipherDef","tls13con.c",262
))
;
263 if (!cipherDef) {
264 return ssl_hash_none;
265 }
266 return cipherDef->prf_hash;
267}
268
269SSLHashType
270tls13_GetHash(const sslSocket *ss)
271{
272 /* suite_def may not be set yet when doing EPSK 0-Rtt. */
273 if (!ss->ssl3.hs.suite_def) {
274 if (ss->xtnData.selectedPsk) {
275 return ss->xtnData.selectedPsk->hash;
276 }
277 /* This should never happen. */
278 PORT_Assert(0)((0)?((void)0):PR_Assert("0","tls13con.c",278));
279 return ssl_hash_none;
280 }
281
282 /* All TLS 1.3 cipher suites must have an explict PRF hash. */
283 PORT_Assert(ss->ssl3.hs.suite_def->prf_hash != ssl_hash_none)((ss->ssl3.hs.suite_def->prf_hash != ssl_hash_none)?((void
)0):PR_Assert("ss->ssl3.hs.suite_def->prf_hash != ssl_hash_none"
,"tls13con.c",283))
;
284 return ss->ssl3.hs.suite_def->prf_hash;
285}
286
287SECStatus
288tls13_GetHashAndCipher(PRUint16 version, PRUint16 cipherSuite,
289 SSLHashType *hash, const ssl3BulkCipherDef **cipher)
290{
291 if (version < SSL_LIBRARY_VERSION_TLS_1_30x0304) {
292 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
293 return SECFailure;
294 }
295
296 // Lookup and check the suite.
297 SSLVersionRange vrange = { version, version };
298 if (!ssl3_CipherSuiteAllowedForVersionRange(cipherSuite, &vrange)) {
299 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
300 return SECFailure;
301 }
302 const ssl3CipherSuiteDef *suiteDef = ssl_LookupCipherSuiteDef(cipherSuite);
303 const ssl3BulkCipherDef *cipherDef = ssl_GetBulkCipherDef(suiteDef);
304 if (cipherDef->type != type_aead) {
305 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
306 return SECFailure;
307 }
308 *hash = suiteDef->prf_hash;
309 if (cipher != NULL((void*)0)) {
310 *cipher = cipherDef;
311 }
312 return SECSuccess;
313}
314
315unsigned int
316tls13_GetHashSizeForHash(SSLHashType hash)
317{
318 switch (hash) {
319 case ssl_hash_sha256:
320 return 32;
321 case ssl_hash_sha384:
322 return 48;
323 default:
324 PORT_Assert(0)((0)?((void)0):PR_Assert("0","tls13con.c",324));
325 }
326 return 32;
327}
328
329unsigned int
330tls13_GetHashSize(const sslSocket *ss)
331{
332 return tls13_GetHashSizeForHash(tls13_GetHash(ss));
333}
334
335static CK_MECHANISM_TYPE
336tls13_GetHmacMechanismFromHash(SSLHashType hashType)
337{
338 switch (hashType) {
339 case ssl_hash_sha256:
340 return CKM_SHA256_HMAC0x00000251UL;
341 case ssl_hash_sha384:
342 return CKM_SHA384_HMAC0x00000261UL;
343 default:
344 PORT_Assert(0)((0)?((void)0):PR_Assert("0","tls13con.c",344));
345 }
346 return CKM_SHA256_HMAC0x00000251UL;
347}
348
349static CK_MECHANISM_TYPE
350tls13_GetHmacMechanism(const sslSocket *ss)
351{
352 return tls13_GetHmacMechanismFromHash(tls13_GetHash(ss));
353}
354
355SECStatus
356tls13_ComputeHash(sslSocket *ss, SSL3Hashes *hashes,
357 const PRUint8 *buf, unsigned int len,
358 SSLHashType hash)
359{
360 SECStatus rv;
361
362 rv = PK11_HashBuf(ssl3_HashTypeToOID(hash), hashes->u.raw, buf, len);
363 if (rv != SECSuccess) {
364 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__, "tls13con.c"
, 364); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0); tls13_FatalError(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error
); } while (0)
;
365 return SECFailure;
366 }
367 hashes->len = tls13_GetHashSizeForHash(hash);
368
369 return SECSuccess;
370}
371
372static SECStatus
373tls13_CreateKEMKeyPair(sslSocket *ss, const sslNamedGroupDef *groupDef,
374 sslKeyPair **outKeyPair)
375{
376 PORT_Assert(groupDef)((groupDef)?((void)0):PR_Assert("groupDef","tls13con.c",376));
377 if (groupDef->name != ssl_grp_kem_xyber768d00) {
378 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
379 return SECFailure;
380 }
381
382 sslKeyPair *keyPair = NULL((void*)0);
383 SECKEYPrivateKey *privKey = NULL((void*)0);
384 SECKEYPublicKey *pubKey = NULL((void*)0);
385 CK_MECHANISM_TYPE mechanism = CKM_NSS_KYBER_KEY_PAIR_GEN((0x80000000UL | 0x4E534350) + 45);
386 CK_NSS_KEM_PARAMETER_SET_TYPE paramSet = CKP_NSS_KYBER_768_ROUND3((0x80000000UL | 0x4E534350) + 1);
387
388 PK11SlotInfo *slot = PK11_GetBestSlot(mechanism, ss->pkcs11PinArg);
389 if (!slot) {
390 goto loser;
391 }
392
393 privKey = PK11_GenerateKeyPairWithOpFlags(slot, mechanism,
394 &paramSet, &pubKey, PK11_ATTR_SESSION0x00000002L | PK11_ATTR_SENSITIVE0x00000040L | PK11_ATTR_PRIVATE0x00000004L,
395 CKF_DERIVE0x00080000UL, CKF_DERIVE0x00080000UL, ss->pkcs11PinArg);
396 PK11_FreeSlot(slot);
397 if (!privKey || !pubKey) {
398 goto loser;
399 }
400
401 keyPair = ssl_NewKeyPair(privKey, pubKey);
402 if (!keyPair) {
403 goto loser;
404 }
405
406 SSL_TRC(50, ("%d: SSL[%d]: Create Kyber ephemeral key %d",if (ssl_trace >= (50)) ssl_Trace ("%d: SSL[%d]: Create Kyber ephemeral key %d"
, getpid(), ss ? ss->fd : ((void*)0), groupDef->name)
407 SSL_GETPID(), ss ? ss->fd : NULL, groupDef->name))if (ssl_trace >= (50)) ssl_Trace ("%d: SSL[%d]: Create Kyber ephemeral key %d"
, getpid(), ss ? ss->fd : ((void*)0), groupDef->name)
;
408 PRINT_BUF(50, (ss, "Public Key", pubKey->u.kyber.publicValue.data,if (ssl_trace >= (50)) ssl_PrintBuf (ss, "Public Key", pubKey
->u.kyber.publicValue.data, pubKey->u.kyber.publicValue
.len)
409 pubKey->u.kyber.publicValue.len))if (ssl_trace >= (50)) ssl_PrintBuf (ss, "Public Key", pubKey
->u.kyber.publicValue.data, pubKey->u.kyber.publicValue
.len)
;
410#ifdef TRACE
411 if (ssl_trace >= 50) {
412 SECItem d = { siBuffer, NULL((void*)0), 0 };
413 SECStatus rv = PK11_ReadRawAttribute(PK11_TypePrivKey, privKey, CKA_VALUE0x00000011UL, &d);
414 if (rv == SECSuccess) {
415 PRINT_BUF(50, (ss, "Private Key", d.data, d.len))if (ssl_trace >= (50)) ssl_PrintBuf (ss, "Private Key", d.
data, d.len)
;
416 SECITEM_FreeItemSECITEM_FreeItem_Util(&d, PR_FALSE0);
417 } else {
418 SSL_TRC(50, ("Error extracting private key"))if (ssl_trace >= (50)) ssl_Trace ("Error extracting private key"
)
;
419 }
420 }
421#endif
422
423 *outKeyPair = keyPair;
424 return SECSuccess;
425
426loser:
427 SECKEY_DestroyPrivateKey(privKey);
428 SECKEY_DestroyPublicKey(pubKey);
429 ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
430 return SECFailure;
431}
432
433SECStatus
434tls13_CreateKeyShare(sslSocket *ss, const sslNamedGroupDef *groupDef,
435 sslEphemeralKeyPair **outKeyPair)
436{
437 SECStatus rv;
438 const ssl3DHParams *params;
439 sslEphemeralKeyPair *keyPair = NULL((void*)0);
440
441 PORT_Assert(groupDef)((groupDef)?((void)0):PR_Assert("groupDef","tls13con.c",441));
442 switch (groupDef->keaType) {
443 case ssl_kea_ecdh_hybrid:
444 if (groupDef->name != ssl_grp_kem_xyber768d00) {
445 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
446 return SECFailure;
447 }
448 rv = ssl_CreateECDHEphemeralKeyPair(ss, ssl_LookupNamedGroup(ssl_grp_ec_curve25519), &keyPair);
449 if (rv != SECSuccess) {
450 return SECFailure;
451 }
452 keyPair->group = groupDef;
453 break;
454 case ssl_kea_ecdh:
455 rv = ssl_CreateECDHEphemeralKeyPair(ss, groupDef, &keyPair);
456 if (rv != SECSuccess) {
457 return SECFailure;
458 }
459 break;
460 case ssl_kea_dh:
461 params = ssl_GetDHEParams(groupDef);
462 PORT_Assert(params->name != ssl_grp_ffdhe_custom)((params->name != ssl_grp_ffdhe_custom)?((void)0):PR_Assert
("params->name != ssl_grp_ffdhe_custom","tls13con.c",462))
;
463 rv = ssl_CreateDHEKeyPair(groupDef, params, &keyPair);
464 if (rv != SECSuccess) {
465 return SECFailure;
466 }
467 break;
468 default:
469 PORT_Assert(0)((0)?((void)0):PR_Assert("0","tls13con.c",469));
470 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
471 return SECFailure;
472 }
473
474 // If we're creating an ECDH + KEM hybrid share and we're the client, then
475 // we still need to generate the KEM key pair. Otherwise we're done.
476 if (groupDef->keaType == ssl_kea_ecdh_hybrid && !ss->sec.isServer) {
477 rv = tls13_CreateKEMKeyPair(ss, groupDef, &keyPair->kemKeys);
478 if (rv != SECSuccess) {
479 ssl_FreeEphemeralKeyPair(keyPair);
480 return SECFailure;
481 }
482 }
483
484 *outKeyPair = keyPair;
485 return SECSuccess;
486}
487
488SECStatus
489tls13_AddKeyShare(sslSocket *ss, const sslNamedGroupDef *groupDef)
490{
491 sslEphemeralKeyPair *keyPair = NULL((void*)0);
492 SECStatus rv;
493
494 rv = tls13_CreateKeyShare(ss, groupDef, &keyPair);
495 if (rv != SECSuccess) {
496 return SECFailure;
497 }
498 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)
;
499 return SECSuccess;
500}
501
502SECStatus
503SSL_SendAdditionalKeyShares(PRFileDesc *fd, unsigned int count)
504{
505 sslSocket *ss = ssl_FindSocket(fd);
506 if (!ss) {
507 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
508 return SECFailure;
509 }
510
511 ss->additionalShares = count;
512 return SECSuccess;
513}
514
515/*
516 * Generate shares for ECDHE and FFDHE. This picks the first enabled group of
517 * the requisite type and creates a share for that.
518 *
519 * Called from ssl3_SendClientHello.
520 */
521SECStatus
522tls13_SetupClientHello(sslSocket *ss, sslClientHelloType chType)
523{
524 unsigned int i;
525 SSL3Statistics *ssl3stats = SSL_GetStatistics();
526 NewSessionTicket *session_ticket = NULL((void*)0);
527 sslSessionID *sid = ss->sec.ci.sid;
528 unsigned int numShares = 0;
529 SECStatus rv;
530
531 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)"
,"tls13con.c",531))
;
532 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)"
,"tls13con.c",532))
;
533
534 rv = tls13_ClientSetupEch(ss, chType);
535 if (rv != SECSuccess) {
536 return SECFailure;
537 }
538
539 /* Everything below here is only run on the first CH. */
540 if (chType != client_hello_initial) {
541 return SECSuccess;
542 }
543
544 rv = tls13_ClientGreaseSetup(ss);
545 if (rv != SECSuccess) {
546 return SECFailure;
547 }
548
549 /* Select the first enabled group.
550 * TODO(ekr@rtfm.com): be smarter about offering the group
551 * that the other side negotiated if we are resuming. */
552 PORT_Assert(PR_CLIST_IS_EMPTY(&ss->ephemeralKeyPairs))((((&ss->ephemeralKeyPairs)->next == (&ss->ephemeralKeyPairs
)))?((void)0):PR_Assert("PR_CLIST_IS_EMPTY(&ss->ephemeralKeyPairs)"
,"tls13con.c",552))
;
553 for (i = 0; i < SSL_NAMED_GROUP_COUNT32; ++i) {
554 if (!ss->namedGroupPreferences[i]) {
555 continue;
556 }
557 rv = tls13_AddKeyShare(ss, ss->namedGroupPreferences[i]);
558 if (rv != SECSuccess) {
559 return SECFailure;
560 }
561 if (++numShares > ss->additionalShares) {
562 break;
563 }
564 }
565
566 if (PR_CLIST_IS_EMPTY(&ss->ephemeralKeyPairs)((&ss->ephemeralKeyPairs)->next == (&ss->ephemeralKeyPairs
))
) {
567 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_NO_CIPHERS_SUPPORTED);
568 return SECFailure;
569 }
570
571 /* Try to do stateless resumption, if we can. */
572 if (sid->cached != never_cached &&
573 sid->version >= SSL_LIBRARY_VERSION_TLS_1_30x0304) {
574 /* The caller must be holding sid->u.ssl3.lock for reading. */
575 session_ticket = &sid->u.ssl3.locked.sessionTicket;
576 PORT_Assert(session_ticket && session_ticket->ticket.data)((session_ticket && session_ticket->ticket.data)?(
(void)0):PR_Assert("session_ticket && session_ticket->ticket.data"
,"tls13con.c",576))
;
577
578 if (ssl_TicketTimeValid(ss, session_ticket)) {
579 ss->statelessResume = PR_TRUE1;
580 }
581
582 if (ss->statelessResume) {
583 PORT_Assert(ss->sec.ci.sid)((ss->sec.ci.sid)?((void)0):PR_Assert("ss->sec.ci.sid",
"tls13con.c",583))
;
584 rv = tls13_RecoverWrappedSharedSecret(ss, ss->sec.ci.sid);
585 if (rv != SECSuccess) {
586 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__, "tls13con.c"
, 586); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0); tls13_FatalError(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error
); } while (0)
;
587 SSL_AtomicIncrementLong(&ssl3stats->sch_sid_cache_not_ok);
588 ssl_UncacheSessionID(ss);
589 ssl_FreeSID(ss->sec.ci.sid);
590 ss->sec.ci.sid = NULL((void*)0);
591 return SECFailure;
592 }
593
594 ss->ssl3.hs.cipher_suite = ss->sec.ci.sid->u.ssl3.cipherSuite;
595 rv = ssl3_SetupCipherSuite(ss, PR_FALSE0);
596 if (rv != SECSuccess) {
597 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__, "tls13con.c"
, 597); PORT_SetError_Util(PORT_GetError_Util()); } while (0)
; tls13_FatalError(ss, PORT_GetError_Util(), internal_error);
} while (0)
;
598 return SECFailure;
599 }
600 PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks))((!((&ss->ssl3.hs.psks)->next == (&ss->ssl3.
hs.psks)))?((void)0):PR_Assert("!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks)"
,"tls13con.c",600))
;
601 }
602 }
603
604 /* Derive the binder keys if any PSKs. */
605 if (!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks)((&ss->ssl3.hs.psks)->next == (&ss->ssl3.hs.
psks))
) {
606 /* If an External PSK specified a suite, use that. */
607 sslPsk *psk = (sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks)(&ss->ssl3.hs.psks)->next;
608 if (!ss->statelessResume &&
609 psk->type == ssl_psk_external &&
610 psk->zeroRttSuite != TLS_NULL_WITH_NULL_NULL0x0000) {
611 ss->ssl3.hs.cipher_suite = psk->zeroRttSuite;
612 }
613
614 rv = tls13_ComputeEarlySecretsWithPsk(ss);
615 if (rv != SECSuccess) {
616 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__, "tls13con.c"
, 616); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0); tls13_FatalError(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error
); } while (0)
;
617 return SECFailure;
618 }
619 }
620
621 return SECSuccess;
622}
623
624static SECStatus
625tls13_ImportDHEKeyShare(SECKEYPublicKey *peerKey,
626 PRUint8 *b, PRUint32 length,
627 SECKEYPublicKey *pubKey)
628{
629 SECStatus rv;
630 SECItem publicValue = { siBuffer, NULL((void*)0), 0 };
631
632 publicValue.data = b;
633 publicValue.len = length;
634 if (!ssl_IsValidDHEShare(&pubKey->u.dh.prime, &publicValue)) {
635 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_MALFORMED_DHE_KEY_SHARE);
636 return SECFailure;
637 }
638
639 peerKey->keyType = dhKey;
640 rv = SECITEM_CopyItemSECITEM_CopyItem_Util(peerKey->arena, &peerKey->u.dh.prime,
641 &pubKey->u.dh.prime);
642 if (rv != SECSuccess)
643 return SECFailure;
644 rv = SECITEM_CopyItemSECITEM_CopyItem_Util(peerKey->arena, &peerKey->u.dh.base,
645 &pubKey->u.dh.base);
646 if (rv != SECSuccess)
647 return SECFailure;
648 rv = SECITEM_CopyItemSECITEM_CopyItem_Util(peerKey->arena, &peerKey->u.dh.publicValue,
649 &publicValue);
650 if (rv != SECSuccess)
651 return SECFailure;
652
653 return SECSuccess;
654}
655
656static SECStatus
657tls13_ImportKEMKeyShare(SECKEYPublicKey *peerKey, TLS13KeyShareEntry *entry)
658{
659 SECItem pk = { siBuffer, NULL((void*)0), 0 };
660 SECStatus rv;
661
662 if (entry->group->name != ssl_grp_kem_xyber768d00) {
663 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
664 return SECFailure;
665 }
666
667 if (entry->key_exchange.len != X25519_PUBLIC_KEY_BYTES32U + KYBER768_PUBLIC_KEY_BYTES1184U) {
668 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_MALFORMED_HYBRID_KEY_SHARE);
669 return SECFailure;
670 }
671 pk.data = entry->key_exchange.data + X25519_PUBLIC_KEY_BYTES32U;
672 pk.len = entry->key_exchange.len - X25519_PUBLIC_KEY_BYTES32U;
673
674 peerKey->keyType = kyberKey;
675 peerKey->u.kyber.params = params_kyber768_round3;
676
677 rv = SECITEM_CopyItemSECITEM_CopyItem_Util(peerKey->arena, &peerKey->u.kyber.publicValue, &pk);
678 if (rv != SECSuccess) {
679 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_NO_MEMORY);
680 return SECFailure;
681 }
682
683 return SECSuccess;
684}
685
686static SECStatus
687tls13_HandleKEMCiphertext(sslSocket *ss, TLS13KeyShareEntry *entry, sslKeyPair *keyPair, PK11SymKey **outKey)
688{
689 SECItem ct = { siBuffer, NULL((void*)0), 0 };
690 SECStatus rv;
691
692 switch (entry->group->name) {
693 case ssl_grp_kem_xyber768d00:
694 if (entry->key_exchange.len != X25519_PUBLIC_KEY_BYTES32U + KYBER768_CIPHERTEXT_BYTES1088U) {
695 ssl_MapLowLevelError(SSL_ERROR_RX_MALFORMED_HYBRID_KEY_SHARE);
696 return SECFailure;
697 }
698 ct.data = entry->key_exchange.data + X25519_PUBLIC_KEY_BYTES32U;
699 ct.len = entry->key_exchange.len - X25519_PUBLIC_KEY_BYTES32U;
700 break;
701 default:
702 PORT_Assert(0)((0)?((void)0):PR_Assert("0","tls13con.c",702));
703 ssl_MapLowLevelError(SEC_ERROR_LIBRARY_FAILURE);
704 return SECFailure;
705 }
706
707 rv = PK11_Decapsulate(keyPair->privKey, &ct, CKM_HKDF_DERIVE0x0000402aUL, PK11_ATTR_SESSION0x00000002L | PK11_ATTR_SENSITIVE0x00000040L, CKF_DERIVE0x00080000UL, outKey);
708 if (rv != SECSuccess) {
709 ssl_MapLowLevelError(SSL_ERROR_KEY_EXCHANGE_FAILURE);
710 }
711 return rv;
712}
713
714static SECStatus
715tls13_HandleKEMKey(sslSocket *ss,
716 TLS13KeyShareEntry *entry,
717 PK11SymKey **key,
718 SECItem **ciphertext)
719{
720 PORTCheapArenaPool arena;
721 SECKEYPublicKey *peerKey;
722 CK_OBJECT_HANDLE handle;
723 SECStatus rv;
724
725 PORT_InitCheapArena(&arena, DER_DEFAULT_CHUNKSIZE(2048));
726 peerKey = PORT_ArenaZNew(&arena.arena, SECKEYPublicKey)(SECKEYPublicKey *)PORT_ArenaZAlloc_Util(&arena.arena, sizeof
(SECKEYPublicKey))
;
727 if (peerKey == NULL((void*)0)) {
728 goto loser;
729 }
730 peerKey->arena = &arena.arena;
731 peerKey->pkcs11Slot = NULL((void*)0);
732 peerKey->pkcs11ID = CK_INVALID_HANDLE0;
733
734 rv = tls13_ImportKEMKeyShare(peerKey, entry);
735 if (rv != SECSuccess) {
736 goto loser;
737 }
738
739 PK11SlotInfo *slot = PK11_GetBestSlot(CKM_NSS_KYBER((0x80000000UL | 0x4E534350) + 46), ss->pkcs11PinArg);
740 if (!slot) {
741 goto loser;
742 }
743
744 handle = PK11_ImportPublicKey(slot, peerKey, PR_FALSE0);
745 PK11_FreeSlot(slot); /* peerKey holds a slot reference on success. */
746 if (handle == CK_INVALID_HANDLE0) {
747 goto loser;
748 }
749
750 rv = PK11_Encapsulate(peerKey,
Value stored to 'rv' is never read
751 CKM_HKDF_DERIVE0x0000402aUL, PK11_ATTR_SESSION0x00000002L | PK11_ATTR_SENSITIVE0x00000040L | PK11_ATTR_PRIVATE0x00000004L,
752 CKF_DERIVE0x00080000UL, key, ciphertext);
753
754 /* Destroy the imported public key */
755 PORT_Assert(peerKey->pkcs11Slot)((peerKey->pkcs11Slot)?((void)0):PR_Assert("peerKey->pkcs11Slot"
,"tls13con.c",755))
;
756 PK11_DestroyObject(peerKey->pkcs11Slot, peerKey->pkcs11ID);
757 PK11_FreeSlot(peerKey->pkcs11Slot);
758
759 PORT_DestroyCheapArena(&arena);
760 return SECSuccess;
761
762loser:
763 PORT_DestroyCheapArena(&arena);
764 return SECFailure;
765}
766
767SECStatus
768tls13_HandleKeyShare(sslSocket *ss,
769 TLS13KeyShareEntry *entry,
770 sslKeyPair *keyPair,
771 SSLHashType hash,
772 PK11SymKey **out)
773{
774 PORTCheapArenaPool arena;
775 SECKEYPublicKey *peerKey;
776 CK_MECHANISM_TYPE mechanism;
777 PK11SymKey *key;
778 SECStatus rv;
779 int keySize = 0;
780
781 PORT_InitCheapArena(&arena, DER_DEFAULT_CHUNKSIZE(2048));
782 peerKey = PORT_ArenaZNew(&arena.arena, SECKEYPublicKey)(SECKEYPublicKey *)PORT_ArenaZAlloc_Util(&arena.arena, sizeof
(SECKEYPublicKey))
;
783 if (peerKey == NULL((void*)0)) {
784 goto loser;
785 }
786 peerKey->arena = &arena.arena;
787 peerKey->pkcs11Slot = NULL((void*)0);
788 peerKey->pkcs11ID = CK_INVALID_HANDLE0;
789
790 switch (entry->group->keaType) {
791 case ssl_kea_ecdh_hybrid:
792 if (entry->group->name != ssl_grp_kem_xyber768d00 || entry->key_exchange.len < X25519_PUBLIC_KEY_BYTES32U) {
793 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_MALFORMED_HYBRID_KEY_SHARE);
794 goto loser;
795 }
796 rv = ssl_ImportECDHKeyShare(peerKey,
797 entry->key_exchange.data,
798 X25519_PUBLIC_KEY_BYTES32U,
799 ssl_LookupNamedGroup(ssl_grp_ec_curve25519));
800 mechanism = CKM_ECDH1_DERIVE0x00001050UL;
801 break;
802 case ssl_kea_ecdh:
803 rv = ssl_ImportECDHKeyShare(peerKey,
804 entry->key_exchange.data,
805 entry->key_exchange.len,
806 entry->group);
807 mechanism = CKM_ECDH1_DERIVE0x00001050UL;
808 break;
809 case ssl_kea_dh:
810 rv = tls13_ImportDHEKeyShare(peerKey,
811 entry->key_exchange.data,
812 entry->key_exchange.len,
813 keyPair->pubKey);
814 mechanism = CKM_DH_PKCS_DERIVE0x00000021UL;
815 keySize = peerKey->u.dh.publicValue.len;
816 break;
817 default:
818 PORT_Assert(0)((0)?((void)0):PR_Assert("0","tls13con.c",818));
819 goto loser;
820 }
821 if (rv != SECSuccess) {
822 goto loser;
823 }
824
825 key = PK11_PubDeriveWithKDF(
826 keyPair->privKey, peerKey, PR_FALSE0, NULL((void*)0), NULL((void*)0), mechanism,
827 CKM_HKDF_DERIVE0x0000402aUL, CKA_DERIVE0x0000010CUL, keySize, CKD_NULL0x00000001UL, NULL((void*)0), NULL((void*)0));
828 if (!key) {
829 ssl_MapLowLevelError(SSL_ERROR_KEY_EXCHANGE_FAILURE);
830 goto loser;
831 }
832
833 *out = key;
834 PORT_DestroyCheapArena(&arena);
835 return SECSuccess;
836
837loser:
838 PORT_DestroyCheapArena(&arena);
839 return SECFailure;
840}
841
842static PRBool
843tls13_UseServerSecret(sslSocket *ss, SSLSecretDirection direction)
844{
845 return ss->sec.isServer == (direction == ssl_secret_write);
846}
847
848static PK11SymKey **
849tls13_TrafficSecretRef(sslSocket *ss, SSLSecretDirection direction)
850{
851 if (tls13_UseServerSecret(ss, direction)) {
852 return &ss->ssl3.hs.serverTrafficSecret;
853 }
854 return &ss->ssl3.hs.clientTrafficSecret;
855}
856
857SECStatus
858tls13_UpdateTrafficKeys(sslSocket *ss, SSLSecretDirection direction)
859{
860 PK11SymKey **secret;
861 PK11SymKey *updatedSecret;
862 PRUint16 epoch;
863 SECStatus rv;
864
865 secret = tls13_TrafficSecretRef(ss, direction);
866 rv = tls13_HkdfExpandLabel(*secret, tls13_GetHash(ss),
867 NULL((void*)0), 0,
868 kHkdfLabelTrafficUpdate,
869 strlen(kHkdfLabelTrafficUpdate),
870 tls13_GetHmacMechanism(ss),
871 tls13_GetHashSize(ss),
872 ss->protocolVariant,
873 &updatedSecret);
874 if (rv != SECSuccess) {
875 return SECFailure;
876 }
877
878 PK11_FreeSymKey(*secret);
879 *secret = updatedSecret;
880
881 ssl_GetSpecReadLock(ss){ if (!ss->opt.noLocks) NSSRWLock_LockRead_Util((ss)->specLock
); }
;
882 if (direction == ssl_secret_read) {
883 epoch = ss->ssl3.crSpec->epoch;
884 } else {
885 epoch = ss->ssl3.cwSpec->epoch;
886 }
887 ssl_ReleaseSpecReadLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockRead_Util((ss)->
specLock); }
;
888
889 if (epoch == PR_UINT16_MAX65535U) {
890 /* Good chance that this is an overflow from too many updates. */
891 FATAL_ERROR(ss, SSL_ERROR_TOO_MANY_KEY_UPDATES, internal_error)do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_TOO_MANY_KEY_UPDATES, __func__
, "tls13con.c", 891); PORT_SetError_Util(SSL_ERROR_TOO_MANY_KEY_UPDATES
); } while (0); tls13_FatalError(ss, SSL_ERROR_TOO_MANY_KEY_UPDATES
, internal_error); } while (0)
;
892 return SECFailure;
893 }
894 ++epoch;
895
896 if (ss->secretCallback) {
897 ss->secretCallback(ss->fd, epoch, direction, updatedSecret,
898 ss->secretCallbackArg);
899 }
900 rv = tls13_SetCipherSpec(ss, epoch, direction, PR_FALSE0);
901 if (rv != SECSuccess) {
902 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__, "tls13con.c"
, 902); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0); tls13_FatalError(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error
); } while (0)
;
903 return SECFailure;
904 }
905 return SECSuccess;
906}
907
908SECStatus
909tls13_SendKeyUpdate(sslSocket *ss, tls13KeyUpdateRequest request, PRBool buffer)
910{
911 SECStatus rv;
912
913 SSL_TRC(3, ("%d: TLS13[%d]: %s send key update, response %s",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: %s send key update, response %s"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
), (request == update_requested) ? "requested" : "not requested"
)
914 SSL_GETPID(), ss->fd, SSL_ROLE(ss),if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: %s send key update, response %s"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
), (request == update_requested) ? "requested" : "not requested"
)
915 (request == update_requested) ? "requested"if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: %s send key update, response %s"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
), (request == update_requested) ? "requested" : "not requested"
)
916 : "not requested"))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: %s send key update, response %s"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
), (request == update_requested) ? "requested" : "not requested"
)
;
917
918 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)"
,"tls13con.c",918))
;
919 PORT_Assert(!ss->sec.isServer || !ss->ssl3.clientCertRequested)((!ss->sec.isServer || !ss->ssl3.clientCertRequested)?(
(void)0):PR_Assert("!ss->sec.isServer || !ss->ssl3.clientCertRequested"
,"tls13con.c",919))
;
920
921 if (!tls13_IsPostHandshake(ss)) {
922 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
923 return SECFailure;
924 }
925
926 rv = TLS13_CHECK_HS_STATE(ss, SEC_ERROR_LIBRARY_FAILURE,tls13_CheckHsState(ss, SEC_ERROR_LIBRARY_FAILURE, "SEC_ERROR_LIBRARY_FAILURE"
, __func__, "tls13con.c", 927, idle_handshake, wait_invalid)
927 idle_handshake)tls13_CheckHsState(ss, SEC_ERROR_LIBRARY_FAILURE, "SEC_ERROR_LIBRARY_FAILURE"
, __func__, "tls13con.c", 927, idle_handshake, wait_invalid)
;
928 if (rv != SECSuccess) {
929 return SECFailure;
930 }
931
932 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
933 rv = dtls13_MaybeSendKeyUpdate(ss, request, buffer);
934 if (rv != SECSuccess) {
935 /* Error code set already. */
936 return SECFailure;
937 }
938 return rv;
939 }
940
941 ssl_GetXmitBufLock(ss){ if (!ss->opt.noLocks) PR_EnterMonitor(((ss)->xmitBufLock
)); }
;
942 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_key_update, 1);
943 if (rv != SECSuccess) {
944 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__, "tls13con.c"
, 944); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0); tls13_FatalError(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error
); } while (0)
;
945 goto loser;
946 }
947 rv = ssl3_AppendHandshakeNumber(ss, request, 1);
948 if (rv != SECSuccess) {
949 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__, "tls13con.c"
, 949); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0); tls13_FatalError(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error
); } while (0)
;
950 goto loser;
951 }
952
953 /* If we have been asked to buffer, then do so. This allows us to coalesce
954 * a KeyUpdate with a pending write. */
955 rv = ssl3_FlushHandshake(ss, buffer ? ssl_SEND_FLAG_FORCE_INTO_BUFFER0x40000000 : 0);
956 if (rv != SECSuccess) {
957 goto loser; /* error code set by ssl3_FlushHandshake */
958 }
959 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
;
960
961 rv = tls13_UpdateTrafficKeys(ss, ssl_secret_write);
962 if (rv != SECSuccess) {
963 goto loser; /* error code set by tls13_UpdateTrafficKeys */
964 }
965
966 return SECSuccess;
967
968loser:
969 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
;
970 return SECFailure;
971}
972
973SECStatus
974SSLExp_KeyUpdate(PRFileDesc *fd, PRBool requestUpdate)
975{
976 SECStatus rv;
977 sslSocket *ss = ssl_FindSocket(fd);
978 if (!ss) {
979 return SECFailure;
980 }
981
982 if (!tls13_IsPostHandshake(ss)) {
983 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
984 return SECFailure;
985 }
986
987 if (ss->ssl3.clientCertRequested) {
988 PORT_SetErrorPORT_SetError_Util(PR_WOULD_BLOCK_ERROR(-5998L));
989 return SECFailure;
990 }
991
992 rv = TLS13_CHECK_HS_STATE(ss, SEC_ERROR_INVALID_ARGS,tls13_CheckHsState(ss, SEC_ERROR_INVALID_ARGS, "SEC_ERROR_INVALID_ARGS"
, __func__, "tls13con.c", 993, idle_handshake, wait_invalid)
993 idle_handshake)tls13_CheckHsState(ss, SEC_ERROR_INVALID_ARGS, "SEC_ERROR_INVALID_ARGS"
, __func__, "tls13con.c", 993, idle_handshake, wait_invalid)
;
994 if (rv != SECSuccess) {
995 return SECFailure;
996 }
997
998 ssl_GetSSL3HandshakeLock(ss){ if (!ss->opt.noLocks) { ((!((PR_GetMonitorEntryCount(((ss
)->xmitBufLock)) > 0)))?((void)0):PR_Assert("!ssl_HaveXmitBufLock(ss)"
,"tls13con.c",998)); PR_EnterMonitor(((ss)->ssl3HandshakeLock
)); } }
;
999 rv = tls13_SendKeyUpdate(ss, requestUpdate ? update_requested : update_not_requested,
1000 PR_FALSE0 /* don't buffer */);
1001
1002 /* Remember that we are the ones that initiated this KeyUpdate. */
1003 if (rv == SECSuccess) {
1004 ss->ssl3.peerRequestedKeyUpdate = PR_FALSE0;
1005 }
1006 ssl_ReleaseSSL3HandshakeLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->ssl3HandshakeLock
)); }
;
1007 return rv;
1008}
1009
1010SECStatus
1011SSLExp_SetCertificateCompressionAlgorithm(PRFileDesc *fd, SSLCertificateCompressionAlgorithm alg)
1012{
1013 sslSocket *ss = ssl_FindSocket(fd);
1014 if (!ss) {
1015 return SECFailure; /* Code already set. */
1016 }
1017
1018 ssl_GetSSL3HandshakeLock(ss){ if (!ss->opt.noLocks) { ((!((PR_GetMonitorEntryCount(((ss
)->xmitBufLock)) > 0)))?((void)0):PR_Assert("!ssl_HaveXmitBufLock(ss)"
,"tls13con.c",1018)); PR_EnterMonitor(((ss)->ssl3HandshakeLock
)); } }
;
1019 if (ss->ssl3.supportedCertCompressionAlgorithmsCount == MAX_SUPPORTED_CERTIFICATE_COMPRESSION_ALGS32) {
1020 goto loser;
1021 }
1022
1023 /* Reserved ID */
1024 if (alg.id == 0) {
1025 goto loser;
1026 }
1027
1028 if (alg.encode == NULL((void*)0) && alg.decode == NULL((void*)0)) {
1029 goto loser;
1030 }
1031
1032 /* Checking that we have not yet registed an algorithm with the same ID. */
1033 for (int i = 0; i < ss->ssl3.supportedCertCompressionAlgorithmsCount; i++) {
1034 if (ss->ssl3.supportedCertCompressionAlgorithms[i].id == alg.id) {
1035 goto loser;
1036 }
1037 }
1038
1039 PORT_Memcpymemcpy(&ss->ssl3.supportedCertCompressionAlgorithms
1040 [ss->ssl3.supportedCertCompressionAlgorithmsCount],
1041 &alg, sizeof(alg));
1042 ss->ssl3.supportedCertCompressionAlgorithmsCount += 1;
1043 ssl_ReleaseSSL3HandshakeLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->ssl3HandshakeLock
)); }
;
1044 return SECSuccess;
1045
1046loser:
1047 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
1048 ssl_ReleaseSSL3HandshakeLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->ssl3HandshakeLock
)); }
;
1049 return SECFailure;
1050}
1051
1052/*
1053 * enum {
1054 * update_not_requested(0), update_requested(1), (255)
1055 * } KeyUpdateRequest;
1056 *
1057 * struct {
1058 * KeyUpdateRequest request_update;
1059 * } KeyUpdate;
1060 */
1061
1062/* If we're handing the DTLS1.3 message, we silently fail if there is a parsing problem. */
1063static SECStatus
1064tls13_HandleKeyUpdate(sslSocket *ss, PRUint8 *b, unsigned int length)
1065{
1066 SECStatus rv;
1067 PRUint32 update;
1068
1069 SSL_TRC(3, ("%d: TLS13[%d]: %s handle key update",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: %s handle key update"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
))
1070 SSL_GETPID(), ss->fd, SSL_ROLE(ss)))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: %s handle key update"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
))
;
1071
1072 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)"
,"tls13con.c",1072))
;
1073 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)"
,"tls13con.c",1073))
;
1074
1075 if (!tls13_IsPostHandshake(ss)) {
1076 FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_KEY_UPDATE, 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_KEY_UPDATE, __func__
, "tls13con.c", 1076); PORT_SetError_Util(SSL_ERROR_RX_UNEXPECTED_KEY_UPDATE
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_UNEXPECTED_KEY_UPDATE
, unexpected_message); } while (0)
;
1077 return SECFailure;
1078 }
1079
1080 rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_KEY_UPDATE,tls13_CheckHsState(ss, SSL_ERROR_RX_UNEXPECTED_KEY_UPDATE, "SSL_ERROR_RX_UNEXPECTED_KEY_UPDATE"
, __func__, "tls13con.c", 1081, idle_handshake, wait_invalid)
1081 idle_handshake)tls13_CheckHsState(ss, SSL_ERROR_RX_UNEXPECTED_KEY_UPDATE, "SSL_ERROR_RX_UNEXPECTED_KEY_UPDATE"
, __func__, "tls13con.c", 1081, idle_handshake, wait_invalid)
;
1082 if (rv != SECSuccess) {
1083 /* We should never be idle_handshake prior to firstHsDone. */
1084 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__, "tls13con.c"
, 1084); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0); tls13_FatalError(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error
); } while (0)
;
1085 return SECFailure;
1086 }
1087
1088 rv = ssl3_ConsumeHandshakeNumber(ss, &update, 1, &b, &length);
1089 if (rv != SECSuccess) {
1090 return SECFailure; /* Error code set already. */
1091 }
1092 if (length != 0) {
1093 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_KEY_UPDATE, decode_error)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_KEY_UPDATE, __func__
, "tls13con.c", 1093); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_KEY_UPDATE
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_KEY_UPDATE
, decode_error); } while (0)
;
1094 return SECFailure;
1095 }
1096 if (!(update == update_requested ||
1097 update == update_not_requested)) {
1098 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_KEY_UPDATE, decode_error)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_KEY_UPDATE, __func__
, "tls13con.c", 1098); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_KEY_UPDATE
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_KEY_UPDATE
, decode_error); } while (0)
;
1099 return SECFailure;
1100 }
1101
1102 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
1103 return dtls13_HandleKeyUpdate(ss, b, length, update);
1104 }
1105
1106 rv = tls13_UpdateTrafficKeys(ss, ssl_secret_read);
1107 if (rv != SECSuccess) {
1108 return SECFailure; /* Error code set by tls13_UpdateTrafficKeys. */
1109 }
1110
1111 if (update == update_requested) {
1112 PRBool sendUpdate;
1113 if (ss->ssl3.clientCertRequested) {
1114 /* Post-handshake auth is in progress; defer sending a key update. */
1115 ss->ssl3.hs.keyUpdateDeferred = PR_TRUE1;
1116 ss->ssl3.hs.deferredKeyUpdateRequest = update_not_requested;
1117 sendUpdate = PR_FALSE0;
1118 } else if (ss->ssl3.peerRequestedKeyUpdate) {
1119 /* Only send an update if we have sent with the current spec. This
1120 * prevents us from being forced to crank forward pointlessly. */
1121 ssl_GetSpecReadLock(ss){ if (!ss->opt.noLocks) NSSRWLock_LockRead_Util((ss)->specLock
); }
;
1122 sendUpdate = ss->ssl3.cwSpec->nextSeqNum > 0;
1123 ssl_ReleaseSpecReadLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockRead_Util((ss)->
specLock); }
;
1124 } else {
1125 sendUpdate = PR_TRUE1;
1126 }
1127 if (sendUpdate) {
1128 /* Respond immediately (don't buffer). */
1129 rv = tls13_SendKeyUpdate(ss, update_not_requested, PR_FALSE0);
1130 if (rv != SECSuccess) {
1131 return SECFailure; /* Error already set. */
1132 }
1133 }
1134 ss->ssl3.peerRequestedKeyUpdate = PR_TRUE1;
1135 }
1136
1137 return SECSuccess;
1138}
1139
1140SECStatus
1141SSLExp_SendCertificateRequest(PRFileDesc *fd)
1142{
1143 SECStatus rv;
1144 sslSocket *ss = ssl_FindSocket(fd);
1145 if (!ss) {
1146 return SECFailure;
1147 }
1148
1149 /* Not supported. */
1150 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
1151 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_VERSION);
1152 return SECFailure;
1153 }
1154
1155 if (!tls13_IsPostHandshake(ss)) {
1156 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
1157 return SECFailure;
1158 }
1159
1160 if (ss->ssl3.clientCertRequested) {
1161 PORT_SetErrorPORT_SetError_Util(PR_WOULD_BLOCK_ERROR(-5998L));
1162 return SECFailure;
1163 }
1164
1165 /* Disallow a CertificateRequest if this connection uses an external PSK. */
1166 if (ss->sec.authType == ssl_auth_psk) {
1167 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_FEATURE_DISABLED);
1168 return SECFailure;
1169 }
1170
1171 rv = TLS13_CHECK_HS_STATE(ss, SEC_ERROR_INVALID_ARGS,tls13_CheckHsState(ss, SEC_ERROR_INVALID_ARGS, "SEC_ERROR_INVALID_ARGS"
, __func__, "tls13con.c", 1172, idle_handshake, wait_invalid)
1172 idle_handshake)tls13_CheckHsState(ss, SEC_ERROR_INVALID_ARGS, "SEC_ERROR_INVALID_ARGS"
, __func__, "tls13con.c", 1172, idle_handshake, wait_invalid)
;
1173 if (rv != SECSuccess) {
1174 return SECFailure;
1175 }
1176
1177 if (!ssl3_ExtensionNegotiated(ss, ssl_tls13_post_handshake_auth_xtn)) {
1178 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_MISSING_POST_HANDSHAKE_AUTH_EXTENSION);
1179 return SECFailure;
1180 }
1181
1182 ssl_GetSSL3HandshakeLock(ss){ if (!ss->opt.noLocks) { ((!((PR_GetMonitorEntryCount(((ss
)->xmitBufLock)) > 0)))?((void)0):PR_Assert("!ssl_HaveXmitBufLock(ss)"
,"tls13con.c",1182)); PR_EnterMonitor(((ss)->ssl3HandshakeLock
)); } }
;
1183
1184 rv = tls13_SendCertificateRequest(ss);
1185 if (rv == SECSuccess) {
1186 ssl_GetXmitBufLock(ss){ if (!ss->opt.noLocks) PR_EnterMonitor(((ss)->xmitBufLock
)); }
;
1187 rv = ssl3_FlushHandshake(ss, 0);
1188 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
;
1189 ss->ssl3.clientCertRequested = PR_TRUE1;
1190 }
1191
1192 ssl_ReleaseSSL3HandshakeLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->ssl3HandshakeLock
)); }
;
1193 return rv;
1194}
1195
1196SECStatus
1197tls13_HandlePostHelloHandshakeMessage(sslSocket *ss, PRUint8 *b, PRUint32 length)
1198{
1199 if (ss->sec.isServer && ss->ssl3.hs.zeroRttIgnore != ssl_0rtt_ignore_none) {
1200 SSL_TRC(3, ("%d: TLS13[%d]: successfully decrypted handshake after "if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: successfully decrypted handshake after "
"failed 0-RTT", getpid(), ss->fd)
1201 "failed 0-RTT",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: successfully decrypted handshake after "
"failed 0-RTT", getpid(), ss->fd)
1202 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: successfully decrypted handshake after "
"failed 0-RTT", getpid(), ss->fd)
;
1203 ss->ssl3.hs.zeroRttIgnore = ssl_0rtt_ignore_none;
1204 }
1205
1206 /* TODO(ekr@rtfm.com): Would it be better to check all the states here? */
1207 switch (ss->ssl3.hs.msg_type) {
1208 case ssl_hs_certificate:
1209 return tls13_HandleCertificate(ss, b, length, PR_FALSE0);
1210 case ssl_hs_compressed_certificate:
1211 return tls13_HandleCertificateDecode(ss, b, length);
1212 case ssl_hs_certificate_request:
1213 return tls13_HandleCertificateRequest(ss, b, length);
1214
1215 case ssl_hs_certificate_verify:
1216 return tls13_HandleCertificateVerify(ss, b, length);
1217
1218 case ssl_hs_encrypted_extensions:
1219 return tls13_HandleEncryptedExtensions(ss, b, length);
1220
1221 case ssl_hs_new_session_ticket:
1222 return tls13_HandleNewSessionTicket(ss, b, length);
1223
1224 case ssl_hs_finished:
1225 if (ss->sec.isServer) {
1226 return tls13_ServerHandleFinished(ss, b, length);
1227 } else {
1228 return tls13_ClientHandleFinished(ss, b, length);
1229 }
1230
1231 case ssl_hs_end_of_early_data:
1232 return tls13_HandleEndOfEarlyData(ss, b, length);
1233
1234 case ssl_hs_key_update:
1235 return tls13_HandleKeyUpdate(ss, b, length);
1236
1237 default:
1238 FATAL_ERROR(ss, SSL_ERROR_RX_UNKNOWN_HANDSHAKE, 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_UNKNOWN_HANDSHAKE, __func__
, "tls13con.c", 1238); PORT_SetError_Util(SSL_ERROR_RX_UNKNOWN_HANDSHAKE
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_UNKNOWN_HANDSHAKE
, unexpected_message); } while (0)
;
1239 return SECFailure;
1240 }
1241
1242 PORT_Assert(0)((0)?((void)0):PR_Assert("0","tls13con.c",1242)); /* Unreached */
1243 return SECFailure;
1244}
1245
1246static SECStatus
1247tls13_RecoverWrappedSharedSecret(sslSocket *ss, sslSessionID *sid)
1248{
1249 PK11SymKey *wrapKey; /* wrapping key */
1250 SECItem wrappedMS = { siBuffer, NULL((void*)0), 0 };
1251 SSLHashType hashType;
1252
1253 SSL_TRC(3, ("%d: TLS13[%d]: recovering static secret (%s)",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: recovering static secret (%s)"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
))
1254 SSL_GETPID(), ss->fd, SSL_ROLE(ss)))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: recovering static secret (%s)"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
))
;
1255
1256 /* Now find the hash used as the PRF for the previous handshake. */
1257 hashType = tls13_GetHashForCipherSuite(sid->u.ssl3.cipherSuite);
1258
1259 /* If we are the server, we compute the wrapping key, but if we
1260 * are the client, its coordinates are stored with the ticket. */
1261 if (ss->sec.isServer) {
1262 wrapKey = ssl3_GetWrappingKey(ss, NULL((void*)0),
1263 sid->u.ssl3.masterWrapMech,
1264 ss->pkcs11PinArg);
1265 } else {
1266 PK11SlotInfo *slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
1267 sid->u.ssl3.masterSlotID);
1268 if (!slot)
1269 return SECFailure;
1270
1271 wrapKey = PK11_GetWrapKey(slot,
1272 sid->u.ssl3.masterWrapIndex,
1273 sid->u.ssl3.masterWrapMech,
1274 sid->u.ssl3.masterWrapSeries,
1275 ss->pkcs11PinArg);
1276 PK11_FreeSlot(slot);
1277 }
1278 if (!wrapKey) {
1279 return SECFailure;
1280 }
1281
1282 wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
1283 wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len;
1284
1285 PK11SymKey *unwrappedPsk = ssl_unwrapSymKey(wrapKey, sid->u.ssl3.masterWrapMech,
1286 NULL((void*)0), &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE0x00000371UL,
1287 CKA_DERIVE0x0000010CUL, tls13_GetHashSizeForHash(hashType),
1288 CKF_SIGN0x00000800UL | CKF_VERIFY0x00002000, ss->pkcs11PinArg);
1289 PK11_FreeSymKey(wrapKey);
1290 if (!unwrappedPsk) {
1291 return SECFailure;
1292 }
1293 sslPsk *rpsk = tls13_MakePsk(unwrappedPsk, ssl_psk_resume, hashType, NULL((void*)0));
1294 if (!rpsk) {
1295 PK11_FreeSymKey(unwrappedPsk);
1296 return SECFailure;
1297 }
1298 if (sid->u.ssl3.locked.sessionTicket.flags & ticket_allow_early_data) {
1299 rpsk->maxEarlyData = sid->u.ssl3.locked.sessionTicket.max_early_data_size;
1300 rpsk->zeroRttSuite = sid->u.ssl3.cipherSuite;
1301 }
1302 PRINT_KEY(50, (ss, "Recovered RMS", rpsk->key))if (ssl_trace >= (50)) ssl_PrintKey (ss, "Recovered RMS", rpsk
->key)
;
1303 PORT_Assert(PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks) ||((((&ss->ssl3.hs.psks)->next == (&ss->ssl3.hs
.psks)) || ((sslPsk *)(&ss->ssl3.hs.psks)->next)->
type != ssl_psk_resume)?((void)0):PR_Assert("PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks) || ((sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks))->type != ssl_psk_resume"
,"tls13con.c",1304))
1304 ((sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks))->type != ssl_psk_resume)((((&ss->ssl3.hs.psks)->next == (&ss->ssl3.hs
.psks)) || ((sslPsk *)(&ss->ssl3.hs.psks)->next)->
type != ssl_psk_resume)?((void)0):PR_Assert("PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks) || ((sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks))->type != ssl_psk_resume"
,"tls13con.c",1304))
;
1305
1306 if (ss->sec.isServer) {
1307 /* In server, we couldn't select the RPSK in the extension handler
1308 * since it was not unwrapped yet. We're committed now, so select
1309 * it and add it to the list (to ensure it is freed). */
1310 ss->xtnData.selectedPsk = rpsk;
1311 }
1312 PR_APPEND_LINK(&rpsk->link, &ss->ssl3.hs.psks)do { (&rpsk->link)->next = (&ss->ssl3.hs.psks
); (&rpsk->link)->prev = (&ss->ssl3.hs.psks)
->prev; (&ss->ssl3.hs.psks)->prev->next = (&
rpsk->link); (&ss->ssl3.hs.psks)->prev = (&rpsk
->link); } while (0)
;
1313
1314 return SECSuccess;
1315}
1316
1317/* Key Derivation Functions.
1318 *
1319 * 0
1320 * |
1321 * v
1322 * PSK -> HKDF-Extract = Early Secret
1323 * |
1324 * +-----> Derive-Secret(., "ext binder" | "res binder", "")
1325 * | = binder_key
1326 * |
1327 * +-----> Derive-Secret(., "c e traffic",
1328 * | ClientHello)
1329 * | = client_early_traffic_secret
1330 * |
1331 * +-----> Derive-Secret(., "e exp master",
1332 * | ClientHello)
1333 * | = early_exporter_secret
1334 * v
1335 * Derive-Secret(., "derived", "")
1336 * |
1337 * v
1338 *(EC)DHE -> HKDF-Extract = Handshake Secret
1339 * |
1340 * +-----> Derive-Secret(., "c hs traffic",
1341 * | ClientHello...ServerHello)
1342 * | = client_handshake_traffic_secret
1343 * |
1344 * +-----> Derive-Secret(., "s hs traffic",
1345 * | ClientHello...ServerHello)
1346 * | = server_handshake_traffic_secret
1347 * v
1348 * Derive-Secret(., "derived", "")
1349 * |
1350 * v
1351 * 0 -> HKDF-Extract = Master Secret
1352 * |
1353 * +-----> Derive-Secret(., "c ap traffic",
1354 * | ClientHello...Server Finished)
1355 * | = client_traffic_secret_0
1356 * |
1357 * +-----> Derive-Secret(., "s ap traffic",
1358 * | ClientHello...Server Finished)
1359 * | = server_traffic_secret_0
1360 * |
1361 * +-----> Derive-Secret(., "exp master",
1362 * | ClientHello...Server Finished)
1363 * | = exporter_secret
1364 * |
1365 * +-----> Derive-Secret(., "res master",
1366 * ClientHello...Client Finished)
1367 * = resumption_master_secret
1368 *
1369 */
1370static SECStatus
1371tls13_ComputeEarlySecretsWithPsk(sslSocket *ss)
1372{
1373 SECStatus rv;
1374
1375 SSL_TRC(5, ("%d: TLS13[%d]: compute early secrets (%s)",if (ssl_trace >= (5)) ssl_Trace ("%d: TLS13[%d]: compute early secrets (%s)"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
))
1376 SSL_GETPID(), ss->fd, SSL_ROLE(ss)))if (ssl_trace >= (5)) ssl_Trace ("%d: TLS13[%d]: compute early secrets (%s)"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
))
;
1377
1378 PORT_Assert(!ss->ssl3.hs.currentSecret)((!ss->ssl3.hs.currentSecret)?((void)0):PR_Assert("!ss->ssl3.hs.currentSecret"
,"tls13con.c",1378))
;
1379 sslPsk *psk = NULL((void*)0);
1380
1381 if (ss->sec.isServer) {
1382 psk = ss->xtnData.selectedPsk;
1383 } else {
1384 /* Client to use the first PSK for early secrets. */
1385 PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks))((!((&ss->ssl3.hs.psks)->next == (&ss->ssl3.
hs.psks)))?((void)0):PR_Assert("!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks)"
,"tls13con.c",1385))
;
1386 psk = (sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks)(&ss->ssl3.hs.psks)->next;
1387 }
1388 PORT_Assert(psk && psk->key)((psk && psk->key)?((void)0):PR_Assert("psk && psk->key"
,"tls13con.c",1388))
;
1389 PORT_Assert(psk->hash != ssl_hash_none)((psk->hash != ssl_hash_none)?((void)0):PR_Assert("psk->hash != ssl_hash_none"
,"tls13con.c",1389))
;
1390
1391 PK11SymKey *earlySecret = NULL((void*)0);
1392 rv = tls13_HkdfExtract(NULL((void*)0), psk->key, psk->hash, &earlySecret);
1393 if (rv != SECSuccess) {
1394 return SECFailure;
1395 }
1396
1397 /* No longer need the raw input key */
1398 PK11_FreeSymKey(psk->key);
1399 psk->key = NULL((void*)0);
1400 const char *label = (psk->type == ssl_psk_resume) ? kHkdfLabelResPskBinderKey : kHkdfLabelExtPskBinderKey;
1401 rv = tls13_DeriveSecretNullHash(ss, earlySecret,
1402 label, strlen(label),
1403 &psk->binderKey, psk->hash);
1404 if (rv != SECSuccess) {
1405 PK11_FreeSymKey(earlySecret);
1406 return SECFailure;
1407 }
1408 ss->ssl3.hs.currentSecret = earlySecret;
1409
1410 return SECSuccess;
1411}
1412
1413/* This derives the early traffic and early exporter secrets. */
1414static SECStatus
1415tls13_DeriveEarlySecrets(sslSocket *ss)
1416{
1417 SECStatus rv;
1418 PORT_Assert(ss->ssl3.hs.currentSecret)((ss->ssl3.hs.currentSecret)?((void)0):PR_Assert("ss->ssl3.hs.currentSecret"
,"tls13con.c",1418))
;
1419 rv = tls13_DeriveSecretWrap(ss, ss->ssl3.hs.currentSecret,
1420 kHkdfLabelClient,
1421 kHkdfLabelEarlyTrafficSecret,
1422 keylogLabelClientEarlyTrafficSecret,
1423 &ss->ssl3.hs.clientEarlyTrafficSecret);
1424 if (rv != SECSuccess) {
1425 return SECFailure;
1426 }
1427
1428 if (ss->secretCallback) {
1429 ss->secretCallback(ss->fd, (PRUint16)TrafficKeyEarlyApplicationData,
1430 ss->sec.isServer ? ssl_secret_read : ssl_secret_write,
1431 ss->ssl3.hs.clientEarlyTrafficSecret,
1432 ss->secretCallbackArg);
1433 }
1434
1435 rv = tls13_DeriveSecretWrap(ss, ss->ssl3.hs.currentSecret,
1436 NULL((void*)0), kHkdfLabelEarlyExporterSecret,
1437 keylogLabelEarlyExporterSecret,
1438 &ss->ssl3.hs.earlyExporterSecret);
1439 if (rv != SECSuccess) {
1440 return SECFailure;
1441 }
1442
1443 return SECSuccess;
1444}
1445
1446static SECStatus
1447tls13_ComputeHandshakeSecret(sslSocket *ss)
1448{
1449 SECStatus rv;
1450 PK11SymKey *derivedSecret = NULL((void*)0);
1451 PK11SymKey *newSecret = NULL((void*)0);
1452 SSL_TRC(5, ("%d: TLS13[%d]: compute handshake secret (%s)",if (ssl_trace >= (5)) ssl_Trace ("%d: TLS13[%d]: compute handshake secret (%s)"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
))
1453 SSL_GETPID(), ss->fd, SSL_ROLE(ss)))if (ssl_trace >= (5)) ssl_Trace ("%d: TLS13[%d]: compute handshake secret (%s)"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
))
;
1454
1455 /* If no PSK, generate the default early secret. */
1456 if (!ss->ssl3.hs.currentSecret) {
1457 PORT_Assert(!ss->xtnData.selectedPsk)((!ss->xtnData.selectedPsk)?((void)0):PR_Assert("!ss->xtnData.selectedPsk"
,"tls13con.c",1457))
;
1458 rv = tls13_HkdfExtract(NULL((void*)0), NULL((void*)0),
1459 tls13_GetHash(ss), &ss->ssl3.hs.currentSecret);
1460 if (rv != SECSuccess) {
1461 return SECFailure;
1462 }
1463 }
1464 PORT_Assert(ss->ssl3.hs.currentSecret)((ss->ssl3.hs.currentSecret)?((void)0):PR_Assert("ss->ssl3.hs.currentSecret"
,"tls13con.c",1464))
;
1465 PORT_Assert(ss->ssl3.hs.dheSecret)((ss->ssl3.hs.dheSecret)?((void)0):PR_Assert("ss->ssl3.hs.dheSecret"
,"tls13con.c",1465))
;
1466
1467 /* Derive-Secret(., "derived", "") */
1468 rv = tls13_DeriveSecretNullHash(ss, ss->ssl3.hs.currentSecret,
1469 kHkdfLabelDerivedSecret,
1470 strlen(kHkdfLabelDerivedSecret),
1471 &derivedSecret, tls13_GetHash(ss));
1472 if (rv != SECSuccess) {
1473 LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE)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__, "tls13con.c"
, 1473); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0)
;
1474 return rv;
1475 }
1476
1477 /* HKDF-Extract(ECDHE, .) = Handshake Secret */
1478 rv = tls13_HkdfExtract(derivedSecret, ss->ssl3.hs.dheSecret,
1479 tls13_GetHash(ss), &newSecret);
1480 PK11_FreeSymKey(derivedSecret);
1481 if (rv != SECSuccess) {
1482 LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE)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__, "tls13con.c"
, 1482); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0)
;
1483 return rv;
1484 }
1485
1486 PK11_FreeSymKey(ss->ssl3.hs.currentSecret);
1487 ss->ssl3.hs.currentSecret = newSecret;
1488 return SECSuccess;
1489}
1490
1491static SECStatus
1492tls13_ComputeHandshakeSecrets(sslSocket *ss)
1493{
1494 SECStatus rv;
1495 PK11SymKey *derivedSecret = NULL((void*)0);
1496 PK11SymKey *newSecret = NULL((void*)0);
1497
1498 PK11_FreeSymKey(ss->ssl3.hs.dheSecret);
1499 ss->ssl3.hs.dheSecret = NULL((void*)0);
1500
1501 SSL_TRC(5, ("%d: TLS13[%d]: compute handshake secrets (%s)",if (ssl_trace >= (5)) ssl_Trace ("%d: TLS13[%d]: compute handshake secrets (%s)"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
))
1502 SSL_GETPID(), ss->fd, SSL_ROLE(ss)))if (ssl_trace >= (5)) ssl_Trace ("%d: TLS13[%d]: compute handshake secrets (%s)"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
))
;
1503
1504 /* Now compute |*HsTrafficSecret| */
1505 rv = tls13_DeriveSecretWrap(ss, ss->ssl3.hs.currentSecret,
1506 kHkdfLabelClient,
1507 kHkdfLabelHandshakeTrafficSecret,
1508 keylogLabelClientHsTrafficSecret,
1509 &ss->ssl3.hs.clientHsTrafficSecret);
1510 if (rv != SECSuccess) {
1511 LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE)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__, "tls13con.c"
, 1511); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0)
;
1512 return rv;
1513 }
1514 rv = tls13_DeriveSecretWrap(ss, ss->ssl3.hs.currentSecret,
1515 kHkdfLabelServer,
1516 kHkdfLabelHandshakeTrafficSecret,
1517 keylogLabelServerHsTrafficSecret,
1518 &ss->ssl3.hs.serverHsTrafficSecret);
1519 if (rv != SECSuccess) {
1520 LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE)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__, "tls13con.c"
, 1520); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0)
;
1521 return rv;
1522 }
1523
1524 if (ss->secretCallback) {
1525 SSLSecretDirection dir =
1526 ss->sec.isServer ? ssl_secret_read : ssl_secret_write;
1527 ss->secretCallback(ss->fd, (PRUint16)TrafficKeyHandshake, dir,
1528 ss->ssl3.hs.clientHsTrafficSecret,
1529 ss->secretCallbackArg);
1530 dir = ss->sec.isServer ? ssl_secret_write : ssl_secret_read;
1531 ss->secretCallback(ss->fd, (PRUint16)TrafficKeyHandshake, dir,
1532 ss->ssl3.hs.serverHsTrafficSecret,
1533 ss->secretCallbackArg);
1534 }
1535
1536 SSL_TRC(5, ("%d: TLS13[%d]: compute master secret (%s)",if (ssl_trace >= (5)) ssl_Trace ("%d: TLS13[%d]: compute master secret (%s)"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
))
1537 SSL_GETPID(), ss->fd, SSL_ROLE(ss)))if (ssl_trace >= (5)) ssl_Trace ("%d: TLS13[%d]: compute master secret (%s)"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
))
;
1538
1539 /* Crank HKDF forward to make master secret, which we
1540 * stuff in current secret. */
1541 rv = tls13_DeriveSecretNullHash(ss, ss->ssl3.hs.currentSecret,
1542 kHkdfLabelDerivedSecret,
1543 strlen(kHkdfLabelDerivedSecret),
1544 &derivedSecret, tls13_GetHash(ss));
1545 if (rv != SECSuccess) {
1546 LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE)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__, "tls13con.c"
, 1546); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0)
;
1547 return rv;
1548 }
1549 rv = tls13_HkdfExtract(derivedSecret,
1550 NULL((void*)0),
1551 tls13_GetHash(ss),
1552 &newSecret);
1553 PK11_FreeSymKey(derivedSecret);
1554 if (rv != SECSuccess) {
1555 LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE)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__, "tls13con.c"
, 1555); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0)
;
1556 return SECFailure;
1557 }
1558 PK11_FreeSymKey(ss->ssl3.hs.currentSecret);
1559 ss->ssl3.hs.currentSecret = newSecret;
1560
1561 return SECSuccess;
1562}
1563
1564static SECStatus
1565tls13_ComputeApplicationSecrets(sslSocket *ss)
1566{
1567 SECStatus rv;
1568
1569 rv = tls13_DeriveSecretWrap(ss, ss->ssl3.hs.currentSecret,
1570 kHkdfLabelClient,
1571 kHkdfLabelApplicationTrafficSecret,
1572 keylogLabelClientTrafficSecret,
1573 &ss->ssl3.hs.clientTrafficSecret);
1574 if (rv != SECSuccess) {
1575 return SECFailure;
1576 }
1577 rv = tls13_DeriveSecretWrap(ss, ss->ssl3.hs.currentSecret,
1578 kHkdfLabelServer,
1579 kHkdfLabelApplicationTrafficSecret,
1580 keylogLabelServerTrafficSecret,
1581 &ss->ssl3.hs.serverTrafficSecret);
1582 if (rv != SECSuccess) {
1583 return SECFailure;
1584 }
1585
1586 if (ss->secretCallback) {
1587 SSLSecretDirection dir =
1588 ss->sec.isServer ? ssl_secret_read : ssl_secret_write;
1589 ss->secretCallback(ss->fd, (PRUint16)TrafficKeyApplicationData,
1590 dir, ss->ssl3.hs.clientTrafficSecret,
1591 ss->secretCallbackArg);
1592 dir = ss->sec.isServer ? ssl_secret_write : ssl_secret_read;
1593 ss->secretCallback(ss->fd, (PRUint16)TrafficKeyApplicationData,
1594 dir, ss->ssl3.hs.serverTrafficSecret,
1595 ss->secretCallbackArg);
1596 }
1597
1598 rv = tls13_DeriveSecretWrap(ss, ss->ssl3.hs.currentSecret,
1599 NULL((void*)0), kHkdfLabelExporterMasterSecret,
1600 keylogLabelExporterSecret,
1601 &ss->ssl3.hs.exporterSecret);
1602 if (rv != SECSuccess) {
1603 return SECFailure;
1604 }
1605
1606 return SECSuccess;
1607}
1608
1609static SECStatus
1610tls13_ComputeFinalSecrets(sslSocket *ss)
1611{
1612 SECStatus rv;
1613
1614 PORT_Assert(!ss->ssl3.crSpec->masterSecret)((!ss->ssl3.crSpec->masterSecret)?((void)0):PR_Assert("!ss->ssl3.crSpec->masterSecret"
,"tls13con.c",1614))
;
1615 PORT_Assert(!ss->ssl3.cwSpec->masterSecret)((!ss->ssl3.cwSpec->masterSecret)?((void)0):PR_Assert("!ss->ssl3.cwSpec->masterSecret"
,"tls13con.c",1615))
;
1616 PORT_Assert(ss->ssl3.hs.currentSecret)((ss->ssl3.hs.currentSecret)?((void)0):PR_Assert("ss->ssl3.hs.currentSecret"
,"tls13con.c",1616))
;
1617 rv = tls13_DeriveSecretWrap(ss, ss->ssl3.hs.currentSecret,
1618 NULL((void*)0), kHkdfLabelResumptionMasterSecret,
1619 NULL((void*)0),
1620 &ss->ssl3.hs.resumptionMasterSecret);
1621 PK11_FreeSymKey(ss->ssl3.hs.currentSecret);
1622 ss->ssl3.hs.currentSecret = NULL((void*)0);
1623 if (rv != SECSuccess) {
1624 return SECFailure;
1625 }
1626
1627 return SECSuccess;
1628}
1629
1630static void
1631tls13_RestoreCipherInfo(sslSocket *ss, sslSessionID *sid)
1632{
1633 /* Set these to match the cached value.
1634 * TODO(ekr@rtfm.com): Make a version with the "true" values.
1635 * Bug 1256137.
1636 */
1637 ss->sec.authType = sid->authType;
1638 ss->sec.authKeyBits = sid->authKeyBits;
1639 ss->sec.originalKeaGroup = ssl_LookupNamedGroup(sid->keaGroup);
1640 ss->sec.signatureScheme = sid->sigScheme;
1641}
1642
1643/* Check whether resumption-PSK is allowed. */
1644static PRBool
1645tls13_CanResume(sslSocket *ss, const sslSessionID *sid)
1646{
1647 const sslServerCert *sc;
1648
1649 if (!sid) {
1650 return PR_FALSE0;
1651 }
1652
1653 if (sid->version != ss->version) {
1654 return PR_FALSE0;
1655 }
1656
1657#ifdef UNSAFE_FUZZER_MODE
1658 /* When fuzzing, sid could contain garbage that will crash tls13_GetHashForCipherSuite.
1659 * Do a direct comparison of cipher suites. This makes us refuse to resume when the
1660 * protocol allows it, but resumption is discretionary anyway. */
1661 if (sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite) {
1662#else
1663 if (tls13_GetHashForCipherSuite(sid->u.ssl3.cipherSuite) != tls13_GetHashForCipherSuite(ss->ssl3.hs.cipher_suite)) {
1664#endif
1665 return PR_FALSE0;
1666 }
1667
1668 /* Server sids don't remember the server cert we previously sent, but they
1669 * do remember the type of certificate we originally used, so we can locate
1670 * it again, provided that the current ssl socket has had its server certs
1671 * configured the same as the previous one. */
1672 sc = ssl_FindServerCert(ss, sid->authType, sid->namedCurve);
1673 if (!sc || !sc->serverCert) {
1674 return PR_FALSE0;
1675 }
1676
1677 return PR_TRUE1;
1678}
1679
1680static PRBool
1681tls13_CanNegotiateZeroRtt(sslSocket *ss, const sslSessionID *sid)
1682{
1683 PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_sent)((ss->ssl3.hs.zeroRttState == ssl_0rtt_sent)?((void)0):PR_Assert
("ss->ssl3.hs.zeroRttState == ssl_0rtt_sent","tls13con.c",
1683))
;
1684 sslPsk *psk = ss->xtnData.selectedPsk;
1685
1686 if (!ss->opt.enable0RttData) {
1687 return PR_FALSE0;
1688 }
1689 if (!psk) {
1690 return PR_FALSE0;
1691 }
1692 if (psk->zeroRttSuite == TLS_NULL_WITH_NULL_NULL0x0000) {
1693 return PR_FALSE0;
1694 }
1695 if (!psk->maxEarlyData) {
1696 return PR_FALSE0;
1697 }
1698 if (ss->ssl3.hs.cipher_suite != psk->zeroRttSuite) {
1699 return PR_FALSE0;
1700 }
1701 if (psk->type == ssl_psk_resume) {
1702 if (!sid) {
1703 return PR_FALSE0;
1704 }
1705 PORT_Assert(sid->u.ssl3.locked.sessionTicket.flags & ticket_allow_early_data)((sid->u.ssl3.locked.sessionTicket.flags & ticket_allow_early_data
)?((void)0):PR_Assert("sid->u.ssl3.locked.sessionTicket.flags & ticket_allow_early_data"
,"tls13con.c",1705))
;
1706 PORT_Assert(ss->statelessResume)((ss->statelessResume)?((void)0):PR_Assert("ss->statelessResume"
,"tls13con.c",1706))
;
1707 if (!ss->statelessResume) {
1708 return PR_FALSE0;
1709 }
1710 if (SECITEM_CompareItemSECITEM_CompareItem_Util(&ss->xtnData.nextProto,
1711 &sid->u.ssl3.alpnSelection) != 0) {
1712 return PR_FALSE0;
1713 }
1714 } else if (psk->type != ssl_psk_external) {
1715 PORT_Assert(0)((0)?((void)0):PR_Assert("0","tls13con.c",1715));
1716 return PR_FALSE0;
1717 }
1718
1719 if (tls13_IsReplay(ss, sid)) {
1720 return PR_FALSE0;
1721 }
1722
1723 return PR_TRUE1;
1724}
1725
1726/* Called from tls13_HandleClientHelloPart2 to update the state of 0-RTT handling.
1727 *
1728 * 0-RTT is only permitted if:
1729 * 1. The early data extension was present.
1730 * 2. We are resuming a session.
1731 * 3. The 0-RTT option is set.
1732 * 4. The ticket allowed 0-RTT.
1733 * 5. We negotiated the same ALPN value as in the ticket.
1734 */
1735static void
1736tls13_NegotiateZeroRtt(sslSocket *ss, const sslSessionID *sid)
1737{
1738 SSL_TRC(3, ("%d: TLS13[%d]: negotiate 0-RTT %p",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: negotiate 0-RTT %p"
, getpid(), ss->fd, sid)
1739 SSL_GETPID(), ss->fd, sid))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: negotiate 0-RTT %p"
, getpid(), ss->fd, sid)
;
1740
1741 /* tls13_ServerHandleEarlyDataXtn sets this to ssl_0rtt_sent, so this will
1742 * be ssl_0rtt_none unless early_data is present. */
1743 if (ss->ssl3.hs.zeroRttState == ssl_0rtt_none) {
1744 return;
1745 }
1746
1747 if (ss->ssl3.hs.zeroRttState == ssl_0rtt_ignored) {
1748 /* HelloRetryRequest causes 0-RTT to be ignored. On the second
1749 * ClientHello, reset the ignore state so that decryption failure is
1750 * handled normally. */
1751 if (ss->ssl3.hs.zeroRttIgnore == ssl_0rtt_ignore_hrr) {
1752 PORT_Assert(ss->ssl3.hs.helloRetry)((ss->ssl3.hs.helloRetry)?((void)0):PR_Assert("ss->ssl3.hs.helloRetry"
,"tls13con.c",1752))
;
1753 ss->ssl3.hs.zeroRttState = ssl_0rtt_none;
1754 ss->ssl3.hs.zeroRttIgnore = ssl_0rtt_ignore_none;
1755 } else {
1756 SSL_TRC(3, ("%d: TLS13[%d]: application ignored 0-RTT",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: application ignored 0-RTT"
, getpid(), ss->fd)
1757 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: application ignored 0-RTT"
, getpid(), ss->fd)
;
1758 }
1759 return;
1760 }
1761
1762 if (!tls13_CanNegotiateZeroRtt(ss, sid)) {
1763 SSL_TRC(3, ("%d: TLS13[%d]: ignore 0-RTT", SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: ignore 0-RTT"
, getpid(), ss->fd)
;
1764 ss->ssl3.hs.zeroRttState = ssl_0rtt_ignored;
1765 ss->ssl3.hs.zeroRttIgnore = ssl_0rtt_ignore_trial;
1766 return;
1767 }
1768
1769 SSL_TRC(3, ("%d: TLS13[%d]: enable 0-RTT", SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: enable 0-RTT"
, getpid(), ss->fd)
;
1770 PORT_Assert(ss->xtnData.selectedPsk)((ss->xtnData.selectedPsk)?((void)0):PR_Assert("ss->xtnData.selectedPsk"
,"tls13con.c",1770))
;
1771 ss->ssl3.hs.zeroRttState = ssl_0rtt_accepted;
1772 ss->ssl3.hs.zeroRttIgnore = ssl_0rtt_ignore_none;
1773 ss->ssl3.hs.zeroRttSuite = ss->ssl3.hs.cipher_suite;
1774 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_0rtt_cipher_suite(1U << 2);
1775}
1776
1777/* Check if the offered group is acceptable. */
1778static PRBool
1779tls13_isGroupAcceptable(const sslNamedGroupDef *offered,
1780 const sslNamedGroupDef *preferredGroup)
1781{
1782 /* We accept epsilon (e) bits around the offered group size. */
1783 const unsigned int e = 2;
1784
1785 PORT_Assert(offered)((offered)?((void)0):PR_Assert("offered","tls13con.c",1785));
1786 PORT_Assert(preferredGroup)((preferredGroup)?((void)0):PR_Assert("preferredGroup","tls13con.c"
,1786))
;
1787
1788 if (offered->bits >= preferredGroup->bits - e &&
1789 offered->bits <= preferredGroup->bits + e) {
1790 return PR_TRUE1;
1791 }
1792
1793 return PR_FALSE0;
1794}
1795
1796/* Find remote key share for given group and return it.
1797 * Returns NULL if no key share is found. */
1798static TLS13KeyShareEntry *
1799tls13_FindKeyShareEntry(sslSocket *ss, const sslNamedGroupDef *group)
1800{
1801 PRCList *cur_p = PR_NEXT_LINK(&ss->xtnData.remoteKeyShares)((&ss->xtnData.remoteKeyShares)->next);
1802 while (cur_p != &ss->xtnData.remoteKeyShares) {
1803 TLS13KeyShareEntry *offer = (TLS13KeyShareEntry *)cur_p;
1804 if (offer->group == group) {
1805 return offer;
1806 }
1807 cur_p = PR_NEXT_LINK(cur_p)((cur_p)->next);
1808 }
1809 return NULL((void*)0);
1810}
1811
1812static SECStatus
1813tls13_NegotiateKeyExchange(sslSocket *ss,
1814 const sslNamedGroupDef **requestedGroup,
1815 TLS13KeyShareEntry **clientShare)
1816{
1817 unsigned int index;
1818 TLS13KeyShareEntry *entry = NULL((void*)0);
1819 const sslNamedGroupDef *preferredGroup = NULL((void*)0);
1820
1821 /* We insist on DHE. */
1822 if (ssl3_ExtensionNegotiated(ss, ssl_tls13_pre_shared_key_xtn)) {
1823 if (!ssl3_ExtensionNegotiated(ss, ssl_tls13_psk_key_exchange_modes_xtn)) {
1824 FATAL_ERROR(ss, SSL_ERROR_MISSING_PSK_KEY_EXCHANGE_MODES,do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_MISSING_PSK_KEY_EXCHANGE_MODES
, __func__, "tls13con.c", 1825); PORT_SetError_Util(SSL_ERROR_MISSING_PSK_KEY_EXCHANGE_MODES
); } while (0); tls13_FatalError(ss, SSL_ERROR_MISSING_PSK_KEY_EXCHANGE_MODES
, missing_extension); } while (0)
1825 missing_extension)do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_MISSING_PSK_KEY_EXCHANGE_MODES
, __func__, "tls13con.c", 1825); PORT_SetError_Util(SSL_ERROR_MISSING_PSK_KEY_EXCHANGE_MODES
); } while (0); tls13_FatalError(ss, SSL_ERROR_MISSING_PSK_KEY_EXCHANGE_MODES
, missing_extension); } while (0)
;
1826 return SECFailure;
1827 }
1828 /* Since the server insists on DHE to provide forward secracy, for
1829 * every other PskKem value but DHE stateless resumption is disabled,
1830 * this includes other specified and GREASE values. */
1831 if (!memchr(ss->xtnData.psk_ke_modes.data, tls13_psk_dh_ke,
1832 ss->xtnData.psk_ke_modes.len)) {
1833 SSL_TRC(3, ("%d: TLS13[%d]: client offered PSK without DH",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: client offered PSK without DH"
, getpid(), ss->fd)
1834 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: client offered PSK without DH"
, getpid(), ss->fd)
;
1835 ss->statelessResume = PR_FALSE0;
1836 }
1837 }
1838
1839 /* Now figure out which key share we like the best out of the
1840 * mutually supported groups, regardless of what the client offered
1841 * for key shares.
1842 */
1843 if (!ssl3_ExtensionNegotiated(ss, ssl_supported_groups_xtn)) {
1844 FATAL_ERROR(ss, SSL_ERROR_MISSING_SUPPORTED_GROUPS_EXTENSION,do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_MISSING_SUPPORTED_GROUPS_EXTENSION
, __func__, "tls13con.c", 1845); PORT_SetError_Util(SSL_ERROR_MISSING_SUPPORTED_GROUPS_EXTENSION
); } while (0); tls13_FatalError(ss, SSL_ERROR_MISSING_SUPPORTED_GROUPS_EXTENSION
, missing_extension); } while (0)
1845 missing_extension)do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_MISSING_SUPPORTED_GROUPS_EXTENSION
, __func__, "tls13con.c", 1845); PORT_SetError_Util(SSL_ERROR_MISSING_SUPPORTED_GROUPS_EXTENSION
); } while (0); tls13_FatalError(ss, SSL_ERROR_MISSING_SUPPORTED_GROUPS_EXTENSION
, missing_extension); } while (0)
;
1846 return SECFailure;
1847 }
1848
1849 SSL_TRC(3, ("%d: TLS13[%d]: selected KE = %s", SSL_GETPID(),if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: selected KE = %s"
, getpid(), ss->fd, ss->statelessResume || ss->xtnData
.selectedPsk ? "PSK + (EC)DHE" : "(EC)DHE")
1850 ss->fd, ss->statelessResume || ss->xtnData.selectedPsk ? "PSK + (EC)DHE" : "(EC)DHE"))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: selected KE = %s"
, getpid(), ss->fd, ss->statelessResume || ss->xtnData
.selectedPsk ? "PSK + (EC)DHE" : "(EC)DHE")
;
1851
1852 /* Find the preferred group and an according client key share available. */
1853 for (index = 0; index < SSL_NAMED_GROUP_COUNT32; ++index) {
1854 /* Continue to the next group if this one is not enabled. */
1855 if (!ss->namedGroupPreferences[index]) {
1856 /* There's a gap in the preferred groups list. Assume this is a group
1857 * that's not supported by the client but preferred by the server. */
1858 if (preferredGroup) {
1859 entry = NULL((void*)0);
1860 break;
1861 }
1862 continue;
1863 }
1864
1865 /* Check if the client sent a key share for this group. */
1866 entry = tls13_FindKeyShareEntry(ss, ss->namedGroupPreferences[index]);
1867
1868 if (preferredGroup) {
1869 /* We already found our preferred group but the group didn't have a share. */
1870 if (entry) {
1871 /* The client sent a key share with group ss->namedGroupPreferences[index] */
1872 if (tls13_isGroupAcceptable(ss->namedGroupPreferences[index],
1873 preferredGroup)) {
1874 /* This is not the preferred group, but it's acceptable */
1875 preferredGroup = ss->namedGroupPreferences[index];
1876 } else {
1877 /* The proposed group is not acceptable. */
1878 entry = NULL((void*)0);
1879 }
1880 }
1881 break;
1882 } else {
1883 /* The first enabled group is the preferred group. */
1884 preferredGroup = ss->namedGroupPreferences[index];
1885 if (entry) {
1886 break;
1887 }
1888 }
1889 }
1890
1891 if (!preferredGroup) {
1892 FATAL_ERROR(ss, SSL_ERROR_NO_CYPHER_OVERLAP, handshake_failure)do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_NO_CYPHER_OVERLAP, __func__,
"tls13con.c", 1892); PORT_SetError_Util(SSL_ERROR_NO_CYPHER_OVERLAP
); } while (0); tls13_FatalError(ss, SSL_ERROR_NO_CYPHER_OVERLAP
, handshake_failure); } while (0)
;
1893 return SECFailure;
1894 }
1895 SSL_TRC(3, ("%d: TLS13[%d]: group = %d", SSL_GETPID(), ss->fd,if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: group = %d"
, getpid(), ss->fd, preferredGroup->name)
1896 preferredGroup->name))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: group = %d"
, getpid(), ss->fd, preferredGroup->name)
;
1897
1898 /* Either provide a share, or provide a group that should be requested in a
1899 * HelloRetryRequest, but not both. */
1900 if (entry) {
1901 PORT_Assert(preferredGroup == entry->group)((preferredGroup == entry->group)?((void)0):PR_Assert("preferredGroup == entry->group"
,"tls13con.c",1901))
;
1902 *clientShare = entry;
1903 *requestedGroup = NULL((void*)0);
1904 } else {
1905 *clientShare = NULL((void*)0);
1906 *requestedGroup = preferredGroup;
1907 }
1908 return SECSuccess;
1909}
1910
1911SECStatus
1912tls13_SelectServerCert(sslSocket *ss)
1913{
1914 PRCList *cursor;
1915 SECStatus rv;
1916
1917 if (!ssl3_ExtensionNegotiated(ss, ssl_signature_algorithms_xtn)) {
1918 FATAL_ERROR(ss, SSL_ERROR_MISSING_SIGNATURE_ALGORITHMS_EXTENSION,do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_MISSING_SIGNATURE_ALGORITHMS_EXTENSION
, __func__, "tls13con.c", 1919); PORT_SetError_Util(SSL_ERROR_MISSING_SIGNATURE_ALGORITHMS_EXTENSION
); } while (0); tls13_FatalError(ss, SSL_ERROR_MISSING_SIGNATURE_ALGORITHMS_EXTENSION
, missing_extension); } while (0)
1919 missing_extension)do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_MISSING_SIGNATURE_ALGORITHMS_EXTENSION
, __func__, "tls13con.c", 1919); PORT_SetError_Util(SSL_ERROR_MISSING_SIGNATURE_ALGORITHMS_EXTENSION
); } while (0); tls13_FatalError(ss, SSL_ERROR_MISSING_SIGNATURE_ALGORITHMS_EXTENSION
, missing_extension); } while (0)
;
1920 return SECFailure;
1921 }
1922
1923 /* This picks the first certificate that has:
1924 * a) the right authentication method, and
1925 * b) the right named curve (EC only)
1926 *
1927 * We might want to do some sort of ranking here later. For now, it's all
1928 * based on what order they are configured in. */
1929 for (cursor = PR_NEXT_LINK(&ss->serverCerts)((&ss->serverCerts)->next);
1930 cursor != &ss->serverCerts;
1931 cursor = PR_NEXT_LINK(cursor)((cursor)->next)) {
1932 sslServerCert *cert = (sslServerCert *)cursor;
1933
1934 if (SSL_CERT_IS_ONLY(cert, ssl_auth_rsa_decrypt)((cert)->authTypes == (1 << (ssl_auth_rsa_decrypt)))) {
1935 continue;
1936 }
1937
1938 rv = ssl_PickSignatureScheme(ss,
1939 cert->serverCert,
1940 cert->serverKeyPair->pubKey,
1941 cert->serverKeyPair->privKey,
1942 ss->xtnData.sigSchemes,
1943 ss->xtnData.numSigSchemes,
1944 PR_FALSE0,
1945 &ss->ssl3.hs.signatureScheme);
1946 if (rv == SECSuccess) {
1947 /* Found one. */
1948 ss->sec.serverCert = cert;
1949
1950 /* If we can use a delegated credential (DC) for authentication in
1951 * the current handshake, then commit to using it now. We'll send a
1952 * DC as an extension and use the DC private key to sign the
1953 * handshake.
1954 *
1955 * This sets the signature scheme to be the signature scheme
1956 * indicated by the DC.
1957 */
1958 rv = tls13_MaybeSetDelegatedCredential(ss);
1959 if (rv != SECSuccess) {
1960 return SECFailure; /* Failure indicates an internal error. */
1961 }
1962
1963 ss->sec.authType = ss->ssl3.hs.kea_def_mutable.authKeyType =
1964 ssl_SignatureSchemeToAuthType(ss->ssl3.hs.signatureScheme);
1965 ss->sec.authKeyBits = cert->serverKeyBits;
1966 return SECSuccess;
1967 }
1968 }
1969
1970 FATAL_ERROR(ss, SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM,do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM
, __func__, "tls13con.c", 1971); PORT_SetError_Util(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM
); } while (0); tls13_FatalError(ss, SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM
, handshake_failure); } while (0)
1971 handshake_failure)do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM
, __func__, "tls13con.c", 1971); PORT_SetError_Util(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM
); } while (0); tls13_FatalError(ss, SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM
, handshake_failure); } while (0)
;
1972 return SECFailure;
1973}
1974
1975/* Note: |requestedGroup| is non-NULL when we send a key_share extension. */
1976static SECStatus
1977tls13_MaybeSendHelloRetry(sslSocket *ss, const sslNamedGroupDef *requestedGroup,
1978 PRBool *hrrSent)
1979{
1980 SSLHelloRetryRequestAction action = ssl_hello_retry_accept;
1981 PRUint8 token[256] = { 0 };
1982 unsigned int tokenLen = 0;
1983 SECStatus rv;
1984
1985 if (ss->hrrCallback) {
1986 action = ss->hrrCallback(!ss->ssl3.hs.helloRetry,
1987 ss->xtnData.applicationToken.data,
1988 ss->xtnData.applicationToken.len,
1989 token, &tokenLen, sizeof(token),
1990 ss->hrrCallbackArg);
1991 }
1992
1993 /* These use SSL3_SendAlert directly to avoid an assertion in
1994 * tls13_FatalError(), which is ordinarily OK. */
1995 if (action == ssl_hello_retry_request && ss->ssl3.hs.helloRetry) {
1996 (void)SSL3_SendAlert(ss, alert_fatal, internal_error);
1997 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_APP_CALLBACK_ERROR);
1998 return SECFailure;
1999 }
2000
2001 if (action != ssl_hello_retry_request && tokenLen) {
2002 (void)SSL3_SendAlert(ss, alert_fatal, internal_error);
2003 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_APP_CALLBACK_ERROR);
2004 return SECFailure;
2005 }
2006
2007 if (tokenLen > sizeof(token)) {
2008 (void)SSL3_SendAlert(ss, alert_fatal, internal_error);
2009 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_APP_CALLBACK_ERROR);
2010 return SECFailure;
2011 }
2012
2013 if (action == ssl_hello_retry_fail) {
2014 FATAL_ERROR(ss, SSL_ERROR_APPLICATION_ABORT, handshake_failure)do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_APPLICATION_ABORT, __func__,
"tls13con.c", 2014); PORT_SetError_Util(SSL_ERROR_APPLICATION_ABORT
); } while (0); tls13_FatalError(ss, SSL_ERROR_APPLICATION_ABORT
, handshake_failure); } while (0)
;
2015 return SECFailure;
2016 }
2017
2018 if (action == ssl_hello_retry_reject_0rtt) {
2019 ss->ssl3.hs.zeroRttState = ssl_0rtt_ignored;
2020 ss->ssl3.hs.zeroRttIgnore = ssl_0rtt_ignore_trial;
2021 }
2022
2023 if (!requestedGroup && action != ssl_hello_retry_request) {
2024 return SECSuccess;
2025 }
2026
2027 rv = tls13_SendHelloRetryRequest(ss, requestedGroup, token, tokenLen);
2028 if (rv != SECSuccess) {
2029 return SECFailure; /* Code already set. */
2030 }
2031
2032 /* We may have received ECH, but have to start over with CH2. */
2033 ss->ssl3.hs.echAccepted = PR_FALSE0;
2034 PK11_HPKE_DestroyContext(ss->ssl3.hs.echHpkeCtx, PR_TRUE1);
2035 ss->ssl3.hs.echHpkeCtx = NULL((void*)0);
2036
2037 *hrrSent = PR_TRUE1;
2038 return SECSuccess;
2039}
2040
2041static SECStatus
2042tls13_NegotiateAuthentication(sslSocket *ss)
2043{
2044 if (ss->statelessResume) {
2045 SSL_TRC(3, ("%d: TLS13[%d]: selected resumption PSK authentication",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: selected resumption PSK authentication"
, getpid(), ss->fd)
2046 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: selected resumption PSK authentication"
, getpid(), ss->fd)
;
2047 ss->ssl3.hs.signatureScheme = ssl_sig_none;
2048 ss->ssl3.hs.kea_def_mutable.authKeyType = ssl_auth_psk;
2049 /* Overwritten by tls13_RestoreCipherInfo. */
2050 ss->sec.authType = ssl_auth_psk;
2051 return SECSuccess;
2052 } else if (ss->xtnData.selectedPsk) {
2053 /* If the EPSK doesn't specify a suite, use what was negotiated.
2054 * Else, only use the EPSK if we negotiated that suite. */
2055 if (ss->xtnData.selectedPsk->zeroRttSuite == TLS_NULL_WITH_NULL_NULL0x0000 ||
2056 ss->ssl3.hs.cipher_suite == ss->xtnData.selectedPsk->zeroRttSuite) {
2057 SSL_TRC(3, ("%d: TLS13[%d]: selected external PSK authentication",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: selected external PSK authentication"
, getpid(), ss->fd)
2058 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: selected external PSK authentication"
, getpid(), ss->fd)
;
2059 ss->ssl3.hs.signatureScheme = ssl_sig_none;
2060 ss->ssl3.hs.kea_def_mutable.authKeyType = ssl_auth_psk;
2061 ss->sec.authType = ssl_auth_psk;
2062 return SECSuccess;
2063 }
2064 }
2065
2066 /* If there were PSKs, they are no longer needed. */
2067 if (ss->xtnData.selectedPsk) {
2068 tls13_DestroyPskList(&ss->ssl3.hs.psks);
2069 ss->xtnData.selectedPsk = NULL((void*)0);
2070 }
2071
2072 SSL_TRC(3, ("%d: TLS13[%d]: selected certificate authentication",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: selected certificate authentication"
, getpid(), ss->fd)
2073 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: selected certificate authentication"
, getpid(), ss->fd)
;
2074 SECStatus rv = tls13_SelectServerCert(ss);
2075 if (rv != SECSuccess) {
2076 return SECFailure;
2077 }
2078 return SECSuccess;
2079}
2080/* Called from ssl3_HandleClientHello after we have parsed the
2081 * ClientHello and are sure that we are going to do TLS 1.3
2082 * or fail. */
2083SECStatus
2084tls13_HandleClientHelloPart2(sslSocket *ss,
2085 const SECItem *suites,
2086 sslSessionID *sid,
2087 const PRUint8 *msg,
2088 unsigned int len)
2089{
2090 SECStatus rv;
2091 SSL3Statistics *ssl3stats = SSL_GetStatistics();
2092 const sslNamedGroupDef *requestedGroup = NULL((void*)0);
2093 TLS13KeyShareEntry *clientShare = NULL((void*)0);
2094 ssl3CipherSuite previousCipherSuite = 0;
2095 const sslNamedGroupDef *previousGroup = NULL((void*)0);
2096 PRBool hrr = PR_FALSE0;
2097 PRBool previousOfferedEch;
2098
2099 /* If the legacy_version field is set to 0x300 or smaller,
2100 * reject the connection with protocol_version alert. */
2101 if (ss->clientHelloVersion <= SSL_LIBRARY_VERSION_3_00x0300) {
2102 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, 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_RX_MALFORMED_CLIENT_HELLO, __func__
, "tls13con.c", 2102); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO
, protocol_version); } while (0)
;
2103 goto loser;
2104 }
2105
2106 ss->ssl3.hs.endOfFlight = PR_TRUE1;
2107
2108 if (ssl3_ExtensionNegotiated(ss, ssl_tls13_early_data_xtn)) {
2109 ss->ssl3.hs.zeroRttState = ssl_0rtt_sent;
2110 }
2111
2112 /* Negotiate cipher suite. */
2113 rv = ssl3_NegotiateCipherSuite(ss, suites, PR_FALSE0);
2114 if (rv != SECSuccess) {
2115 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__, "tls13con.c"
, 2115); PORT_SetError_Util(PORT_GetError_Util()); } while (0
); tls13_FatalError(ss, PORT_GetError_Util(), handshake_failure
); } while (0)
;
2116 goto loser;
2117 }
2118
2119 /* If we are going around again, then we should make sure that the cipher
2120 * suite selection doesn't change. That's a sign of client shennanigans. */
2121 if (ss->ssl3.hs.helloRetry) {
2122
2123 /* Update sequence numbers before checking the cookie so that any alerts
2124 * we generate are sent with the right sequence numbers. */
2125 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
2126 /* Count the first ClientHello and the HelloRetryRequest. */
2127 ss->ssl3.hs.sendMessageSeq = 1;
2128 ss->ssl3.hs.recvMessageSeq = 1;
2129 ssl_GetSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_LockWrite_Util((ss)->
specLock); }
;
2130 /* Increase the write sequence number. The read sequence number
2131 * will be reset after this to early data or handshake. */
2132 ss->ssl3.cwSpec->nextSeqNum = 1;
2133 ssl_ReleaseSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockWrite_Util((ss)->
specLock); }
;
2134 }
2135
2136 if (!ssl3_ExtensionNegotiated(ss, ssl_tls13_cookie_xtn) ||
2137 !ss->xtnData.cookie.len) {
2138 FATAL_ERROR(ss, SSL_ERROR_MISSING_COOKIE_EXTENSION,do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_MISSING_COOKIE_EXTENSION, __func__
, "tls13con.c", 2139); PORT_SetError_Util(SSL_ERROR_MISSING_COOKIE_EXTENSION
); } while (0); tls13_FatalError(ss, SSL_ERROR_MISSING_COOKIE_EXTENSION
, missing_extension); } while (0)
2139 missing_extension)do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_MISSING_COOKIE_EXTENSION, __func__
, "tls13con.c", 2139); PORT_SetError_Util(SSL_ERROR_MISSING_COOKIE_EXTENSION
); } while (0); tls13_FatalError(ss, SSL_ERROR_MISSING_COOKIE_EXTENSION
, missing_extension); } while (0)
;
2140 goto loser;
2141 }
2142 PRINT_BUF(50, (ss, "Client sent cookie",if (ssl_trace >= (50)) ssl_PrintBuf (ss, "Client sent cookie"
, ss->xtnData.cookie.data, ss->xtnData.cookie.len)
2143 ss->xtnData.cookie.data, ss->xtnData.cookie.len))if (ssl_trace >= (50)) ssl_PrintBuf (ss, "Client sent cookie"
, ss->xtnData.cookie.data, ss->xtnData.cookie.len)
;
2144
2145 rv = tls13_HandleHrrCookie(ss, ss->xtnData.cookie.data,
2146 ss->xtnData.cookie.len,
2147 &previousCipherSuite,
2148 &previousGroup,
2149 &previousOfferedEch, NULL((void*)0), PR_TRUE1);
2150
2151 if (rv != SECSuccess) {
2152 FATAL_ERROR(ss, SSL_ERROR_BAD_2ND_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_BAD_2ND_CLIENT_HELLO, __func__
, "tls13con.c", 2152); PORT_SetError_Util(SSL_ERROR_BAD_2ND_CLIENT_HELLO
); } while (0); tls13_FatalError(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO
, illegal_parameter); } while (0)
;
2153 goto loser;
2154 }
2155 }
2156
2157 /* Now merge the ClientHello into the hash state. */
2158 rv = ssl_HashHandshakeMessage(ss, ssl_hs_client_hello, msg, len);
2159 if (rv != SECSuccess) {
2160 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__, "tls13con.c"
, 2160); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0); tls13_FatalError(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error
); } while (0)
;
2161 goto loser;
2162 }
2163
2164 /* Now create a synthetic kea_def that we can tweak. */
2165 ss->ssl3.hs.kea_def_mutable = *ss->ssl3.hs.kea_def;
2166 ss->ssl3.hs.kea_def = &ss->ssl3.hs.kea_def_mutable;
2167
2168 /* Note: We call this quite a bit earlier than with TLS 1.2 and
2169 * before. */
2170 rv = ssl3_ServerCallSNICallback(ss);
2171 if (rv != SECSuccess) {
2172 goto loser; /* An alert has already been sent. */
2173 }
2174
2175 /* Check if we could in principle resume. */
2176 if (ss->statelessResume) {
2177 PORT_Assert(sid)((sid)?((void)0):PR_Assert("sid","tls13con.c",2177));
2178 if (!sid) {
2179 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__, "tls13con.c"
, 2179); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0); tls13_FatalError(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error
); } while (0)
;
2180 return SECFailure;
2181 }
2182 if (!tls13_CanResume(ss, sid)) {
2183 ss->statelessResume = PR_FALSE0;
2184 }
2185 }
2186
2187 /* Select key exchange. */
2188 rv = tls13_NegotiateKeyExchange(ss, &requestedGroup, &clientShare);
2189 if (rv != SECSuccess) {
2190 goto loser;
2191 }
2192 /* We should get either one of these, but not both. */
2193 PORT_Assert((requestedGroup && !clientShare) ||(((requestedGroup && !clientShare) || (!requestedGroup
&& clientShare))?((void)0):PR_Assert("(requestedGroup && !clientShare) || (!requestedGroup && clientShare)"
,"tls13con.c",2194))
2194 (!requestedGroup && clientShare))(((requestedGroup && !clientShare) || (!requestedGroup
&& clientShare))?((void)0):PR_Assert("(requestedGroup && !clientShare) || (!requestedGroup && clientShare)"
,"tls13con.c",2194))
;
2195
2196 /* After HelloRetryRequest, check consistency of cipher and group. */
2197 if (ss->ssl3.hs.helloRetry) {
2198 PORT_Assert(previousCipherSuite)((previousCipherSuite)?((void)0):PR_Assert("previousCipherSuite"
,"tls13con.c",2198))
;
2199 if (ss->ssl3.hs.cipher_suite != previousCipherSuite) {
2200 FATAL_ERROR(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO,do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_BAD_2ND_CLIENT_HELLO, __func__
, "tls13con.c", 2201); PORT_SetError_Util(SSL_ERROR_BAD_2ND_CLIENT_HELLO
); } while (0); tls13_FatalError(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO
, illegal_parameter); } while (0)
2201 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_BAD_2ND_CLIENT_HELLO, __func__
, "tls13con.c", 2201); PORT_SetError_Util(SSL_ERROR_BAD_2ND_CLIENT_HELLO
); } while (0); tls13_FatalError(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO
, illegal_parameter); } while (0)
;
2202 goto loser;
2203 }
2204 if (!clientShare) {
2205 FATAL_ERROR(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO,do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_BAD_2ND_CLIENT_HELLO, __func__
, "tls13con.c", 2206); PORT_SetError_Util(SSL_ERROR_BAD_2ND_CLIENT_HELLO
); } while (0); tls13_FatalError(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO
, illegal_parameter); } while (0)
2206 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_BAD_2ND_CLIENT_HELLO, __func__
, "tls13con.c", 2206); PORT_SetError_Util(SSL_ERROR_BAD_2ND_CLIENT_HELLO
); } while (0); tls13_FatalError(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO
, illegal_parameter); } while (0)
;
2207 goto loser;
2208 }
2209
2210 /* CH1/CH2 must either both include ECH, or both exclude it. */
2211 if (previousOfferedEch != (ss->xtnData.ech != NULL((void*)0))) {
2212 FATAL_ERROR(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO,do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_BAD_2ND_CLIENT_HELLO, __func__
, "tls13con.c", 2213); PORT_SetError_Util(SSL_ERROR_BAD_2ND_CLIENT_HELLO
); } while (0); tls13_FatalError(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO
, previousOfferedEch ? missing_extension : illegal_parameter)
; } while (0)
2213 previousOfferedEch ? missing_extension : 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_BAD_2ND_CLIENT_HELLO, __func__
, "tls13con.c", 2213); PORT_SetError_Util(SSL_ERROR_BAD_2ND_CLIENT_HELLO
); } while (0); tls13_FatalError(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO
, previousOfferedEch ? missing_extension : illegal_parameter)
; } while (0)
;
2214 goto loser;
2215 }
2216
2217 /* If we requested a new key share, check that the client provided just
2218 * one of the right type. */
2219 if (previousGroup) {
2220 if (PR_PREV_LINK(&ss->xtnData.remoteKeyShares)((&ss->xtnData.remoteKeyShares)->prev) !=
2221 PR_NEXT_LINK(&ss->xtnData.remoteKeyShares)((&ss->xtnData.remoteKeyShares)->next)) {
2222 FATAL_ERROR(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO,do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_BAD_2ND_CLIENT_HELLO, __func__
, "tls13con.c", 2223); PORT_SetError_Util(SSL_ERROR_BAD_2ND_CLIENT_HELLO
); } while (0); tls13_FatalError(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO
, illegal_parameter); } while (0)
2223 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_BAD_2ND_CLIENT_HELLO, __func__
, "tls13con.c", 2223); PORT_SetError_Util(SSL_ERROR_BAD_2ND_CLIENT_HELLO
); } while (0); tls13_FatalError(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO
, illegal_parameter); } while (0)
;
2224 goto loser;
2225 }
2226 if (clientShare->group != previousGroup) {
2227 FATAL_ERROR(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO,do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_BAD_2ND_CLIENT_HELLO, __func__
, "tls13con.c", 2228); PORT_SetError_Util(SSL_ERROR_BAD_2ND_CLIENT_HELLO
); } while (0); tls13_FatalError(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO
, illegal_parameter); } while (0)
2228 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_BAD_2ND_CLIENT_HELLO, __func__
, "tls13con.c", 2228); PORT_SetError_Util(SSL_ERROR_BAD_2ND_CLIENT_HELLO
); } while (0); tls13_FatalError(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO
, illegal_parameter); } while (0)
;
2229 goto loser;
2230 }
2231 }
2232 }
2233
2234 rv = tls13_MaybeSendHelloRetry(ss, requestedGroup, &hrr);
2235 if (rv != SECSuccess) {
2236 goto loser;
2237 }
2238 if (hrr) {
2239 if (sid) { /* Free the sid. */
2240 ssl_UncacheSessionID(ss);
2241 ssl_FreeSID(sid);
2242 }
2243 PORT_Assert(ss->ssl3.hs.helloRetry)((ss->ssl3.hs.helloRetry)?((void)0):PR_Assert("ss->ssl3.hs.helloRetry"
,"tls13con.c",2243))
;
2244 return SECSuccess;
2245 }
2246
2247 /* Select the authentication (this is also handshake shape). */
2248 rv = tls13_NegotiateAuthentication(ss);
2249 if (rv != SECSuccess) {
2250 goto loser;
2251 }
2252
2253 if (ss->sec.authType == ssl_auth_psk) {
2254 if (ss->statelessResume) {
2255 /* We are now committed to trying to resume. */
2256 PORT_Assert(sid)((sid)?((void)0):PR_Assert("sid","tls13con.c",2256));
2257 /* Check that the negotiated SNI and the cached SNI match. */
2258 if (SECITEM_CompareItemSECITEM_CompareItem_Util(&sid->u.ssl3.srvName,
2259 &ss->ssl3.hs.srvVirtName) != SECEqual) {
2260 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO,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__
, "tls13con.c", 2261); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO
, handshake_failure); } while (0)
2261 handshake_failure)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__
, "tls13con.c", 2261); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO
, handshake_failure); } while (0)
;
2262 goto loser;
2263 }
2264
2265 ss->sec.serverCert = ssl_FindServerCert(ss, sid->authType,
2266 sid->namedCurve);
2267 PORT_Assert(ss->sec.serverCert)((ss->sec.serverCert)?((void)0):PR_Assert("ss->sec.serverCert"
,"tls13con.c",2267))
;
2268
2269 rv = tls13_RecoverWrappedSharedSecret(ss, sid);
2270 if (rv != SECSuccess) {
2271 SSL_AtomicIncrementLong(&ssl3stats->hch_sid_cache_not_ok);
2272 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__, "tls13con.c"
, 2272); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0); tls13_FatalError(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error
); } while (0)
;
2273 goto loser;
2274 }
2275 tls13_RestoreCipherInfo(ss, sid);
2276
2277 ss->sec.localCert = CERT_DupCertificate(ss->sec.serverCert->serverCert);
2278 if (sid->peerCert != NULL((void*)0)) {
2279 ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
2280 }
2281 } else if (sid) {
2282 /* We should never have a SID in the non-resumption case. */
2283 PORT_Assert(0)((0)?((void)0):PR_Assert("0","tls13con.c",2283));
2284 ssl_UncacheSessionID(ss);
2285 ssl_FreeSID(sid);
2286 sid = NULL((void*)0);
2287 }
2288 ssl3_RegisterExtensionSender(
2289 ss, &ss->xtnData,
2290 ssl_tls13_pre_shared_key_xtn, tls13_ServerSendPreSharedKeyXtn);
2291 tls13_NegotiateZeroRtt(ss, sid);
2292
2293 rv = tls13_ComputeEarlySecretsWithPsk(ss);
2294 if (rv != SECSuccess) {
2295 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__, "tls13con.c"
, 2295); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0); tls13_FatalError(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error
); } while (0)
;
2296 return SECFailure;
2297 }
2298 } else {
2299 if (sid) { /* we had a sid, but it's no longer valid, free it */
2300 SSL_AtomicIncrementLong(&ssl3stats->hch_sid_cache_not_ok);
2301 ssl_UncacheSessionID(ss);
2302 ssl_FreeSID(sid);
2303 sid = NULL((void*)0);
2304 }
2305 tls13_NegotiateZeroRtt(ss, NULL((void*)0));
2306 }
2307
2308 if (ss->statelessResume) {
2309 PORT_Assert(ss->xtnData.selectedPsk)((ss->xtnData.selectedPsk)?((void)0):PR_Assert("ss->xtnData.selectedPsk"
,"tls13con.c",2309))
;
2310 PORT_Assert(ss->ssl3.hs.kea_def_mutable.authKeyType == ssl_auth_psk)((ss->ssl3.hs.kea_def_mutable.authKeyType == ssl_auth_psk)
?((void)0):PR_Assert("ss->ssl3.hs.kea_def_mutable.authKeyType == ssl_auth_psk"
,"tls13con.c",2310))
;
2311 }
2312
2313 /* Now that we have the binder key, check the binder. */
2314 if (ss->xtnData.selectedPsk) {
2315 SSL3Hashes hashes;
2316 PORT_Assert(ss->ssl3.hs.messages.len > ss->xtnData.pskBindersLen)((ss->ssl3.hs.messages.len > ss->xtnData.pskBindersLen
)?((void)0):PR_Assert("ss->ssl3.hs.messages.len > ss->xtnData.pskBindersLen"
,"tls13con.c",2316))
;
2317 rv = tls13_ComputePskBinderHash(
2318 ss,
2319 ss->ssl3.hs.messages.buf,
2320 ss->ssl3.hs.messages.len - ss->xtnData.pskBindersLen,
2321 &hashes, tls13_GetHash(ss));
2322 if (rv != SECSuccess) {
2323 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__, "tls13con.c"
, 2323); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0); tls13_FatalError(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error
); } while (0)
;
2324 goto loser;
2325 }
2326
2327 PORT_Assert(ss->xtnData.selectedPsk->hash == tls13_GetHash(ss))((ss->xtnData.selectedPsk->hash == tls13_GetHash(ss))?(
(void)0):PR_Assert("ss->xtnData.selectedPsk->hash == tls13_GetHash(ss)"
,"tls13con.c",2327))
;
2328 PORT_Assert(ss->ssl3.hs.suite_def)((ss->ssl3.hs.suite_def)?((void)0):PR_Assert("ss->ssl3.hs.suite_def"
,"tls13con.c",2328))
;
2329 rv = tls13_VerifyFinished(ss, ssl_hs_client_hello,
2330 ss->xtnData.selectedPsk->binderKey,
2331 ss->xtnData.pskBinder.data,
2332 ss->xtnData.pskBinder.len,
2333 &hashes);
2334 }
2335 if (rv != SECSuccess) {
2336 goto loser;
2337 }
2338
2339 /* This needs to go after we verify the psk binder. */
2340 rv = ssl3_InitHandshakeHashes(ss);
2341 if (rv != SECSuccess) {
2342 goto loser;
2343 }
2344
2345 /* If this is TLS 1.3 we are expecting a ClientKeyShare
2346 * extension. Missing/absent extension cause failure
2347 * below. */
2348 rv = tls13_HandleClientKeyShare(ss, clientShare);
2349 if (rv != SECSuccess) {
2350 goto loser; /* An alert was sent already. */
2351 }
2352
2353 /* From this point we are either committed to resumption, or not. */
2354 if (ss->statelessResume) {
2355 SSL_AtomicIncrementLong(&ssl3stats->hch_sid_cache_hits);
2356 SSL_AtomicIncrementLong(&ssl3stats->hch_sid_stateless_resumes);
2357 } else {
2358 if (sid) {
2359 /* We had a sid, but it's no longer valid, free it. */
2360 SSL_AtomicIncrementLong(&ssl3stats->hch_sid_cache_not_ok);
2361 ssl_UncacheSessionID(ss);
2362 ssl_FreeSID(sid);
2363 } else if (!ss->xtnData.selectedPsk) {
2364 SSL_AtomicIncrementLong(&ssl3stats->hch_sid_cache_misses);
2365 }
2366
2367 sid = ssl3_NewSessionID(ss, PR_TRUE1);
2368 if (!sid) {
2369 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__, "tls13con.c"
, 2369); PORT_SetError_Util(PORT_GetError_Util()); } while (0
); tls13_FatalError(ss, PORT_GetError_Util(), internal_error)
; } while (0)
;
2370 return SECFailure;
2371 }
2372 }
2373 /* Take ownership of the session. */
2374 ss->sec.ci.sid = sid;
2375 sid = NULL((void*)0);
2376
2377 if (ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) {
2378 rv = tls13_DeriveEarlySecrets(ss);
2379 if (rv != SECSuccess) {
2380 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__, "tls13con.c"
, 2380); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0); tls13_FatalError(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error
); } while (0)
;
2381 return SECFailure;
2382 }
2383 }
2384
2385 ssl_GetXmitBufLock(ss){ if (!ss->opt.noLocks) PR_EnterMonitor(((ss)->xmitBufLock
)); }
;
2386 rv = tls13_SendServerHelloSequence(ss);
2387 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
;
2388 if (rv != SECSuccess) {
2389 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__, "tls13con.c"
, 2389); PORT_SetError_Util(PORT_GetError_Util()); } while (0
); tls13_FatalError(ss, PORT_GetError_Util(), handshake_failure
); } while (0)
;
2390 return SECFailure;
2391 }
2392
2393 /* We're done with PSKs */
2394 tls13_DestroyPskList(&ss->ssl3.hs.psks);
2395 ss->xtnData.selectedPsk = NULL((void*)0);
2396
2397 return SECSuccess;
2398
2399loser:
2400 if (sid) {
2401 ssl_UncacheSessionID(ss);
2402 ssl_FreeSID(sid);
2403 }
2404 return SECFailure;
2405}
2406
2407SECStatus
2408SSLExp_HelloRetryRequestCallback(PRFileDesc *fd,
2409 SSLHelloRetryRequestCallback cb, void *arg)
2410{
2411 sslSocket *ss = ssl_FindSocket(fd);
2412 if (!ss) {
2413 return SECFailure; /* Code already set. */
2414 }
2415
2416 ss->hrrCallback = cb;
2417 ss->hrrCallbackArg = arg;
2418 return SECSuccess;
2419}
2420
2421/*
2422 * struct {
2423 * ProtocolVersion server_version;
2424 * CipherSuite cipher_suite;
2425 * Extension extensions<2..2^16-1>;
2426 * } HelloRetryRequest;
2427 *
2428 * Note: this function takes an empty buffer and returns
2429 * a non-empty one on success, in which case the caller must
2430 * eventually clean up.
2431 */
2432SECStatus
2433tls13_ConstructHelloRetryRequest(sslSocket *ss,
2434 ssl3CipherSuite cipherSuite,
2435 const sslNamedGroupDef *selectedGroup,
2436 PRUint8 *cookie, unsigned int cookieLen,
2437 const PRUint8 *cookieGreaseEchSignal,
2438 sslBuffer *buffer)
2439{
2440 SECStatus rv;
2441 sslBuffer extensionsBuf = SSL_BUFFER_EMPTY{ ((void*)0), 0, 0, 0 };
2442 PORT_Assert(buffer->len == 0)((buffer->len == 0)?((void)0):PR_Assert("buffer->len == 0"
,"tls13con.c",2442))
;
2443
2444 /* Note: cookie is pointing to a stack variable, so is only valid
2445 * now. */
2446 ss->xtnData.selectedGroup = selectedGroup;
2447 ss->xtnData.cookie.data = cookie;
2448 ss->xtnData.cookie.len = cookieLen;
2449
2450 /* Set restored ss->ssl3.hs.greaseEchBuf value for ECH HRR extension
2451 * reconstruction. */
2452 if (cookieGreaseEchSignal) {
2453 PORT_Assert(!ss->ssl3.hs.greaseEchBuf.len)((!ss->ssl3.hs.greaseEchBuf.len)?((void)0):PR_Assert("!ss->ssl3.hs.greaseEchBuf.len"
,"tls13con.c",2453))
;
2454 rv = sslBuffer_Append(&ss->ssl3.hs.greaseEchBuf,
2455 cookieGreaseEchSignal,
2456 TLS13_ECH_SIGNAL_LEN8);
2457 if (rv != SECSuccess) {
2458 goto loser;
2459 }
2460 }
2461 rv = ssl_ConstructExtensions(ss, &extensionsBuf,
2462 ssl_hs_hello_retry_request);
2463 /* Reset ss->ssl3.hs.greaseEchBuf if it was changed. */
2464 if (cookieGreaseEchSignal) {
2465 sslBuffer_Clear(&ss->ssl3.hs.greaseEchBuf);
2466 }
2467 if (rv != SECSuccess) {
2468 goto loser;
2469 }
2470 /* These extensions can't be empty. */
2471 PORT_Assert(SSL_BUFFER_LEN(&extensionsBuf) > 0)((((&extensionsBuf)->len) > 0)?((void)0):PR_Assert(
"SSL_BUFFER_LEN(&extensionsBuf) > 0","tls13con.c",2471
))
;
2472
2473 /* Clean up cookie so we're not pointing at random memory. */
2474 ss->xtnData.cookie.data = NULL((void*)0);
2475 ss->xtnData.cookie.len = 0;
2476
2477 rv = ssl_ConstructServerHello(ss, PR_TRUE1, &extensionsBuf, buffer);
2478 if (rv != SECSuccess) {
2479 goto loser;
2480 }
2481 sslBuffer_Clear(&extensionsBuf);
2482 return SECSuccess;
2483
2484loser:
2485 sslBuffer_Clear(&extensionsBuf);
2486 sslBuffer_Clear(buffer);
2487 return SECFailure;
2488}
2489
2490static SECStatus
2491tls13_SendHelloRetryRequest(sslSocket *ss,
2492 const sslNamedGroupDef *requestedGroup,
2493 const PRUint8 *appToken, unsigned int appTokenLen)
2494{
2495 SECStatus rv;
2496 unsigned int cookieLen;
2497 PRUint8 cookie[1024];
2498 sslBuffer messageBuf = SSL_BUFFER_EMPTY{ ((void*)0), 0, 0, 0 };
2499
2500 SSL_TRC(3, ("%d: TLS13[%d]: send hello retry request handshake",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: send hello retry request handshake"
, getpid(), ss->fd)
2501 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: send hello retry request handshake"
, getpid(), ss->fd)
;
2502
2503 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)"
,"tls13con.c",2503))
;
2504
2505 /* If an ECH backend or shared-mode server accepted ECH when offered,
2506 * the HRR extension's payload must be set to 8 zero bytes, these are
2507 * overwritten with the accept_confirmation value after the handshake
2508 * transcript calculation.
2509 * If a client-facing or shared-mode server did not accept ECH when offered
2510 * OR if ECH GREASE is enabled on the server and a ECH extension was
2511 * received, a 8 byte random value is set as the extension's payload
2512 * [draft-ietf-tls-esni-14, Section 7].
2513 *
2514 * The (temporary) payload is written to the extension in tls13exthandle.c/
2515 * tls13_ServerSendHrrEchXtn(). */
2516 if (ss->xtnData.ech) {
2517 PRUint8 echGreaseRaw[TLS13_ECH_SIGNAL_LEN8] = { 0 };
2518 if (!(ss->ssl3.hs.echAccepted ||
2519 (ss->opt.enableTls13BackendEch &&
2520 ss->xtnData.ech &&
2521 ss->xtnData.ech->receivedInnerXtn))) {
2522 rv = PK11_GenerateRandom(echGreaseRaw, TLS13_ECH_SIGNAL_LEN8);
2523 if (rv != SECSuccess) {
2524 return SECFailure;
2525 }
2526 SSL_TRC(100, ("Generated random value for ECH HRR GREASE."))if (ssl_trace >= (100)) ssl_Trace ("Generated random value for ECH HRR GREASE."
)
;
2527 }
2528 sslBuffer echGreaseBuffer = SSL_BUFFER_EMPTY{ ((void*)0), 0, 0, 0 };
2529 rv = sslBuffer_Append(&echGreaseBuffer, echGreaseRaw, sizeof(echGreaseRaw));
2530 if (rv != SECSuccess) {
2531 return SECFailure;
2532 }
2533 /* HRR GREASE/accept_confirmation zero bytes placeholder buffer. */
2534 ss->ssl3.hs.greaseEchBuf = echGreaseBuffer;
2535 }
2536
2537 /* Compute the cookie we are going to need. */
2538 rv = tls13_MakeHrrCookie(ss, requestedGroup,
2539 appToken, appTokenLen,
2540 cookie, &cookieLen, sizeof(cookie));
2541 if (rv != SECSuccess) {
2542 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__, "tls13con.c"
, 2542); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0); tls13_FatalError(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error
); } while (0)
;
2543 return SECFailure;
2544 }
2545
2546 /* Now build the body of the message. */
2547 rv = tls13_ConstructHelloRetryRequest(ss, ss->ssl3.hs.cipher_suite,
2548 requestedGroup,
2549 cookie, cookieLen,
2550 NULL((void*)0), &messageBuf);
2551 if (rv != SECSuccess) {
2552 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__, "tls13con.c"
, 2552); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0); tls13_FatalError(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error
); } while (0)
;
2553 return SECFailure;
2554 }
2555
2556 /* And send it. */
2557 ssl_GetXmitBufLock(ss){ if (!ss->opt.noLocks) PR_EnterMonitor(((ss)->xmitBufLock
)); }
;
2558 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_server_hello,
2559 SSL_BUFFER_LEN(&messageBuf)((&messageBuf)->len));
2560 if (rv != SECSuccess) {
2561 goto loser;
2562 }
2563 rv = ssl3_AppendBufferToHandshake(ss, &messageBuf);
2564 if (rv != SECSuccess) {
2565 goto loser;
2566 }
2567 sslBuffer_Clear(&messageBuf); /* Done with messageBuf */
2568
2569 if (ss->ssl3.hs.fakeSid.len) {
2570 PRInt32 sent;
2571
2572 PORT_Assert(!IS_DTLS(ss))((!(ss->protocolVariant == ssl_variant_datagram))?((void)0
):PR_Assert("!IS_DTLS(ss)","tls13con.c",2572))
;
2573 rv = ssl3_SendChangeCipherSpecsInt(ss);
2574 if (rv != SECSuccess) {
2575 goto loser;
2576 }
2577 /* ssl3_SendChangeCipherSpecsInt() only flushes to the output buffer, so we
2578 * have to force a send. */
2579 sent = ssl_SendSavedWriteData(ss);
2580 if (sent < 0 && PORT_GetErrorPORT_GetError_Util() != PR_WOULD_BLOCK_ERROR(-5998L)) {
2581 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_SOCKET_WRITE_FAILURE);
2582 goto loser;
2583 }
2584 } else {
2585 rv = ssl3_FlushHandshake(ss, 0);
2586 if (rv != SECSuccess) {
2587 goto loser; /* error code set by ssl3_FlushHandshake */
2588 }
2589 }
2590
2591 /* We depend on this being exactly one record and one message. */
2592 PORT_Assert(!IS_DTLS(ss) || (ss->ssl3.hs.sendMessageSeq == 1 &&((!(ss->protocolVariant == ssl_variant_datagram) || (ss->
ssl3.hs.sendMessageSeq == 1 && ss->ssl3.cwSpec->
nextSeqNum == 1))?((void)0):PR_Assert("!IS_DTLS(ss) || (ss->ssl3.hs.sendMessageSeq == 1 && ss->ssl3.cwSpec->nextSeqNum == 1)"
,"tls13con.c",2593))
2593 ss->ssl3.cwSpec->nextSeqNum == 1))((!(ss->protocolVariant == ssl_variant_datagram) || (ss->
ssl3.hs.sendMessageSeq == 1 && ss->ssl3.cwSpec->
nextSeqNum == 1))?((void)0):PR_Assert("!IS_DTLS(ss) || (ss->ssl3.hs.sendMessageSeq == 1 && ss->ssl3.cwSpec->nextSeqNum == 1)"
,"tls13con.c",2593))
;
2594 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
;
2595
2596 ss->ssl3.hs.helloRetry = PR_TRUE1;
2597
2598 /* We received early data but have to ignore it because we sent a retry. */
2599 if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent) {
2600 ss->ssl3.hs.zeroRttState = ssl_0rtt_ignored;
2601 ss->ssl3.hs.zeroRttIgnore = ssl_0rtt_ignore_hrr;
2602 }
2603
2604 return SECSuccess;
2605
2606loser:
2607 sslBuffer_Clear(&messageBuf);
2608 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
;
2609 return SECFailure;
2610}
2611
2612/* Called from tls13_HandleClientHello.
2613 *
2614 * Caller must hold Handshake and RecvBuf locks.
2615 */
2616
2617static SECStatus
2618tls13_HandleClientKeyShare(sslSocket *ss, TLS13KeyShareEntry *peerShare)
2619{
2620 SECStatus rv;
2621 sslEphemeralKeyPair *keyPair; /* ours */
2622 SECItem *ciphertext = NULL((void*)0);
2623 PK11SymKey *dheSecret = NULL((void*)0);
2624 PK11SymKey *kemSecret = NULL((void*)0);
2625
2626 SSL_TRC(3, ("%d: TLS13[%d]: handle client_key_share handshake",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: handle client_key_share handshake"
, getpid(), ss->fd)
2627 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: handle client_key_share handshake"
, getpid(), ss->fd)
;
2628
2629 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)"
,"tls13con.c",2629))
;
2630 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)"
,"tls13con.c",2630))
;
2631 PORT_Assert(peerShare)((peerShare)?((void)0):PR_Assert("peerShare","tls13con.c",2631
))
;
2632
2633 tls13_SetKeyExchangeType(ss, peerShare->group);
2634
2635 /* Generate our key */
2636 rv = tls13_AddKeyShare(ss, peerShare->group);
2637 if (rv != SECSuccess) {
2638 return rv;
2639 }
2640
2641 /* We should have exactly one key share. */
2642 PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ephemeralKeyPairs))((!((&ss->ephemeralKeyPairs)->next == (&ss->
ephemeralKeyPairs)))?((void)0):PR_Assert("!PR_CLIST_IS_EMPTY(&ss->ephemeralKeyPairs)"
,"tls13con.c",2642))
;
2643 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)"
,"tls13con.c",2644))
2644 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)"
,"tls13con.c",2644))
;
2645
2646 keyPair = ((sslEphemeralKeyPair *)PR_NEXT_LINK(&ss->ephemeralKeyPairs)((&ss->ephemeralKeyPairs)->next));
2647 ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits(keyPair->keys->pubKey);
2648
2649 /* Register the sender */
2650 rv = ssl3_RegisterExtensionSender(ss, &ss->xtnData, ssl_tls13_key_share_xtn,
2651 tls13_ServerSendKeyShareXtn);
2652 if (rv != SECSuccess) {
2653 return SECFailure; /* Error code set already. */
2654 }
2655
2656 rv = tls13_HandleKeyShare(ss, peerShare, keyPair->keys,
2657 tls13_GetHash(ss),
2658 &dheSecret);
2659 if (rv != SECSuccess) {
2660 goto loser; /* Error code already set. */
2661 }
2662
2663 if (peerShare->group->keaType == ssl_kea_ecdh_hybrid) {
2664 rv = tls13_HandleKEMKey(ss, peerShare, &kemSecret, &ciphertext);
2665 if (rv != SECSuccess) {
2666 goto loser; /* Error set by tls13_HandleKEMKey */
2667 }
2668 // We may need to handle different "combiners" here in the future. For
2669 // now this is specific to xyber768d00.
2670 PORT_Assert(peerShare->group->name == ssl_grp_kem_xyber768d00)((peerShare->group->name == ssl_grp_kem_xyber768d00)?((
void)0):PR_Assert("peerShare->group->name == ssl_grp_kem_xyber768d00"
,"tls13con.c",2670))
;
2671 ss->ssl3.hs.dheSecret = PK11_ConcatSymKeys(dheSecret, kemSecret, CKM_HKDF_DERIVE0x0000402aUL, CKA_DERIVE0x0000010CUL);
2672 if (!ss->ssl3.hs.dheSecret) {
2673 goto loser; /* Error set by PK11_ConcatSymKeys */
2674 }
2675 keyPair->kemCt = ciphertext;
2676 PK11_FreeSymKey(dheSecret);
2677 PK11_FreeSymKey(kemSecret);
2678 } else {
2679 ss->ssl3.hs.dheSecret = dheSecret;
2680 }
2681
2682 return SECSuccess;
2683
2684loser:
2685 SECITEM_FreeItemSECITEM_FreeItem_Util(ciphertext, PR_TRUE1);
2686 PK11_FreeSymKey(dheSecret);
2687 PK11_FreeSymKey(kemSecret);
2688 FATAL_ERROR(ss, PORT_GetError(), illegal_parameter)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__, "tls13con.c"
, 2688); PORT_SetError_Util(PORT_GetError_Util()); } while (0
); tls13_FatalError(ss, PORT_GetError_Util(), illegal_parameter
); } while (0)
;
2689 return SECFailure;
2690}
2691
2692/*
2693 * [draft-ietf-tls-tls13-11] Section 6.3.3.2
2694 *
2695 * opaque DistinguishedName<1..2^16-1>;
2696 *
2697 * struct {
2698 * opaque certificate_extension_oid<1..2^8-1>;
2699 * opaque certificate_extension_values<0..2^16-1>;
2700 * } CertificateExtension;
2701 *
2702 * struct {
2703 * opaque certificate_request_context<0..2^8-1>;
2704 * SignatureAndHashAlgorithm
2705 * supported_signature_algorithms<2..2^16-2>;
2706 * DistinguishedName certificate_authorities<0..2^16-1>;
2707 * CertificateExtension certificate_extensions<0..2^16-1>;
2708 * } CertificateRequest;
2709 */
2710static SECStatus
2711tls13_SendCertificateRequest(sslSocket *ss)
2712{
2713 SECStatus rv;
2714 sslBuffer extensionBuf = SSL_BUFFER_EMPTY{ ((void*)0), 0, 0, 0 };
2715 unsigned int offset = 0;
2716
2717 SSL_TRC(3, ("%d: TLS13[%d]: begin send certificate_request",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: begin send certificate_request"
, getpid(), ss->fd)
2718 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: begin send certificate_request"
, getpid(), ss->fd)
;
2719
2720 if (ss->firstHsDone) {
2721 PORT_Assert(ss->ssl3.hs.shaPostHandshake == NULL)((ss->ssl3.hs.shaPostHandshake == ((void*)0))?((void)0):PR_Assert
("ss->ssl3.hs.shaPostHandshake == NULL","tls13con.c",2721)
)
;
2722 ss->ssl3.hs.shaPostHandshake = PK11_CloneContext(ss->ssl3.hs.sha);
2723 if (ss->ssl3.hs.shaPostHandshake == NULL((void*)0)) {
2724 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
2725 return SECFailure;
2726 }
2727 }
2728
2729 rv = ssl_ConstructExtensions(ss, &extensionBuf, ssl_hs_certificate_request);
2730 if (rv != SECSuccess) {
2731 return SECFailure; /* Code already set. */
2732 }
2733 /* We should always have at least one of these. */
2734 PORT_Assert(SSL_BUFFER_LEN(&extensionBuf) > 0)((((&extensionBuf)->len) > 0)?((void)0):PR_Assert("SSL_BUFFER_LEN(&extensionBuf) > 0"
,"tls13con.c",2734))
;
2735
2736 /* Create a new request context for post-handshake authentication */
2737 if (ss->firstHsDone) {
2738 PRUint8 context[16];
2739 SECItem contextItem = { siBuffer, context, sizeof(context) };
2740
2741 rv = PK11_GenerateRandom(context, sizeof(context));
2742 if (rv != SECSuccess) {
2743 goto loser;
2744 }
2745
2746 SECITEM_FreeItemSECITEM_FreeItem_Util(&ss->xtnData.certReqContext, PR_FALSE0);
2747 rv = SECITEM_CopyItemSECITEM_CopyItem_Util(NULL((void*)0), &ss->xtnData.certReqContext, &contextItem);
2748 if (rv != SECSuccess) {
2749 FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, 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_NO_MEMORY, __func__, "tls13con.c"
, 2749); PORT_SetError_Util(SEC_ERROR_NO_MEMORY); } while (0)
; tls13_FatalError(ss, SEC_ERROR_NO_MEMORY, internal_error); }
while (0)
;
2750 goto loser;
2751 }
2752
2753 offset = SSL_BUFFER_LEN(&ss->sec.ci.sendBuf)((&ss->sec.ci.sendBuf)->len);
2754 }
2755
2756 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_request,
2757 1 + /* request context length */
2758 ss->xtnData.certReqContext.len +
2759 2 + /* extension length */
2760 SSL_BUFFER_LEN(&extensionBuf)((&extensionBuf)->len));
2761 if (rv != SECSuccess) {
2762 goto loser; /* err set by AppendHandshake. */
2763 }
2764
2765 /* Context. */
2766 rv = ssl3_AppendHandshakeVariable(ss, ss->xtnData.certReqContext.data,
2767 ss->xtnData.certReqContext.len, 1);
2768 if (rv != SECSuccess) {
2769 goto loser; /* err set by AppendHandshake. */
2770 }
2771 /* Extensions. */
2772 rv = ssl3_AppendBufferToHandshakeVariable(ss, &extensionBuf, 2);
2773 if (rv != SECSuccess) {
2774 goto loser; /* err set by AppendHandshake. */
2775 }
2776
2777 if (ss->firstHsDone) {
2778 rv = ssl3_UpdatePostHandshakeHashes(ss,
2779 SSL_BUFFER_BASE(&ss->sec.ci.sendBuf)((&ss->sec.ci.sendBuf)->buf) + offset,
2780 SSL_BUFFER_LEN(&ss->sec.ci.sendBuf)((&ss->sec.ci.sendBuf)->len) - offset);
2781 if (rv != SECSuccess) {
2782 goto loser;
2783 }
2784 }
2785
2786 sslBuffer_Clear(&extensionBuf);
2787 return SECSuccess;
2788
2789loser:
2790 sslBuffer_Clear(&extensionBuf);
2791 return SECFailure;
2792}
2793
2794/* [draft-ietf-tls-tls13; S 4.4.1] says:
2795 *
2796 * Transcript-Hash(ClientHello1, HelloRetryRequest, ... MN) =
2797 * Hash(message_hash || // Handshake type
2798 * 00 00 Hash.length || // Handshake message length
2799 * Hash(ClientHello1) || // Hash of ClientHello1
2800 * HelloRetryRequest ... MN)
2801 *
2802 * For an ECH handshake, the process occurs for the outer
2803 * transcript in |ss->ssl3.hs.messages| and the inner
2804 * transcript in |ss->ssl3.hs.echInnerMessages|.
2805 */
2806static SECStatus
2807tls13_ReinjectHandshakeTranscript(sslSocket *ss)
2808{
2809 SSL3Hashes hashes;
2810 SSL3Hashes echInnerHashes;
2811 SECStatus rv;
2812
2813 /* First compute the hash. */
2814 rv = tls13_ComputeHash(ss, &hashes,
2815 ss->ssl3.hs.messages.buf,
2816 ss->ssl3.hs.messages.len,
2817 tls13_GetHash(ss));
2818 if (rv != SECSuccess) {
2819 return SECFailure;
2820 }
2821
2822 if (ss->ssl3.hs.echHpkeCtx) {
2823 rv = tls13_ComputeHash(ss, &echInnerHashes,
2824 ss->ssl3.hs.echInnerMessages.buf,
2825 ss->ssl3.hs.echInnerMessages.len,
2826 tls13_GetHash(ss));
2827 if (rv != SECSuccess) {
2828 return SECFailure;
2829 }
2830 }
2831
2832 ssl3_RestartHandshakeHashes(ss);
2833
2834 /* Reinject the message. The Default context variant updates
2835 * the default hash state. Use it for both non-ECH and ECH Outer. */
2836 rv = ssl_HashHandshakeMessageDefault(ss, ssl_hs_message_hash,
2837 hashes.u.raw, hashes.len);
2838 if (rv != SECSuccess) {
2839 return SECFailure;
2840 }
2841
2842 if (ss->ssl3.hs.echHpkeCtx) {
2843 rv = ssl_HashHandshakeMessageEchInner(ss, ssl_hs_message_hash,
2844 echInnerHashes.u.raw,
2845 echInnerHashes.len);
2846 if (rv != SECSuccess) {
2847 return SECFailure;
2848 }
2849 }
2850
2851 return SECSuccess;
2852}
2853static unsigned int
2854ssl_ListCount(PRCList *list)
2855{
2856 unsigned int c = 0;
2857 PRCList *cur;
2858 for (cur = PR_NEXT_LINK(list)((list)->next); cur != list; cur = PR_NEXT_LINK(cur)((cur)->next)) {
2859 ++c;
2860 }
2861 return c;
2862}
2863
2864/*
2865 * savedMsg contains the HelloRetryRequest message. When its extensions are parsed
2866 * in ssl3_HandleParsedExtensions, the handler for ECH HRR extensions (tls13_ClientHandleHrrEchXtn)
2867 * will take a reference into the message buffer.
2868 *
2869 * This reference is then used in tls13_MaybeHandleEchSignal in order to compute
2870 * the transcript for the ECH signal calculation. This was felt to be preferable
2871 * to re-parsing the HelloRetryRequest message in order to create the transcript.
2872 *
2873 * Consequently, savedMsg should not be moved or mutated between these
2874 * function calls.
2875 */
2876SECStatus
2877tls13_HandleHelloRetryRequest(sslSocket *ss, const PRUint8 *savedMsg,
2878 PRUint32 savedLength)
2879{
2880 SECStatus rv;
2881
2882 SSL_TRC(3, ("%d: TLS13[%d]: handle hello retry request",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: handle hello retry request"
, getpid(), ss->fd)
2883 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: handle hello retry request"
, getpid(), ss->fd)
;
2884
2885 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)"
,"tls13con.c",2885))
;
2886 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)"
,"tls13con.c",2886))
;
2887
2888 if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_30x0304) {
2889 FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_HELLO_RETRY_REQUEST,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_HELLO_RETRY_REQUEST
, __func__, "tls13con.c", 2890); PORT_SetError_Util(SSL_ERROR_RX_UNEXPECTED_HELLO_RETRY_REQUEST
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_UNEXPECTED_HELLO_RETRY_REQUEST
, unexpected_message); } while (0)
2890 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_HELLO_RETRY_REQUEST
, __func__, "tls13con.c", 2890); PORT_SetError_Util(SSL_ERROR_RX_UNEXPECTED_HELLO_RETRY_REQUEST
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_UNEXPECTED_HELLO_RETRY_REQUEST
, unexpected_message); } while (0)
;
2891 return SECFailure;
2892 }
2893 PORT_Assert(ss->ssl3.hs.ws == wait_server_hello)((ss->ssl3.hs.ws == wait_server_hello)?((void)0):PR_Assert
("ss->ssl3.hs.ws == wait_server_hello","tls13con.c",2893))
;
2894
2895 if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent) {
2896 ss->ssl3.hs.zeroRttState = ssl_0rtt_ignored;
2897 /* Restore the null cipher spec for writing. */
2898 ssl_GetSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_LockWrite_Util((ss)->
specLock); }
;
2899 ssl_CipherSpecRelease(ss->ssl3.cwSpec);
2900 ss->ssl3.cwSpec = ssl_FindCipherSpecByEpoch(ss, ssl_secret_write,
2901 TrafficKeyClearText);
2902 PORT_Assert(ss->ssl3.cwSpec)((ss->ssl3.cwSpec)?((void)0):PR_Assert("ss->ssl3.cwSpec"
,"tls13con.c",2902))
;
2903 ssl_ReleaseSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockWrite_Util((ss)->
specLock); }
;
2904 } else {
2905 PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_none)((ss->ssl3.hs.zeroRttState == ssl_0rtt_none)?((void)0):PR_Assert
("ss->ssl3.hs.zeroRttState == ssl_0rtt_none","tls13con.c",
2905))
;
2906 }
2907 /* Set the spec version, because we want to send CH now with 0303 */
2908 tls13_SetSpecRecordVersion(ss, ss->ssl3.cwSpec);
2909
2910 /* Extensions must contain more than just supported_versions. This will
2911 * ensure that a HelloRetryRequest isn't a no-op: we must have at least two
2912 * extensions, supported_versions plus one other. That other must be one
2913 * that we understand and recognize as being valid for HelloRetryRequest,
2914 * and should alter our next Client Hello. */
2915 unsigned int requiredExtensions = 1;
2916 /* The ECH HRR extension is a no-op from the client's perspective. */
2917 if (ss->xtnData.ech) {
2918 requiredExtensions++;
2919 }
2920 if (ssl_ListCount(&ss->ssl3.hs.remoteExtensions) <= requiredExtensions) {
2921 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_HELLO_RETRY_REQUEST,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_HELLO_RETRY_REQUEST
, __func__, "tls13con.c", 2922); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_HELLO_RETRY_REQUEST
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_HELLO_RETRY_REQUEST
, decode_error); } while (0)
2922 decode_error)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_HELLO_RETRY_REQUEST
, __func__, "tls13con.c", 2922); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_HELLO_RETRY_REQUEST
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_HELLO_RETRY_REQUEST
, decode_error); } while (0)
;
2923 return SECFailure;
2924 }
2925
2926 rv = ssl3_HandleParsedExtensions(ss, ssl_hs_hello_retry_request);
2927 ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
2928 if (rv != SECSuccess) {
2929 return SECFailure; /* Error code set below */
2930 }
2931 rv = tls13_MaybeHandleEchSignal(ss, savedMsg, savedLength, PR_TRUE1);
2932 if (rv != SECSuccess) {
2933 return SECFailure;
2934 }
2935 ss->ssl3.hs.helloRetry = PR_TRUE1;
2936 rv = tls13_ReinjectHandshakeTranscript(ss);
2937 if (rv != SECSuccess) {
2938 return rv;
2939 }
2940
2941 rv = ssl_HashHandshakeMessage(ss, ssl_hs_server_hello,
2942 savedMsg, savedLength);
2943 if (rv != SECSuccess) {
2944 return SECFailure;
2945 }
2946
2947 ssl_GetXmitBufLock(ss){ if (!ss->opt.noLocks) PR_EnterMonitor(((ss)->xmitBufLock
)); }
;
2948 if (ss->opt.enableTls13CompatMode && !IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram) &&
2949 ss->ssl3.hs.zeroRttState == ssl_0rtt_none) {
2950 rv = ssl3_SendChangeCipherSpecsInt(ss);
2951 if (rv != SECSuccess) {
2952 goto loser;
2953 }
2954 }
2955
2956 rv = ssl3_SendClientHello(ss, client_hello_retry);
2957 if (rv != SECSuccess) {
2958 goto loser;
2959 }
2960
2961 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
;
2962 return SECSuccess;
2963
2964loser:
2965 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
;
2966 return SECFailure;
2967}
2968
2969static SECStatus
2970tls13_SendPostHandshakeCertificate(sslSocket *ss)
2971{
2972 SECStatus rv;
2973 if (ss->ssl3.hs.restartTarget) {
2974 PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget")PR_Assert("unexpected ss->ssl3.hs.restartTarget","tls13con.c"
,2974)
;
2975 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
2976 return SECFailure;
2977 }
2978
2979 if (ss->ssl3.hs.clientCertificatePending) {
2980 SSL_TRC(3, ("%d: TLS13[%d]: deferring tls13_SendClientSecondFlight because"if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: deferring tls13_SendClientSecondFlight because"
" certificate authentication is still pending.", getpid(), ss
->fd)
2981 " certificate authentication is still pending.",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: deferring tls13_SendClientSecondFlight because"
" certificate authentication is still pending.", getpid(), ss
->fd)
2982 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: deferring tls13_SendClientSecondFlight because"
" certificate authentication is still pending.", getpid(), ss
->fd)
;
2983 ss->ssl3.hs.restartTarget = tls13_SendPostHandshakeCertificate;
2984 PORT_SetErrorPORT_SetError_Util(PR_WOULD_BLOCK_ERROR(-5998L));
2985 return SECFailure;
2986 }
2987
2988 ssl_GetXmitBufLock(ss){ if (!ss->opt.noLocks) PR_EnterMonitor(((ss)->xmitBufLock
)); }
;
2989 rv = tls13_SendClientSecondFlight(ss);
2990 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
;
2991 PORT_Assert(ss->ssl3.hs.ws == idle_handshake)((ss->ssl3.hs.ws == idle_handshake)?((void)0):PR_Assert("ss->ssl3.hs.ws == idle_handshake"
,"tls13con.c",2991))
;
2992 PORT_Assert(ss->ssl3.hs.shaPostHandshake != NULL)((ss->ssl3.hs.shaPostHandshake != ((void*)0))?((void)0):PR_Assert
("ss->ssl3.hs.shaPostHandshake != NULL","tls13con.c",2992)
)
;
2993 PK11_DestroyContext(ss->ssl3.hs.shaPostHandshake, PR_TRUE1);
2994 ss->ssl3.hs.shaPostHandshake = NULL((void*)0);
2995 if (rv != SECSuccess) {
2996 return SECFailure;
2997 }
2998 return rv;
2999}
3000
3001static SECStatus
3002tls13_HandleCertificateRequest(sslSocket *ss, PRUint8 *b, PRUint32 length)
3003{
3004 SECStatus rv;
3005 SECItem context = { siBuffer, NULL((void*)0), 0 };
3006 SECItem extensionsData = { siBuffer, NULL((void*)0), 0 };
3007
3008 SSL_TRC(3, ("%d: TLS13[%d]: handle certificate_request sequence",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: handle certificate_request sequence"
, getpid(), ss->fd)
3009 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: handle certificate_request sequence"
, getpid(), ss->fd)
;
3010
3011 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)"
,"tls13con.c",3011))
;
3012 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)"
,"tls13con.c",3012))
;
3013
3014 /* Client */
3015 if (ss->opt.enablePostHandshakeAuth) {
3016 rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST,tls13_CheckHsState(ss, SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST, "SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST"
, __func__, "tls13con.c", 3017, wait_cert_request, idle_handshake
, wait_invalid)
3017 wait_cert_request, idle_handshake)tls13_CheckHsState(ss, SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST, "SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST"
, __func__, "tls13con.c", 3017, wait_cert_request, idle_handshake
, wait_invalid)
;
3018 } else {
3019 rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST,tls13_CheckHsState(ss, SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST, "SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST"
, __func__, "tls13con.c", 3020, wait_cert_request, wait_invalid
)
3020 wait_cert_request)tls13_CheckHsState(ss, SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST, "SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST"
, __func__, "tls13con.c", 3020, wait_cert_request, wait_invalid
)
;
3021 }
3022 if (rv != SECSuccess) {
3023 return SECFailure;
3024 }
3025
3026 /* MUST NOT combine external PSKs with certificate authentication. */
3027 if (ss->sec.authType == ssl_auth_psk) {
3028 FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST, 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_CERT_REQUEST, __func__
, "tls13con.c", 3028); PORT_SetError_Util(SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST
, unexpected_message); } while (0)
;
3029 return SECFailure;
3030 }
3031
3032 if (tls13_IsPostHandshake(ss)) {
3033 PORT_Assert(ss->ssl3.hs.shaPostHandshake == NULL)((ss->ssl3.hs.shaPostHandshake == ((void*)0))?((void)0):PR_Assert
("ss->ssl3.hs.shaPostHandshake == NULL","tls13con.c",3033)
)
;
3034 ss->ssl3.hs.shaPostHandshake = PK11_CloneContext(ss->ssl3.hs.sha);
3035 if (ss->ssl3.hs.shaPostHandshake == NULL((void*)0)) {
3036 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
3037 return SECFailure;
3038 }
3039 rv = ssl_HashPostHandshakeMessage(ss, ssl_hs_certificate_request, b, length);
3040 if (rv != SECSuccess) {
3041 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__, "tls13con.c"
, 3041); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0); tls13_FatalError(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error
); } while (0)
;
3042 return SECFailure;
3043 }
3044
3045 /* clean up anything left from previous handshake. */
3046 if (ss->ssl3.clientCertChain != NULL((void*)0)) {
3047 CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
3048 ss->ssl3.clientCertChain = NULL((void*)0);
3049 }
3050 if (ss->ssl3.clientCertificate != NULL((void*)0)) {
3051 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
3052 ss->ssl3.clientCertificate = NULL((void*)0);
3053 }
3054 if (ss->ssl3.clientPrivateKey != NULL((void*)0)) {
3055 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
3056 ss->ssl3.clientPrivateKey = NULL((void*)0);
3057 }
3058 if (ss->ssl3.hs.clientAuthSignatureSchemes != NULL((void*)0)) {
3059 PORT_FreePORT_Free_Util(ss->ssl3.hs.clientAuthSignatureSchemes);
3060 ss->ssl3.hs.clientAuthSignatureSchemes = NULL((void*)0);
3061 ss->ssl3.hs.clientAuthSignatureSchemesLen = 0;
3062 }
3063 SECITEM_FreeItemSECITEM_FreeItem_Util(&ss->xtnData.certReqContext, PR_FALSE0);
3064 ss->xtnData.certReqContext.data = NULL((void*)0);
3065 } else {
3066 PORT_Assert(ss->ssl3.clientCertChain == NULL)((ss->ssl3.clientCertChain == ((void*)0))?((void)0):PR_Assert
("ss->ssl3.clientCertChain == NULL","tls13con.c",3066))
;
3067 PORT_Assert(ss->ssl3.clientCertificate == NULL)((ss->ssl3.clientCertificate == ((void*)0))?((void)0):PR_Assert
("ss->ssl3.clientCertificate == NULL","tls13con.c",3067))
;
3068 PORT_Assert(ss->ssl3.clientPrivateKey == NULL)((ss->ssl3.clientPrivateKey == ((void*)0))?((void)0):PR_Assert
("ss->ssl3.clientPrivateKey == NULL","tls13con.c",3068))
;
3069 PORT_Assert(ss->ssl3.hs.clientAuthSignatureSchemes == NULL)((ss->ssl3.hs.clientAuthSignatureSchemes == ((void*)0))?((
void)0):PR_Assert("ss->ssl3.hs.clientAuthSignatureSchemes == NULL"
,"tls13con.c",3069))
;
3070 PORT_Assert(ss->ssl3.hs.clientAuthSignatureSchemesLen == 0)((ss->ssl3.hs.clientAuthSignatureSchemesLen == 0)?((void)0
):PR_Assert("ss->ssl3.hs.clientAuthSignatureSchemesLen == 0"
,"tls13con.c",3070))
;
3071 PORT_Assert(!ss->ssl3.hs.clientCertRequested)((!ss->ssl3.hs.clientCertRequested)?((void)0):PR_Assert("!ss->ssl3.hs.clientCertRequested"
,"tls13con.c",3071))
;
3072 PORT_Assert(ss->xtnData.certReqContext.data == NULL)((ss->xtnData.certReqContext.data == ((void*)0))?((void)0)
:PR_Assert("ss->xtnData.certReqContext.data == NULL","tls13con.c"
,3072))
;
3073 }
3074
3075 rv = ssl3_ConsumeHandshakeVariable(ss, &context, 1, &b, &length);
3076 if (rv != SECSuccess) {
3077 return SECFailure;
3078 }
3079
3080 /* Unless it is a post-handshake client auth, the certificate
3081 * request context must be empty. */
3082 if (!tls13_IsPostHandshake(ss) && context.len > 0) {
3083 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERT_REQUEST, 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_CERT_REQUEST, __func__
, "tls13con.c", 3083); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CERT_REQUEST
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_CERT_REQUEST
, illegal_parameter); } while (0)
;
3084 return SECFailure;
3085 }
3086
3087 rv = ssl3_ConsumeHandshakeVariable(ss, &extensionsData, 2, &b, &length);
3088 if (rv != SECSuccess) {
3089 return SECFailure;
3090 }
3091
3092 if (length) {
3093 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERT_REQUEST, decode_error)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_CERT_REQUEST, __func__
, "tls13con.c", 3093); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CERT_REQUEST
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_CERT_REQUEST
, decode_error); } while (0)
;
3094 return SECFailure;
3095 }
3096
3097 /* Process all the extensions. */
3098 rv = ssl3_HandleExtensions(ss, &extensionsData.data, &extensionsData.len,
3099 ssl_hs_certificate_request);
3100 if (rv != SECSuccess) {
3101 return SECFailure;
3102 }
3103
3104 if (!ss->xtnData.numSigSchemes) {
3105 FATAL_ERROR(ss, SSL_ERROR_MISSING_SIGNATURE_ALGORITHMS_EXTENSION,do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_MISSING_SIGNATURE_ALGORITHMS_EXTENSION
, __func__, "tls13con.c", 3106); PORT_SetError_Util(SSL_ERROR_MISSING_SIGNATURE_ALGORITHMS_EXTENSION
); } while (0); tls13_FatalError(ss, SSL_ERROR_MISSING_SIGNATURE_ALGORITHMS_EXTENSION
, missing_extension); } while (0)
3106 missing_extension)do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_MISSING_SIGNATURE_ALGORITHMS_EXTENSION
, __func__, "tls13con.c", 3106); PORT_SetError_Util(SSL_ERROR_MISSING_SIGNATURE_ALGORITHMS_EXTENSION
); } while (0); tls13_FatalError(ss, SSL_ERROR_MISSING_SIGNATURE_ALGORITHMS_EXTENSION
, missing_extension); } while (0)
;
3107 return SECFailure;
3108 }
3109
3110 rv = SECITEM_CopyItemSECITEM_CopyItem_Util(NULL((void*)0), &ss->xtnData.certReqContext, &context);
3111 if (rv != SECSuccess) {
3112 return SECFailure;
3113 }
3114
3115 ss->ssl3.hs.clientCertRequested = PR_TRUE1;
3116
3117 if (ss->firstHsDone) {
3118
3119 /* Request a client certificate. */
3120 rv = ssl3_BeginHandleCertificateRequest(
3121 ss, ss->xtnData.sigSchemes, ss->xtnData.numSigSchemes,
3122 &ss->xtnData.certReqAuthorities);
3123 if (rv != SECSuccess) {
3124 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__, "tls13con.c"
, 3124); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0); tls13_FatalError(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error
); } while (0)
;
3125 return rv;
3126 }
3127 rv = tls13_SendPostHandshakeCertificate(ss);
3128 } else {
3129 TLS13_SET_HS_STATE(ss, wait_server_cert)tls13_SetHsState(ss, wait_server_cert, __func__, "tls13con.c"
, 3129)
;
3130 }
3131 return SECSuccess;
3132}
3133
3134PRBool
3135tls13_ShouldRequestClientAuth(sslSocket *ss)
3136{
3137 /* Even if we are configured to request a certificate, we can't
3138 * if this handshake used a PSK, even when we are resuming. */
3139 return ss->opt.requestCertificate &&
3140 ss->ssl3.hs.kea_def->authKeyType != ssl_auth_psk;
3141}
3142
3143static SECStatus
3144tls13_SendEncryptedServerSequence(sslSocket *ss)
3145{
3146 SECStatus rv;
3147
3148 rv = tls13_ComputeHandshakeSecrets(ss);
3149 if (rv != SECSuccess) {
3150 return SECFailure; /* error code is set. */
3151 }
3152
3153 rv = tls13_SetCipherSpec(ss, TrafficKeyHandshake,
3154 ssl_secret_write, PR_FALSE0);
3155 if (rv != SECSuccess) {
3156 LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE)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__, "tls13con.c"
, 3156); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0)
;
3157 return SECFailure;
3158 }
3159
3160 if (ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) {
3161 rv = ssl3_RegisterExtensionSender(ss, &ss->xtnData,
3162 ssl_tls13_early_data_xtn,
3163 ssl_SendEmptyExtension);
3164 if (rv != SECSuccess) {
3165 return SECFailure; /* Error code set already. */
3166 }
3167 }
3168
3169 rv = tls13_SendEncryptedExtensions(ss);
3170 if (rv != SECSuccess) {
3171 return SECFailure; /* error code is set. */
3172 }
3173
3174 if (tls13_ShouldRequestClientAuth(ss)) {
3175 rv = tls13_SendCertificateRequest(ss);
3176 if (rv != SECSuccess) {
3177 return SECFailure; /* error code is set. */
3178 }
3179 }
3180 if (ss->ssl3.hs.signatureScheme != ssl_sig_none) {
3181 SECKEYPrivateKey *svrPrivKey;
3182
3183 rv = tls13_SendCertificate(ss);
3184 if (rv != SECSuccess) {
3185 return SECFailure; /* error code is set. */
3186 }
3187
3188 if (tls13_IsSigningWithDelegatedCredential(ss)) {
3189 SSL_TRC(3, ("%d: TLS13[%d]: Signing with delegated credential",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: Signing with delegated credential"
, getpid(), ss->fd)
3190 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: Signing with delegated credential"
, getpid(), ss->fd)
;
3191 svrPrivKey = ss->sec.serverCert->delegCredKeyPair->privKey;
3192 } else {
3193 svrPrivKey = ss->sec.serverCert->serverKeyPair->privKey;
3194 }
3195
3196 rv = tls13_SendCertificateVerify(ss, svrPrivKey);
3197 if (rv != SECSuccess) {
3198 return SECFailure; /* err code is set. */
3199 }
3200 }
3201
3202 rv = tls13_SendFinished(ss, ss->ssl3.hs.serverHsTrafficSecret);
3203 if (rv != SECSuccess) {
3204 return SECFailure; /* error code is set. */
3205 }
3206
3207 return SECSuccess;
3208}
3209
3210/* Called from: ssl3_HandleClientHello */
3211static SECStatus
3212tls13_SendServerHelloSequence(sslSocket *ss)
3213{
3214 SECStatus rv;
3215 PRErrorCode err = 0;
3216
3217 SSL_TRC(3, ("%d: TLS13[%d]: begin send server_hello sequence",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: begin send server_hello sequence"
, getpid(), ss->fd)
3218 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: begin send server_hello sequence"
, getpid(), ss->fd)
;
3219
3220 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)"
,"tls13con.c",3220))
;
3221 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)"
,"tls13con.c",3221))
;
3222
3223 rv = ssl3_RegisterExtensionSender(ss, &ss->xtnData,
3224 ssl_tls13_supported_versions_xtn,
3225 tls13_ServerSendSupportedVersionsXtn);
3226 if (rv != SECSuccess) {
3227 return SECFailure;
3228 }
3229
3230 rv = tls13_ComputeHandshakeSecret(ss);
3231 if (rv != SECSuccess) {
3232 return SECFailure; /* error code is set. */
3233 }
3234
3235 rv = ssl3_SendServerHello(ss);
3236 if (rv != SECSuccess) {
3237 return rv; /* err code is set. */
3238 }
3239
3240 if (ss->ssl3.hs.fakeSid.len) {
3241 PORT_Assert(!IS_DTLS(ss))((!(ss->protocolVariant == ssl_variant_datagram))?((void)0
):PR_Assert("!IS_DTLS(ss)","tls13con.c",3241))
;
3242 SECITEM_FreeItemSECITEM_FreeItem_Util(&ss->ssl3.hs.fakeSid, PR_FALSE0);
3243 if (!ss->ssl3.hs.helloRetry) {
3244 rv = ssl3_SendChangeCipherSpecsInt(ss);
3245 if (rv != SECSuccess) {
3246 return rv;
3247 }
3248 }
3249 }
3250
3251 rv = tls13_SendEncryptedServerSequence(ss);
3252 if (rv != SECSuccess) {
3253 err = PORT_GetErrorPORT_GetError_Util();
3254 }
3255 /* Even if we get an error, since the ServerHello was successfully
3256 * serialized, we should give it a chance to reach the network. This gives
3257 * the client a chance to perform the key exchange and decrypt the alert
3258 * we're about to send. */
3259 rv |= ssl3_FlushHandshake(ss, 0);
3260 if (rv != SECSuccess) {
3261 if (err) {
3262 PORT_SetErrorPORT_SetError_Util(err);
3263 }
3264 return SECFailure;
3265 }
3266
3267 /* Compute the rest of the secrets except for the resumption
3268 * and exporter secret. */
3269 rv = tls13_ComputeApplicationSecrets(ss);
3270 if (rv != SECSuccess) {
3271 LOG_ERROR(ss, PORT_GetError())do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, PORT_GetError_Util(), __func__, "tls13con.c"
, 3271); PORT_SetError_Util(PORT_GetError_Util()); } while (0
)
;
3272 return SECFailure;
3273 }
3274
3275 rv = tls13_SetCipherSpec(ss, TrafficKeyApplicationData,
3276 ssl_secret_write, PR_FALSE0);
3277 if (rv != SECSuccess) {
3278 LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE)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__, "tls13con.c"
, 3278); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0)
;
3279 return SECFailure;
3280 }
3281
3282 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
3283 /* We need this for reading ACKs. */
3284 ssl_CipherSpecAddRef(ss->ssl3.crSpec);
3285 }
3286 if (ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) {
3287 rv = tls13_SetCipherSpec(ss, TrafficKeyEarlyApplicationData,
3288 ssl_secret_read, PR_TRUE1);
3289 if (rv != SECSuccess) {
3290 LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE)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__, "tls13con.c"
, 3290); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0)
;
3291 return SECFailure;
3292 }
3293 TLS13_SET_HS_STATE(ss, wait_end_of_early_data)tls13_SetHsState(ss, wait_end_of_early_data, __func__, "tls13con.c"
, 3293)
;
3294 } else {
3295 PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_none ||((ss->ssl3.hs.zeroRttState == ssl_0rtt_none || ss->ssl3
.hs.zeroRttState == ssl_0rtt_ignored)?((void)0):PR_Assert("ss->ssl3.hs.zeroRttState == ssl_0rtt_none || ss->ssl3.hs.zeroRttState == ssl_0rtt_ignored"
,"tls13con.c",3296))
3296 ss->ssl3.hs.zeroRttState == ssl_0rtt_ignored)((ss->ssl3.hs.zeroRttState == ssl_0rtt_none || ss->ssl3
.hs.zeroRttState == ssl_0rtt_ignored)?((void)0):PR_Assert("ss->ssl3.hs.zeroRttState == ssl_0rtt_none || ss->ssl3.hs.zeroRttState == ssl_0rtt_ignored"
,"tls13con.c",3296))
;
3297
3298 rv = tls13_SetCipherSpec(ss,
3299 TrafficKeyHandshake,
3300 ssl_secret_read, PR_FALSE0);
3301 if (rv != SECSuccess) {
3302 LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE)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__, "tls13con.c"
, 3302); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0)
;
3303 return SECFailure;
3304 }
3305 if (tls13_ShouldRequestClientAuth(ss)) {
3306 TLS13_SET_HS_STATE(ss, wait_client_cert)tls13_SetHsState(ss, wait_client_cert, __func__, "tls13con.c"
, 3306)
;
3307 } else {
3308 TLS13_SET_HS_STATE(ss, wait_finished)tls13_SetHsState(ss, wait_finished, __func__, "tls13con.c", 3308
)
;
3309 }
3310 }
3311
3312 /* Here we set a baseline value for our RTT estimation.
3313 * This value is updated when we get a response from the client. */
3314 ss->ssl3.hs.rttEstimate = ssl_Time(ss);
3315 return SECSuccess;
3316}
3317
3318SECStatus
3319tls13_HandleServerHelloPart2(sslSocket *ss, const PRUint8 *savedMsg, PRUint32 savedLength)
3320{
3321 SECStatus rv;
3322 sslSessionID *sid = ss->sec.ci.sid;
3323 SSL3Statistics *ssl3stats = SSL_GetStatistics();
3324
3325 if (ssl3_ExtensionNegotiated(ss, ssl_tls13_pre_shared_key_xtn)) {
3326 PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks))((!((&ss->ssl3.hs.psks)->next == (&ss->ssl3.
hs.psks)))?((void)0):PR_Assert("!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks)"
,"tls13con.c",3326))
;
3327 PORT_Assert(ss->xtnData.selectedPsk)((ss->xtnData.selectedPsk)?((void)0):PR_Assert("ss->xtnData.selectedPsk"
,"tls13con.c",3327))
;
3328
3329 if (ss->xtnData.selectedPsk->type != ssl_psk_resume) {
3330 ss->statelessResume = PR_FALSE0;
3331 }
3332 } else {
3333 /* We may have offered a PSK. If the server didn't negotiate
3334 * it, clear this state to re-extract the Early Secret. */
3335 if (ss->ssl3.hs.currentSecret) {
3336 /* We might have dropped incompatible PSKs on HRR
3337 * (see RFC8466, Section 4.1.4). */
3338 PORT_Assert(ss->ssl3.hs.helloRetry ||((ss->ssl3.hs.helloRetry || ssl3_ExtensionAdvertised(ss, ssl_tls13_pre_shared_key_xtn
))?((void)0):PR_Assert("ss->ssl3.hs.helloRetry || ssl3_ExtensionAdvertised(ss, ssl_tls13_pre_shared_key_xtn)"
,"tls13con.c",3339))
3339 ssl3_ExtensionAdvertised(ss, ssl_tls13_pre_shared_key_xtn))((ss->ssl3.hs.helloRetry || ssl3_ExtensionAdvertised(ss, ssl_tls13_pre_shared_key_xtn
))?((void)0):PR_Assert("ss->ssl3.hs.helloRetry || ssl3_ExtensionAdvertised(ss, ssl_tls13_pre_shared_key_xtn)"
,"tls13con.c",3339))
;
3340 PK11_FreeSymKey(ss->ssl3.hs.currentSecret);
3341 ss->ssl3.hs.currentSecret = NULL((void*)0);
3342 }
3343 ss->statelessResume = PR_FALSE0;
3344 ss->xtnData.selectedPsk = NULL((void*)0);
3345 }
3346
3347 if (ss->statelessResume) {
3348 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"
,"tls13con.c",3348))
;
3349 if (tls13_GetHash(ss) !=
3350 tls13_GetHashForCipherSuite(sid->u.ssl3.cipherSuite)) {
3351 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_SERVER_HELLO,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_SERVER_HELLO, __func__
, "tls13con.c", 3352); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_SERVER_HELLO
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_SERVER_HELLO
, illegal_parameter); } while (0)
3352 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_SERVER_HELLO, __func__
, "tls13con.c", 3352); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_SERVER_HELLO
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_SERVER_HELLO
, illegal_parameter); } while (0)
;
3353 return SECFailure;
3354 }
3355 }
3356
3357 /* Now create a synthetic kea_def that we can tweak. */
3358 ss->ssl3.hs.kea_def_mutable = *ss->ssl3.hs.kea_def;
3359 ss->ssl3.hs.kea_def = &ss->ssl3.hs.kea_def_mutable;
3360
3361 if (ss->xtnData.selectedPsk) {
3362 ss->ssl3.hs.kea_def_mutable.authKeyType = ssl_auth_psk;
3363 if (ss->statelessResume) {
3364 tls13_RestoreCipherInfo(ss, sid);
3365 if (sid->peerCert) {
3366 ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
3367 }
3368
3369 SSL_AtomicIncrementLong(&ssl3stats->hsh_sid_cache_hits);
3370 SSL_AtomicIncrementLong(&ssl3stats->hsh_sid_stateless_resumes);
3371 } else {
3372 ss->sec.authType = ssl_auth_psk;
3373 }
3374 } else {
3375 if (ss->statelessResume &&
3376 ssl3_ExtensionAdvertised(ss, ssl_tls13_pre_shared_key_xtn)) {
3377 SSL_AtomicIncrementLong(&ssl3stats->hsh_sid_cache_misses);
3378 }
3379 if (sid->cached == in_client_cache) {
3380 /* If we tried to resume and failed, let's not try again. */
3381 ssl_UncacheSessionID(ss);
3382 }
3383 }
3384
3385 /* Discard current SID and make a new one, though it may eventually
3386 * end up looking a lot like the old one.
3387 */
3388 ssl_FreeSID(sid);
3389 ss->sec.ci.sid = sid = ssl3_NewSessionID(ss, PR_FALSE0);
3390 if (sid == NULL((void*)0)) {
3391 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__, "tls13con.c"
, 3391); PORT_SetError_Util(PORT_GetError_Util()); } while (0
); tls13_FatalError(ss, PORT_GetError_Util(), internal_error)
; } while (0)
;
3392 return SECFailure;
3393 }
3394 if (ss->statelessResume) {
3395 PORT_Assert(ss->sec.peerCert)((ss->sec.peerCert)?((void)0):PR_Assert("ss->sec.peerCert"
,"tls13con.c",3395))
;
3396 sid->peerCert = CERT_DupCertificate(ss->sec.peerCert);
3397 }
3398 sid->version = ss->version;
3399
3400 rv = tls13_HandleServerKeyShare(ss);
3401 if (rv != SECSuccess) {
3402 return SECFailure;
3403 }
3404
3405 rv = tls13_ComputeHandshakeSecret(ss);
3406 if (rv != SECSuccess) {
3407 return SECFailure; /* error code is set. */
3408 }
3409
3410 rv = tls13_MaybeHandleEchSignal(ss, savedMsg, savedLength, PR_FALSE0);
3411 if (rv != SECSuccess) {
3412 return SECFailure; /* error code is set. */
3413 }
3414
3415 rv = tls13_ComputeHandshakeSecrets(ss);
3416 if (rv != SECSuccess) {
3417 return SECFailure; /* error code is set. */
3418 }
3419
3420 if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent) {
3421 /* When we send 0-RTT, we saved the null spec in case we needed it to
3422 * send another ClientHello in response to a HelloRetryRequest. Now
3423 * that we won't be receiving a HelloRetryRequest, release the spec. */
3424 ssl_CipherSpecReleaseByEpoch(ss, ssl_secret_write, TrafficKeyClearText);
3425 }
3426
3427 rv = tls13_SetCipherSpec(ss, TrafficKeyHandshake,
3428 ssl_secret_read, PR_FALSE0);
3429 if (rv != SECSuccess) {
3430 FATAL_ERROR(ss, SSL_ERROR_INIT_CIPHER_SUITE_FAILURE, internal_error)do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_INIT_CIPHER_SUITE_FAILURE, __func__
, "tls13con.c", 3430); PORT_SetError_Util(SSL_ERROR_INIT_CIPHER_SUITE_FAILURE
); } while (0); tls13_FatalError(ss, SSL_ERROR_INIT_CIPHER_SUITE_FAILURE
, internal_error); } while (0)
;
3431 return SECFailure;
3432 }
3433 TLS13_SET_HS_STATE(ss, wait_encrypted_extensions)tls13_SetHsState(ss, wait_encrypted_extensions, __func__, "tls13con.c"
, 3433)
;
3434
3435 return SECSuccess;
3436}
3437
3438static void
3439tls13_SetKeyExchangeType(sslSocket *ss, const sslNamedGroupDef *group)
3440{
3441 ss->sec.keaGroup = group;
3442 switch (group->keaType) {
3443 /* Note: These overwrite on resumption.... so if you start with ECDH
3444 * and resume with DH, we report DH. That's fine, since no answer
3445 * is really right. */
3446 case ssl_kea_ecdh:
3447 ss->ssl3.hs.kea_def_mutable.exchKeyType =
3448 ss->statelessResume ? ssl_kea_ecdh_psk : ssl_kea_ecdh;
3449 ss->sec.keaType = ssl_kea_ecdh;
3450 break;
3451 case ssl_kea_ecdh_hybrid:
3452 ss->ssl3.hs.kea_def_mutable.exchKeyType =
3453 ss->statelessResume ? ssl_kea_ecdh_hybrid_psk : ssl_kea_ecdh_hybrid;
3454 ss->sec.keaType = ssl_kea_ecdh_hybrid;
3455 break;
3456 case ssl_kea_dh:
3457 ss->ssl3.hs.kea_def_mutable.exchKeyType =
3458 ss->statelessResume ? ssl_kea_dh_psk : ssl_kea_dh;
3459 ss->sec.keaType = ssl_kea_dh;
3460 break;
3461 default:
3462 PORT_Assert(0)((0)?((void)0):PR_Assert("0","tls13con.c",3462));
3463 }
3464}
3465
3466/*
3467 * Called from ssl3_HandleServerHello.
3468 *
3469 * Caller must hold Handshake and RecvBuf locks.
3470 */
3471static SECStatus
3472tls13_HandleServerKeyShare(sslSocket *ss)
3473{
3474 SECStatus rv;
3475 TLS13KeyShareEntry *entry;
3476 sslEphemeralKeyPair *keyPair;
3477 PK11SymKey *dheSecret = NULL((void*)0);
3478 PK11SymKey *kemSecret = NULL((void*)0);
3479
3480 SSL_TRC(3, ("%d: TLS13[%d]: handle server_key_share handshake",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: handle server_key_share handshake"
, getpid(), ss->fd)
3481 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: handle server_key_share handshake"
, getpid(), ss->fd)
;
3482 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)"
,"tls13con.c",3482))
;
3483 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)"
,"tls13con.c",3483))
;
3484
3485 /* This list should have one entry. */
3486 if (PR_CLIST_IS_EMPTY(&ss->xtnData.remoteKeyShares)((&ss->xtnData.remoteKeyShares)->next == (&ss->
xtnData.remoteKeyShares))
) {
3487 FATAL_ERROR(ss, SSL_ERROR_MISSING_KEY_SHARE, missing_extension)do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_MISSING_KEY_SHARE, __func__,
"tls13con.c", 3487); PORT_SetError_Util(SSL_ERROR_MISSING_KEY_SHARE
); } while (0); tls13_FatalError(ss, SSL_ERROR_MISSING_KEY_SHARE
, missing_extension); } while (0)
;
3488 return SECFailure;
3489 }
3490
3491 entry = (TLS13KeyShareEntry *)PR_NEXT_LINK(&ss->xtnData.remoteKeyShares)((&ss->xtnData.remoteKeyShares)->next);
3492 PORT_Assert(PR_NEXT_LINK(&entry->link) == &ss->xtnData.remoteKeyShares)((((&entry->link)->next) == &ss->xtnData.remoteKeyShares
)?((void)0):PR_Assert("PR_NEXT_LINK(&entry->link) == &ss->xtnData.remoteKeyShares"
,"tls13con.c",3492))
;
3493
3494 /* Now get our matching key. */
3495 keyPair = ssl_LookupEphemeralKeyPair(ss, entry->group);
3496 if (!keyPair) {
3497 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_KEY_SHARE, 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_KEY_SHARE, __func__
, "tls13con.c", 3497); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_KEY_SHARE
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_KEY_SHARE
, illegal_parameter); } while (0)
;
3498 return SECFailure;
3499 }
3500
3501 PORT_Assert(ssl_NamedGroupEnabled(ss, entry->group))((ssl_NamedGroupEnabled(ss, entry->group))?((void)0):PR_Assert
("ssl_NamedGroupEnabled(ss, entry->group)","tls13con.c",3501
))
;
3502
3503 rv = tls13_HandleKeyShare(ss, entry, keyPair->keys,
3504 tls13_GetHash(ss),
3505 &dheSecret);
3506 if (rv != SECSuccess) {
3507 goto loser; /* Error code already set. */
3508 }
3509
3510 if (entry->group->keaType == ssl_kea_ecdh_hybrid) {
3511 rv = tls13_HandleKEMCiphertext(ss, entry, keyPair->kemKeys, &kemSecret);
3512 if (rv != SECSuccess) {
3513 goto loser; /* Error set by tls13_HandleKEMCiphertext */
3514 }
3515 // We may need to handle different "combiners" here in the future. For
3516 // now this is specific to xyber768d00.
3517 PORT_Assert(entry->group->name == ssl_grp_kem_xyber768d00)((entry->group->name == ssl_grp_kem_xyber768d00)?((void
)0):PR_Assert("entry->group->name == ssl_grp_kem_xyber768d00"
,"tls13con.c",3517))
;
3518 ss->ssl3.hs.dheSecret = PK11_ConcatSymKeys(dheSecret, kemSecret, CKM_HKDF_DERIVE0x0000402aUL, CKA_DERIVE0x0000010CUL);
3519 if (!ss->ssl3.hs.dheSecret) {
3520 goto loser; /* Error set by PK11_ConcatSymKeys */
3521 }
3522 PK11_FreeSymKey(dheSecret);
3523 PK11_FreeSymKey(kemSecret);
3524 } else {
3525 ss->ssl3.hs.dheSecret = dheSecret;
3526 }
3527
3528 tls13_SetKeyExchangeType(ss, entry->group);
3529 ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits(keyPair->keys->pubKey);
3530
3531 return SECSuccess;
3532
3533loser:
3534 PK11_FreeSymKey(dheSecret);
3535 PK11_FreeSymKey(kemSecret);
3536 FATAL_ERROR(ss, PORT_GetError(), illegal_parameter)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__, "tls13con.c"
, 3536); PORT_SetError_Util(PORT_GetError_Util()); } while (0
); tls13_FatalError(ss, PORT_GetError_Util(), illegal_parameter
); } while (0)
;
3537 return SECFailure;
3538}
3539
3540static PRBool
3541tls13_FindCompressionAlgAndCheckIfSupportsEncoding(sslSocket *ss)
3542{
3543 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)"
,"tls13con.c",3543))
;
3544 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)"
,"tls13con.c",3544))
;
3545
3546 for (int j = 0; j < ss->ssl3.supportedCertCompressionAlgorithmsCount; j++) {
3547 if (ss->ssl3.supportedCertCompressionAlgorithms[j].id == ss->xtnData.compressionAlg) {
3548 if (ss->ssl3.supportedCertCompressionAlgorithms[j].encode != NULL((void*)0)) {
3549 return PR_TRUE1;
3550 }
3551 return PR_FALSE0;
3552 }
3553 }
3554
3555 return PR_FALSE0;
3556}
3557
3558static SECStatus
3559tls13_FindCompressionAlgAndEncodeCertificate(
3560 sslSocket *ss, SECItem *certificateToEncode, SECItem *encodedCertificate)
3561{
3562 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)"
,"tls13con.c",3562))
;
3563 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)"
,"tls13con.c",3563))
;
3564
3565 SECStatus rv = SECFailure;
3566 for (int j = 0; j < ss->ssl3.supportedCertCompressionAlgorithmsCount; j++) {
3567 if (ss->ssl3.supportedCertCompressionAlgorithms[j].id == ss->xtnData.compressionAlg &&
3568 ss->ssl3.supportedCertCompressionAlgorithms[j].encode != NULL((void*)0)) {
3569 rv = ss->ssl3.supportedCertCompressionAlgorithms[j].encode(
3570 certificateToEncode, encodedCertificate);
3571 return rv;
3572 }
3573 }
3574
3575 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_CERTIFICATE_COMPRESSION_ALGORITHM_NOT_SUPPORTED);
3576 return SECFailure;
3577}
3578
3579static SECStatus
3580tls13_SendCompressedCertificate(sslSocket *ss, sslBuffer *bufferCertificate)
3581{
3582 /* TLS Certificate Compression. RFC 8879 */
3583 /* As the encoding function takes as input a SECItem,
3584 * we convert bufferCertificate to certificateToEncode.
3585 *
3586 * encodedCertificate is used to store the certificate
3587 * after encoding.
3588 */
3589 SECItem encodedCertificate = { siBuffer, NULL((void*)0), 0 };
3590 SECItem certificateToEncode = { siBuffer, NULL((void*)0), 0 };
3591 SECStatus rv = SECFailure;
3592
3593 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)"
,"tls13con.c",3593))
;
3594 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)"
,"tls13con.c",3594))
;
3595
3596 SSL_TRC(30, ("%d: TLS13[%d]: %s is encoding the certificate using the %s compression algorithm",if (ssl_trace >= (30)) ssl_Trace ("%d: TLS13[%d]: %s is encoding the certificate using the %s compression algorithm"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
), ssl3_mapCertificateCompressionAlgorithmToName(ss, ss->xtnData
.compressionAlg))
3597 SSL_GETPID(), ss->fd, SSL_ROLE(ss),if (ssl_trace >= (30)) ssl_Trace ("%d: TLS13[%d]: %s is encoding the certificate using the %s compression algorithm"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
), ssl3_mapCertificateCompressionAlgorithmToName(ss, ss->xtnData
.compressionAlg))
3598 ssl3_mapCertificateCompressionAlgorithmToName(ss, ss->xtnData.compressionAlg)))if (ssl_trace >= (30)) ssl_Trace ("%d: TLS13[%d]: %s is encoding the certificate using the %s compression algorithm"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
), ssl3_mapCertificateCompressionAlgorithmToName(ss, ss->xtnData
.compressionAlg))
;
3599
3600 PRINT_BUF(50, (NULL, "The certificate before encoding:",if (ssl_trace >= (50)) ssl_PrintBuf (((void*)0), "The certificate before encoding:"
, bufferCertificate->buf, bufferCertificate->len)
3601 bufferCertificate->buf, bufferCertificate->len))if (ssl_trace >= (50)) ssl_PrintBuf (((void*)0), "The certificate before encoding:"
, bufferCertificate->buf, bufferCertificate->len)
;
3602
3603 PRUint32 lengthUnencodedMessage = bufferCertificate->len;
3604 rv = ssl3_CopyToSECItem(bufferCertificate, &certificateToEncode);
3605 if (rv != SECSuccess) {
3606 SSL_TRC(50, ("%d: TLS13[%d]: %s has failed encoding the certificate.",if (ssl_trace >= (50)) ssl_Trace ("%d: TLS13[%d]: %s has failed encoding the certificate."
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
))
3607 SSL_GETPID(), ss->fd, SSL_ROLE(ss)))if (ssl_trace >= (50)) ssl_Trace ("%d: TLS13[%d]: %s has failed encoding the certificate."
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
))
;
3608 goto loser; /* Code already set. */
3609 }
3610
3611 rv = tls13_FindCompressionAlgAndEncodeCertificate(ss, &certificateToEncode,
3612 &encodedCertificate);
3613 if (rv != SECSuccess) {
3614 SSL_TRC(50, ("%d: TLS13[%d]: %s has failed encoding the certificate.",if (ssl_trace >= (50)) ssl_Trace ("%d: TLS13[%d]: %s has failed encoding the certificate."
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
))
3615 SSL_GETPID(), ss->fd, SSL_ROLE(ss)))if (ssl_trace >= (50)) ssl_Trace ("%d: TLS13[%d]: %s has failed encoding the certificate."
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
))
;
3616 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_NO_MEMORY);
3617 goto loser; /* Code already set. */
3618 }
3619
3620 /* The CompressedCertificate message is formed as follows:
3621 * struct {
3622 * CertificateCompressionAlgorithm algorithm;
3623 * uint24 uncompressed_length;
3624 * opaque compressed_certificate_message<1..2^24-1>;
3625 * } CompressedCertificate;
3626 */
3627
3628 if (encodedCertificate.len < 1) {
3629 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
3630 goto loser;
3631 }
3632
3633 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_compressed_certificate,
3634 encodedCertificate.len + 2 + 3 + 3);
3635 if (rv != SECSuccess) {
3636 goto loser; /* err set by AppendHandshake. */
3637 }
3638
3639 rv = ssl3_AppendHandshakeNumber(ss, ss->xtnData.compressionAlg, 2);
3640 if (rv != SECSuccess) {
3641 goto loser; /* err set by AppendHandshake. */
3642 }
3643
3644 rv = ssl3_AppendHandshakeNumber(ss, lengthUnencodedMessage, 3);
3645 if (rv != SECSuccess) {
3646 goto loser; /* err set by AppendHandshake. */
3647 }
3648
3649 PRINT_BUF(30, (NULL, "The encoded certificate: ",if (ssl_trace >= (30)) ssl_PrintBuf (((void*)0), "The encoded certificate: "
, encodedCertificate.data, encodedCertificate.len)
3650 encodedCertificate.data, encodedCertificate.len))if (ssl_trace >= (30)) ssl_PrintBuf (((void*)0), "The encoded certificate: "
, encodedCertificate.data, encodedCertificate.len)
;
3651
3652 rv = ssl3_AppendHandshakeVariable(ss, encodedCertificate.data, encodedCertificate.len, 3);
3653 if (rv != SECSuccess) {
3654 goto loser; /* err set by AppendHandshake. */
3655 }
3656
3657 SECITEM_FreeItemSECITEM_FreeItem_Util(&certificateToEncode, PR_FALSE0);
3658 SECITEM_FreeItemSECITEM_FreeItem_Util(&encodedCertificate, PR_FALSE0);
3659 return SECSuccess;
3660
3661loser:
3662 SECITEM_FreeItemSECITEM_FreeItem_Util(&certificateToEncode, PR_FALSE0);
3663 SECITEM_FreeItemSECITEM_FreeItem_Util(&encodedCertificate, PR_FALSE0);
3664 return SECFailure;
3665}
3666
3667/*
3668 * opaque ASN1Cert<1..2^24-1>;
3669 *
3670 * struct {
3671 * ASN1Cert cert_data;
3672 * Extension extensions<0..2^16-1>;
3673 * } CertificateEntry;
3674 *
3675 * struct {
3676 * opaque certificate_request_context<0..2^8-1>;
3677 * CertificateEntry certificate_list<0..2^24-1>;
3678 * } Certificate;
3679 */
3680static SECStatus
3681tls13_SendCertificate(sslSocket *ss)
3682{
3683 SECStatus rv;
3684 CERTCertificateList *certChain;
3685 int certChainLen = 0;
3686 int i;
3687 SECItem context = { siBuffer, NULL((void*)0), 0 };
3688 sslBuffer extensionBuf = SSL_BUFFER_EMPTY{ ((void*)0), 0, 0, 0 };
3689 sslBuffer bufferCertificate = SSL_BUFFER_EMPTY{ ((void*)0), 0, 0, 0 };
3690
3691 SSL_TRC(3, ("%d: TLS1.3[%d]: send certificate handshake",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS1.3[%d]: send certificate handshake"
, getpid(), ss->fd)
3692 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS1.3[%d]: send certificate handshake"
, getpid(), ss->fd)
;
3693
3694 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)"
,"tls13con.c",3694))
;
3695 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)"
,"tls13con.c",3695))
;
3696
3697 if (ss->sec.isServer) {
3698 PORT_Assert(!ss->sec.localCert)((!ss->sec.localCert)?((void)0):PR_Assert("!ss->sec.localCert"
,"tls13con.c",3698))
;
3699 /* A server certificate is selected in tls13_SelectServerCert(). */
3700 PORT_Assert(ss->sec.serverCert)((ss->sec.serverCert)?((void)0):PR_Assert("ss->sec.serverCert"
,"tls13con.c",3700))
;
3701
3702 certChain = ss->sec.serverCert->serverCertChain;
3703 ss->sec.localCert = CERT_DupCertificate(ss->sec.serverCert->serverCert);
3704 } else {
3705 if (ss->sec.localCert)
3706 CERT_DestroyCertificate(ss->sec.localCert);
3707
3708 certChain = ss->ssl3.clientCertChain;
3709 ss->sec.localCert = CERT_DupCertificate(ss->ssl3.clientCertificate);
3710 }
3711
3712 if (!ss->sec.isServer) {
3713 PORT_Assert(ss->ssl3.hs.clientCertRequested)((ss->ssl3.hs.clientCertRequested)?((void)0):PR_Assert("ss->ssl3.hs.clientCertRequested"
,"tls13con.c",3713))
;
3714 context = ss->xtnData.certReqContext;
3715 }
3716
3717 if (certChain) {
3718 for (i = 0; i < certChain->len; i++) {
3719 /* Each cert is 3 octet length, cert, and extensions */
3720 certChainLen += 3 + certChain->certs[i].len + 2;
3721 }
3722
3723 /* Build the extensions. This only applies to the leaf cert, because we
3724 * don't yet send extensions for non-leaf certs. */
3725 rv = ssl_ConstructExtensions(ss, &extensionBuf, ssl_hs_certificate);
3726 if (rv != SECSuccess) {
3727 return SECFailure; /* code already set */
3728 }
3729 /* extensionBuf.len is only added once, for the leaf cert. */
3730 certChainLen += SSL_BUFFER_LEN(&extensionBuf)((&extensionBuf)->len);
3731 }
3732
3733 rv = sslBuffer_AppendVariable(&bufferCertificate, context.data, context.len, 1);
3734 if (rv != SECSuccess) {
3735 goto loser; /* Code already set. */
3736 }
3737
3738 rv = sslBuffer_AppendNumber(&bufferCertificate, certChainLen, 3);
3739 if (rv != SECSuccess) {
3740 goto loser; /* Code already set. */
3741 }
3742
3743 if (certChain) {
3744 for (i = 0; i < certChain->len; i++) {
3745 rv = sslBuffer_AppendVariable(&bufferCertificate, certChain->certs[i].data,
3746 certChain->certs[i].len, 3);
3747 if (rv != SECSuccess) {
3748 goto loser; /* Code already set. */
3749 }
3750
3751 if (i) {
3752 /* Not end-entity. */
3753 rv = sslBuffer_AppendNumber(&bufferCertificate, 0, 2);
3754 if (rv != SECSuccess) {
3755 goto loser; /* Code already set. */
3756 }
3757 continue;
3758 }
3759
3760 rv = sslBuffer_AppendBufferVariable(&bufferCertificate, &extensionBuf, 2);
3761 if (rv != SECSuccess) {
3762 goto loser; /* Code already set. */
3763 }
3764 }
3765 }
3766
3767 /* If no compression mechanism was established or
3768 * the compression mechanism supports only decoding,
3769 * we continue as before. */
3770 if (ss->xtnData.compressionAlg == 0 || !tls13_FindCompressionAlgAndCheckIfSupportsEncoding(ss)) {
3771 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate,
3772 1 + context.len + 3 + certChainLen);
3773 if (rv != SECSuccess) {
3774 goto loser; /* err set by AppendHandshake. */
3775 }
3776 rv = ssl3_AppendBufferToHandshake(ss, &bufferCertificate);
3777 if (rv != SECSuccess) {
3778 goto loser; /* err set by AppendHandshake. */
3779 }
3780 } else {
3781 rv = tls13_SendCompressedCertificate(ss, &bufferCertificate);
3782 if (rv != SECSuccess) {
3783 goto loser; /* err set by tls13_SendCompressedCertificate. */
3784 }
3785 }
3786
3787 sslBuffer_Clear(&bufferCertificate);
3788 sslBuffer_Clear(&extensionBuf);
3789 return SECSuccess;
3790
3791loser:
3792 sslBuffer_Clear(&bufferCertificate);
3793 sslBuffer_Clear(&extensionBuf);
3794 return SECFailure;
3795}
3796
3797static SECStatus
3798tls13_HandleCertificateEntry(sslSocket *ss, SECItem *data, PRBool first,
3799 CERTCertificate **certp)
3800{
3801 SECStatus rv;
3802 SECItem certData;
3803 SECItem extensionsData;
3804 CERTCertificate *cert = NULL((void*)0);
3805
3806 rv = ssl3_ConsumeHandshakeVariable(ss, &certData,
3807 3, &data->data, &data->len);
3808 if (rv != SECSuccess) {
3809 return SECFailure;
3810 }
3811
3812 rv = ssl3_ConsumeHandshakeVariable(ss, &extensionsData,
3813 2, &data->data, &data->len);
3814 if (rv != SECSuccess) {
3815 return SECFailure;
3816 }
3817
3818 /* Parse all the extensions. */
3819 if (first && !ss->sec.isServer) {
3820 rv = ssl3_HandleExtensions(ss, &extensionsData.data,
3821 &extensionsData.len,
3822 ssl_hs_certificate);
3823 if (rv != SECSuccess) {
3824 return SECFailure;
3825 }
3826 /* TODO(ekr@rtfm.com): Copy out SCTs. Bug 1315727. */
3827 }
3828
3829 cert = CERT_NewTempCertificate(ss->dbHandle, &certData, NULL((void*)0),
3830 PR_FALSE0, PR_TRUE1);
3831
3832 if (!cert) {
3833 PRErrorCode errCode = PORT_GetErrorPORT_GetError_Util();
3834 switch (errCode) {
3835 case PR_OUT_OF_MEMORY_ERROR(-6000L):
3836 case SEC_ERROR_BAD_DATABASE:
3837 case SEC_ERROR_NO_MEMORY:
3838 FATAL_ERROR(ss, errCode, internal_error)do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, errCode, __func__, "tls13con.c", 3838)
; PORT_SetError_Util(errCode); } while (0); tls13_FatalError(
ss, errCode, internal_error); } while (0)
;
3839 return SECFailure;
3840 default:
3841 ssl3_SendAlertForCertError(ss, errCode);
3842 return SECFailure;
3843 }
3844 }
3845
3846 *certp = cert;
3847
3848 return SECSuccess;
3849}
3850
3851static SECStatus
3852tls13_EnsureCerticateExpected(sslSocket *ss)
3853{
3854 SECStatus rv = SECFailure;
3855 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)"
,"tls13con.c",3855))
;
3856 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)"
,"tls13con.c",3856))
;
3857
3858 if (ss->sec.isServer) {
3859 /* Receiving this message might be the first sign we have that
3860 * early data is over, so pretend we received EOED. */
3861 rv = tls13_MaybeHandleSuppressedEndOfEarlyData(ss);
3862 if (rv != SECSuccess) {
3863 return SECFailure; /* Code already set. */
3864 }
3865
3866 if (ss->ssl3.clientCertRequested) {
3867 rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERTIFICATE,tls13_CheckHsState(ss, SSL_ERROR_RX_UNEXPECTED_CERTIFICATE, "SSL_ERROR_RX_UNEXPECTED_CERTIFICATE"
, __func__, "tls13con.c", 3868, idle_handshake, wait_invalid)
3868 idle_handshake)tls13_CheckHsState(ss, SSL_ERROR_RX_UNEXPECTED_CERTIFICATE, "SSL_ERROR_RX_UNEXPECTED_CERTIFICATE"
, __func__, "tls13con.c", 3868, idle_handshake, wait_invalid)
;
3869 } else {
3870 rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERTIFICATE,tls13_CheckHsState(ss, SSL_ERROR_RX_UNEXPECTED_CERTIFICATE, "SSL_ERROR_RX_UNEXPECTED_CERTIFICATE"
, __func__, "tls13con.c", 3871, wait_client_cert, wait_invalid
)
3871 wait_client_cert)tls13_CheckHsState(ss, SSL_ERROR_RX_UNEXPECTED_CERTIFICATE, "SSL_ERROR_RX_UNEXPECTED_CERTIFICATE"
, __func__, "tls13con.c", 3871, wait_client_cert, wait_invalid
)
;
3872 }
3873 } else {
3874 rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERTIFICATE,tls13_CheckHsState(ss, SSL_ERROR_RX_UNEXPECTED_CERTIFICATE, "SSL_ERROR_RX_UNEXPECTED_CERTIFICATE"
, __func__, "tls13con.c", 3875, wait_cert_request, wait_server_cert
, wait_invalid)
3875 wait_cert_request, wait_server_cert)tls13_CheckHsState(ss, SSL_ERROR_RX_UNEXPECTED_CERTIFICATE, "SSL_ERROR_RX_UNEXPECTED_CERTIFICATE"
, __func__, "tls13con.c", 3875, wait_cert_request, wait_server_cert
, wait_invalid)
;
3876 }
3877 return rv;
3878}
3879
3880/* RFC 8879 TLS Certificate Compression
3881 * struct {
3882 * CertificateCompressionAlgorithm algorithm;
3883 * uint24 uncompressed_length;
3884 * opaque compressed_certificate_message<1..2^24-1>;
3885 * } CompressedCertificate;
3886 */
3887static SECStatus
3888tls13_HandleCertificateDecode(sslSocket *ss, PRUint8 *b, PRUint32 length)
3889{
3890 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)"
,"tls13con.c",3890))
;
3891 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)"
,"tls13con.c",3891))
;
3892
3893 SECStatus rv = SECFailure;
3894
3895 if (!ss->xtnData.certificateCompressionAdvertised) {
3896 FATAL_ERROR(ss, SEC_ERROR_UNEXPECTED_COMPRESSED_CERTIFICATE, decode_error)do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SEC_ERROR_UNEXPECTED_COMPRESSED_CERTIFICATE
, __func__, "tls13con.c", 3896); PORT_SetError_Util(SEC_ERROR_UNEXPECTED_COMPRESSED_CERTIFICATE
); } while (0); tls13_FatalError(ss, SEC_ERROR_UNEXPECTED_COMPRESSED_CERTIFICATE
, decode_error); } while (0)
;
3897 return SECFailure;
3898 }
3899
3900 rv = tls13_EnsureCerticateExpected(ss);
3901 if (rv != SECSuccess) {
3902 return SECFailure; /* Code already set. */
3903 }
3904
3905 if (ss->firstHsDone) {
3906 rv = ssl_HashPostHandshakeMessage(ss, ssl_hs_compressed_certificate, b, length);
3907 if (rv != SECSuccess) {
3908 return rv;
3909 }
3910 }
3911
3912 SSL_TRC(30, ("%d: TLS1.3[%d]: %s handles certificate compression handshake",if (ssl_trace >= (30)) ssl_Trace ("%d: TLS1.3[%d]: %s handles certificate compression handshake"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
))
3913 SSL_GETPID(), ss->fd, SSL_ROLE(ss)))if (ssl_trace >= (30)) ssl_Trace ("%d: TLS1.3[%d]: %s handles certificate compression handshake"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
))
;
3914
3915 PRINT_BUF(50, (NULL, "The certificate before decoding:", b, length))if (ssl_trace >= (50)) ssl_PrintBuf (((void*)0), "The certificate before decoding:"
, b, length)
;
3916 /* Reading CertificateCompressionAlgorithm. */
3917 PRUint32 compressionAlg = 0;
3918 rv = ssl3_ConsumeHandshakeNumber(ss, &compressionAlg, 2, &b, &length);
3919 if (rv != SECSuccess) {
3920 return SECFailure; /* Alert already sent. */
3921 }
3922
3923 PRBool compressionAlgorithmIsSupported = PR_FALSE0;
3924 SECStatus (*certificateDecodingFunc)(const SECItem *, SECItem *, size_t) = NULL((void*)0);
3925 for (int i = 0; i < ss->ssl3.supportedCertCompressionAlgorithmsCount; i++) {
3926 if (ss->ssl3.supportedCertCompressionAlgorithms[i].id == compressionAlg) {
3927 compressionAlgorithmIsSupported = PR_TRUE1;
3928 certificateDecodingFunc = ss->ssl3.supportedCertCompressionAlgorithms[i].decode;
3929 }
3930 }
3931
3932 /* Peer selected a compression algorithm we do not support (and did not advertise). */
3933 if (!compressionAlgorithmIsSupported) {
3934 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_CERTIFICATE_COMPRESSION_ALGORITHM_NOT_SUPPORTED);
3935 FATAL_ERROR(ss, PORT_GetError(), illegal_parameter)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__, "tls13con.c"
, 3935); PORT_SetError_Util(PORT_GetError_Util()); } while (0
); tls13_FatalError(ss, PORT_GetError_Util(), illegal_parameter
); } while (0)
;
3936 return SECFailure;
3937 }
3938
3939 /* The algorithm does not support decoding. */
3940 if (certificateDecodingFunc == NULL((void*)0)) {
3941 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
3942 FATAL_ERROR(ss, PORT_GetError(), illegal_parameter)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__, "tls13con.c"
, 3942); PORT_SetError_Util(PORT_GetError_Util()); } while (0
); tls13_FatalError(ss, PORT_GetError_Util(), illegal_parameter
); } while (0)
;
3943 return SECFailure;
3944 }
3945
3946 SSL_TRC(30, ("%d: TLS13[%d]: %s is decoding the certificate using the %s compression algorithm",if (ssl_trace >= (30)) ssl_Trace ("%d: TLS13[%d]: %s is decoding the certificate using the %s compression algorithm"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
), ssl3_mapCertificateCompressionAlgorithmToName(ss, compressionAlg
))
3947 SSL_GETPID(), ss->fd, SSL_ROLE(ss),if (ssl_trace >= (30)) ssl_Trace ("%d: TLS13[%d]: %s is decoding the certificate using the %s compression algorithm"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
), ssl3_mapCertificateCompressionAlgorithmToName(ss, compressionAlg
))
3948 ssl3_mapCertificateCompressionAlgorithmToName(ss, compressionAlg)))if (ssl_trace >= (30)) ssl_Trace ("%d: TLS13[%d]: %s is decoding the certificate using the %s compression algorithm"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
), ssl3_mapCertificateCompressionAlgorithmToName(ss, compressionAlg
))
;
3949 PRUint32 decodedCertificateLen = 0;
3950 rv = ssl3_ConsumeHandshakeNumber(ss, &decodedCertificateLen, 3, &b, &length);
3951 if (rv != SECSuccess) {
3952 return SECFailure; /* alert has been sent */
3953 }
3954
3955 /* If the received CompressedCertificate message cannot be decompressed,
3956 * he connection MUST be terminated with the "bad_certificate" alert.
3957 */
3958 if (decodedCertificateLen == 0) {
3959 SSL_TRC(50, ("%d: TLS13[%d]: %s decoded certificate length is incorrect",if (ssl_trace >= (50)) ssl_Trace ("%d: TLS13[%d]: %s decoded certificate length is incorrect"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
), ssl3_mapCertificateCompressionAlgorithmToName(ss, compressionAlg
))
3960 SSL_GETPID(), ss->fd, SSL_ROLE(ss),if (ssl_trace >= (50)) ssl_Trace ("%d: TLS13[%d]: %s decoded certificate length is incorrect"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
), ssl3_mapCertificateCompressionAlgorithmToName(ss, compressionAlg
))
3961 ssl3_mapCertificateCompressionAlgorithmToName(ss, compressionAlg)))if (ssl_trace >= (50)) ssl_Trace ("%d: TLS13[%d]: %s decoded certificate length is incorrect"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
), ssl3_mapCertificateCompressionAlgorithmToName(ss, compressionAlg
))
;
3962 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE, bad_certificate)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_CERTIFICATE, __func__
, "tls13con.c", 3962); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CERTIFICATE
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE
, bad_certificate); } while (0)
;
3963 return SECFailure;
3964 }
3965
3966 /* opaque compressed_certificate_message<1..2^24-1>; */
3967 PRUint32 compressedCertificateMessageLen = 0;
3968 rv = ssl3_ConsumeHandshakeNumber(ss, &compressedCertificateMessageLen, 3, &b, &length);
3969 if (rv != SECSuccess) {
3970 return SECFailure; /* alert has been sent */
3971 }
3972
3973 if (compressedCertificateMessageLen == 0 || compressedCertificateMessageLen != length) {
3974 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE, bad_certificate)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_CERTIFICATE, __func__
, "tls13con.c", 3974); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CERTIFICATE
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE
, bad_certificate); } while (0)
;
3975 return SECFailure;
3976 }
3977
3978 /* Decoding received certificate. */
3979 SECItem decodedCertificate = { siBuffer, NULL((void*)0), 0 };
3980 if (!SECITEM_AllocItemSECITEM_AllocItem_Util(NULL((void*)0), &decodedCertificate, decodedCertificateLen)) {
3981 FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, 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_NO_MEMORY, __func__, "tls13con.c"
, 3981); PORT_SetError_Util(SEC_ERROR_NO_MEMORY); } while (0)
; tls13_FatalError(ss, SEC_ERROR_NO_MEMORY, internal_error); }
while (0)
;
3982 return SECFailure;
3983 }
3984
3985 SECItem encodedCertAsSecItem = { siBuffer, b, compressedCertificateMessageLen };
3986 rv = certificateDecodingFunc(&encodedCertAsSecItem, &decodedCertificate, decodedCertificateLen);
3987
3988 if (rv != SECSuccess) {
3989 SSL_TRC(50, ("%d: TLS13[%d]: %s decoding of the certificate has failed",if (ssl_trace >= (50)) ssl_Trace ("%d: TLS13[%d]: %s decoding of the certificate has failed"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
), ssl3_mapCertificateCompressionAlgorithmToName(ss, compressionAlg
))
3990 SSL_GETPID(), ss->fd, SSL_ROLE(ss),if (ssl_trace >= (50)) ssl_Trace ("%d: TLS13[%d]: %s decoding of the certificate has failed"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
), ssl3_mapCertificateCompressionAlgorithmToName(ss, compressionAlg
))
3991 ssl3_mapCertificateCompressionAlgorithmToName(ss, compressionAlg)))if (ssl_trace >= (50)) ssl_Trace ("%d: TLS13[%d]: %s decoding of the certificate has failed"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
), ssl3_mapCertificateCompressionAlgorithmToName(ss, compressionAlg
))
;
3992 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE, bad_certificate)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_CERTIFICATE, __func__
, "tls13con.c", 3992); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CERTIFICATE
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE
, bad_certificate); } while (0)
;
3993 goto loser;
3994 }
3995 PRINT_BUF(60, (ss, "consume bytes:", b, compressedCertificateMessageLen))if (ssl_trace >= (60)) ssl_PrintBuf (ss, "consume bytes:",
b, compressedCertificateMessageLen)
;
3996 *b += compressedCertificateMessageLen;
3997 length -= compressedCertificateMessageLen;
3998
3999 /* If, after decompression, the specified length does not match the actual length,
4000 * the party receiving the invalid message MUST abort the connection
4001 * with the "bad_certificate" alert.
4002 */
4003 if (decodedCertificateLen != decodedCertificate.len) {
4004 SSL_TRC(50, ("%d: TLS13[%d]: %s certificate length does not correspond to extension length",if (ssl_trace >= (50)) ssl_Trace ("%d: TLS13[%d]: %s certificate length does not correspond to extension length"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
), ssl3_mapCertificateCompressionAlgorithmToName(ss, compressionAlg
))
4005 SSL_GETPID(), ss->fd, SSL_ROLE(ss),if (ssl_trace >= (50)) ssl_Trace ("%d: TLS13[%d]: %s certificate length does not correspond to extension length"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
), ssl3_mapCertificateCompressionAlgorithmToName(ss, compressionAlg
))
4006 ssl3_mapCertificateCompressionAlgorithmToName(ss, compressionAlg)))if (ssl_trace >= (50)) ssl_Trace ("%d: TLS13[%d]: %s certificate length does not correspond to extension length"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
), ssl3_mapCertificateCompressionAlgorithmToName(ss, compressionAlg
))
;
4007 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE, bad_certificate)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_CERTIFICATE, __func__
, "tls13con.c", 4007); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CERTIFICATE
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE
, bad_certificate); } while (0)
;
4008 goto loser;
4009 }
4010
4011 PRINT_BUF(50, (NULL, "Decoded certificate",if (ssl_trace >= (50)) ssl_PrintBuf (((void*)0), "Decoded certificate"
, decodedCertificate.data, decodedCertificate.len)
4012 decodedCertificate.data, decodedCertificate.len))if (ssl_trace >= (50)) ssl_PrintBuf (((void*)0), "Decoded certificate"
, decodedCertificate.data, decodedCertificate.len)
;
4013
4014 /* compressed_certificate_message: The result of applying the indicated
4015 * compression algorithm to the encoded Certificate message that
4016 * would have been sent if certificate compression was not in use.
4017 *
4018 * After decompression, the Certificate message MUST be processed as if
4019 * it were encoded without being compressed. This way, the parsing and
4020 * the verification have the same security properties as they would have
4021 * in TLS normally.
4022 */
4023 rv = tls13_HandleCertificate(ss, decodedCertificate.data, decodedCertificate.len, PR_TRUE1);
4024 if (rv != SECSuccess) {
4025 goto loser;
4026 }
4027 /* We allow only one compressed certificate to be handled after each
4028 certificate compression advertisement.
4029 See test CertificateCompression_TwoEncodedCertificateRequests. */
4030 ss->xtnData.certificateCompressionAdvertised = PR_FALSE0;
4031 SECITEM_FreeItemSECITEM_FreeItem_Util(&decodedCertificate, PR_FALSE0);
4032 return SECSuccess;
4033
4034loser:
4035 SECITEM_FreeItemSECITEM_FreeItem_Util(&decodedCertificate, PR_FALSE0);
4036 return SECFailure;
4037}
4038
4039/* Called from tls13_CompleteHandleHandshakeMessage() when it has deciphered a complete
4040 * tls13 Certificate message.
4041 * Caller must hold Handshake and RecvBuf locks.
4042 */
4043static SECStatus
4044tls13_HandleCertificate(sslSocket *ss, PRUint8 *b, PRUint32 length, PRBool alreadyHashed)
4045{
4046 SECStatus rv;
4047 SECItem context = { siBuffer, NULL((void*)0), 0 };
4048 SECItem certList;
4049 PRBool first = PR_TRUE1;
4050 ssl3CertNode *lastCert = NULL((void*)0);
4051
4052 SSL_TRC(3, ("%d: TLS13[%d]: handle certificate handshake",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: handle certificate handshake"
, getpid(), ss->fd)
4053 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: handle certificate handshake"
, getpid(), ss->fd)
;
4054 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)"
,"tls13con.c",4054))
;
4055 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)"
,"tls13con.c",4055))
;
4056
4057 rv = tls13_EnsureCerticateExpected(ss);
4058 if (rv != SECSuccess) {
4059 return SECFailure; /* Code already set. */
4060 }
4061
4062 /* We can ignore any other cleartext from the client. */
4063 if (ss->sec.isServer && IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
4064 ssl_CipherSpecReleaseByEpoch(ss, ssl_secret_read, TrafficKeyClearText);
4065 dtls_ReceivedFirstMessageInFlight(ss);
4066 }
4067
4068 /* AlreadyHashed is true only when Certificate Compression is used. */
4069 if (ss->firstHsDone && !alreadyHashed) {
4070 rv = ssl_HashPostHandshakeMessage(ss, ssl_hs_certificate, b, length);
4071 if (rv != SECSuccess) {
4072 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
4073 return SECFailure;
4074 }
4075 }
4076
4077 if (!ss->firstHsDone && ss->sec.isServer) {
4078 /* Our first shot an getting an RTT estimate. If the client took extra
4079 * time to fetch a certificate, this will be bad, but we can't do much
4080 * about that. */
4081 ss->ssl3.hs.rttEstimate = ssl_Time(ss) - ss->ssl3.hs.rttEstimate;
4082 }
4083
4084 /* Process the context string */
4085 rv = ssl3_ConsumeHandshakeVariable(ss, &context, 1, &b, &length);
4086 if (rv != SECSuccess)
4087 return SECFailure;
4088
4089 if (ss->ssl3.clientCertRequested) {
4090 PORT_Assert(ss->sec.isServer)((ss->sec.isServer)?((void)0):PR_Assert("ss->sec.isServer"
,"tls13con.c",4090))
;
4091 if (SECITEM_CompareItemSECITEM_CompareItem_Util(&context, &ss->xtnData.certReqContext) != 0) {
4092 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE, 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_CERTIFICATE, __func__
, "tls13con.c", 4092); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CERTIFICATE
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE
, illegal_parameter); } while (0)
;
4093 return SECFailure;
4094 }
4095 }
4096 rv = ssl3_ConsumeHandshakeVariable(ss, &certList, 3, &b, &length);
4097 if (rv != SECSuccess) {
4098 return SECFailure;
4099 }
4100 if (length) {
4101 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE, 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_CERTIFICATE, __func__
, "tls13con.c", 4101); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CERTIFICATE
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE
, illegal_parameter); } while (0)
;
4102 return SECFailure;
4103 }
4104
4105 if (!certList.len) {
4106 if (!ss->sec.isServer) {
4107 /* Servers always need to send some cert. */
4108 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE, bad_certificate)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_CERTIFICATE, __func__
, "tls13con.c", 4108); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CERTIFICATE
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE
, bad_certificate); } while (0)
;
4109 return SECFailure;
4110 } else {
4111 /* This is TLS's version of a no_certificate alert. */
4112 /* I'm a server. I've requested a client cert. He hasn't got one. */
4113 rv = ssl3_HandleNoCertificate(ss);
4114 if (rv != SECSuccess) {
4115 return SECFailure;
4116 }
4117
4118 TLS13_SET_HS_STATE(ss, wait_finished)tls13_SetHsState(ss, wait_finished, __func__, "tls13con.c", 4118
)
;
4119 return SECSuccess;
4120 }
4121 }
4122
4123 /* Now clean up. */
4124 ssl3_CleanupPeerCerts(ss);
4125 ss->ssl3.peerCertArena = PORT_NewArenaPORT_NewArena_Util(DER_DEFAULT_CHUNKSIZE(2048));
4126 if (ss->ssl3.peerCertArena == NULL((void*)0)) {
4127 FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, 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_NO_MEMORY, __func__, "tls13con.c"
, 4127); PORT_SetError_Util(SEC_ERROR_NO_MEMORY); } while (0)
; tls13_FatalError(ss, SEC_ERROR_NO_MEMORY, internal_error); }
while (0)
;
4128 return SECFailure;
4129 }
4130
4131 while (certList.len) {
4132 CERTCertificate *cert;
4133
4134 rv = tls13_HandleCertificateEntry(ss, &certList, first,
4135 &cert);
4136 if (rv != SECSuccess) {
4137 ss->xtnData.signedCertTimestamps.len = 0;
4138 return SECFailure;
4139 }
4140
4141 if (first) {
4142 ss->sec.peerCert = cert;
4143
4144 if (ss->xtnData.signedCertTimestamps.len) {
4145 sslSessionID *sid = ss->sec.ci.sid;
4146 rv = SECITEM_CopyItemSECITEM_CopyItem_Util(NULL((void*)0), &sid->u.ssl3.signedCertTimestamps,
4147 &ss->xtnData.signedCertTimestamps);
4148 ss->xtnData.signedCertTimestamps.len = 0;
4149 if (rv != SECSuccess) {
4150 FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, 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_NO_MEMORY, __func__, "tls13con.c"
, 4150); PORT_SetError_Util(SEC_ERROR_NO_MEMORY); } while (0)
; tls13_FatalError(ss, SEC_ERROR_NO_MEMORY, internal_error); }
while (0)
;
4151 return SECFailure;
4152 }
4153 }
4154 } else {
4155 ssl3CertNode *c = PORT_ArenaNew(ss->ssl3.peerCertArena,(ssl3CertNode *)PORT_ArenaAlloc_Util(ss->ssl3.peerCertArena
, sizeof(ssl3CertNode))
4156 ssl3CertNode)(ssl3CertNode *)PORT_ArenaAlloc_Util(ss->ssl3.peerCertArena
, sizeof(ssl3CertNode))
;
4157 if (!c) {
4158 FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, 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_NO_MEMORY, __func__, "tls13con.c"
, 4158); PORT_SetError_Util(SEC_ERROR_NO_MEMORY); } while (0)
; tls13_FatalError(ss, SEC_ERROR_NO_MEMORY, internal_error); }
while (0)
;
4159 return SECFailure;
4160 }
4161 c->cert = cert;
4162 c->next = NULL((void*)0);
4163
4164 if (lastCert) {
4165 lastCert->next = c;
4166 } else {
4167 ss->ssl3.peerCertChain = c;
4168 }
4169 lastCert = c;
4170 }
4171
4172 first = PR_FALSE0;
4173 }
4174 SECKEY_UpdateCertPQG(ss->sec.peerCert);
4175
4176 return ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
4177}
4178
4179/* Add context to the hash functions as described in
4180 [draft-ietf-tls-tls13; Section 4.9.1] */
4181SECStatus
4182tls13_AddContextToHashes(sslSocket *ss, const SSL3Hashes *hashes,
4183 SSLHashType algorithm, PRBool sending,
4184 SSL3Hashes *tbsHash)
4185{
4186 SECStatus rv = SECSuccess;
4187 PK11Context *ctx;
4188 const unsigned char context_padding[] = {
4189 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
4190 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
4191 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
4192 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
4193 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
4194 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
4195 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
4196 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20
4197 };
4198
4199 const char *client_cert_verify_string = "TLS 1.3, client CertificateVerify";
4200 const char *server_cert_verify_string = "TLS 1.3, server CertificateVerify";
4201 const char *context_string = (sending ^ ss->sec.isServer) ? client_cert_verify_string
4202 : server_cert_verify_string;
4203 unsigned int hashlength;
4204
4205 /* Double check that we are doing the same hash.*/
4206 PORT_Assert(hashes->len == tls13_GetHashSize(ss))((hashes->len == tls13_GetHashSize(ss))?((void)0):PR_Assert
("hashes->len == tls13_GetHashSize(ss)","tls13con.c",4206)
)
;
4207
4208 ctx = PK11_CreateDigestContext(ssl3_HashTypeToOID(algorithm));
4209 if (!ctx) {
4210 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_NO_MEMORY);
4211 goto loser;
4212 }
4213
4214 PORT_Assert(SECFailure)((SECFailure)?((void)0):PR_Assert("SECFailure","tls13con.c",4214
))
;
4215 PORT_Assert(!SECSuccess)((!SECSuccess)?((void)0):PR_Assert("!SECSuccess","tls13con.c"
,4215))
;
4216
4217 PRINT_BUF(50, (ss, "TLS 1.3 hash without context", hashes->u.raw, hashes->len))if (ssl_trace >= (50)) ssl_PrintBuf (ss, "TLS 1.3 hash without context"
, hashes->u.raw, hashes->len)
;
4218 PRINT_BUF(50, (ss, "Context string", context_string, strlen(context_string)))if (ssl_trace >= (50)) ssl_PrintBuf (ss, "Context string",
context_string, strlen(context_string))
;
4219 rv |= PK11_DigestBegin(ctx);
4220 rv |= PK11_DigestOp(ctx, context_padding, sizeof(context_padding));
4221 rv |= PK11_DigestOp(ctx, (unsigned char *)context_string,
4222 strlen(context_string) + 1); /* +1 includes the terminating 0 */
4223 rv |= PK11_DigestOp(ctx, hashes->u.raw, hashes->len);
4224 /* Update the hash in-place */
4225 rv |= PK11_DigestFinal(ctx, tbsHash->u.raw, &hashlength, sizeof(tbsHash->u.raw));
4226 PK11_DestroyContext(ctx, PR_TRUE1);
4227 PRINT_BUF(50, (ss, "TLS 1.3 hash with context", tbsHash->u.raw, hashlength))if (ssl_trace >= (50)) ssl_PrintBuf (ss, "TLS 1.3 hash with context"
, tbsHash->u.raw, hashlength)
;
4228
4229 tbsHash->len = hashlength;
4230 tbsHash->hashAlg = algorithm;
4231
4232 if (rv) {
4233 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4234 goto loser;
4235 }
4236 return SECSuccess;
4237
4238loser:
4239 return SECFailure;
4240}
4241
4242/*
4243 * Derive-Secret(Secret, Label, Messages) =
4244 * HKDF-Expand-Label(Secret, Label,
4245 * Hash(Messages) + Hash(resumption_context), L))
4246 */
4247SECStatus
4248tls13_DeriveSecret(sslSocket *ss, PK11SymKey *key,
4249 const char *label,
4250 unsigned int labelLen,
4251 const SSL3Hashes *hashes,
4252 PK11SymKey **dest,
4253 SSLHashType hash)
4254{
4255 SECStatus rv;
4256
4257 rv = tls13_HkdfExpandLabel(key, hash, hashes->u.raw, hashes->len,
4258 label, labelLen, CKM_HKDF_DERIVE0x0000402aUL,
4259 tls13_GetHashSizeForHash(hash),
4260 ss->protocolVariant, dest);
4261 if (rv != SECSuccess) {
4262 LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE)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__, "tls13con.c"
, 4262); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0)
;
4263 return SECFailure;
4264 }
4265 return SECSuccess;
4266}
4267
4268/* Convenience wrapper for the empty hash. */
4269SECStatus
4270tls13_DeriveSecretNullHash(sslSocket *ss, PK11SymKey *key,
4271 const char *label,
4272 unsigned int labelLen,
4273 PK11SymKey **dest,
4274 SSLHashType hash)
4275{
4276 SSL3Hashes hashes;
4277 SECStatus rv;
4278 PRUint8 buf[] = { 0 };
4279
4280 rv = tls13_ComputeHash(ss, &hashes, buf, 0, hash);
4281 if (rv != SECSuccess) {
4282 return SECFailure;
4283 }
4284
4285 return tls13_DeriveSecret(ss, key, label, labelLen, &hashes, dest, hash);
4286}
4287
4288/* Convenience wrapper that lets us supply a separate prefix and suffix. */
4289static SECStatus
4290tls13_DeriveSecretWrap(sslSocket *ss, PK11SymKey *key,
4291 const char *prefix,
4292 const char *suffix,
4293 const char *keylogLabel,
4294 PK11SymKey **dest)
4295{
4296 SECStatus rv;
4297 SSL3Hashes hashes;
4298 char buf[100];
4299 const char *label;
4300
4301 if (prefix) {
4302 if ((strlen(prefix) + strlen(suffix) + 2) > sizeof(buf)) {
4303 PORT_Assert(0)((0)?((void)0):PR_Assert("0","tls13con.c",4303));
4304 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
4305 return SECFailure;
4306 }
4307 (void)PR_snprintf(buf, sizeof(buf), "%s %s",
4308 prefix, suffix);
4309 label = buf;
4310 } else {
4311 label = suffix;
4312 }
4313
4314 SSL_TRC(3, ("%d: TLS13[%d]: deriving secret '%s'",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: deriving secret '%s'"
, getpid(), ss->fd, label)
4315 SSL_GETPID(), ss->fd, label))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: deriving secret '%s'"
, getpid(), ss->fd, label)
;
4316 rv = tls13_ComputeHandshakeHashes(ss, &hashes);
4317 if (rv != SECSuccess) {
4318 PORT_Assert(0)((0)?((void)0):PR_Assert("0","tls13con.c",4318)); /* Should never fail */
4319 ssl_MapLowLevelError(SEC_ERROR_LIBRARY_FAILURE);
4320 return SECFailure;
4321 }
4322
4323 rv = tls13_DeriveSecret(ss, key, label, strlen(label),
4324 &hashes, dest, tls13_GetHash(ss));
4325 if (rv != SECSuccess) {
4326 return SECFailure;
4327 }
4328
4329 if (keylogLabel) {
4330 ssl3_RecordKeyLog(ss, keylogLabel, *dest);
4331 }
4332 return SECSuccess;
4333}
4334
4335SECStatus
4336SSLExp_SecretCallback(PRFileDesc *fd, SSLSecretCallback cb, void *arg)
4337{
4338 sslSocket *ss = ssl_FindSocket(fd);
4339 if (!ss) {
4340 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SecretCallback",if (ssl_debug) ssl_Trace ("%d: SSL[%d]: bad socket in SSL_SecretCallback"
, getpid(), fd)
4341 SSL_GETPID(), fd))if (ssl_debug) ssl_Trace ("%d: SSL[%d]: bad socket in SSL_SecretCallback"
, getpid(), fd)
;
4342 return SECFailure;
4343 }
4344
4345 ssl_Get1stHandshakeLock(ss){ if (!ss->opt.noLocks) { (((PR_GetMonitorEntryCount(((ss)
->firstHandshakeLock)) > 0) || !((PR_GetMonitorEntryCount
(((ss)->recvBufLock)) > 0)))?((void)0):PR_Assert("PZ_InMonitor((ss)->firstHandshakeLock) || !ssl_HaveRecvBufLock(ss)"
,"tls13con.c",4345)); PR_EnterMonitor(((ss)->firstHandshakeLock
)); } }
;
4346 ssl_GetSSL3HandshakeLock(ss){ if (!ss->opt.noLocks) { ((!((PR_GetMonitorEntryCount(((ss
)->xmitBufLock)) > 0)))?((void)0):PR_Assert("!ssl_HaveXmitBufLock(ss)"
,"tls13con.c",4346)); PR_EnterMonitor(((ss)->ssl3HandshakeLock
)); } }
;
4347 ss->secretCallback = cb;
4348 ss->secretCallbackArg = arg;
4349 ssl_ReleaseSSL3HandshakeLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->ssl3HandshakeLock
)); }
;
4350 ssl_Release1stHandshakeLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->firstHandshakeLock
)); }
;
4351 return SECSuccess;
4352}
4353
4354/* Derive traffic keys for the next cipher spec in the queue. */
4355static SECStatus
4356tls13_DeriveTrafficKeys(sslSocket *ss, ssl3CipherSpec *spec,
4357 TrafficKeyType type,
4358 PRBool deleteSecret)
4359{
4360 size_t keySize = spec->cipherDef->key_size;
4361 size_t ivSize = spec->cipherDef->iv_size +
4362 spec->cipherDef->explicit_nonce_size; /* This isn't always going to
4363 * work, but it does for
4364 * AES-GCM */
4365 CK_MECHANISM_TYPE bulkAlgorithm = ssl3_Alg2Mech(spec->cipherDef->calg);
4366 PK11SymKey **prkp = NULL((void*)0);
4367 PK11SymKey *prk = NULL((void*)0);
4368 PRBool clientSecret;
4369 SECStatus rv;
4370 /* These labels are just used for debugging. */
4371 static const char kHkdfPhaseEarlyApplicationDataKeys[] = "early application data";
4372 static const char kHkdfPhaseHandshakeKeys[] = "handshake data";
4373 static const char kHkdfPhaseApplicationDataKeys[] = "application data";
4374
4375 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)"
,"tls13con.c",4375))
;
4376
4377 clientSecret = !tls13_UseServerSecret(ss, spec->direction);
4378 switch (type) {
4379 case TrafficKeyEarlyApplicationData:
4380 PORT_Assert(clientSecret)((clientSecret)?((void)0):PR_Assert("clientSecret","tls13con.c"
,4380))
;
4381 prkp = &ss->ssl3.hs.clientEarlyTrafficSecret;
4382 spec->phase = kHkdfPhaseEarlyApplicationDataKeys;
4383 break;
4384 case TrafficKeyHandshake:
4385 prkp = clientSecret ? &ss->ssl3.hs.clientHsTrafficSecret
4386 : &ss->ssl3.hs.serverHsTrafficSecret;
4387 spec->phase = kHkdfPhaseHandshakeKeys;
4388 break;
4389 case TrafficKeyApplicationData:
4390 prkp = clientSecret ? &ss->ssl3.hs.clientTrafficSecret
4391 : &ss->ssl3.hs.serverTrafficSecret;
4392 spec->phase = kHkdfPhaseApplicationDataKeys;
4393 break;
4394 default:
4395 LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE)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__, "tls13con.c"
, 4395); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0)
;
4396 PORT_Assert(0)((0)?((void)0):PR_Assert("0","tls13con.c",4396));
4397 return SECFailure;
4398 }
4399 PORT_Assert(prkp != NULL)((prkp != ((void*)0))?((void)0):PR_Assert("prkp != NULL","tls13con.c"
,4399))
;
4400 prk = *prkp;
4401
4402 SSL_TRC(3, ("%d: TLS13[%d]: deriving %s traffic keys epoch=%d (%s)",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: deriving %s traffic keys epoch=%d (%s)"
, getpid(), ss->fd, ((spec->direction == ssl_secret_read
) ? "read" : "write"), spec->epoch, spec->phase)
4403 SSL_GETPID(), ss->fd, SPEC_DIR(spec),if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: deriving %s traffic keys epoch=%d (%s)"
, getpid(), ss->fd, ((spec->direction == ssl_secret_read
) ? "read" : "write"), spec->epoch, spec->phase)
4404 spec->epoch, spec->phase))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: deriving %s traffic keys epoch=%d (%s)"
, getpid(), ss->fd, ((spec->direction == ssl_secret_read
) ? "read" : "write"), spec->epoch, spec->phase)
;
4405
4406 rv = tls13_HkdfExpandLabel(prk, tls13_GetHash(ss),
4407 NULL((void*)0), 0,
4408 kHkdfPurposeKey, strlen(kHkdfPurposeKey),
4409 bulkAlgorithm, keySize,
4410 ss->protocolVariant,
4411 &spec->keyMaterial.key);
4412 if (rv != SECSuccess) {
4413 LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE)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__, "tls13con.c"
, 4413); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0)
;
4414 PORT_Assert(0)((0)?((void)0):PR_Assert("0","tls13con.c",4414));
4415 goto loser;
4416 }
4417
4418 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram) && spec->epoch > 0) {
4419 rv = ssl_CreateMaskingContextInner(spec->version, ss->ssl3.hs.cipher_suite,
4420 ss->protocolVariant, prk, kHkdfPurposeSn,
4421 strlen(kHkdfPurposeSn), &spec->maskContext);
4422 if (rv != SECSuccess) {
4423 LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE)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__, "tls13con.c"
, 4423); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0)
;
4424 PORT_Assert(0)((0)?((void)0):PR_Assert("0","tls13con.c",4424));
4425 goto loser;
4426 }
4427 }
4428
4429 rv = tls13_HkdfExpandLabelRaw(prk, tls13_GetHash(ss),
4430 NULL((void*)0), 0,
4431 kHkdfPurposeIv, strlen(kHkdfPurposeIv),
4432 ss->protocolVariant,
4433 spec->keyMaterial.iv, ivSize);
4434 if (rv != SECSuccess) {
4435 LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE)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__, "tls13con.c"
, 4435); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0)
;
4436 PORT_Assert(0)((0)?((void)0):PR_Assert("0","tls13con.c",4436));
4437 goto loser;
4438 }
4439
4440 if (deleteSecret) {
4441 PK11_FreeSymKey(prk);
4442 *prkp = NULL((void*)0);
4443 }
4444 return SECSuccess;
4445
4446loser:
4447 return SECFailure;
4448}
4449
4450void
4451tls13_SetSpecRecordVersion(sslSocket *ss, ssl3CipherSpec *spec)
4452{
4453 /* Set the record version to pretend to be (D)TLS 1.2. */
4454 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
4455 spec->recordVersion = SSL_LIBRARY_VERSION_DTLS_1_2_WIRE((~0x0102) & 0xffff);
4456 } else {
4457 spec->recordVersion = SSL_LIBRARY_VERSION_TLS_1_20x0303;
4458 }
4459 SSL_TRC(10, ("%d: TLS13[%d]: set spec=%d record version to 0x%04x",if (ssl_trace >= (10)) ssl_Trace ("%d: TLS13[%d]: set spec=%d record version to 0x%04x"
, getpid(), ss->fd, spec, spec->recordVersion)
4460 SSL_GETPID(), ss->fd, spec, spec->recordVersion))if (ssl_trace >= (10)) ssl_Trace ("%d: TLS13[%d]: set spec=%d record version to 0x%04x"
, getpid(), ss->fd, spec, spec->recordVersion)
;
4461}
4462
4463static SECStatus
4464tls13_SetupPendingCipherSpec(sslSocket *ss, ssl3CipherSpec *spec)
4465{
4466 ssl3CipherSuite suite = ss->ssl3.hs.cipher_suite;
4467
4468 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)"
,"tls13con.c",4468))
;
4469 PORT_Assert(spec->epoch)((spec->epoch)?((void)0):PR_Assert("spec->epoch","tls13con.c"
,4469))
;
4470
4471 /* Version isn't set when we send 0-RTT data. */
4472 spec->version = PR_MAX(SSL_LIBRARY_VERSION_TLS_1_3, ss->version)((0x0304)>(ss->version)?(0x0304):(ss->version));
4473
4474 ssl_SaveCipherSpec(ss, spec);
4475 /* We want to keep read cipher specs around longer because
4476 * there are cases where we might get either epoch N or
4477 * epoch N+1. */
4478 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram) && spec->direction == ssl_secret_read) {
4479 ssl_CipherSpecAddRef(spec);
4480 }
4481
4482 SSL_TRC(3, ("%d: TLS13[%d]: Set Pending Cipher Suite to 0x%04x",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: Set Pending Cipher Suite to 0x%04x"
, getpid(), ss->fd, suite)
4483 SSL_GETPID(), ss->fd, suite))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: Set Pending Cipher Suite to 0x%04x"
, getpid(), ss->fd, suite)
;
4484
4485 spec->cipherDef = ssl_GetBulkCipherDef(ssl_LookupCipherSuiteDef(suite));
4486
4487 if (spec->epoch == TrafficKeyEarlyApplicationData) {
4488 if (ss->xtnData.selectedPsk &&
4489 ss->xtnData.selectedPsk->zeroRttSuite != TLS_NULL_WITH_NULL_NULL0x0000) {
4490 spec->earlyDataRemaining = ss->xtnData.selectedPsk->maxEarlyData;
4491 }
4492 }
4493
4494 tls13_SetSpecRecordVersion(ss, spec);
4495
4496 /* The record size limit is reduced by one so that the remainder of the
4497 * record handling code can use the same checks for all versions. */
4498 if (ssl3_ExtensionNegotiated(ss, ssl_record_size_limit_xtn)) {
4499 spec->recordSizeLimit = ((spec->direction == ssl_secret_read)
4500 ? ss->opt.recordSizeLimit
4501 : ss->xtnData.recordSizeLimit) -
4502 1;
4503 } else {
4504 spec->recordSizeLimit = MAX_FRAGMENT_LENGTH16384;
4505 }
4506 return SECSuccess;
4507}
4508
4509/*
4510 * Initialize the cipher context. All TLS 1.3 operations are AEAD,
4511 * so they are all message contexts.
4512 */
4513static SECStatus
4514tls13_InitPendingContext(sslSocket *ss, ssl3CipherSpec *spec)
4515{
4516 CK_MECHANISM_TYPE encMechanism;
4517 CK_ATTRIBUTE_TYPE encMode;
4518 SECItem iv;
4519 SSLCipherAlgorithm calg;
4520
4521 calg = spec->cipherDef->calg;
4522
4523 encMechanism = ssl3_Alg2Mech(calg);
4524 encMode = CKA_NSS_MESSAGE0x82000000L | ((spec->direction == ssl_secret_write) ? CKA_ENCRYPT0x00000104UL : CKA_DECRYPT0x00000105UL);
4525 iv.data = NULL((void*)0);
4526 iv.len = 0;
4527
4528 /*
4529 * build the context
4530 */
4531 spec->cipherContext = PK11_CreateContextBySymKey(encMechanism, encMode,
4532 spec->keyMaterial.key,
4533 &iv);
4534 if (!spec->cipherContext) {
4535 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
4536 return SECFailure;
4537 }
4538 return SECSuccess;
4539}
4540
4541/*
4542 * Called before sending alerts to set up the right key on the client.
4543 * We might encounter errors during the handshake where the current
4544 * key is ClearText or EarlyApplicationData. This
4545 * function switches to the Handshake key if possible.
4546 */
4547SECStatus
4548tls13_SetAlertCipherSpec(sslSocket *ss)
4549{
4550 SECStatus rv;
4551
4552 if (ss->sec.isServer) {
4553 return SECSuccess;
4554 }
4555 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_30x0304) {
4556 return SECSuccess;
4557 }
4558 if (TLS13_IN_HS_STATE(ss, wait_server_hello)tls13_InHsState(ss, wait_server_hello, wait_invalid)) {
4559 return SECSuccess;
4560 }
4561 if ((ss->ssl3.cwSpec->epoch != TrafficKeyClearText) &&
4562 (ss->ssl3.cwSpec->epoch != TrafficKeyEarlyApplicationData)) {
4563 return SECSuccess;
4564 }
4565
4566 rv = tls13_SetCipherSpec(ss, TrafficKeyHandshake,
4567 ssl_secret_write, PR_FALSE0);
4568 if (rv != SECSuccess) {
4569 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
4570 return SECFailure;
4571 }
4572 return SECSuccess;
4573}
4574
4575/* Install a new cipher spec for this direction.
4576 *
4577 * During the handshake, the values for |epoch| take values from the
4578 * TrafficKeyType enum. Afterwards, key update increments them.
4579 */
4580static SECStatus
4581tls13_SetCipherSpec(sslSocket *ss, PRUint16 epoch,
4582 SSLSecretDirection direction, PRBool deleteSecret)
4583{
4584 TrafficKeyType type;
4585 SECStatus rv;
4586 ssl3CipherSpec *spec = NULL((void*)0);
4587 ssl3CipherSpec **specp;
4588
4589 /* Flush out old handshake data. */
4590 ssl_GetXmitBufLock(ss){ if (!ss->opt.noLocks) PR_EnterMonitor(((ss)->xmitBufLock
)); }
;
4591 rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER0x40000000);
4592 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
;
4593 if (rv != SECSuccess) {
4594 return SECFailure;
4595 }
4596
4597 /* Create the new spec. */
4598 spec = ssl_CreateCipherSpec(ss, direction);
4599 if (!spec) {
4600 return SECFailure;
4601 }
4602 spec->epoch = epoch;
4603 spec->nextSeqNum = 0;
4604 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
4605 dtls_InitRecvdRecords(&spec->recvdRecords);
4606 }
4607
4608 /* This depends on spec having a valid direction and epoch. */
4609 rv = tls13_SetupPendingCipherSpec(ss, spec);
4610 if (rv != SECSuccess) {
4611 goto loser;
4612 }
4613
4614 type = (TrafficKeyType)PR_MIN(TrafficKeyApplicationData, epoch)((TrafficKeyApplicationData)<(epoch)?(TrafficKeyApplicationData
):(epoch))
;
4615 rv = tls13_DeriveTrafficKeys(ss, spec, type, deleteSecret);
4616 if (rv != SECSuccess) {
4617 goto loser;
4618 }
4619
4620 rv = tls13_InitPendingContext(ss, spec);
4621 if (rv != SECSuccess) {
4622 goto loser;
4623 }
4624
4625 /* Now that we've set almost everything up, finally cut over. */
4626 specp = (direction == ssl_secret_read) ? &ss->ssl3.crSpec : &ss->ssl3.cwSpec;
4627 ssl_GetSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_LockWrite_Util((ss)->
specLock); }
;
4628 ssl_CipherSpecRelease(*specp); /* May delete old cipher. */
4629 *specp = spec; /* Overwrite. */
4630 ssl_ReleaseSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockWrite_Util((ss)->
specLock); }
;
4631
4632 SSL_TRC(3, ("%d: TLS13[%d]: %s installed key for epoch=%d (%s) dir=%s",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: %s installed key for epoch=%d (%s) dir=%s"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
), spec->epoch, spec->phase, ((spec->direction == ssl_secret_read
) ? "read" : "write"))
4633 SSL_GETPID(), ss->fd, SSL_ROLE(ss), spec->epoch,if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: %s installed key for epoch=%d (%s) dir=%s"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
), spec->epoch, spec->phase, ((spec->direction == ssl_secret_read
) ? "read" : "write"))
4634 spec->phase, SPEC_DIR(spec)))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: %s installed key for epoch=%d (%s) dir=%s"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
), spec->epoch, spec->phase, ((spec->direction == ssl_secret_read
) ? "read" : "write"))
;
4635 return SECSuccess;
4636
4637loser:
4638 ssl_CipherSpecRelease(spec);
4639 return SECFailure;
4640}
4641
4642SECStatus
4643tls13_ComputeHandshakeHashes(sslSocket *ss, SSL3Hashes *hashes)
4644{
4645 SECStatus rv;
4646 PK11Context *ctx = NULL((void*)0);
4647 PRBool useEchInner;
4648 sslBuffer *transcript;
4649
4650 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)"
,"tls13con.c",4650))
;
4651 if (ss->ssl3.hs.hashType == handshake_hash_unknown) {
4652 /* Backup: if we haven't done any hashing, then hash now.
4653 * This happens when we are doing 0-RTT on the client. */
4654 ctx = PK11_CreateDigestContext(ssl3_HashTypeToOID(tls13_GetHash(ss)));
4655 if (!ctx) {
4656 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4657 return SECFailure;
4658 }
4659
4660 if (PK11_DigestBegin(ctx) != SECSuccess) {
4661 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4662 goto loser;
4663 }
4664
4665 /* One might expect this to use ss->ssl3.hs.echAccepted,
4666 * but with 0-RTT we don't know that yet. */
4667 useEchInner = ss->sec.isServer ? PR_FALSE0 : !!ss->ssl3.hs.echHpkeCtx;
4668 transcript = useEchInner ? &ss->ssl3.hs.echInnerMessages : &ss->ssl3.hs.messages;
4669
4670 PRINT_BUF(10, (ss, "Handshake hash computed over saved messages",if (ssl_trace >= (10)) ssl_PrintBuf (ss, "Handshake hash computed over saved messages"
, transcript->buf, transcript->len)
4671 transcript->buf,if (ssl_trace >= (10)) ssl_PrintBuf (ss, "Handshake hash computed over saved messages"
, transcript->buf, transcript->len)
4672 transcript->len))if (ssl_trace >= (10)) ssl_PrintBuf (ss, "Handshake hash computed over saved messages"
, transcript->buf, transcript->len)
;
4673
4674 if (PK11_DigestOp(ctx,
4675 transcript->buf,
4676 transcript->len) != SECSuccess) {
4677 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4678 goto loser;
4679 }
4680 } else {
4681 if (ss->firstHsDone) {
4682 ctx = PK11_CloneContext(ss->ssl3.hs.shaPostHandshake);
4683 } else {
4684 ctx = PK11_CloneContext(ss->ssl3.hs.sha);
4685 }
4686 if (!ctx) {
4687 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4688 return SECFailure;
4689 }
4690 }
4691
4692 rv = PK11_DigestFinal(ctx, hashes->u.raw,
4693 &hashes->len,
4694 sizeof(hashes->u.raw));
4695 if (rv != SECSuccess) {
4696 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4697 goto loser;
4698 }
4699
4700 PRINT_BUF(10, (ss, "Handshake hash", hashes->u.raw, hashes->len))if (ssl_trace >= (10)) ssl_PrintBuf (ss, "Handshake hash",
hashes->u.raw, hashes->len)
;
4701 PORT_Assert(hashes->len == tls13_GetHashSize(ss))((hashes->len == tls13_GetHashSize(ss))?((void)0):PR_Assert
("hashes->len == tls13_GetHashSize(ss)","tls13con.c",4701)
)
;
4702 PK11_DestroyContext(ctx, PR_TRUE1);
4703
4704 return SECSuccess;
4705
4706loser:
4707 PK11_DestroyContext(ctx, PR_TRUE1);
4708 return SECFailure;
4709}
4710
4711TLS13KeyShareEntry *
4712tls13_CopyKeyShareEntry(TLS13KeyShareEntry *o)
4713{
4714 TLS13KeyShareEntry *n;
4715
4716 PORT_Assert(o)((o)?((void)0):PR_Assert("o","tls13con.c",4716));
4717 n = PORT_ZNew(TLS13KeyShareEntry)(TLS13KeyShareEntry *)PORT_ZAlloc_Util(sizeof(TLS13KeyShareEntry
))
;
4718 if (!n) {
4719 return NULL((void*)0);
4720 }
4721
4722 if (SECSuccess != SECITEM_CopyItemSECITEM_CopyItem_Util(NULL((void*)0), &n->key_exchange, &o->key_exchange)) {
4723 PORT_FreePORT_Free_Util(n);
4724 return NULL((void*)0);
4725 }
4726 n->group = o->group;
4727 return n;
4728}
4729
4730void
4731tls13_DestroyKeyShareEntry(TLS13KeyShareEntry *offer)
4732{
4733 if (!offer) {
4734 return;
4735 }
4736 SECITEM_ZfreeItemSECITEM_ZfreeItem_Util(&offer->key_exchange, PR_FALSE0);
4737 PORT_ZFreePORT_ZFree_Util(offer, sizeof(*offer));
4738}
4739
4740void
4741tls13_DestroyKeyShares(PRCList *list)
4742{
4743 PRCList *cur_p;
4744
4745 /* The list must be initialized. */
4746 PORT_Assert(PR_LIST_HEAD(list))(((list)->next)?((void)0):PR_Assert("PR_LIST_HEAD(list)","tls13con.c"
,4746))
;
4747
4748 while (!PR_CLIST_IS_EMPTY(list)((list)->next == (list))) {
4749 cur_p = PR_LIST_TAIL(list)(list)->prev;
4750 PR_REMOVE_LINK(cur_p)do { (cur_p)->prev->next = (cur_p)->next; (cur_p)->
next->prev = (cur_p)->prev; } while (0)
;
4751 tls13_DestroyKeyShareEntry((TLS13KeyShareEntry *)cur_p);
4752 }
4753}
4754
4755void
4756tls13_DestroyEarlyData(PRCList *list)
4757{
4758 PRCList *cur_p;
4759
4760 while (!PR_CLIST_IS_EMPTY(list)((list)->next == (list))) {
4761 TLS13EarlyData *msg;
4762
4763 cur_p = PR_LIST_TAIL(list)(list)->prev;
4764 msg = (TLS13EarlyData *)cur_p;
4765
4766 PR_REMOVE_LINK(cur_p)do { (cur_p)->prev->next = (cur_p)->next; (cur_p)->
next->prev = (cur_p)->prev; } while (0)
;
4767 SECITEM_ZfreeItemSECITEM_ZfreeItem_Util(&msg->data, PR_FALSE0);
4768 PORT_ZFreePORT_ZFree_Util(msg, sizeof(*msg));
4769 }
4770}
4771
4772/* draft-ietf-tls-tls13 Section 5.2.2 specifies the following
4773 * nonce algorithm:
4774 *
4775 * The length of the per-record nonce (iv_length) is set to max(8 bytes,
4776 * N_MIN) for the AEAD algorithm (see [RFC5116] Section 4). An AEAD
4777 * algorithm where N_MAX is less than 8 bytes MUST NOT be used with TLS.
4778 * The per-record nonce for the AEAD construction is formed as follows:
4779 *
4780 * 1. The 64-bit record sequence number is padded to the left with
4781 * zeroes to iv_length.
4782 *
4783 * 2. The padded sequence number is XORed with the static
4784 * client_write_iv or server_write_iv, depending on the role.
4785 *
4786 * The resulting quantity (of length iv_length) is used as the per-
4787 * record nonce.
4788 *
4789 * Existing suites have the same nonce size: N_MIN = N_MAX = 12 bytes
4790 *
4791 * See RFC 5288 and https://tools.ietf.org/html/draft-ietf-tls-chacha20-poly1305-04#section-2
4792 */
4793static void
4794tls13_WriteNonce(const unsigned char *ivIn, unsigned int ivInLen,
4795 const unsigned char *nonce, unsigned int nonceLen,
4796 unsigned char *ivOut, unsigned int ivOutLen)
4797{
4798 size_t i;
4799 unsigned int offset = ivOutLen - nonceLen;
4800
4801 PORT_Assert(ivInLen <= ivOutLen)((ivInLen <= ivOutLen)?((void)0):PR_Assert("ivInLen <= ivOutLen"
,"tls13con.c",4801))
;
4802 PORT_Assert(nonceLen <= ivOutLen)((nonceLen <= ivOutLen)?((void)0):PR_Assert("nonceLen <= ivOutLen"
,"tls13con.c",4802))
;
4803 PORT_Memsetmemset(ivOut, 0, ivOutLen);
4804 PORT_Memcpymemcpy(ivOut, ivIn, ivInLen);
4805
4806 /* XOR the last n bytes of the IV with the nonce (should be a counter). */
4807 for (i = 0; i < nonceLen; ++i) {
4808 ivOut[offset + i] ^= nonce[i];
4809 }
4810 PRINT_BUF(50, (NULL, "Nonce", ivOut, ivOutLen))if (ssl_trace >= (50)) ssl_PrintBuf (((void*)0), "Nonce", ivOut
, ivOutLen)
;
4811}
4812
4813/* Setup the IV for AEAD encrypt. The PKCS #11 module will add the
4814 * counter, but it doesn't know about the DTLS epic, so we add it here.
4815 */
4816unsigned int
4817tls13_SetupAeadIv(PRBool isDTLS, SSL3ProtocolVersion v, unsigned char *ivOut, unsigned char *ivIn,
4818 unsigned int offset, unsigned int ivLen, DTLSEpoch epoch)
4819{
4820 PORT_Memcpymemcpy(ivOut, ivIn, ivLen);
4821 if (isDTLS && v < SSL_LIBRARY_VERSION_TLS_1_30x0304) {
4822 /* handle the tls 1.2 counter mode case, the epoc is copied
4823 * instead of xored. We accomplish this by clearing ivOut
4824 * before running xor. */
4825 if (offset >= ivLen) {
4826 ivOut[offset] = ivOut[offset + 1] = 0;
4827 }
4828 ivOut[offset] ^= (unsigned char)(epoch >> BPB8) & 0xff;
4829 ivOut[offset + 1] ^= (unsigned char)(epoch)&0xff;
4830 offset += 2;
4831 }
4832
4833 return offset;
4834}
4835
4836/*
4837 * Do a single AEAD for TLS. This differs from PK11_AEADOp in the following
4838 * ways.
4839 * 1) If context is not supplied, it treats the operation as a single shot
4840 * and creates a context from symKey and mech.
4841 * 2) It always assumes the tag will be at the end of the buffer
4842 * (in on decrypt, out on encrypt) just like the old single shot.
4843 * 3) If we aren't generating an IV, it uses tls13_WriteNonce to create the
4844 * nonce.
4845 * NOTE is context is supplied, symKey and mech are ignored
4846 */
4847SECStatus
4848tls13_AEAD(PK11Context *context, PRBool decrypt,
4849 CK_GENERATOR_FUNCTION ivGen, unsigned int fixedbits,
4850 const unsigned char *ivIn, unsigned char *ivOut, unsigned int ivLen,
4851 const unsigned char *nonceIn, unsigned int nonceLen,
4852 const unsigned char *aad, unsigned int aadLen,
4853 unsigned char *out, unsigned int *outLen, unsigned int maxout,
4854 unsigned int tagLen, const unsigned char *in, unsigned int inLen)
4855{
4856 unsigned char *tag;
4857 unsigned char iv[MAX_IV_LENGTH24];
4858 unsigned char tagbuf[HASH_LENGTH_MAX64];
4859 SECStatus rv;
4860
4861 /* must have either context or the symKey set */
4862 if (!context) {
4863 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
4864 return SECFailure;
4865 }
4866
4867 PORT_Assert(ivLen <= MAX_IV_LENGTH)((ivLen <= 24)?((void)0):PR_Assert("ivLen <= MAX_IV_LENGTH"
,"tls13con.c",4867))
;
4868 PORT_Assert(tagLen <= HASH_LENGTH_MAX)((tagLen <= 64)?((void)0):PR_Assert("tagLen <= HASH_LENGTH_MAX"
,"tls13con.c",4868))
;
4869 if (!ivOut) {
4870 ivOut = iv; /* caller doesn't need a returned, iv */
4871 }
4872
4873 if (ivGen == CKG_NO_GENERATE0x00000000UL) {
4874 tls13_WriteNonce(ivIn, ivLen, nonceIn, nonceLen, ivOut, ivLen);
4875 } else if (ivIn != ivOut) {
4876 PORT_Memcpymemcpy(ivOut, ivIn, ivLen);
4877 }
4878 if (decrypt) {
4879 inLen = inLen - tagLen;
4880 tag = (unsigned char *)in + inLen;
4881 /* tag is const on decrypt, but returned on encrypt */
4882 } else {
4883 /* tag is written to a separate buffer, then added to the end
4884 * of the actual output buffer. This allows output buffer to be larger
4885 * than the input buffer and everything still work */
4886 tag = tagbuf;
4887 }
4888 rv = PK11_AEADOp(context, ivGen, fixedbits, ivOut, ivLen, aad, aadLen,
4889 out, (int *)outLen, maxout, tag, tagLen, in, inLen);
4890 /* on encrypt SSL always puts the tag at the end of the buffer */
4891 if ((rv == SECSuccess) && !(decrypt)) {
4892 unsigned int len = *outLen;
4893 /* make sure there is still space */
4894 if (len + tagLen > maxout) {
4895 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_OUTPUT_LEN);
4896 return SECFailure;
4897 }
4898 PORT_Memcpymemcpy(out + len, tag, tagLen);
4899 *outLen += tagLen;
4900 }
4901 return rv;
4902}
4903
4904static SECStatus
4905tls13_HandleEncryptedExtensions(sslSocket *ss, PRUint8 *b, PRUint32 length)
4906{
4907 SECStatus rv;
4908 PRUint32 innerLength;
4909 SECItem oldAlpn = { siBuffer, NULL((void*)0), 0 };
4910
4911 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)"
,"tls13con.c",4911))
;
4912 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)"
,"tls13con.c",4912))
;
4913
4914 SSL_TRC(3, ("%d: TLS13[%d]: handle encrypted extensions",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: handle encrypted extensions"
, getpid(), ss->fd)
4915 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: handle encrypted extensions"
, getpid(), ss->fd)
;
4916
4917 rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_ENCRYPTED_EXTENSIONS,tls13_CheckHsState(ss, SSL_ERROR_RX_UNEXPECTED_ENCRYPTED_EXTENSIONS
, "SSL_ERROR_RX_UNEXPECTED_ENCRYPTED_EXTENSIONS", __func__, "tls13con.c"
, 4918, wait_encrypted_extensions, wait_invalid)
4918 wait_encrypted_extensions)tls13_CheckHsState(ss, SSL_ERROR_RX_UNEXPECTED_ENCRYPTED_EXTENSIONS
, "SSL_ERROR_RX_UNEXPECTED_ENCRYPTED_EXTENSIONS", __func__, "tls13con.c"
, 4918, wait_encrypted_extensions, wait_invalid)
;
4919 if (rv != SECSuccess) {
4920 return SECFailure;
4921 }
4922
4923 rv = ssl3_ConsumeHandshakeNumber(ss, &innerLength, 2, &b, &length);
4924 if (rv != SECSuccess) {
4925 return SECFailure; /* Alert already sent. */
4926 }
4927 if (innerLength != length) {
4928 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS,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_ENCRYPTED_EXTENSIONS
, __func__, "tls13con.c", 4929); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS
, illegal_parameter); } while (0)
4929 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_ENCRYPTED_EXTENSIONS
, __func__, "tls13con.c", 4929); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS
, illegal_parameter); } while (0)
;
4930 return SECFailure;
4931 }
4932
4933 /* If we are doing 0-RTT, then we already have an ALPN value. Stash
4934 * it for comparison. */
4935 if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent &&
4936 ss->xtnData.nextProtoState == SSL_NEXT_PROTO_EARLY_VALUE) {
4937 oldAlpn = ss->xtnData.nextProto;
4938 ss->xtnData.nextProto.data = NULL((void*)0);
4939 ss->xtnData.nextProtoState = SSL_NEXT_PROTO_NO_SUPPORT;
4940 }
4941
4942 rv = ssl3_ParseExtensions(ss, &b, &length);
4943 if (rv != SECSuccess) {
4944 return SECFailure; /* Error code set below */
4945 }
4946
4947 /* Handle the rest of the extensions. */
4948 rv = ssl3_HandleParsedExtensions(ss, ssl_hs_encrypted_extensions);
4949 if (rv != SECSuccess) {
4950 return SECFailure; /* Error code set below */
4951 }
4952
4953 /* We can only get here if we offered 0-RTT. */
4954 if (ssl3_ExtensionNegotiated(ss, ssl_tls13_early_data_xtn)) {
4955 PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_sent)((ss->ssl3.hs.zeroRttState == ssl_0rtt_sent)?((void)0):PR_Assert
("ss->ssl3.hs.zeroRttState == ssl_0rtt_sent","tls13con.c",
4955))
;
4956 if (!ss->xtnData.selectedPsk) {
4957 /* Illegal to accept 0-RTT without also accepting PSK. */
4958 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS,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_ENCRYPTED_EXTENSIONS
, __func__, "tls13con.c", 4959); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS
, illegal_parameter); } while (0)
4959 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_ENCRYPTED_EXTENSIONS
, __func__, "tls13con.c", 4959); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS
, illegal_parameter); } while (0)
;
4960 }
4961 ss->ssl3.hs.zeroRttState = ssl_0rtt_accepted;
4962
4963 /* Check that the server negotiated the same ALPN (if any). */
4964 if (SECITEM_CompareItemSECITEM_CompareItem_Util(&oldAlpn, &ss->xtnData.nextProto)) {
4965 SECITEM_FreeItemSECITEM_FreeItem_Util(&oldAlpn, PR_FALSE0);
4966 FATAL_ERROR(ss, SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID,do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID, __func__
, "tls13con.c", 4967); PORT_SetError_Util(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID
); } while (0); tls13_FatalError(ss, SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID
, illegal_parameter); } while (0)
4967 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_NEXT_PROTOCOL_DATA_INVALID, __func__
, "tls13con.c", 4967); PORT_SetError_Util(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID
); } while (0); tls13_FatalError(ss, SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID
, illegal_parameter); } while (0)
;
4968 return SECFailure;
4969 }
4970 /* Check that the server negotiated the same cipher suite. */
4971 if (ss->ssl3.hs.cipher_suite != ss->ssl3.hs.zeroRttSuite) {
4972 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS,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_ENCRYPTED_EXTENSIONS
, __func__, "tls13con.c", 4973); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS
, illegal_parameter); } while (0)
4973 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_ENCRYPTED_EXTENSIONS
, __func__, "tls13con.c", 4973); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS
, illegal_parameter); } while (0)
;
4974 return SECFailure;
4975 }
4976 } else if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent) {
4977 /* Though we sent 0-RTT, the early_data extension wasn't present so the
4978 * state is unmodified; the server must have rejected 0-RTT. */
4979 ss->ssl3.hs.zeroRttState = ssl_0rtt_ignored;
4980 ss->ssl3.hs.zeroRttIgnore = ssl_0rtt_ignore_trial;
4981 } else {
4982 PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_none ||((ss->ssl3.hs.zeroRttState == ssl_0rtt_none || (ss->ssl3
.hs.helloRetry && ss->ssl3.hs.zeroRttState == ssl_0rtt_ignored
))?((void)0):PR_Assert("ss->ssl3.hs.zeroRttState == ssl_0rtt_none || (ss->ssl3.hs.helloRetry && ss->ssl3.hs.zeroRttState == ssl_0rtt_ignored)"
,"tls13con.c",4984))
4983 (ss->ssl3.hs.helloRetry &&((ss->ssl3.hs.zeroRttState == ssl_0rtt_none || (ss->ssl3
.hs.helloRetry && ss->ssl3.hs.zeroRttState == ssl_0rtt_ignored
))?((void)0):PR_Assert("ss->ssl3.hs.zeroRttState == ssl_0rtt_none || (ss->ssl3.hs.helloRetry && ss->ssl3.hs.zeroRttState == ssl_0rtt_ignored)"
,"tls13con.c",4984))
4984 ss->ssl3.hs.zeroRttState == ssl_0rtt_ignored))((ss->ssl3.hs.zeroRttState == ssl_0rtt_none || (ss->ssl3
.hs.helloRetry && ss->ssl3.hs.zeroRttState == ssl_0rtt_ignored
))?((void)0):PR_Assert("ss->ssl3.hs.zeroRttState == ssl_0rtt_none || (ss->ssl3.hs.helloRetry && ss->ssl3.hs.zeroRttState == ssl_0rtt_ignored)"
,"tls13con.c",4984))
;
4985 }
4986
4987 SECITEM_FreeItemSECITEM_FreeItem_Util(&oldAlpn, PR_FALSE0);
4988 if (ss->ssl3.hs.kea_def->authKeyType == ssl_auth_psk) {
4989 TLS13_SET_HS_STATE(ss, wait_finished)tls13_SetHsState(ss, wait_finished, __func__, "tls13con.c", 4989
)
;
4990 } else {
4991 TLS13_SET_HS_STATE(ss, wait_cert_request)tls13_SetHsState(ss, wait_cert_request, __func__, "tls13con.c"
, 4991)
;
4992 }
4993
4994 /* Client is done with any PSKs */
4995 tls13_DestroyPskList(&ss->ssl3.hs.psks);
4996 ss->xtnData.selectedPsk = NULL((void*)0);
4997
4998 return SECSuccess;
4999}
5000
5001static SECStatus
5002tls13_SendEncryptedExtensions(sslSocket *ss)
5003{
5004 sslBuffer extensions = SSL_BUFFER_EMPTY{ ((void*)0), 0, 0, 0 };
5005 SECStatus rv;
5006
5007 SSL_TRC(3, ("%d: TLS13[%d]: send encrypted extensions handshake",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: send encrypted extensions handshake"
, getpid(), ss->fd)
5008 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: send encrypted extensions handshake"
, getpid(), ss->fd)
;
5009
5010 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)"
,"tls13con.c",5010))
;
5011 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)"
,"tls13con.c",5011))
;
5012
5013 rv = ssl_ConstructExtensions(ss, &extensions, ssl_hs_encrypted_extensions);
5014 if (rv != SECSuccess) {
5015 return SECFailure;
5016 }
5017
5018 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_encrypted_extensions,
5019 SSL_BUFFER_LEN(&extensions)((&extensions)->len) + 2);
5020 if (rv != SECSuccess) {
5021 LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE)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__, "tls13con.c"
, 5021); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0)
;
5022 goto loser;
5023 }
5024 rv = ssl3_AppendBufferToHandshakeVariable(ss, &extensions, 2);
5025 if (rv != SECSuccess) {
5026 LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE)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__, "tls13con.c"
, 5026); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0)
;
5027 goto loser;
5028 }
5029 sslBuffer_Clear(&extensions);
5030 return SECSuccess;
5031
5032loser:
5033 sslBuffer_Clear(&extensions);
5034 return SECFailure;
5035}
5036
5037SECStatus
5038tls13_SendCertificateVerify(sslSocket *ss, SECKEYPrivateKey *privKey)
5039{
5040 SECStatus rv = SECFailure;
5041 SECItem buf = { siBuffer, NULL((void*)0), 0 };
5042 unsigned int len;
5043 SSLHashType hashAlg;
5044 SSL3Hashes hash;
5045 SSL3Hashes tbsHash; /* The hash "to be signed". */
5046
5047 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)"
,"tls13con.c",5047))
;
5048 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)"
,"tls13con.c",5048))
;
5049
5050 SSL_TRC(3, ("%d: TLS13[%d]: send certificate_verify handshake",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: send certificate_verify handshake"
, getpid(), ss->fd)
5051 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: send certificate_verify handshake"
, getpid(), ss->fd)
;
5052
5053 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"
,"tls13con.c",5053))
;
5054 rv = tls13_ComputeHandshakeHashes(ss, &hash);
5055 if (rv != SECSuccess) {
5056 return SECFailure;
5057 }
5058
5059 /* We should have picked a signature scheme when we received a
5060 * CertificateRequest, or when we picked a server certificate. */
5061 PORT_Assert(ss->ssl3.hs.signatureScheme != ssl_sig_none)((ss->ssl3.hs.signatureScheme != ssl_sig_none)?((void)0):PR_Assert
("ss->ssl3.hs.signatureScheme != ssl_sig_none","tls13con.c"
,5061))
;
5062 if (ss->ssl3.hs.signatureScheme == ssl_sig_none) {
5063 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
5064 return SECFailure;
5065 }
5066 hashAlg = ssl_SignatureSchemeToHashType(ss->ssl3.hs.signatureScheme);
5067 rv = tls13_AddContextToHashes(ss, &hash, hashAlg,
5068 PR_TRUE1, &tbsHash);
5069 if (rv != SECSuccess) {
5070 return SECFailure;
5071 }
5072
5073 rv = ssl3_SignHashes(ss, &tbsHash, privKey, &buf);
5074 if (rv == SECSuccess && !ss->sec.isServer) {
5075 /* Remember the info about the slot that did the signing.
5076 * Later, when doing an SSL restart handshake, verify this.
5077 * These calls are mere accessors, and can't fail.
5078 */
5079 PK11SlotInfo *slot;
5080 sslSessionID *sid = ss->sec.ci.sid;
5081
5082 slot = PK11_GetSlotFromPrivateKey(privKey);
5083 sid->u.ssl3.clAuthSeries = PK11_GetSlotSeries(slot);
5084 sid->u.ssl3.clAuthSlotID = PK11_GetSlotID(slot);
5085 sid->u.ssl3.clAuthModuleID = PK11_GetModuleID(slot);
5086 sid->u.ssl3.clAuthValid = PR_TRUE1;
5087 PK11_FreeSlot(slot);
5088 }
5089 if (rv != SECSuccess) {
5090 goto done; /* err code was set by ssl3_SignHashes */
5091 }
5092
5093 len = buf.len + 2 + 2;
5094
5095 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_verify, len);
5096 if (rv != SECSuccess) {
5097 goto done; /* error code set by AppendHandshake */
5098 }
5099
5100 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.signatureScheme, 2);
5101 if (rv != SECSuccess) {
5102 goto done; /* err set by AppendHandshakeNumber */
5103 }
5104
5105 rv = ssl3_AppendHandshakeVariable(ss, buf.data, buf.len, 2);
5106 if (rv != SECSuccess) {
5107 goto done; /* error code set by AppendHandshake */
5108 }
5109
5110done:
5111 /* For parity with the allocation functions, which don't use
5112 * SECITEM_AllocItem(). */
5113 if (buf.data)
5114 PORT_FreePORT_Free_Util(buf.data);
5115 return rv;
5116}
5117
5118/* Called from tls13_CompleteHandleHandshakeMessage() when it has deciphered a complete
5119 * tls13 CertificateVerify message
5120 * Caller must hold Handshake and RecvBuf locks.
5121 */
5122SECStatus
5123tls13_HandleCertificateVerify(sslSocket *ss, PRUint8 *b, PRUint32 length)
5124{
5125 sslDelegatedCredential *dc = ss->xtnData.peerDelegCred;
5126 CERTSubjectPublicKeyInfo *spki;
5127 SECKEYPublicKey *pubKey = NULL((void*)0);
5128 SECItem signed_hash = { siBuffer, NULL((void*)0), 0 };
5129 SECStatus rv;
5130 SSLSignatureScheme sigScheme;
5131 SSLHashType hashAlg;
5132 SSL3Hashes tbsHash;
5133 SSL3Hashes hashes;
5134
5135 SSL_TRC(3, ("%d: TLS13[%d]: handle certificate_verify handshake",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: handle certificate_verify handshake"
, getpid(), ss->fd)
5136 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: handle certificate_verify handshake"
, getpid(), ss->fd)
;
5137 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)"
,"tls13con.c",5137))
;
5138 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)"
,"tls13con.c",5138))
;
5139
5140 rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY,tls13_CheckHsState(ss, SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY, "SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY"
, __func__, "tls13con.c", 5141, wait_cert_verify, wait_invalid
)
5141 wait_cert_verify)tls13_CheckHsState(ss, SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY, "SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY"
, __func__, "tls13con.c", 5141, wait_cert_verify, wait_invalid
)
;
5142 if (rv != SECSuccess) {
5143 return SECFailure;
5144 }
5145
5146 rv = tls13_ComputeHandshakeHashes(ss, &hashes);
5147 if (rv != SECSuccess) {
5148 return SECFailure;
5149 }
5150
5151 if (ss->firstHsDone) {
5152 rv = ssl_HashPostHandshakeMessage(ss, ssl_hs_certificate_verify, b, length);
5153 } else {
5154 rv = ssl_HashHandshakeMessage(ss, ssl_hs_certificate_verify, b, length);
5155 }
5156 if (rv != SECSuccess) {
5157 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
5158 return SECFailure;
5159 }
5160
5161 rv = ssl_ConsumeSignatureScheme(ss, &b, &length, &sigScheme);
5162 if (rv != SECSuccess) {
5163 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERT_VERIFY, 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_CERT_VERIFY, __func__
, "tls13con.c", 5163); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CERT_VERIFY
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_CERT_VERIFY
, illegal_parameter); } while (0)
;
5164 return SECFailure;
5165 }
5166
5167 /* Set the |spki| used to verify the handshake. When verifying with a
5168 * delegated credential (DC), this corresponds to the DC public key;
5169 * otherwise it correspond to the public key of the peer's end-entity
5170 * certificate.
5171 */
5172 if (tls13_IsVerifyingWithDelegatedCredential(ss)) {
5173 /* DelegatedCredential.cred.expected_cert_verify_algorithm is expected
5174 * to match CertificateVerify.scheme.
5175 * DelegatedCredential.cred.expected_cert_verify_algorithm must also be
5176 * the same as was reported in ssl3_AuthCertificate.
5177 */
5178 if (sigScheme != dc->expectedCertVerifyAlg || sigScheme != ss->sec.signatureScheme) {
5179 FATAL_ERROR(ss, SSL_ERROR_DC_CERT_VERIFY_ALG_MISMATCH, 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_DC_CERT_VERIFY_ALG_MISMATCH,
__func__, "tls13con.c", 5179); PORT_SetError_Util(SSL_ERROR_DC_CERT_VERIFY_ALG_MISMATCH
); } while (0); tls13_FatalError(ss, SSL_ERROR_DC_CERT_VERIFY_ALG_MISMATCH
, illegal_parameter); } while (0)
;
5180 return SECFailure;
5181 }
5182
5183 /* Verify the DC has three steps: (1) use the peer's end-entity
5184 * certificate to verify DelegatedCredential.signature, (2) check that
5185 * the certificate has the correct key usage, and (3) check that the DC
5186 * hasn't expired.
5187 */
5188 rv = tls13_VerifyDelegatedCredential(ss, dc);
5189 if (rv != SECSuccess) { /* Calls FATAL_ERROR() */
5190 return SECFailure;
5191 }
5192
5193 SSL_TRC(3, ("%d: TLS13[%d]: Verifying with delegated credential",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: Verifying with delegated credential"
, getpid(), ss->fd)
5194 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: Verifying with delegated credential"
, getpid(), ss->fd)
;
5195 spki = dc->spki;
5196 } else {
5197 spki = &ss->sec.peerCert->subjectPublicKeyInfo;
5198 }
5199
5200 rv = ssl_CheckSignatureSchemeConsistency(ss, sigScheme, spki);
5201 if (rv != SECSuccess) {
5202 /* Error set already */
5203 FATAL_ERROR(ss, PORT_GetError(), illegal_parameter)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__, "tls13con.c"
, 5203); PORT_SetError_Util(PORT_GetError_Util()); } while (0
); tls13_FatalError(ss, PORT_GetError_Util(), illegal_parameter
); } while (0)
;
5204 return SECFailure;
5205 }
5206 hashAlg = ssl_SignatureSchemeToHashType(sigScheme);
5207
5208 rv = tls13_AddContextToHashes(ss, &hashes, hashAlg, PR_FALSE0, &tbsHash);
5209 if (rv != SECSuccess) {
5210 FATAL_ERROR(ss, SSL_ERROR_DIGEST_FAILURE, internal_error)do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_DIGEST_FAILURE, __func__, "tls13con.c"
, 5210); PORT_SetError_Util(SSL_ERROR_DIGEST_FAILURE); } while
(0); tls13_FatalError(ss, SSL_ERROR_DIGEST_FAILURE, internal_error
); } while (0)
;
5211 return SECFailure;
5212 }
5213
5214 rv = ssl3_ConsumeHandshakeVariable(ss, &signed_hash, 2, &b, &length);
5215 if (rv != SECSuccess) {
5216 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CERT_VERIFY);
5217 return SECFailure;
5218 }
5219
5220 if (length != 0) {
5221 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERT_VERIFY, decode_error)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_CERT_VERIFY, __func__
, "tls13con.c", 5221); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CERT_VERIFY
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_CERT_VERIFY
, decode_error); } while (0)
;
5222 return SECFailure;
5223 }
5224
5225 pubKey = SECKEY_ExtractPublicKey(spki);
5226 if (pubKey == NULL((void*)0)) {
5227 ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
5228 return SECFailure;
5229 }
5230
5231 rv = ssl_VerifySignedHashesWithPubKey(ss, pubKey, sigScheme,
5232 &tbsHash, &signed_hash);
5233 if (rv != SECSuccess) {
5234 FATAL_ERROR(ss, PORT_GetError(), decrypt_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__, "tls13con.c"
, 5234); PORT_SetError_Util(PORT_GetError_Util()); } while (0
); tls13_FatalError(ss, PORT_GetError_Util(), decrypt_error);
} while (0)
;
5235 goto loser;
5236 }
5237
5238 /* Set the auth type and verify it is what we captured in ssl3_AuthCertificate */
5239 if (!ss->sec.isServer) {
5240 ss->sec.authType = ssl_SignatureSchemeToAuthType(sigScheme);
5241
5242 uint32_t prelimAuthKeyBits = ss->sec.authKeyBits;
5243 rv = ssl_SetAuthKeyBits(ss, pubKey);
5244 if (rv != SECSuccess) {
5245 goto loser; /* Alert sent and code set. */
5246 }
5247
5248 if (prelimAuthKeyBits != ss->sec.authKeyBits) {
5249 FATAL_ERROR(ss, SSL_ERROR_DC_CERT_VERIFY_ALG_MISMATCH, 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_DC_CERT_VERIFY_ALG_MISMATCH,
__func__, "tls13con.c", 5249); PORT_SetError_Util(SSL_ERROR_DC_CERT_VERIFY_ALG_MISMATCH
); } while (0); tls13_FatalError(ss, SSL_ERROR_DC_CERT_VERIFY_ALG_MISMATCH
, illegal_parameter); } while (0)
;
5250 goto loser;
5251 }
5252 }
5253
5254 /* Request a client certificate now if one was requested. */
5255 if (ss->ssl3.hs.clientCertRequested) {
5256 PORT_Assert(!ss->sec.isServer)((!ss->sec.isServer)?((void)0):PR_Assert("!ss->sec.isServer"
,"tls13con.c",5256))
;
5257 rv = ssl3_BeginHandleCertificateRequest(
5258 ss, ss->xtnData.sigSchemes, ss->xtnData.numSigSchemes,
5259 &ss->xtnData.certReqAuthorities);
5260 if (rv != SECSuccess) {
5261 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__, "tls13con.c"
, 5261); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0); tls13_FatalError(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error
); } while (0)
;
5262 goto loser;
5263 }
5264 }
5265
5266 SECKEY_DestroyPublicKey(pubKey);
5267 TLS13_SET_HS_STATE(ss, wait_finished)tls13_SetHsState(ss, wait_finished, __func__, "tls13con.c", 5267
)
;
5268 return SECSuccess;
5269
5270loser:
5271 SECKEY_DestroyPublicKey(pubKey);
5272 return SECFailure;
5273}
5274
5275/* Compute the PSK binder hash over:
5276 * Client HRR prefix, if present in ss->ssl3.hs.messages or ss->ssl3.hs.echInnerMessages,
5277 * |len| bytes of |buf| */
5278static SECStatus
5279tls13_ComputePskBinderHash(sslSocket *ss, PRUint8 *b, size_t length,
5280 SSL3Hashes *hashes, SSLHashType hashType)
5281{
5282 SECStatus rv;
5283 PK11Context *ctx = NULL((void*)0);
5284 sslBuffer *clientResidual = NULL((void*)0);
5285 if (!ss->sec.isServer) {
5286 /* On the server, HRR residual is already buffered. */
5287 clientResidual = ss->ssl3.hs.echHpkeCtx ? &ss->ssl3.hs.echInnerMessages : &ss->ssl3.hs.messages;
5288 }
5289 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"
,"tls13con.c",5289))
;
5290 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)"
,"tls13con.c",5290))
;
5291
5292 PRINT_BUF(10, (NULL, "Binder computed over ClientHello",if (ssl_trace >= (10)) ssl_PrintBuf (((void*)0), "Binder computed over ClientHello"
, b, length)
5293 b, length))if (ssl_trace >= (10)) ssl_PrintBuf (((void*)0), "Binder computed over ClientHello"
, b, length)
;
5294
5295 ctx = PK11_CreateDigestContext(ssl3_HashTypeToOID(hashType));
5296 if (!ctx) {
5297 goto loser;
5298 }
5299 rv = PK11_DigestBegin(ctx);
5300 if (rv != SECSuccess) {
5301 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
5302 goto loser;
5303 }
5304
5305 if (clientResidual && clientResidual->len) {
5306 PRINT_BUF(10, (NULL, " with HRR prefix", clientResidual->buf,if (ssl_trace >= (10)) ssl_PrintBuf (((void*)0), " with HRR prefix"
, clientResidual->buf, clientResidual->len)
5307 clientResidual->len))if (ssl_trace >= (10)) ssl_PrintBuf (((void*)0), " with HRR prefix"
, clientResidual->buf, clientResidual->len)
;
5308 rv = PK11_DigestOp(ctx, clientResidual->buf, clientResidual->len);
5309 if (rv != SECSuccess) {
5310 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
5311 goto loser;
5312 }
5313 }
5314
5315 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram) && !ss->sec.isServer) {
5316 /* Removing the unnecessary header fields.
5317 * See ssl3_AppendHandshakeHeader.*/
5318 PORT_Assert(length >= 12)((length >= 12)?((void)0):PR_Assert("length >= 12","tls13con.c"
,5318))
;
5319 rv = PK11_DigestOp(ctx, b, 4);
5320 if (rv != SECSuccess) {
5321 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
5322 goto loser;
5323 }
5324 rv = PK11_DigestOp(ctx, b + 12, length - 12);
5325 } else {
5326 rv = PK11_DigestOp(ctx, b, length);
5327 }
5328 if (rv != SECSuccess) {
5329 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
5330 goto loser;
5331 }
5332 rv = PK11_DigestFinal(ctx, hashes->u.raw, &hashes->len, sizeof(hashes->u.raw));
5333 if (rv != SECSuccess) {
5334 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
5335 goto loser;
5336 }
5337
5338 PK11_DestroyContext(ctx, PR_TRUE1);
5339 PRINT_BUF(10, (NULL, "PSK Binder hash", hashes->u.raw, hashes->len))if (ssl_trace >= (10)) ssl_PrintBuf (((void*)0), "PSK Binder hash"
, hashes->u.raw, hashes->len)
;
5340 return SECSuccess;
5341
5342loser:
5343 if (ctx) {
5344 PK11_DestroyContext(ctx, PR_TRUE1);
5345 }
5346 return SECFailure;
5347}
5348
5349/* Compute and inject the PSK Binder for sending.
5350 *
5351 * When sending a ClientHello, we construct all the extensions with a dummy
5352 * value for the binder. To construct the binder, we commit the entire message
5353 * up to the point where the binders start. Then we calculate the hash using
5354 * the saved message (in ss->ssl3.hs.messages). This is written over the dummy
5355 * binder, after which we write the remainder of the binder extension. */
5356SECStatus
5357tls13_WriteExtensionsWithBinder(sslSocket *ss, sslBuffer *extensions, sslBuffer *chBuf)
5358{
5359 SSL3Hashes hashes;
5360 SECStatus rv;
5361
5362 PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks))((!((&ss->ssl3.hs.psks)->next == (&ss->ssl3.
hs.psks)))?((void)0):PR_Assert("!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks)"
,"tls13con.c",5362))
;
5363 sslPsk *psk = (sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks)(&ss->ssl3.hs.psks)->next;
5364 unsigned int size = tls13_GetHashSizeForHash(psk->hash);
5365 unsigned int prefixLen = extensions->len - size - 3;
5366 unsigned int finishedLen;
5367
5368 PORT_Assert(extensions->len >= size + 3)((extensions->len >= size + 3)?((void)0):PR_Assert("extensions->len >= size + 3"
,"tls13con.c",5368))
;
5369
5370 rv = sslBuffer_AppendNumber(chBuf, extensions->len, 2);
5371 if (rv != SECSuccess) {
5372 return SECFailure;
5373 }
5374
5375 /* Only write the extension up to the point before the binders. Assume that
5376 * the pre_shared_key extension is at the end of the buffer. Don't write
5377 * the binder, or the lengths that precede it (a 2 octet length for the list
5378 * of all binders, plus a 1 octet length for the binder length). */
5379 rv = sslBuffer_Append(chBuf, extensions->buf, prefixLen);
5380 if (rv != SECSuccess) {
5381 return SECFailure;
5382 }
5383
5384 /* Calculate the binder based on what has been written out. */
5385 rv = tls13_ComputePskBinderHash(ss, chBuf->buf, chBuf->len, &hashes, psk->hash);
5386 if (rv != SECSuccess) {
5387 return SECFailure;
5388 }
5389
5390 /* Write the binder into the extensions buffer, over the zeros we reserved
5391 * previously. This avoids an allocation and means that we don't need a
5392 * separate write for the extra bits that precede the binder. */
5393 PORT_Assert(psk->binderKey)((psk->binderKey)?((void)0):PR_Assert("psk->binderKey",
"tls13con.c",5393))
;
5394 rv = tls13_ComputeFinished(ss, psk->binderKey,
5395 psk->hash, &hashes, PR_TRUE1,
5396 extensions->buf + extensions->len - size,
5397 &finishedLen, size);
5398 if (rv != SECSuccess) {
5399 return SECFailure;
5400 }
5401 PORT_Assert(finishedLen == size)((finishedLen == size)?((void)0):PR_Assert("finishedLen == size"
,"tls13con.c",5401))
;
5402
5403 /* Write out the remainder of the extension. */
5404 rv = sslBuffer_Append(chBuf, extensions->buf + prefixLen,
5405 extensions->len - prefixLen);
5406 if (rv != SECSuccess) {
5407 return SECFailure;
5408 }
5409
5410 return SECSuccess;
5411}
5412
5413static SECStatus
5414tls13_ComputeFinished(sslSocket *ss, PK11SymKey *baseKey,
5415 SSLHashType hashType, const SSL3Hashes *hashes,
5416 PRBool sending, PRUint8 *output, unsigned int *outputLen,
5417 unsigned int maxOutputLen)
5418{
5419 SECStatus rv;
5420 PK11Context *hmacCtx = NULL((void*)0);
5421 CK_MECHANISM_TYPE macAlg = tls13_GetHmacMechanismFromHash(hashType);
5422 SECItem param = { siBuffer, NULL((void*)0), 0 };
5423 unsigned int outputLenUint;
5424 const char *label = kHkdfLabelFinishedSecret;
5425 PK11SymKey *secret = NULL((void*)0);
5426
5427 PORT_Assert(baseKey)((baseKey)?((void)0):PR_Assert("baseKey","tls13con.c",5427));
5428 SSL_TRC(3, ("%d: TLS13[%d]: %s calculate finished",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: %s calculate finished"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
))
5429 SSL_GETPID(), ss->fd, SSL_ROLE(ss)))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: %s calculate finished"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
))
;
5430 PRINT_BUF(50, (ss, "Handshake hash", hashes->u.raw, hashes->len))if (ssl_trace >= (50)) ssl_PrintBuf (ss, "Handshake hash",
hashes->u.raw, hashes->len)
;
5431
5432 /* Now derive the appropriate finished secret from the base secret. */
5433 rv = tls13_HkdfExpandLabel(baseKey, hashType,
5434 NULL((void*)0), 0, label, strlen(label),
5435 tls13_GetHmacMechanismFromHash(hashType),
5436 tls13_GetHashSizeForHash(hashType),
5437 ss->protocolVariant, &secret);
5438 if (rv != SECSuccess) {
5439 goto abort;
5440 }
5441
5442 PORT_Assert(hashes->len == tls13_GetHashSizeForHash(hashType))((hashes->len == tls13_GetHashSizeForHash(hashType))?((void
)0):PR_Assert("hashes->len == tls13_GetHashSizeForHash(hashType)"
,"tls13con.c",5442))
;
5443 hmacCtx = PK11_CreateContextBySymKey(macAlg, CKA_SIGN0x00000108UL,
5444 secret, &param);
5445 if (!hmacCtx) {
5446 goto abort;
5447 }
5448
5449 rv = PK11_DigestBegin(hmacCtx);
5450 if (rv != SECSuccess)
5451 goto abort;
5452
5453 rv = PK11_DigestOp(hmacCtx, hashes->u.raw, hashes->len);
5454 if (rv != SECSuccess)
5455 goto abort;
5456
5457 PORT_Assert(maxOutputLen >= tls13_GetHashSizeForHash(hashType))((maxOutputLen >= tls13_GetHashSizeForHash(hashType))?((void
)0):PR_Assert("maxOutputLen >= tls13_GetHashSizeForHash(hashType)"
,"tls13con.c",5457))
;
5458 rv = PK11_DigestFinal(hmacCtx, output, &outputLenUint, maxOutputLen);
5459 if (rv != SECSuccess)
5460 goto abort;
5461 *outputLen = outputLenUint;
5462
5463 PK11_FreeSymKey(secret);
5464 PK11_DestroyContext(hmacCtx, PR_TRUE1);
5465 PRINT_BUF(50, (ss, "finished value", output, outputLenUint))if (ssl_trace >= (50)) ssl_PrintBuf (ss, "finished value",
output, outputLenUint)
;
5466 return SECSuccess;
5467
5468abort:
5469 if (secret) {
5470 PK11_FreeSymKey(secret);
5471 }
5472
5473 if (hmacCtx) {
5474 PK11_DestroyContext(hmacCtx, PR_TRUE1);
5475 }
5476
5477 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
5478 return SECFailure;
5479}
5480
5481static SECStatus
5482tls13_SendFinished(sslSocket *ss, PK11SymKey *baseKey)
5483{
5484 SECStatus rv;
5485 PRUint8 finishedBuf[TLS13_MAX_FINISHED_SIZE64];
5486 unsigned int finishedLen;
5487 SSL3Hashes hashes;
5488
5489 SSL_TRC(3, ("%d: TLS13[%d]: send finished handshake", SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: send finished handshake"
, getpid(), ss->fd)
;
5490
5491 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)"
,"tls13con.c",5491))
;
5492 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)"
,"tls13con.c",5492))
;
5493
5494 rv = tls13_ComputeHandshakeHashes(ss, &hashes);
5495 if (rv != SECSuccess) {
5496 LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE)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__, "tls13con.c"
, 5496); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0)
;
5497 return SECFailure;
5498 }
5499
5500 ssl_GetSpecReadLock(ss){ if (!ss->opt.noLocks) NSSRWLock_LockRead_Util((ss)->specLock
); }
;
5501 rv = tls13_ComputeFinished(ss, baseKey, tls13_GetHash(ss), &hashes, PR_TRUE1,
5502 finishedBuf, &finishedLen, sizeof(finishedBuf));
5503 ssl_ReleaseSpecReadLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockRead_Util((ss)->
specLock); }
;
5504 if (rv != SECSuccess) {
5505 LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE)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__, "tls13con.c"
, 5505); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0)
;
5506 return SECFailure;
5507 }
5508
5509 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_finished, finishedLen);
5510 if (rv != SECSuccess) {
5511 return SECFailure; /* Error code already set. */
5512 }
5513
5514 rv = ssl3_AppendHandshake(ss, finishedBuf, finishedLen);
5515 if (rv != SECSuccess) {
5516 return SECFailure; /* Error code already set. */
5517 }
5518
5519 /* TODO(ekr@rtfm.com): Record key log */
5520 return SECSuccess;
5521}
5522
5523static SECStatus
5524tls13_VerifyFinished(sslSocket *ss, SSLHandshakeType message,
5525 PK11SymKey *secret,
5526 PRUint8 *b, PRUint32 length,
5527 const SSL3Hashes *hashes)
5528{
5529 SECStatus rv;
5530 PRUint8 finishedBuf[TLS13_MAX_FINISHED_SIZE64];
5531 unsigned int finishedLen;
5532
5533 if (!hashes) {
5534 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__, "tls13con.c"
, 5534); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0); tls13_FatalError(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error
); } while (0)
;
5535 return SECFailure;
5536 }
5537
5538 rv = tls13_ComputeFinished(ss, secret, tls13_GetHash(ss), hashes, PR_FALSE0,
5539 finishedBuf, &finishedLen, sizeof(finishedBuf));
5540 if (rv != SECSuccess) {
5541 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__, "tls13con.c"
, 5541); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0); tls13_FatalError(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error
); } while (0)
;
5542 return SECFailure;
5543 }
5544
5545 if (length != finishedLen) {
5546#ifndef UNSAFE_FUZZER_MODE
5547 FATAL_ERROR(ss, message == ssl_hs_finished ? SSL_ERROR_RX_MALFORMED_FINISHED : 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, message == ssl_hs_finished ? SSL_ERROR_RX_MALFORMED_FINISHED
: SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, __func__, "tls13con.c"
, 5547); PORT_SetError_Util(message == ssl_hs_finished ? SSL_ERROR_RX_MALFORMED_FINISHED
: SSL_ERROR_RX_MALFORMED_CLIENT_HELLO); } while (0); tls13_FatalError
(ss, message == ssl_hs_finished ? SSL_ERROR_RX_MALFORMED_FINISHED
: SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter); }
while (0)
;
5548 return SECFailure;
5549#endif
5550 }
5551
5552 if (NSS_SecureMemcmp(b, finishedBuf, finishedLen) != 0) {
5553#ifndef UNSAFE_FUZZER_MODE
5554 FATAL_ERROR(ss, SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE,do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE, __func__
, "tls13con.c", 5555); PORT_SetError_Util(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE
); } while (0); tls13_FatalError(ss, SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE
, decrypt_error); } while (0)
5555 decrypt_error)do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE, __func__
, "tls13con.c", 5555); PORT_SetError_Util(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE
); } while (0); tls13_FatalError(ss, SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE
, decrypt_error); } while (0)
;
5556 return SECFailure;
5557#endif
5558 }
5559
5560 return SECSuccess;
5561}
5562
5563static SECStatus
5564tls13_CommonHandleFinished(sslSocket *ss, PK11SymKey *key,
5565 PRUint8 *b, PRUint32 length)
5566{
5567 SECStatus rv;
5568 SSL3Hashes hashes;
5569
5570 rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_FINISHED,tls13_CheckHsState(ss, SSL_ERROR_RX_UNEXPECTED_FINISHED, "SSL_ERROR_RX_UNEXPECTED_FINISHED"
, __func__, "tls13con.c", 5571, wait_finished, wait_invalid)
5571 wait_finished)tls13_CheckHsState(ss, SSL_ERROR_RX_UNEXPECTED_FINISHED, "SSL_ERROR_RX_UNEXPECTED_FINISHED"
, __func__, "tls13con.c", 5571, wait_finished, wait_invalid)
;
5572 if (rv != SECSuccess) {
5573 return SECFailure;
5574 }
5575 ss->ssl3.hs.endOfFlight = PR_TRUE1;
5576
5577 rv = tls13_ComputeHandshakeHashes(ss, &hashes);
5578 if (rv != SECSuccess) {
5579 LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE)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__, "tls13con.c"
, 5579); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0)
;
5580 return SECFailure;
5581 }
5582
5583 if (ss->firstHsDone) {
5584 rv = ssl_HashPostHandshakeMessage(ss, ssl_hs_finished, b, length);
5585 } else {
5586 rv = ssl_HashHandshakeMessage(ss, ssl_hs_finished, b, length);
5587 }
5588 if (rv != SECSuccess) {
5589 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
5590 return SECFailure;
5591 }
5592
5593 return tls13_VerifyFinished(ss, ssl_hs_finished,
5594 key, b, length, &hashes);
5595}
5596
5597static SECStatus
5598tls13_ClientHandleFinished(sslSocket *ss, PRUint8 *b, PRUint32 length)
5599{
5600 SECStatus rv;
5601
5602 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)"
,"tls13con.c",5602))
;
5603 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)"
,"tls13con.c",5603))
;
5604
5605 SSL_TRC(3, ("%d: TLS13[%d]: client handle finished handshake",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: client handle finished handshake"
, getpid(), ss->fd)
5606 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: client handle finished handshake"
, getpid(), ss->fd)
;
5607
5608 rv = tls13_CommonHandleFinished(ss, ss->ssl3.hs.serverHsTrafficSecret,
5609 b, length);
5610 if (rv != SECSuccess) {
5611 return SECFailure;
5612 }
5613
5614 return tls13_SendClientSecondRound(ss);
5615}
5616
5617static SECStatus
5618tls13_ServerHandleFinished(sslSocket *ss, PRUint8 *b, PRUint32 length)
5619{
5620 SECStatus rv;
5621
5622 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)"
,"tls13con.c",5622))
;
5623 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)"
,"tls13con.c",5623))
;
5624
5625 SSL_TRC(3, ("%d: TLS13[%d]: server handle finished handshake",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: server handle finished handshake"
, getpid(), ss->fd)
5626 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: server handle finished handshake"
, getpid(), ss->fd)
;
5627
5628 if (!tls13_ShouldRequestClientAuth(ss)) {
5629 /* Receiving this message might be the first sign we have that
5630 * early data is over, so pretend we received EOED. */
5631 rv = tls13_MaybeHandleSuppressedEndOfEarlyData(ss);
5632 if (rv != SECSuccess) {
5633 return SECFailure; /* Code already set. */
5634 }
5635
5636 if (!tls13_IsPostHandshake(ss)) {
5637 /* Finalize the RTT estimate. */
5638 ss->ssl3.hs.rttEstimate = ssl_Time(ss) - ss->ssl3.hs.rttEstimate;
5639 }
5640 }
5641
5642 rv = tls13_CommonHandleFinished(ss,
5643 ss->firstHsDone ? ss->ssl3.hs.clientTrafficSecret : ss->ssl3.hs.clientHsTrafficSecret,
5644 b, length);
5645 if (rv != SECSuccess) {
5646 return SECFailure;
5647 }
5648
5649 if (ss->firstHsDone) {
5650 TLS13_SET_HS_STATE(ss, idle_handshake)tls13_SetHsState(ss, idle_handshake, __func__, "tls13con.c", 5650
)
;
5651
5652 PORT_Assert(ss->ssl3.hs.shaPostHandshake != NULL)((ss->ssl3.hs.shaPostHandshake != ((void*)0))?((void)0):PR_Assert
("ss->ssl3.hs.shaPostHandshake != NULL","tls13con.c",5652)
)
;
5653 PK11_DestroyContext(ss->ssl3.hs.shaPostHandshake, PR_TRUE1);
5654 ss->ssl3.hs.shaPostHandshake = NULL((void*)0);
5655
5656 ss->ssl3.clientCertRequested = PR_FALSE0;
5657
5658 if (ss->ssl3.hs.keyUpdateDeferred) {
5659 rv = tls13_SendKeyUpdate(ss, ss->ssl3.hs.deferredKeyUpdateRequest,
5660 PR_FALSE0);
5661 if (rv != SECSuccess) {
5662 return SECFailure; /* error is set. */
5663 }
5664 ss->ssl3.hs.keyUpdateDeferred = PR_FALSE0;
5665 }
5666
5667 return SECSuccess;
5668 }
5669
5670 if (!tls13_ShouldRequestClientAuth(ss) &&
5671 (ss->ssl3.hs.zeroRttState != ssl_0rtt_done)) {
5672 dtls_ReceivedFirstMessageInFlight(ss);
5673 }
5674
5675 rv = tls13_SetCipherSpec(ss, TrafficKeyApplicationData,
5676 ssl_secret_read, PR_FALSE0);
5677 if (rv != SECSuccess) {
5678 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__, "tls13con.c"
, 5678); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0); tls13_FatalError(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error
); } while (0)
;
5679 return SECFailure;
5680 }
5681
5682 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
5683 ssl_CipherSpecReleaseByEpoch(ss, ssl_secret_read, TrafficKeyClearText);
5684 /* We need to keep the handshake cipher spec so we can
5685 * read re-transmitted client Finished. */
5686 rv = dtls_StartTimer(ss, ss->ssl3.hs.hdTimer,
5687 DTLS_RETRANSMIT_FINISHED_MS30000,
5688 dtls13_HolddownTimerCb);
5689 if (rv != SECSuccess) {
5690 return SECFailure;
5691 }
5692 }
5693
5694 rv = tls13_ComputeFinalSecrets(ss);
5695 if (rv != SECSuccess) {
5696 return SECFailure;
5697 }
5698
5699 rv = tls13_FinishHandshake(ss);
5700 if (rv != SECSuccess) {
5701 return SECFailure;
5702 }
5703
5704 ssl_GetXmitBufLock(ss){ if (!ss->opt.noLocks) PR_EnterMonitor(((ss)->xmitBufLock
)); }
;
5705 /* If resumption, authType is the original value and not ssl_auth_psk. */
5706 if (ss->opt.enableSessionTickets && ss->sec.authType != ssl_auth_psk) {
5707 rv = tls13_SendNewSessionTicket(ss, NULL((void*)0), 0);
5708 if (rv != SECSuccess) {
5709 goto loser;
5710 }
5711 rv = ssl3_FlushHandshake(ss, 0);
5712 if (rv != SECSuccess) {
5713 goto loser;
5714 }
5715 }
5716 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
;
5717 return SECSuccess;
5718
5719loser:
5720 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
;
5721 return SECFailure;
5722}
5723
5724static SECStatus
5725tls13_FinishHandshake(sslSocket *ss)
5726{
5727 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)"
,"tls13con.c",5727))
;
5728 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)"
,"tls13con.c",5728))
;
5729 PORT_Assert(ss->ssl3.hs.restartTarget == NULL)((ss->ssl3.hs.restartTarget == ((void*)0))?((void)0):PR_Assert
("ss->ssl3.hs.restartTarget == NULL","tls13con.c",5729))
;
5730
5731 /* The first handshake is now completed. */
5732 ss->handshake = NULL((void*)0);
5733
5734 /* Don't need this. */
5735 PK11_FreeSymKey(ss->ssl3.hs.clientHsTrafficSecret);
5736 ss->ssl3.hs.clientHsTrafficSecret = NULL((void*)0);
5737 PK11_FreeSymKey(ss->ssl3.hs.serverHsTrafficSecret);
5738 ss->ssl3.hs.serverHsTrafficSecret = NULL((void*)0);
5739
5740 TLS13_SET_HS_STATE(ss, idle_handshake)tls13_SetHsState(ss, idle_handshake, __func__, "tls13con.c", 5740
)
;
5741
5742 return ssl_FinishHandshake(ss);
5743}
5744
5745/* Do the parts of sending the client's second round that require
5746 * the XmitBuf lock. */
5747static SECStatus
5748tls13_SendClientSecondFlight(sslSocket *ss)
5749{
5750 SECStatus rv;
5751 unsigned int offset = 0;
5752
5753 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)"
,"tls13con.c",5753))
;
5754 PORT_Assert(!ss->ssl3.hs.clientCertificatePending)((!ss->ssl3.hs.clientCertificatePending)?((void)0):PR_Assert
("!ss->ssl3.hs.clientCertificatePending","tls13con.c",5754
))
;
5755
5756 PRBool sendClientCert = !ss->ssl3.sendEmptyCert &&
5757 ss->ssl3.clientCertChain != NULL((void*)0) &&
5758 ss->ssl3.clientPrivateKey != NULL((void*)0);
5759
5760 if (ss->firstHsDone) {
5761 offset = SSL_BUFFER_LEN(&ss->sec.ci.sendBuf)((&ss->sec.ci.sendBuf)->len);
5762 }
5763
5764 if (ss->ssl3.sendEmptyCert) {
5765 ss->ssl3.sendEmptyCert = PR_FALSE0;
5766 rv = ssl3_SendEmptyCertificate(ss);
5767 /* Don't send verify */
5768 if (rv != SECSuccess) {
5769 goto alert_error; /* error code is set. */
5770 }
5771 } else if (sendClientCert) {
5772 rv = tls13_SendCertificate(ss);
5773 if (rv != SECSuccess) {
5774 goto alert_error; /* err code was set. */
5775 }
5776 }
5777
5778 if (ss->firstHsDone) {
5779 rv = ssl3_UpdatePostHandshakeHashes(ss,
5780 SSL_BUFFER_BASE(&ss->sec.ci.sendBuf)((&ss->sec.ci.sendBuf)->buf) + offset,
5781 SSL_BUFFER_LEN(&ss->sec.ci.sendBuf)((&ss->sec.ci.sendBuf)->len) - offset);
5782 if (rv != SECSuccess) {
5783 goto alert_error; /* err code was set. */
5784 }
5785 }
5786
5787 if (ss->ssl3.hs.clientCertRequested) {
5788 SECITEM_FreeItemSECITEM_FreeItem_Util(&ss->xtnData.certReqContext, PR_FALSE0);
5789 if (ss->xtnData.certReqAuthorities.arena) {
5790 PORT_FreeArenaPORT_FreeArena_Util(ss->xtnData.certReqAuthorities.arena, PR_FALSE0);
5791 ss->xtnData.certReqAuthorities.arena = NULL((void*)0);
5792 }
5793 PORT_Memsetmemset(&ss->xtnData.certReqAuthorities, 0,
5794 sizeof(ss->xtnData.certReqAuthorities));
5795 ss->ssl3.hs.clientCertRequested = PR_FALSE0;
5796 }
5797
5798 if (sendClientCert) {
5799 if (ss->firstHsDone) {
5800 offset = SSL_BUFFER_LEN(&ss->sec.ci.sendBuf)((&ss->sec.ci.sendBuf)->len);
5801 }
5802
5803 rv = tls13_SendCertificateVerify(ss, ss->ssl3.clientPrivateKey);
5804 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
5805 ss->ssl3.clientPrivateKey = NULL((void*)0);
5806 if (rv != SECSuccess) {
5807 goto alert_error; /* err code was set. */
5808 }
5809
5810 if (ss->firstHsDone) {
5811 rv = ssl3_UpdatePostHandshakeHashes(ss,
5812 SSL_BUFFER_BASE(&ss->sec.ci.sendBuf)((&ss->sec.ci.sendBuf)->buf) + offset,
5813 SSL_BUFFER_LEN(&ss->sec.ci.sendBuf)((&ss->sec.ci.sendBuf)->len) - offset);
5814 if (rv != SECSuccess) {
5815 goto alert_error; /* err code was set. */
5816 }
5817 }
5818 }
5819
5820 rv = tls13_SendFinished(ss, ss->firstHsDone ? ss->ssl3.hs.clientTrafficSecret : ss->ssl3.hs.clientHsTrafficSecret);
5821 if (rv != SECSuccess) {
5822 goto alert_error; /* err code was set. */
5823 }
5824 rv = ssl3_FlushHandshake(ss, 0);
5825 if (rv != SECSuccess) {
5826 /* No point in sending an alert here because we're not going to
5827 * be able to send it if we couldn't flush the handshake. */
5828 goto error;
5829 }
5830
5831 return SECSuccess;
5832
5833alert_error:
5834 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__, "tls13con.c"
, 5834); PORT_SetError_Util(PORT_GetError_Util()); } while (0
); tls13_FatalError(ss, PORT_GetError_Util(), internal_error)
; } while (0)
;
5835 return SECFailure;
5836error:
5837 LOG_ERROR(ss, PORT_GetError())do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, PORT_GetError_Util(), __func__, "tls13con.c"
, 5837); PORT_SetError_Util(PORT_GetError_Util()); } while (0
)
;
5838 return SECFailure;
5839}
5840
5841static SECStatus
5842tls13_SendClientSecondRound(sslSocket *ss)
5843{
5844 SECStatus rv;
5845
5846 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)"
,"tls13con.c",5846))
;
5847 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)"
,"tls13con.c",5847))
;
5848
5849 /* Defer client authentication sending if we are still waiting for server
5850 * authentication. This avoids unnecessary disclosure of client credentials
5851 * to an unauthenticated server.
5852 */
5853 if (ss->ssl3.hs.restartTarget) {
5854 PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget")PR_Assert("unexpected ss->ssl3.hs.restartTarget","tls13con.c"
,5854)
;
5855 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
5856 return SECFailure;
5857 }
5858 if (ss->ssl3.hs.authCertificatePending || ss->ssl3.hs.clientCertificatePending) {
5859 SSL_TRC(3, ("%d: TLS13[%d]: deferring tls13_SendClientSecondRound because"if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: deferring tls13_SendClientSecondRound because"
" certificate authentication is still pending.", getpid(), ss
->fd)
5860 " certificate authentication is still pending.",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: deferring tls13_SendClientSecondRound because"
" certificate authentication is still pending.", getpid(), ss
->fd)
5861 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: deferring tls13_SendClientSecondRound because"
" certificate authentication is still pending.", getpid(), ss
->fd)
;
5862 ss->ssl3.hs.restartTarget = tls13_SendClientSecondRound;
5863 PORT_SetErrorPORT_SetError_Util(PR_WOULD_BLOCK_ERROR(-5998L));
5864 return SECFailure;
5865 }
5866
5867 rv = tls13_ComputeApplicationSecrets(ss);
5868 if (rv != SECSuccess) {
5869 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__, "tls13con.c"
, 5869); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0); tls13_FatalError(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error
); } while (0)
;
5870 return SECFailure;
5871 }
5872
5873 if (ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) {
5874 ssl_GetXmitBufLock(ss){ if (!ss->opt.noLocks) PR_EnterMonitor(((ss)->xmitBufLock
)); }
; /*******************************/
5875 rv = tls13_SendEndOfEarlyData(ss);
5876 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
; /*******************************/
5877 if (rv != SECSuccess) {
5878 return SECFailure; /* Error code already set. */
5879 }
5880 } else if (ss->opt.enableTls13CompatMode && !IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram) &&
5881 ss->ssl3.hs.zeroRttState == ssl_0rtt_none &&
5882 !ss->ssl3.hs.helloRetry) {
5883 ssl_GetXmitBufLock(ss){ if (!ss->opt.noLocks) PR_EnterMonitor(((ss)->xmitBufLock
)); }
; /*******************************/
5884 rv = ssl3_SendChangeCipherSpecsInt(ss);
5885 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
; /*******************************/
5886 if (rv != SECSuccess) {
5887 return rv;
5888 }
5889 }
5890
5891 rv = tls13_SetCipherSpec(ss, TrafficKeyHandshake,
5892 ssl_secret_write, PR_FALSE0);
5893 if (rv != SECSuccess) {
5894 FATAL_ERROR(ss, SSL_ERROR_INIT_CIPHER_SUITE_FAILURE, internal_error)do { do { if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)"
, getpid(), ss->fd, SSL_ERROR_INIT_CIPHER_SUITE_FAILURE, __func__
, "tls13con.c", 5894); PORT_SetError_Util(SSL_ERROR_INIT_CIPHER_SUITE_FAILURE
); } while (0); tls13_FatalError(ss, SSL_ERROR_INIT_CIPHER_SUITE_FAILURE
, internal_error); } while (0)
;
5895 return SECFailure;
5896 }
5897
5898 rv = tls13_SetCipherSpec(ss, TrafficKeyApplicationData,
5899 ssl_secret_read, PR_FALSE0);
5900 if (rv != SECSuccess) {
5901 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__, "tls13con.c"
, 5901); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0); tls13_FatalError(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error
); } while (0)
;
5902 return SECFailure;
5903 }
5904
5905 ssl_GetXmitBufLock(ss){ if (!ss->opt.noLocks) PR_EnterMonitor(((ss)->xmitBufLock
)); }
; /*******************************/
5906 /* This call can't block, as clientAuthCertificatePending is checked above */
5907 rv = tls13_SendClientSecondFlight(ss);
5908 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
; /*******************************/
5909 if (rv != SECSuccess) {
5910 return SECFailure;
5911 }
5912 rv = tls13_SetCipherSpec(ss, TrafficKeyApplicationData,
5913 ssl_secret_write, PR_FALSE0);
5914 if (rv != SECSuccess) {
5915 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
5916 return SECFailure;
5917 }
5918
5919 rv = tls13_ComputeFinalSecrets(ss);
5920 if (rv != SECSuccess) {
5921 return SECFailure;
5922 }
5923
5924 /* The handshake is now finished */
5925 return tls13_FinishHandshake(ss);
5926}
5927
5928/*
5929 * enum { (65535) } TicketExtensionType;
5930 *
5931 * struct {
5932 * TicketExtensionType extension_type;
5933 * opaque extension_data<0..2^16-1>;
5934 * } TicketExtension;
5935 *
5936 * struct {
5937 * uint32 ticket_lifetime;
5938 * uint32 ticket_age_add;
5939 * opaque ticket_nonce<1..255>;
5940 * opaque ticket<1..2^16-1>;
5941 * TicketExtension extensions<0..2^16-2>;
5942 * } NewSessionTicket;
5943 */
5944
5945static SECStatus
5946tls13_SendNewSessionTicket(sslSocket *ss, const PRUint8 *appToken,
5947 unsigned int appTokenLen)
5948{
5949 PRUint16 message_length;
5950 PK11SymKey *secret;
5951 SECItem ticket_data = { 0, NULL((void*)0), 0 };
5952 SECStatus rv;
5953 NewSessionTicket ticket = { 0 };
5954 PRUint32 max_early_data_size_len = 0;
5955 PRUint32 greaseLen = 0;
5956 PRUint8 ticketNonce[sizeof(ss->ssl3.hs.ticketNonce)];
5957 sslBuffer ticketNonceBuf = SSL_BUFFER(ticketNonce){ ticketNonce, 0, sizeof(ticketNonce), 1 };
5958
5959 SSL_TRC(3, ("%d: TLS13[%d]: send new session ticket message %d",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: send new session ticket message %d"
, getpid(), ss->fd, ss->ssl3.hs.ticketNonce)
5960 SSL_GETPID(), ss->fd, ss->ssl3.hs.ticketNonce))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: send new session ticket message %d"
, getpid(), ss->fd, ss->ssl3.hs.ticketNonce)
;
5961
5962 ticket.flags = 0;
5963 if (ss->opt.enable0RttData) {
5964 ticket.flags |= ticket_allow_early_data;
5965 max_early_data_size_len = 8; /* type + len + value. */
5966 }
5967 ticket.ticket_lifetime_hint = ssl_ticket_lifetime;
5968
5969 if (ss->opt.enableGrease) {
5970 greaseLen = 4; /* type + len + 0 (empty) */
5971 }
5972
5973 /* The ticket age obfuscator. */
5974 rv = PK11_GenerateRandom((PRUint8 *)&ticket.ticket_age_add,
5975 sizeof(ticket.ticket_age_add));
5976 if (rv != SECSuccess)
5977 goto loser;
5978
5979 rv = sslBuffer_AppendNumber(&ticketNonceBuf, ss->ssl3.hs.ticketNonce,
5980 sizeof(ticketNonce));
5981 if (rv != SECSuccess) {
5982 goto loser;
5983 }
5984 ++ss->ssl3.hs.ticketNonce;
5985 rv = tls13_HkdfExpandLabel(ss->ssl3.hs.resumptionMasterSecret,
5986 tls13_GetHash(ss),
5987 ticketNonce, sizeof(ticketNonce),
5988 kHkdfLabelResumption,
5989 strlen(kHkdfLabelResumption),
5990 CKM_HKDF_DERIVE0x0000402aUL,
5991 tls13_GetHashSize(ss),
5992 ss->protocolVariant, &secret);
5993 if (rv != SECSuccess) {
5994 goto loser;
5995 }
5996
5997 rv = ssl3_EncodeSessionTicket(ss, &ticket, appToken, appTokenLen,
5998 secret, &ticket_data);
5999 PK11_FreeSymKey(secret);
6000 if (rv != SECSuccess)
6001 goto loser;
6002
6003 message_length =
6004 4 + /* lifetime */
6005 4 + /* ticket_age_add */
6006 1 + sizeof(ticketNonce) + /* ticket_nonce */
6007 2 + /* extensions lentgh */
6008 max_early_data_size_len + /* max_early_data_size extension length */
6009 greaseLen + /* GREASE extension length */
6010 2 + /* ticket length */
6011 ticket_data.len;
6012
6013 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_new_session_ticket,
6014 message_length);
6015 if (rv != SECSuccess)
6016 goto loser;
6017
6018 /* This is a fixed value. */
6019 rv = ssl3_AppendHandshakeNumber(ss, ssl_ticket_lifetime, 4);
6020 if (rv != SECSuccess)
6021 goto loser;
6022
6023 rv = ssl3_AppendHandshakeNumber(ss, ticket.ticket_age_add, 4);
6024 if (rv != SECSuccess)
6025 goto loser;
6026
6027 /* The ticket nonce. */
6028 rv = ssl3_AppendHandshakeVariable(ss, ticketNonce, sizeof(ticketNonce), 1);
6029 if (rv != SECSuccess)
6030 goto loser;
6031
6032 /* Encode the ticket. */
6033 rv = ssl3_AppendHandshakeVariable(
6034 ss, ticket_data.data, ticket_data.len, 2);
6035 if (rv != SECSuccess)
6036 goto loser;
6037
6038 /* Extensions */
6039 rv = ssl3_AppendHandshakeNumber(ss, max_early_data_size_len + greaseLen, 2);
6040 if (rv != SECSuccess)
6041 goto loser;
6042
6043 /* GREASE NewSessionTicket:
6044 * When sending a NewSessionTicket message in TLS 1.3, a server MAY select
6045 * one or more GREASE extension values and advertise them as extensions
6046 * with varying length and contents [RFC8701, SEction 4.1]. */
6047 if (ss->opt.enableGrease) {
6048 PR_ASSERT(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3)((ss->version >= 0x0304)?((void)0):PR_Assert("ss->version >= SSL_LIBRARY_VERSION_TLS_1_3"
,"tls13con.c",6048))
;
6049
6050 PRUint16 grease;
6051 rv = tls13_RandomGreaseValue(&grease);
6052 if (rv != SECSuccess)
6053 goto loser;
6054 /* Extension type */
6055 rv = ssl3_AppendHandshakeNumber(ss, grease, 2);
6056 if (rv != SECSuccess)
6057 goto loser;
6058 /* Extension length */
6059 rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
6060 if (rv != SECSuccess)
6061 goto loser;
6062 }
6063
6064 /* Max early data size extension. */
6065 if (max_early_data_size_len) {
6066 rv = ssl3_AppendHandshakeNumber(
6067 ss, ssl_tls13_early_data_xtn, 2);
6068 if (rv != SECSuccess)
6069 goto loser;
6070
6071 /* Length */
6072 rv = ssl3_AppendHandshakeNumber(ss, 4, 2);
6073 if (rv != SECSuccess)
6074 goto loser;
6075
6076 rv = ssl3_AppendHandshakeNumber(ss, ss->opt.maxEarlyDataSize, 4);
6077 if (rv != SECSuccess)
6078 goto loser;
6079 }
6080
6081 SECITEM_FreeItemSECITEM_FreeItem_Util(&ticket_data, PR_FALSE0);
6082 return SECSuccess;
6083
6084loser:
6085 if (ticket_data.data) {
6086 SECITEM_FreeItemSECITEM_FreeItem_Util(&ticket_data, PR_FALSE0);
6087 }
6088 return SECFailure;
6089}
6090
6091SECStatus
6092SSLExp_SendSessionTicket(PRFileDesc *fd, const PRUint8 *token,
6093 unsigned int tokenLen)
6094{
6095 sslSocket *ss;
6096 SECStatus rv;
6097
6098 ss = ssl_FindSocket(fd);
6099 if (!ss) {
6100 return SECFailure;
6101 }
6102
6103 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
6104 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_VERSION);
6105 return SECFailure;
6106 }
6107
6108 if (!ss->sec.isServer || !tls13_IsPostHandshake(ss) ||
6109 tokenLen > 0xffff) {
6110 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
6111 return SECFailure;
6112 }
6113
6114 /* Disable tickets if we can trace this connection back to a PSK.
6115 * We aren't able to issue tickets (currently) without a certificate.
6116 * As PSK =~ resumption, there is no reason to do this. */
6117 if (ss->sec.authType == ssl_auth_psk) {
6118 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_FEATURE_DISABLED);
6119 return SECFailure;
6120 }
6121
6122 ssl_GetSSL3HandshakeLock(ss){ if (!ss->opt.noLocks) { ((!((PR_GetMonitorEntryCount(((ss
)->xmitBufLock)) > 0)))?((void)0):PR_Assert("!ssl_HaveXmitBufLock(ss)"
,"tls13con.c",6122)); PR_EnterMonitor(((ss)->ssl3HandshakeLock
)); } }
;
6123 ssl_GetXmitBufLock(ss){ if (!ss->opt.noLocks) PR_EnterMonitor(((ss)->xmitBufLock
)); }
;
6124 rv = tls13_SendNewSessionTicket(ss, token, tokenLen);
6125 if (rv == SECSuccess) {
6126 rv = ssl3_FlushHandshake(ss, 0);
6127 }
6128 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
;
6129 ssl_ReleaseSSL3HandshakeLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->ssl3HandshakeLock
)); }
;
6130
6131 return rv;
6132}
6133
6134static SECStatus
6135tls13_HandleNewSessionTicket(sslSocket *ss, PRUint8 *b, PRUint32 length)
6136{
6137 SECStatus rv;
6138 PRUint32 utmp;
6139 NewSessionTicket ticket = { 0 };
6140 SECItem data;
6141 SECItem ticket_nonce;
6142 SECItem ticket_data;
6143
6144 SSL_TRC(3, ("%d: TLS13[%d]: handle new session ticket message",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: handle new session ticket message"
, getpid(), ss->fd)
6145 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: handle new session ticket message"
, getpid(), ss->fd)
;
6146
6147 rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET,tls13_CheckHsState(ss, SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET
, "SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET", __func__, "tls13con.c"
, 6148, idle_handshake, wait_invalid)
6148 idle_handshake)tls13_CheckHsState(ss, SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET
, "SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET", __func__, "tls13con.c"
, 6148, idle_handshake, wait_invalid)
;
6149 if (rv != SECSuccess) {
6150 return SECFailure;
6151 }
6152 if (!tls13_IsPostHandshake(ss) || ss->sec.isServer) {
6153 FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET,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_NEW_SESSION_TICKET
, __func__, "tls13con.c", 6154); PORT_SetError_Util(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET
, unexpected_message); } while (0)
6154 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_NEW_SESSION_TICKET
, __func__, "tls13con.c", 6154); PORT_SetError_Util(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET
, unexpected_message); } while (0)
;
6155 return SECFailure;
6156 }
6157
6158 ticket.received_timestamp = ssl_Time(ss);
6159 rv = ssl3_ConsumeHandshakeNumber(ss, &ticket.ticket_lifetime_hint, 4, &b,
6160 &length);
6161 if (rv != SECSuccess) {
6162 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET,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_NEW_SESSION_TICKET
, __func__, "tls13con.c", 6163); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET
, decode_error); } while (0)
6163 decode_error)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_NEW_SESSION_TICKET
, __func__, "tls13con.c", 6163); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET
, decode_error); } while (0)
;
6164 return SECFailure;
6165 }
6166 ticket.ticket.type = siBuffer;
6167
6168 rv = ssl3_ConsumeHandshake(ss, &utmp, sizeof(utmp),
6169 &b, &length);
6170 if (rv != SECSuccess) {
6171 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
6172 return SECFailure;
6173 }
6174 ticket.ticket_age_add = PR_ntohl(utmp);
6175
6176 /* The nonce. */
6177 rv = ssl3_ConsumeHandshakeVariable(ss, &ticket_nonce, 1, &b, &length);
6178 if (rv != SECSuccess) {
6179 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET,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_NEW_SESSION_TICKET
, __func__, "tls13con.c", 6180); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET
, decode_error); } while (0)
6180 decode_error)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_NEW_SESSION_TICKET
, __func__, "tls13con.c", 6180); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET
, decode_error); } while (0)
;
6181 return SECFailure;
6182 }
6183
6184 /* Get the ticket value. */
6185 rv = ssl3_ConsumeHandshakeVariable(ss, &ticket_data, 2, &b, &length);
6186 if (rv != SECSuccess || !ticket_data.len) {
6187 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET,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_NEW_SESSION_TICKET
, __func__, "tls13con.c", 6188); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET
, decode_error); } while (0)
6188 decode_error)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_NEW_SESSION_TICKET
, __func__, "tls13con.c", 6188); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET
, decode_error); } while (0)
;
6189 return SECFailure;
6190 }
6191
6192 /* Parse extensions. */
6193 rv = ssl3_ConsumeHandshakeVariable(ss, &data, 2, &b, &length);
6194 if (rv != SECSuccess || length) {
6195 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET,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_NEW_SESSION_TICKET
, __func__, "tls13con.c", 6196); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET
, decode_error); } while (0)
6196 decode_error)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_NEW_SESSION_TICKET
, __func__, "tls13con.c", 6196); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET
, decode_error); } while (0)
;
6197 return SECFailure;
6198 }
6199
6200 rv = ssl3_HandleExtensions(ss, &data.data,
6201 &data.len, ssl_hs_new_session_ticket);
6202 if (rv != SECSuccess) {
6203 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET,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_NEW_SESSION_TICKET
, __func__, "tls13con.c", 6204); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET
, decode_error); } while (0)
6204 decode_error)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_NEW_SESSION_TICKET
, __func__, "tls13con.c", 6204); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET
, decode_error); } while (0)
;
6205 return SECFailure;
6206 }
6207 if (ss->xtnData.max_early_data_size) {
6208 ticket.flags |= ticket_allow_early_data;
6209 ticket.max_early_data_size = ss->xtnData.max_early_data_size;
6210 }
6211
6212 if (!ss->opt.noCache) {
6213 PK11SymKey *secret;
6214
6215 PORT_Assert(ss->sec.ci.sid)((ss->sec.ci.sid)?((void)0):PR_Assert("ss->sec.ci.sid",
"tls13con.c",6215))
;
6216 rv = SECITEM_CopyItemSECITEM_CopyItem_Util(NULL((void*)0), &ticket.ticket, &ticket_data);
6217 if (rv != SECSuccess) {
6218 FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, 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_NO_MEMORY, __func__, "tls13con.c"
, 6218); PORT_SetError_Util(SEC_ERROR_NO_MEMORY); } while (0)
; tls13_FatalError(ss, SEC_ERROR_NO_MEMORY, internal_error); }
while (0)
;
6219 return SECFailure;
6220 }
6221 PRINT_BUF(50, (ss, "Caching session ticket",if (ssl_trace >= (50)) ssl_PrintBuf (ss, "Caching session ticket"
, ticket.ticket.data, ticket.ticket.len)
6222 ticket.ticket.data,if (ssl_trace >= (50)) ssl_PrintBuf (ss, "Caching session ticket"
, ticket.ticket.data, ticket.ticket.len)
6223 ticket.ticket.len))if (ssl_trace >= (50)) ssl_PrintBuf (ss, "Caching session ticket"
, ticket.ticket.data, ticket.ticket.len)
;
6224
6225 /* Replace a previous session ticket when
6226 * we receive a second NewSessionTicket message. */
6227 if (ss->sec.ci.sid->cached == in_client_cache ||
6228 ss->sec.ci.sid->cached == in_external_cache) {
6229 /* Create a new session ID. */
6230 sslSessionID *sid = ssl3_NewSessionID(ss, PR_FALSE0);
6231 if (!sid) {
6232 return SECFailure;
6233 }
6234
6235 /* Copy over the peerCert. */
6236 PORT_Assert(ss->sec.ci.sid->peerCert)((ss->sec.ci.sid->peerCert)?((void)0):PR_Assert("ss->sec.ci.sid->peerCert"
,"tls13con.c",6236))
;
6237 sid->peerCert = CERT_DupCertificate(ss->sec.ci.sid->peerCert);
6238 if (!sid->peerCert) {
6239 ssl_FreeSID(sid);
6240 return SECFailure;
6241 }
6242
6243 /* Destroy the old SID. */
6244 ssl_UncacheSessionID(ss);
6245 ssl_FreeSID(ss->sec.ci.sid);
6246 ss->sec.ci.sid = sid;
6247 }
6248
6249 ssl3_SetSIDSessionTicket(ss->sec.ci.sid, &ticket);
6250 PORT_Assert(!ticket.ticket.data)((!ticket.ticket.data)?((void)0):PR_Assert("!ticket.ticket.data"
,"tls13con.c",6250))
;
6251
6252 rv = tls13_HkdfExpandLabel(ss->ssl3.hs.resumptionMasterSecret,
6253 tls13_GetHash(ss),
6254 ticket_nonce.data, ticket_nonce.len,
6255 kHkdfLabelResumption,
6256 strlen(kHkdfLabelResumption),
6257 CKM_HKDF_DERIVE0x0000402aUL,
6258 tls13_GetHashSize(ss),
6259 ss->protocolVariant, &secret);
6260 if (rv != SECSuccess) {
6261 return SECFailure;
6262 }
6263
6264 rv = ssl3_FillInCachedSID(ss, ss->sec.ci.sid, secret);
6265 PK11_FreeSymKey(secret);
6266 if (rv != SECSuccess) {
6267 return SECFailure;
6268 }
6269
6270 /* Cache the session. */
6271 ssl_CacheSessionID(ss);
6272 }
6273
6274 return SECSuccess;
6275}
6276
6277#define _M_NONE0 0
6278#define _M(a) (1 << PR_MIN(a, 31)((a)<(31)?(a):(31)))
6279#define _M1(a) (_M(ssl_hs_##a))
6280#define _M2(a, b) (_M1(a) | _M1(b))
6281#define _M3(a, b, c) (_M1(a) | _M2(b, c))
6282
6283static const struct {
6284 PRUint16 ex_value;
6285 PRUint32 messages;
6286} KnownExtensions[] = {
6287 { ssl_server_name_xtn, _M2(client_hello, encrypted_extensions) },
6288 { ssl_supported_groups_xtn, _M2(client_hello, encrypted_extensions) },
6289 { ssl_signature_algorithms_xtn, _M2(client_hello, certificate_request) },
6290 { ssl_signature_algorithms_cert_xtn, _M2(client_hello,
6291 certificate_request) },
6292 { ssl_use_srtp_xtn, _M2(client_hello, encrypted_extensions) },
6293 { ssl_app_layer_protocol_xtn, _M2(client_hello, encrypted_extensions) },
6294 { ssl_padding_xtn, _M1(client_hello) },
6295 { ssl_tls13_key_share_xtn, _M3(client_hello, server_hello,
6296 hello_retry_request) },
6297 { ssl_tls13_pre_shared_key_xtn, _M2(client_hello, server_hello) },
6298 { ssl_tls13_psk_key_exchange_modes_xtn, _M1(client_hello) },
6299 { ssl_tls13_early_data_xtn, _M3(client_hello, encrypted_extensions,
6300 new_session_ticket) },
6301 { ssl_signed_cert_timestamp_xtn, _M3(client_hello, certificate_request,
6302 certificate) },
6303 { ssl_cert_status_xtn, _M3(client_hello, certificate_request,
6304 certificate) },
6305 { ssl_delegated_credentials_xtn, _M2(client_hello, certificate) },
6306 { ssl_tls13_cookie_xtn, _M2(client_hello, hello_retry_request) },
6307 { ssl_tls13_certificate_authorities_xtn, _M2(client_hello, certificate_request) },
6308 { ssl_tls13_supported_versions_xtn, _M3(client_hello, server_hello,
6309 hello_retry_request) },
6310 { ssl_record_size_limit_xtn, _M2(client_hello, encrypted_extensions) },
6311 { ssl_tls13_encrypted_client_hello_xtn, _M3(client_hello, encrypted_extensions, hello_retry_request) },
6312 { ssl_tls13_outer_extensions_xtn, _M_NONE0 /* Encoding/decoding only */ },
6313 { ssl_tls13_post_handshake_auth_xtn, _M1(client_hello) },
6314 { ssl_certificate_compression_xtn, _M2(client_hello, certificate_request) }
6315};
6316
6317tls13ExtensionStatus
6318tls13_ExtensionStatus(PRUint16 extension, SSLHandshakeType message)
6319{
6320 unsigned int i;
6321
6322 PORT_Assert((message == ssl_hs_client_hello) ||(((message == ssl_hs_client_hello) || (message == ssl_hs_server_hello
) || (message == ssl_hs_hello_retry_request) || (message == ssl_hs_encrypted_extensions
) || (message == ssl_hs_new_session_ticket) || (message == ssl_hs_certificate
) || (message == ssl_hs_certificate_request))?((void)0):PR_Assert
("(message == ssl_hs_client_hello) || (message == ssl_hs_server_hello) || (message == ssl_hs_hello_retry_request) || (message == ssl_hs_encrypted_extensions) || (message == ssl_hs_new_session_ticket) || (message == ssl_hs_certificate) || (message == ssl_hs_certificate_request)"
,"tls13con.c",6328))
6323 (message == ssl_hs_server_hello) ||(((message == ssl_hs_client_hello) || (message == ssl_hs_server_hello
) || (message == ssl_hs_hello_retry_request) || (message == ssl_hs_encrypted_extensions
) || (message == ssl_hs_new_session_ticket) || (message == ssl_hs_certificate
) || (message == ssl_hs_certificate_request))?((void)0):PR_Assert
("(message == ssl_hs_client_hello) || (message == ssl_hs_server_hello) || (message == ssl_hs_hello_retry_request) || (message == ssl_hs_encrypted_extensions) || (message == ssl_hs_new_session_ticket) || (message == ssl_hs_certificate) || (message == ssl_hs_certificate_request)"
,"tls13con.c",6328))
6324 (message == ssl_hs_hello_retry_request) ||(((message == ssl_hs_client_hello) || (message == ssl_hs_server_hello
) || (message == ssl_hs_hello_retry_request) || (message == ssl_hs_encrypted_extensions
) || (message == ssl_hs_new_session_ticket) || (message == ssl_hs_certificate
) || (message == ssl_hs_certificate_request))?((void)0):PR_Assert
("(message == ssl_hs_client_hello) || (message == ssl_hs_server_hello) || (message == ssl_hs_hello_retry_request) || (message == ssl_hs_encrypted_extensions) || (message == ssl_hs_new_session_ticket) || (message == ssl_hs_certificate) || (message == ssl_hs_certificate_request)"
,"tls13con.c",6328))
6325 (message == ssl_hs_encrypted_extensions) ||(((message == ssl_hs_client_hello) || (message == ssl_hs_server_hello
) || (message == ssl_hs_hello_retry_request) || (message == ssl_hs_encrypted_extensions
) || (message == ssl_hs_new_session_ticket) || (message == ssl_hs_certificate
) || (message == ssl_hs_certificate_request))?((void)0):PR_Assert
("(message == ssl_hs_client_hello) || (message == ssl_hs_server_hello) || (message == ssl_hs_hello_retry_request) || (message == ssl_hs_encrypted_extensions) || (message == ssl_hs_new_session_ticket) || (message == ssl_hs_certificate) || (message == ssl_hs_certificate_request)"
,"tls13con.c",6328))
6326 (message == ssl_hs_new_session_ticket) ||(((message == ssl_hs_client_hello) || (message == ssl_hs_server_hello
) || (message == ssl_hs_hello_retry_request) || (message == ssl_hs_encrypted_extensions
) || (message == ssl_hs_new_session_ticket) || (message == ssl_hs_certificate
) || (message == ssl_hs_certificate_request))?((void)0):PR_Assert
("(message == ssl_hs_client_hello) || (message == ssl_hs_server_hello) || (message == ssl_hs_hello_retry_request) || (message == ssl_hs_encrypted_extensions) || (message == ssl_hs_new_session_ticket) || (message == ssl_hs_certificate) || (message == ssl_hs_certificate_request)"
,"tls13con.c",6328))
6327 (message == ssl_hs_certificate) ||(((message == ssl_hs_client_hello) || (message == ssl_hs_server_hello
) || (message == ssl_hs_hello_retry_request) || (message == ssl_hs_encrypted_extensions
) || (message == ssl_hs_new_session_ticket) || (message == ssl_hs_certificate
) || (message == ssl_hs_certificate_request))?((void)0):PR_Assert
("(message == ssl_hs_client_hello) || (message == ssl_hs_server_hello) || (message == ssl_hs_hello_retry_request) || (message == ssl_hs_encrypted_extensions) || (message == ssl_hs_new_session_ticket) || (message == ssl_hs_certificate) || (message == ssl_hs_certificate_request)"
,"tls13con.c",6328))
6328 (message == ssl_hs_certificate_request))(((message == ssl_hs_client_hello) || (message == ssl_hs_server_hello
) || (message == ssl_hs_hello_retry_request) || (message == ssl_hs_encrypted_extensions
) || (message == ssl_hs_new_session_ticket) || (message == ssl_hs_certificate
) || (message == ssl_hs_certificate_request))?((void)0):PR_Assert
("(message == ssl_hs_client_hello) || (message == ssl_hs_server_hello) || (message == ssl_hs_hello_retry_request) || (message == ssl_hs_encrypted_extensions) || (message == ssl_hs_new_session_ticket) || (message == ssl_hs_certificate) || (message == ssl_hs_certificate_request)"
,"tls13con.c",6328))
;
6329
6330 for (i = 0; i < PR_ARRAY_SIZE(KnownExtensions)(sizeof(KnownExtensions)/sizeof((KnownExtensions)[0])); i++) {
6331 /* Hacky check for message numbers > 30. */
6332 PORT_Assert(!(KnownExtensions[i].messages & (1U << 31)))((!(KnownExtensions[i].messages & (1U << 31)))?((void
)0):PR_Assert("!(KnownExtensions[i].messages & (1U << 31))"
,"tls13con.c",6332))
;
6333 if (KnownExtensions[i].ex_value == extension) {
6334 break;
6335 }
6336 }
6337 if (i >= PR_ARRAY_SIZE(KnownExtensions)(sizeof(KnownExtensions)/sizeof((KnownExtensions)[0]))) {
6338 return tls13_extension_unknown;
6339 }
6340
6341 /* Return "disallowed" if the message mask bit isn't set. */
6342 if (!(_M(message) & KnownExtensions[i].messages)) {
6343 return tls13_extension_disallowed;
6344 }
6345
6346 return tls13_extension_allowed;
6347}
6348
6349#undef _M
6350#undef _M1
6351#undef _M2
6352#undef _M3
6353
6354/* We cheat a bit on additional data because the AEAD interface
6355 * which doesn't have room for the record number. The AAD we
6356 * format is serialized record number followed by the true AD
6357 * (i.e., the record header) plus the serialized record number. */
6358static SECStatus
6359tls13_FormatAdditionalData(
6360 sslSocket *ss,
6361 const PRUint8 *header, unsigned int headerLen,
6362 DTLSEpoch epoch, sslSequenceNumber seqNum,
6363 PRUint8 *aad, unsigned int *aadLength, unsigned int maxLength)
6364{
6365 SECStatus rv;
6366 sslBuffer buf = SSL_BUFFER_FIXED(aad, maxLength){ aad, 0, maxLength, 1 };
6367
6368 if (IS_DTLS_1_OR_12(ss)((ss->protocolVariant == ssl_variant_datagram) && ss
->version < 0x0304)
) {
6369 rv = sslBuffer_AppendNumber(&buf, epoch, 2);
6370 if (rv != SECSuccess) {
6371 return SECFailure;
6372 }
6373 }
6374 rv = sslBuffer_AppendNumber(&buf, seqNum, IS_DTLS_1_OR_12(ss)((ss->protocolVariant == ssl_variant_datagram) && ss
->version < 0x0304)
? 6 : 8);
6375 if (rv != SECSuccess) {
6376 return SECFailure;
6377 }
6378
6379 rv = sslBuffer_Append(&buf, header, headerLen);
6380 if (rv != SECSuccess) {
6381 return SECFailure;
6382 }
6383
6384 *aadLength = buf.len;
6385
6386 return SECSuccess;
6387}
6388
6389PRInt32
6390tls13_LimitEarlyData(sslSocket *ss, SSLContentType type, PRInt32 toSend)
6391{
6392 PRInt32 reduced;
6393
6394 PORT_Assert(type == ssl_ct_application_data)((type == ssl_ct_application_data)?((void)0):PR_Assert("type == ssl_ct_application_data"
,"tls13con.c",6394))
;
6395 PORT_Assert(ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3)((ss->vrange.max >= 0x0304)?((void)0):PR_Assert("ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3"
,"tls13con.c",6395))
;
6396 PORT_Assert(!ss->firstHsDone)((!ss->firstHsDone)?((void)0):PR_Assert("!ss->firstHsDone"
,"tls13con.c",6396))
;
6397 if (ss->ssl3.cwSpec->epoch != TrafficKeyEarlyApplicationData) {
6398 return toSend;
6399 }
6400
6401 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram) && toSend > ss->ssl3.cwSpec->earlyDataRemaining) {
6402 /* Don't split application data records in DTLS. */
6403 return 0;
6404 }
6405
6406 reduced = PR_MIN(toSend, ss->ssl3.cwSpec->earlyDataRemaining)((toSend)<(ss->ssl3.cwSpec->earlyDataRemaining)?(toSend
):(ss->ssl3.cwSpec->earlyDataRemaining))
;
6407 ss->ssl3.cwSpec->earlyDataRemaining -= reduced;
6408 return reduced;
6409}
6410
6411SECStatus
6412tls13_ProtectRecord(sslSocket *ss,
6413 ssl3CipherSpec *cwSpec,
6414 SSLContentType type,
6415 const PRUint8 *pIn,
6416 PRUint32 contentLen,
6417 sslBuffer *wrBuf)
6418{
6419 const ssl3BulkCipherDef *cipher_def = cwSpec->cipherDef;
6420 const int tagLen = cipher_def->tag_size;
6421 SECStatus rv;
6422
6423 PORT_Assert(cwSpec->direction == ssl_secret_write)((cwSpec->direction == ssl_secret_write)?((void)0):PR_Assert
("cwSpec->direction == ssl_secret_write","tls13con.c",6423
))
;
6424 SSL_TRC(3, ("%d: TLS13[%d]: spec=%d epoch=%d (%s) protect 0x%0llx len=%u",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: spec=%d epoch=%d (%s) protect 0x%0llx len=%u"
, getpid(), ss->fd, cwSpec, cwSpec->epoch, cwSpec->phase
, cwSpec->nextSeqNum, contentLen)
6425 SSL_GETPID(), ss->fd, cwSpec, cwSpec->epoch, cwSpec->phase,if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: spec=%d epoch=%d (%s) protect 0x%0llx len=%u"
, getpid(), ss->fd, cwSpec, cwSpec->epoch, cwSpec->phase
, cwSpec->nextSeqNum, contentLen)
6426 cwSpec->nextSeqNum, contentLen))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: spec=%d epoch=%d (%s) protect 0x%0llx len=%u"
, getpid(), ss->fd, cwSpec, cwSpec->epoch, cwSpec->phase
, cwSpec->nextSeqNum, contentLen)
;
6427
6428 if (contentLen + 1 + tagLen > SSL_BUFFER_SPACE(wrBuf)((wrBuf)->space - (wrBuf)->len)) {
6429 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
6430 return SECFailure;
6431 }
6432
6433 /* Copy the data into the wrBuf. We're going to encrypt in-place
6434 * in the AEAD branch anyway */
6435 PORT_Memcpymemcpy(SSL_BUFFER_NEXT(wrBuf)((wrBuf)->buf + (wrBuf)->len), pIn, contentLen);
6436
6437 if (cipher_def->calg == ssl_calg_null) {
6438 /* Shortcut for plaintext */
6439 rv = sslBuffer_Skip(wrBuf, contentLen, NULL((void*)0));
6440 PORT_Assert(rv == SECSuccess)((rv == SECSuccess)?((void)0):PR_Assert("rv == SECSuccess","tls13con.c"
,6440))
;
6441 } else {
6442 PRUint8 hdr[13];
6443 sslBuffer buf = SSL_BUFFER_FIXED(hdr, sizeof(hdr)){ hdr, 0, sizeof(hdr), 1 };
6444 PRBool needsLength;
6445 PRUint8 aad[21];
6446 const int ivLen = cipher_def->iv_size + cipher_def->explicit_nonce_size;
6447 unsigned int ivOffset = ivLen - sizeof(sslSequenceNumber);
6448 unsigned char ivOut[MAX_IV_LENGTH24];
6449
6450 unsigned int aadLen;
6451 unsigned int len;
6452
6453 PORT_Assert(cipher_def->type == type_aead)((cipher_def->type == type_aead)?((void)0):PR_Assert("cipher_def->type == type_aead"
,"tls13con.c",6453))
;
6454
6455 /* If the following condition holds, we can skip the padding logic for
6456 * DTLS 1.3 (4.2.3). This will be the case until we support a cipher
6457 * with tag length < 15B. */
6458 PORT_Assert(tagLen + 1 /* cType */ >= 16)((tagLen + 1 >= 16)?((void)0):PR_Assert("tagLen + 1 >= 16"
,"tls13con.c",6458))
;
6459
6460 /* Add the content type at the end. */
6461 *(SSL_BUFFER_NEXT(wrBuf)((wrBuf)->buf + (wrBuf)->len) + contentLen) = type;
6462
6463 /* Create the header (ugly that we have to do it twice). */
6464 rv = ssl_InsertRecordHeader(ss, cwSpec, ssl_ct_application_data,
6465 &buf, &needsLength);
6466 if (rv != SECSuccess) {
6467 return SECFailure;
6468 }
6469 if (needsLength) {
6470 rv = sslBuffer_AppendNumber(&buf, contentLen + 1 + tagLen, 2);
6471 if (rv != SECSuccess) {
6472 return SECFailure;
6473 }
6474 }
6475 rv = tls13_FormatAdditionalData(ss, SSL_BUFFER_BASE(&buf)((&buf)->buf), SSL_BUFFER_LEN(&buf)((&buf)->len),
6476 cwSpec->epoch, cwSpec->nextSeqNum,
6477 aad, &aadLen, sizeof(aad));
6478 if (rv != SECSuccess) {
6479 return SECFailure;
6480 }
6481 /* set up initial IV value */
6482 ivOffset = tls13_SetupAeadIv(IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram), cwSpec->version, ivOut, cwSpec->keyMaterial.iv,
6483 ivOffset, ivLen, cwSpec->epoch);
6484 rv = tls13_AEAD(cwSpec->cipherContext, PR_FALSE0,
6485 CKG_GENERATE_COUNTER_XOR0x00000004UL, ivOffset * BPB8,
6486 ivOut, ivOut, ivLen, /* iv */
6487 NULL((void*)0), 0, /* nonce */
6488 aad + sizeof(sslSequenceNumber), /* aad */
6489 aadLen - sizeof(sslSequenceNumber),
6490 SSL_BUFFER_NEXT(wrBuf)((wrBuf)->buf + (wrBuf)->len), /* output */
6491 &len, /* out len */
6492 SSL_BUFFER_SPACE(wrBuf)((wrBuf)->space - (wrBuf)->len), /* max out */
6493 tagLen,
6494 SSL_BUFFER_NEXT(wrBuf)((wrBuf)->buf + (wrBuf)->len), /* input */
6495 contentLen + 1); /* input len */
6496 if (rv != SECSuccess) {
6497 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_ENCRYPTION_FAILURE);
6498 return SECFailure;
6499 }
6500 rv = sslBuffer_Skip(wrBuf, len, NULL((void*)0));
6501 PORT_Assert(rv == SECSuccess)((rv == SECSuccess)?((void)0):PR_Assert("rv == SECSuccess","tls13con.c"
,6501))
;
6502 }
6503
6504 return SECSuccess;
6505}
6506
6507/* Unprotect a TLS 1.3 record and leave the result in plaintext.
6508 *
6509 * Called by ssl3_HandleRecord. Caller must hold the spec read lock.
6510 * Therefore, we MUST not call SSL3_SendAlert().
6511 *
6512 * If SECFailure is returned, we:
6513 * 1. Set |*alert| to the alert to be sent.
6514 * 2. Call PORT_SetError() with an appropriate code.
6515 */
6516SECStatus
6517tls13_UnprotectRecord(sslSocket *ss,
6518 ssl3CipherSpec *spec,
6519 SSL3Ciphertext *cText,
6520 sslBuffer *plaintext,
6521 SSLContentType *innerType,
6522 SSL3AlertDescription *alert)
6523{
6524 const ssl3BulkCipherDef *cipher_def = spec->cipherDef;
6525 const int ivLen = cipher_def->iv_size + cipher_def->explicit_nonce_size;
6526 const int tagLen = cipher_def->tag_size;
6527 const int innerTypeLen = 1;
6528
6529 PRUint8 aad[21];
6530 unsigned int aadLen;
6531 SECStatus rv;
6532
6533 *alert = bad_record_mac; /* Default alert for most issues. */
6534
6535 PORT_Assert(spec->direction == ssl_secret_read)((spec->direction == ssl_secret_read)?((void)0):PR_Assert(
"spec->direction == ssl_secret_read","tls13con.c",6535))
;
6536 SSL_TRC(3, ("%d: TLS13[%d]: spec=%d epoch=%d (%s) unprotect 0x%0llx len=%u",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: spec=%d epoch=%d (%s) unprotect 0x%0llx len=%u"
, getpid(), ss->fd, spec, spec->epoch, spec->phase, cText
->seqNum, cText->buf->len)
6537 SSL_GETPID(), ss->fd, spec, spec->epoch, spec->phase,if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: spec=%d epoch=%d (%s) unprotect 0x%0llx len=%u"
, getpid(), ss->fd, spec, spec->epoch, spec->phase, cText
->seqNum, cText->buf->len)
6538 cText->seqNum, cText->buf->len))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: spec=%d epoch=%d (%s) unprotect 0x%0llx len=%u"
, getpid(), ss->fd, spec, spec->epoch, spec->phase, cText
->seqNum, cText->buf->len)
;
6539
6540 /* Verify that the outer content type is right.
6541 *
6542 * For the inner content type as well as lower TLS versions this is checked
6543 * in ssl3con.c/ssl3_HandleNonApllicationData().
6544 *
6545 * For DTLS 1.3 this is checked in ssl3gthr.c/dtls_GatherData(). DTLS drops
6546 * invalid records silently [RFC6347, Section 4.1.2.7].
6547 *
6548 * Also allow the DTLS short header in TLS 1.3. */
6549 if (!(cText->hdr[0] == ssl_ct_application_data ||
6550 (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram) &&
6551 ss->version >= SSL_LIBRARY_VERSION_TLS_1_30x0304 &&
6552 (cText->hdr[0] & 0xe0) == 0x20))) {
6553 SSL_TRC(3,if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: record has invalid exterior type=%2.2x"
, getpid(), ss->fd, cText->hdr[0])
6554 ("%d: TLS13[%d]: record has invalid exterior type=%2.2x",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: record has invalid exterior type=%2.2x"
, getpid(), ss->fd, cText->hdr[0])
6555 SSL_GETPID(), ss->fd, cText->hdr[0]))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: record has invalid exterior type=%2.2x"
, getpid(), ss->fd, cText->hdr[0])
;
6556 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_UNEXPECTED_RECORD_TYPE);
6557 *alert = unexpected_message;
6558 return SECFailure;
6559 }
6560
6561 /* We can perform this test in variable time because the record's total
6562 * length and the ciphersuite are both public knowledge. */
6563 if (cText->buf->len < tagLen) {
6564 SSL_TRC(3,if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: record too short to contain valid AEAD data"
, getpid(), ss->fd)
6565 ("%d: TLS13[%d]: record too short to contain valid AEAD data",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: record too short to contain valid AEAD data"
, getpid(), ss->fd)
6566 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: record too short to contain valid AEAD data"
, getpid(), ss->fd)
;
6567 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_BAD_MAC_READ);
6568 return SECFailure;
6569 }
6570
6571 /* Check if the ciphertext can be valid if we assume maximum plaintext and
6572 * add the specific ciphersuite expansion.
6573 * This way we detect overlong plaintexts/padding before decryption.
6574 * This check enforces size limitations more strict than the RFC.
6575 * (see RFC8446, Section 5.2) */
6576 if (cText->buf->len > (spec->recordSizeLimit + innerTypeLen + tagLen)) {
6577 *alert = record_overflow;
6578 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_RECORD_TOO_LONG);
6579 return SECFailure;
6580 }
6581
6582 /* Check the version number in the record. Stream only. */
6583 if (!IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
6584 SSL3ProtocolVersion version =
6585 ((SSL3ProtocolVersion)cText->hdr[1] << 8) |
6586 (SSL3ProtocolVersion)cText->hdr[2];
6587 if (version != spec->recordVersion) {
6588 /* Do we need a better error here? */
6589 SSL_TRC(3, ("%d: TLS13[%d]: record has bogus version",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: record has bogus version"
, getpid(), ss->fd)
6590 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: record has bogus version"
, getpid(), ss->fd)
;
6591 return SECFailure;
6592 }
6593 }
6594
6595 /* Decrypt */
6596 PORT_Assert(cipher_def->type == type_aead)((cipher_def->type == type_aead)?((void)0):PR_Assert("cipher_def->type == type_aead"
,"tls13con.c",6596))
;
6597 rv = tls13_FormatAdditionalData(ss, cText->hdr, cText->hdrLen,
6598 spec->epoch, cText->seqNum,
6599 aad, &aadLen, sizeof(aad));
6600 if (rv != SECSuccess) {
6601
6602 return SECFailure;
6603 }
6604 rv = tls13_AEAD(spec->cipherContext, PR_TRUE1,
6605 CKG_NO_GENERATE0x00000000UL, 0, /* ignored for decrypt */
6606 spec->keyMaterial.iv, NULL((void*)0), ivLen, /* iv */
6607 aad, sizeof(sslSequenceNumber), /* nonce */
6608 aad + sizeof(sslSequenceNumber), /* aad */
6609 aadLen - sizeof(sslSequenceNumber),
6610 plaintext->buf, /* output */
6611 &plaintext->len, /* outlen */
6612 plaintext->space, /* maxout */
6613 tagLen,
6614 cText->buf->buf, /* in */
6615 cText->buf->len); /* inlen */
6616 if (rv != SECSuccess) {
6617 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
6618 spec->deprotectionFailures++;
6619 }
6620
6621 SSL_TRC(3,if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: record has bogus MAC"
, getpid(), ss->fd)
6622 ("%d: TLS13[%d]: record has bogus MAC",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: record has bogus MAC"
, getpid(), ss->fd)
6623 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: record has bogus MAC"
, getpid(), ss->fd)
;
6624 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_BAD_MAC_READ);
6625 return SECFailure;
6626 }
6627
6628 /* There is a similar test in ssl3_HandleRecord, but this test is needed to
6629 * account for padding. */
6630 if (plaintext->len > spec->recordSizeLimit + innerTypeLen) {
6631 *alert = record_overflow;
6632 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_RECORD_TOO_LONG);
6633 return SECFailure;
6634 }
6635
6636 /* The record is right-padded with 0s, followed by the true
6637 * content type, so read from the right until we receive a
6638 * nonzero byte. */
6639 while (plaintext->len > 0 && !(plaintext->buf[plaintext->len - 1])) {
6640 --plaintext->len;
6641 }
6642
6643 /* Bogus padding. */
6644 if (plaintext->len < 1) {
6645 SSL_TRC(3, ("%d: TLS13[%d]: empty record", SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: empty record"
, getpid(), ss->fd)
;
6646 /* It's safe to report this specifically because it happened
6647 * after the MAC has been verified. */
6648 *alert = unexpected_message;
6649 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_BAD_BLOCK_PADDING);
6650 return SECFailure;
6651 }
6652
6653 /* Record the type. */
6654 *innerType = (SSLContentType)plaintext->buf[plaintext->len - 1];
6655 --plaintext->len;
6656
6657 /* Check for zero-length encrypted Alert and Handshake fragments
6658 * (zero-length + inner content type byte).
6659 *
6660 * Implementations MUST NOT send Handshake and Alert records that have a
6661 * zero-length TLSInnerPlaintext.content; if such a message is received,
6662 * the receiving implementation MUST terminate the connection with an
6663 * "unexpected_message" alert [RFC8446, Section 5.4]. */
6664 if (!plaintext->len && ((!IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram) && cText->hdr[0] == ssl_ct_application_data) ||
6665 (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram) && dtls_IsDtls13Ciphertext(spec->version, cText->hdr[0])))) {
6666 switch (*innerType) {
6667 case ssl_ct_alert:
6668 *alert = unexpected_message;
6669 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_MALFORMED_ALERT);
6670 return SECFailure;
6671 case ssl_ct_handshake:
6672 *alert = unexpected_message;
6673 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_MALFORMED_HANDSHAKE);
6674 return SECFailure;
6675 default:
6676 break;
6677 }
6678 }
6679
6680 /* Check that we haven't received too much 0-RTT data. */
6681 if (spec->epoch == TrafficKeyEarlyApplicationData &&
6682 *innerType == ssl_ct_application_data) {
6683 if (plaintext->len > spec->earlyDataRemaining) {
6684 *alert = unexpected_message;
6685 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_TOO_MUCH_EARLY_DATA);
6686 return SECFailure;
6687 }
6688 spec->earlyDataRemaining -= plaintext->len;
6689 }
6690
6691 SSL_TRC(10,if (ssl_trace >= (10)) ssl_Trace ("%d: TLS13[%d]: %s received record of length=%d, type=%d"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
), plaintext->len, *innerType)
6692 ("%d: TLS13[%d]: %s received record of length=%d, type=%d",if (ssl_trace >= (10)) ssl_Trace ("%d: TLS13[%d]: %s received record of length=%d, type=%d"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
), plaintext->len, *innerType)
6693 SSL_GETPID(), ss->fd, SSL_ROLE(ss), plaintext->len, *innerType))if (ssl_trace >= (10)) ssl_Trace ("%d: TLS13[%d]: %s received record of length=%d, type=%d"
, getpid(), ss->fd, (ss->sec.isServer ? "server" : "client"
), plaintext->len, *innerType)
;
6694
6695 return SECSuccess;
6696}
6697
6698/* 0-RTT is only permitted if:
6699 *
6700 * 1. We are doing TLS 1.3
6701 * 2. This isn't a second ClientHello (in response to HelloRetryRequest)
6702 * 3. The 0-RTT option is set.
6703 * 4. We have a valid ticket or an External PSK.
6704 * 5. If resuming:
6705 * 5a. The server is willing to accept 0-RTT.
6706 * 5b. We have not changed our ALPN settings to disallow the ALPN tag
6707 * in the ticket.
6708 *
6709 * Called from tls13_ClientSendEarlyDataXtn().
6710 */
6711PRBool
6712tls13_ClientAllow0Rtt(const sslSocket *ss, const sslSessionID *sid)
6713{
6714 /* We checked that the cipher suite was still allowed back in
6715 * ssl3_SendClientHello. */
6716 if (sid->version < SSL_LIBRARY_VERSION_TLS_1_30x0304) {
6717 return PR_FALSE0;
6718 }
6719 if (ss->ssl3.hs.helloRetry) {
6720 return PR_FALSE0;
6721 }
6722 if (!ss->opt.enable0RttData) {
6723 return PR_FALSE0;
6724 }
6725 if (PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks)((&ss->ssl3.hs.psks)->next == (&ss->ssl3.hs.
psks))
) {
6726 return PR_FALSE0;
6727 }
6728 sslPsk *psk = (sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks)(&ss->ssl3.hs.psks)->next;
6729
6730 if (psk->zeroRttSuite == TLS_NULL_WITH_NULL_NULL0x0000) {
6731 return PR_FALSE0;
6732 }
6733 if (!psk->maxEarlyData) {
6734 return PR_FALSE0;
6735 }
6736
6737 if (psk->type == ssl_psk_external) {
6738 return psk->hash == tls13_GetHashForCipherSuite(psk->zeroRttSuite);
6739 }
6740 if (psk->type == ssl_psk_resume) {
6741 if (!ss->statelessResume)
6742 return PR_FALSE0;
6743 if ((sid->u.ssl3.locked.sessionTicket.flags & ticket_allow_early_data) == 0)
6744 return PR_FALSE0;
6745 return ssl_AlpnTagAllowed(ss, &sid->u.ssl3.alpnSelection);
6746 }
6747 PORT_Assert(0)((0)?((void)0):PR_Assert("0","tls13con.c",6747));
6748 return PR_FALSE0;
6749}
6750
6751SECStatus
6752tls13_MaybeDo0RTTHandshake(sslSocket *ss)
6753{
6754 SECStatus rv;
6755
6756 /* Don't do anything if there is no early_data xtn, which means we're
6757 * not doing early data. */
6758 if (!ssl3_ExtensionAdvertised(ss, ssl_tls13_early_data_xtn)) {
6759 return SECSuccess;
6760 }
6761
6762 ss->ssl3.hs.zeroRttState = ssl_0rtt_sent;
6763 ss->ssl3.hs.zeroRttSuite = ss->ssl3.hs.cipher_suite;
6764 /* Note: Reset the preliminary info here rather than just add 0-RTT. We are
6765 * only guessing what might happen at this point.*/
6766 ss->ssl3.hs.preliminaryInfo = ssl_preinfo_0rtt_cipher_suite(1U << 2);
6767
6768 SSL_TRC(3, ("%d: TLS13[%d]: in 0-RTT mode", SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: in 0-RTT mode"
, getpid(), ss->fd)
;
6769
6770 /* Set the ALPN data as if it was negotiated. We check in the ServerHello
6771 * handler that the server negotiates the same value. */
6772 if (ss->sec.ci.sid->u.ssl3.alpnSelection.len) {
6773 ss->xtnData.nextProtoState = SSL_NEXT_PROTO_EARLY_VALUE;
6774 rv = SECITEM_CopyItemSECITEM_CopyItem_Util(NULL((void*)0), &ss->xtnData.nextProto,
6775 &ss->sec.ci.sid->u.ssl3.alpnSelection);
6776 if (rv != SECSuccess) {
6777 return SECFailure;
6778 }
6779 }
6780
6781 if (ss->opt.enableTls13CompatMode && !IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
6782 /* Pretend that this is a proper ChangeCipherSpec even though it is sent
6783 * before receiving the ServerHello. */
6784 ssl_GetSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_LockWrite_Util((ss)->
specLock); }
;
6785 tls13_SetSpecRecordVersion(ss, ss->ssl3.cwSpec);
6786 ssl_ReleaseSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockWrite_Util((ss)->
specLock); }
;
6787 ssl_GetXmitBufLock(ss){ if (!ss->opt.noLocks) PR_EnterMonitor(((ss)->xmitBufLock
)); }
;
6788 rv = ssl3_SendChangeCipherSpecsInt(ss);
6789 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
;
6790 if (rv != SECSuccess) {
6791 return SECFailure;
6792 }
6793 }
6794
6795 /* If we have any message that was saved for later hashing.
6796 * The updated hash is then used in tls13_DeriveEarlySecrets. */
6797 rv = ssl3_MaybeUpdateHashWithSavedRecord(ss);
6798 if (rv != SECSuccess) {
6799 return SECFailure;
6800 }
6801
6802 /* If we're trying 0-RTT, derive from the first PSK */
6803 PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks) && !ss->xtnData.selectedPsk)((!((&ss->ssl3.hs.psks)->next == (&ss->ssl3.
hs.psks)) && !ss->xtnData.selectedPsk)?((void)0):PR_Assert
("!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks) && !ss->xtnData.selectedPsk"
,"tls13con.c",6803))
;
6804 ss->xtnData.selectedPsk = (sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks)(&ss->ssl3.hs.psks)->next;
6805 rv = tls13_DeriveEarlySecrets(ss);
6806 if (rv != SECSuccess) {
6807 return SECFailure;
6808 }
6809
6810 /* Save cwSpec in case we get a HelloRetryRequest and have to send another
6811 * ClientHello. */
6812 ssl_CipherSpecAddRef(ss->ssl3.cwSpec);
6813
6814 rv = tls13_SetCipherSpec(ss, TrafficKeyEarlyApplicationData,
6815 ssl_secret_write, PR_TRUE1);
6816 ss->xtnData.selectedPsk = NULL((void*)0);
6817 if (rv != SECSuccess) {
6818 return SECFailure;
6819 }
6820
6821 return SECSuccess;
6822}
6823
6824PRInt32
6825tls13_Read0RttData(sslSocket *ss, PRUint8 *buf, PRInt32 len)
6826{
6827 PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.bufferedEarlyData))((!((&ss->ssl3.hs.bufferedEarlyData)->next == (&
ss->ssl3.hs.bufferedEarlyData)))?((void)0):PR_Assert("!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.bufferedEarlyData)"
,"tls13con.c",6827))
;
6828 PRInt32 offset = 0;
6829 while (!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.bufferedEarlyData)((&ss->ssl3.hs.bufferedEarlyData)->next == (&ss
->ssl3.hs.bufferedEarlyData))
) {
6830 TLS13EarlyData *msg =
6831 (TLS13EarlyData *)PR_NEXT_LINK(&ss->ssl3.hs.bufferedEarlyData)((&ss->ssl3.hs.bufferedEarlyData)->next);
6832 unsigned int tocpy = msg->data.len - msg->consumed;
6833
6834 if (tocpy > (len - offset)) {
6835 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
6836 /* In DTLS, we only return entire records.
6837 * So offset and consumed are always zero. */
6838 PORT_Assert(offset == 0)((offset == 0)?((void)0):PR_Assert("offset == 0","tls13con.c"
,6838))
;
6839 PORT_Assert(msg->consumed == 0)((msg->consumed == 0)?((void)0):PR_Assert("msg->consumed == 0"
,"tls13con.c",6839))
;
6840 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_SHORT_DTLS_READ);
6841 return -1;
6842 }
6843
6844 tocpy = len - offset;
6845 }
6846
6847 PORT_Memcpymemcpy(buf + offset, msg->data.data + msg->consumed, tocpy);
6848 offset += tocpy;
6849 msg->consumed += tocpy;
6850
6851 if (msg->consumed == msg->data.len) {
6852 PR_REMOVE_LINK(&msg->link)do { (&msg->link)->prev->next = (&msg->link
)->next; (&msg->link)->next->prev = (&msg
->link)->prev; } while (0)
;
6853 SECITEM_ZfreeItemSECITEM_ZfreeItem_Util(&msg->data, PR_FALSE0);
6854 PORT_ZFreePORT_ZFree_Util(msg, sizeof(*msg));
6855 }
6856
6857 /* We are done after one record for DTLS; otherwise, when the buffer fills up. */
6858 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram) || offset == len) {
6859 break;
6860 }
6861 }
6862
6863 return offset;
6864}
6865
6866static SECStatus
6867tls13_SendEndOfEarlyData(sslSocket *ss)
6868{
6869 SECStatus rv;
6870
6871 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)"
,"tls13con.c",6871))
;
6872
6873 if (!ss->opt.suppressEndOfEarlyData) {
6874 SSL_TRC(3, ("%d: TLS13[%d]: send EndOfEarlyData", SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: send EndOfEarlyData"
, getpid(), ss->fd)
;
6875 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_end_of_early_data, 0);
6876 if (rv != SECSuccess) {
6877 return rv; /* err set by AppendHandshake. */
6878 }
6879 }
6880
6881 ss->ssl3.hs.zeroRttState = ssl_0rtt_done;
6882 return SECSuccess;
6883}
6884
6885static SECStatus
6886tls13_HandleEndOfEarlyData(sslSocket *ss, const PRUint8 *b, PRUint32 length)
6887{
6888 SECStatus rv;
6889
6890 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"
,"tls13con.c",6890))
;
6891
6892 rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_END_OF_EARLY_DATA,tls13_CheckHsState(ss, SSL_ERROR_RX_UNEXPECTED_END_OF_EARLY_DATA
, "SSL_ERROR_RX_UNEXPECTED_END_OF_EARLY_DATA", __func__, "tls13con.c"
, 6893, wait_end_of_early_data, wait_invalid)
6893 wait_end_of_early_data)tls13_CheckHsState(ss, SSL_ERROR_RX_UNEXPECTED_END_OF_EARLY_DATA
, "SSL_ERROR_RX_UNEXPECTED_END_OF_EARLY_DATA", __func__, "tls13con.c"
, 6893, wait_end_of_early_data, wait_invalid)
;
6894 if (rv != SECSuccess) {
6895 return SECFailure;
6896 }
6897
6898 /* We shouldn't be getting any more early data, and if we do,
6899 * it is because of reordering and we drop it. */
6900 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
6901 ssl_CipherSpecReleaseByEpoch(ss, ssl_secret_read,
6902 TrafficKeyEarlyApplicationData);
6903 dtls_ReceivedFirstMessageInFlight(ss);
6904 }
6905
6906 PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted)((ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted)?((void)0)
:PR_Assert("ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted"
,"tls13con.c",6906))
;
6907
6908 if (length) {
6909 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_END_OF_EARLY_DATA, decode_error)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_END_OF_EARLY_DATA
, __func__, "tls13con.c", 6909); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_END_OF_EARLY_DATA
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_END_OF_EARLY_DATA
, decode_error); } while (0)
;
6910 return SECFailure;
6911 }
6912
6913 rv = tls13_SetCipherSpec(ss, TrafficKeyHandshake,
6914 ssl_secret_read, PR_FALSE0);
6915 if (rv != SECSuccess) {
6916 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
6917 return SECFailure;
6918 }
6919
6920 ss->ssl3.hs.zeroRttState = ssl_0rtt_done;
6921 if (tls13_ShouldRequestClientAuth(ss)) {
6922 TLS13_SET_HS_STATE(ss, wait_client_cert)tls13_SetHsState(ss, wait_client_cert, __func__, "tls13con.c"
, 6922)
;
6923 } else {
6924 TLS13_SET_HS_STATE(ss, wait_finished)tls13_SetHsState(ss, wait_finished, __func__, "tls13con.c", 6924
)
;
6925 }
6926 return SECSuccess;
6927}
6928
6929static SECStatus
6930tls13_MaybeHandleSuppressedEndOfEarlyData(sslSocket *ss)
6931{
6932 PORT_Assert(ss->sec.isServer)((ss->sec.isServer)?((void)0):PR_Assert("ss->sec.isServer"
,"tls13con.c",6932))
;
6933 if (!ss->opt.suppressEndOfEarlyData ||
6934 ss->ssl3.hs.zeroRttState != ssl_0rtt_accepted) {
6935 return SECSuccess;
6936 }
6937
6938 return tls13_HandleEndOfEarlyData(ss, NULL((void*)0), 0);
6939}
6940
6941SECStatus
6942tls13_HandleEarlyApplicationData(sslSocket *ss, sslBuffer *origBuf)
6943{
6944 TLS13EarlyData *ed;
6945 SECItem it = { siBuffer, NULL((void*)0), 0 };
6946
6947 PORT_Assert(ss->sec.isServer)((ss->sec.isServer)?((void)0):PR_Assert("ss->sec.isServer"
,"tls13con.c",6947))
;
6948 PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted)((ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted)?((void)0)
:PR_Assert("ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted"
,"tls13con.c",6948))
;
6949 if (ss->ssl3.hs.zeroRttState != ssl_0rtt_accepted) {
6950 /* Belt and suspenders. */
6951 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__, "tls13con.c"
, 6951); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0); tls13_FatalError(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error
); } while (0)
;
6952 return SECFailure;
6953 }
6954
6955 PRINT_BUF(3, (NULL, "Received early application data",if (ssl_trace >= (3)) ssl_PrintBuf (((void*)0), "Received early application data"
, origBuf->buf, origBuf->len)
6956 origBuf->buf, origBuf->len))if (ssl_trace >= (3)) ssl_PrintBuf (((void*)0), "Received early application data"
, origBuf->buf, origBuf->len)
;
6957 ed = PORT_ZNew(TLS13EarlyData)(TLS13EarlyData *)PORT_ZAlloc_Util(sizeof(TLS13EarlyData));
6958 if (!ed) {
6959 FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, 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_NO_MEMORY, __func__, "tls13con.c"
, 6959); PORT_SetError_Util(SEC_ERROR_NO_MEMORY); } while (0)
; tls13_FatalError(ss, SEC_ERROR_NO_MEMORY, internal_error); }
while (0)
;
6960 return SECFailure;
6961 }
6962 it.data = origBuf->buf;
6963 it.len = origBuf->len;
6964 if (SECITEM_CopyItemSECITEM_CopyItem_Util(NULL((void*)0), &ed->data, &it) != SECSuccess) {
6965 FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, 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_NO_MEMORY, __func__, "tls13con.c"
, 6965); PORT_SetError_Util(SEC_ERROR_NO_MEMORY); } while (0)
; tls13_FatalError(ss, SEC_ERROR_NO_MEMORY, internal_error); }
while (0)
;
6966 return SECFailure;
6967 }
6968 PR_APPEND_LINK(&ed->link, &ss->ssl3.hs.bufferedEarlyData)do { (&ed->link)->next = (&ss->ssl3.hs.bufferedEarlyData
); (&ed->link)->prev = (&ss->ssl3.hs.bufferedEarlyData
)->prev; (&ss->ssl3.hs.bufferedEarlyData)->prev->
next = (&ed->link); (&ss->ssl3.hs.bufferedEarlyData
)->prev = (&ed->link); } while (0)
;
6969
6970 origBuf->len = 0; /* So ssl3_GatherAppDataRecord will keep looping. */
6971
6972 return SECSuccess;
6973}
6974
6975PRUint16
6976tls13_EncodeVersion(SSL3ProtocolVersion version, SSLProtocolVariant variant)
6977{
6978 if (variant == ssl_variant_datagram) {
6979 return dtls_TLSVersionToDTLSVersion(version);
6980 }
6981 /* Stream-variant encodings do not change. */
6982 return (PRUint16)version;
6983}
6984
6985SECStatus
6986tls13_ClientReadSupportedVersion(sslSocket *ss)
6987{
6988 PRUint32 temp;
6989 TLSExtension *versionExtension;
6990 SECItem it;
6991 SECStatus rv;
6992
6993 /* Update the version based on the extension, as necessary. */
6994 versionExtension = ssl3_FindExtension(ss, ssl_tls13_supported_versions_xtn);
6995 if (!versionExtension) {
6996 return SECSuccess;
6997 }
6998
6999 /* Struct copy so we don't damage the extension. */
7000 it = versionExtension->data;
7001
7002 rv = ssl3_ConsumeHandshakeNumber(ss, &temp, 2, &it.data, &it.len);
7003 if (rv != SECSuccess) {
7004 return SECFailure;
7005 }
7006 if (it.len) {
7007 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_SERVER_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_SERVER_HELLO, __func__
, "tls13con.c", 7007); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_SERVER_HELLO
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_SERVER_HELLO
, illegal_parameter); } while (0)
;
7008 return SECFailure;
7009 }
7010
7011 if (temp != tls13_EncodeVersion(SSL_LIBRARY_VERSION_TLS_1_30x0304,
7012 ss->protocolVariant)) {
7013 /* You cannot negotiate < TLS 1.3 with supported_versions. */
7014 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_SERVER_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_SERVER_HELLO, __func__
, "tls13con.c", 7014); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_SERVER_HELLO
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_SERVER_HELLO
, illegal_parameter); } while (0)
;
7015 return SECFailure;
7016 }
7017
7018 /* Any endpoint receiving a Hello message with...ServerHello.legacy_version
7019 * set to 0x0300 (SSL3) MUST abort the handshake with a "protocol_version"
7020 * alert. [RFC8446, Section D.5]
7021 *
7022 * The ServerHello.legacy_version is read into the ss->version field by
7023 * ssl_ClientReadVersion(). */
7024 if (ss->version == SSL_LIBRARY_VERSION_3_00x0300) {
7025 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_SERVER_HELLO, 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_RX_MALFORMED_SERVER_HELLO, __func__
, "tls13con.c", 7025); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_SERVER_HELLO
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_SERVER_HELLO
, protocol_version); } while (0)
;
7026 return SECFailure;
7027 }
7028
7029 ss->version = SSL_LIBRARY_VERSION_TLS_1_30x0304;
7030 return SECSuccess;
7031}
7032
7033/* Pick the highest version we support that is also advertised. */
7034SECStatus
7035tls13_NegotiateVersion(sslSocket *ss, const TLSExtension *supportedVersions)
7036{
7037 PRUint16 version;
7038 /* Make a copy so we're nondestructive. */
7039 SECItem data = supportedVersions->data;
7040 SECItem versions;
7041 SECStatus rv;
7042
7043 rv = ssl3_ConsumeHandshakeVariable(ss, &versions, 1,
7044 &data.data, &data.len);
7045 if (rv != SECSuccess) {
7046 return SECFailure;
7047 }
7048 if (data.len || !versions.len || (versions.len & 1)) {
7049 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__
, "tls13con.c", 7049); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO
, illegal_parameter); } while (0)
;
7050 return SECFailure;
7051 }
7052 for (version = ss->vrange.max; version >= ss->vrange.min; --version) {
7053 if (version < SSL_LIBRARY_VERSION_TLS_1_30x0304 &&
7054 (ss->ssl3.hs.helloRetry || ss->ssl3.hs.echAccepted)) {
7055 /* Prevent negotiating to a lower version after 1.3 HRR or ECH
7056 * When accepting ECH, a different alert is generated.
7057 */
7058 SSL3AlertDescription alert = ss->ssl3.hs.echAccepted ? illegal_parameter : protocol_version;
7059 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_UNSUPPORTED_VERSION);
7060 FATAL_ERROR(ss, SSL_ERROR_UNSUPPORTED_VERSION, alert)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__
, "tls13con.c", 7060); PORT_SetError_Util(SSL_ERROR_UNSUPPORTED_VERSION
); } while (0); tls13_FatalError(ss, SSL_ERROR_UNSUPPORTED_VERSION
, alert); } while (0)
;
7061 return SECFailure;
7062 }
7063
7064 PRUint16 wire = tls13_EncodeVersion(version, ss->protocolVariant);
7065 unsigned long offset;
7066
7067 for (offset = 0; offset < versions.len; offset += 2) {
7068 PRUint16 supported =
7069 (versions.data[offset] << 8) | versions.data[offset + 1];
7070 if (supported == wire) {
7071 ss->version = version;
7072 return SECSuccess;
7073 }
7074 }
7075 }
7076
7077 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__
, "tls13con.c", 7077); PORT_SetError_Util(SSL_ERROR_UNSUPPORTED_VERSION
); } while (0); tls13_FatalError(ss, SSL_ERROR_UNSUPPORTED_VERSION
, protocol_version); } while (0)
;
7078 return SECFailure;
7079}
7080
7081/* This is TLS 1.3 or might negotiate to it. */
7082PRBool
7083tls13_MaybeTls13(sslSocket *ss)
7084{
7085 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_30x0304) {
7086 return PR_TRUE1;
7087 }
7088
7089 if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_30x0304) {
7090 return PR_FALSE0;
7091 }
7092
7093 if (!(ss->ssl3.hs.preliminaryInfo & ssl_preinfo_version(1U << 0))) {
7094 return PR_TRUE1;
7095 }
7096
7097 return PR_FALSE0;
7098}
7099
7100/* Setup random client GREASE values according to RFC8701. State must be kept
7101 * so an equal ClientHello might be send on HelloRetryRequest. */
7102SECStatus
7103tls13_ClientGreaseSetup(sslSocket *ss)
7104{
7105 if (!ss->opt.enableGrease) {
7106 return SECSuccess;
7107 }
7108
7109 PORT_Assert(ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3)((ss->vrange.max >= 0x0304)?((void)0):PR_Assert("ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3"
,"tls13con.c",7109))
;
7110
7111 if (ss->ssl3.hs.grease) {
7112 return SECFailure;
7113 }
7114 ss->ssl3.hs.grease = PORT_AllocPORT_Alloc_Util(sizeof(tls13ClientGrease));
7115 if (!ss->ssl3.hs.grease) {
7116 return SECFailure;
7117 }
7118
7119 tls13ClientGrease *grease = ss->ssl3.hs.grease;
7120 /* We require eight GREASE values and randoms. */
7121 PRUint8 random[8];
7122
7123 /* Generate random GREASE values. */
7124 if (PK11_GenerateRandom(random, sizeof(random)) != SECSuccess) {
7125 return SECFailure;
7126 }
7127 for (size_t i = 0; i < PR_ARRAY_SIZE(grease->idx)(sizeof(grease->idx)/sizeof((grease->idx)[0])); i++) {
7128 random[i] = ((random[i] & 0xf0) | 0x0a);
7129 grease->idx[i] = ((random[i] << 8) | random[i]);
7130 }
7131 /* Specific PskKeyExchangeMode GREASE value. */
7132 grease->pskKem = 0x0b + ((random[8 - 1] >> 5) * 0x1f);
7133
7134 /* Duplicate extensions are not allowed. */
7135 if (grease->idx[grease_extension1] == grease->idx[grease_extension2]) {
7136 grease->idx[grease_extension2] ^= 0x1010;
7137 }
7138
7139 return SECSuccess;
7140}
7141
7142/* Destroy client GREASE state. */
7143void
7144tls13_ClientGreaseDestroy(sslSocket *ss)
7145{
7146 if (ss->ssl3.hs.grease) {
7147 PORT_FreePORT_Free_Util(ss->ssl3.hs.grease);
7148 ss->ssl3.hs.grease = NULL((void*)0);
7149 }
7150}
7151
7152/* Generate a random GREASE value according to RFC8701.
7153 * This function does not provide valid PskKeyExchangeMode GREASE values! */
7154SECStatus
7155tls13_RandomGreaseValue(PRUint16 *out)
7156{
7157 PRUint8 random;
7158
7159 if (PK11_GenerateRandom(&random, sizeof(random)) != SECSuccess) {
7160 return SECFailure;
7161 }
7162
7163 random = ((random & 0xf0) | 0x0a);
7164 *out = ((random << 8) | random);
7165
7166 return SECSuccess;
7167}
7168
7169/* Set TLS 1.3 GREASE Extension random GREASE type. */
7170SECStatus
7171tls13_MaybeGreaseExtensionType(const sslSocket *ss,
7172 const SSLHandshakeType message,
7173 PRUint16 *exType)
7174{
7175 if (*exType != ssl_tls13_grease_xtn) {
7176 return SECSuccess;
7177 }
7178
7179 PR_ASSERT(ss->opt.enableGrease)((ss->opt.enableGrease)?((void)0):PR_Assert("ss->opt.enableGrease"
,"tls13con.c",7179))
;
7180 PR_ASSERT(message == ssl_hs_client_hello ||((message == ssl_hs_client_hello || message == ssl_hs_certificate_request
)?((void)0):PR_Assert("message == ssl_hs_client_hello || message == ssl_hs_certificate_request"
,"tls13con.c",7181))
7181 message == ssl_hs_certificate_request)((message == ssl_hs_client_hello || message == ssl_hs_certificate_request
)?((void)0):PR_Assert("message == ssl_hs_client_hello || message == ssl_hs_certificate_request"
,"tls13con.c",7181))
;
7182
7183 /* GREASE ClientHello:
7184 * A client MAY select one or more GREASE extension values and
7185 * advertise them as extensions with varying length and contents
7186 * [RFC8701, Section 3.1]. */
7187 if (message == ssl_hs_client_hello) {
7188 PR_ASSERT(ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3)((ss->vrange.max >= 0x0304)?((void)0):PR_Assert("ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3"
,"tls13con.c",7188))
;
7189 /* Check if the first GREASE extension was already added. */
7190 if (!ssl3_ExtensionAdvertised(ss, ss->ssl3.hs.grease->idx[grease_extension1])) {
7191 *exType = ss->ssl3.hs.grease->idx[grease_extension1];
7192 } else {
7193 *exType = ss->ssl3.hs.grease->idx[grease_extension2];
7194 }
7195 }
7196 /* GREASE CertificateRequest:
7197 * When sending a CertificateRequest in TLS 1.3, a server MAY behave as
7198 * follows: A server MAY select one or more GREASE extension values and
7199 * advertise them as extensions with varying length and contents
7200 * [RFC8701, Section 4.1]. */
7201 else if (message == ssl_hs_certificate_request) {
7202 PR_ASSERT(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3)((ss->version >= 0x0304)?((void)0):PR_Assert("ss->version >= SSL_LIBRARY_VERSION_TLS_1_3"
,"tls13con.c",7202))
;
7203 /* Get random grease extension type. */
7204 SECStatus rv = tls13_RandomGreaseValue(exType);
7205 if (rv != SECSuccess) {
7206 return SECFailure;
7207 }
7208 }
7209
7210 return SECSuccess;
7211}