Bug Summary

File:s/lib/ssl/tls13con.c
Warning:line 3127, column 9
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/Linux6.7_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-07-11-064940-1262099-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,
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);
Value stored to 'rv' is never read
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 *,
3925 unsigned char *output, size_t outputLen, size_t *usedLen) = NULL((void*)0);
3926 for (int i = 0; i < ss->ssl3.supportedCertCompressionAlgorithmsCount; i++) {
3927 if (ss->ssl3.supportedCertCompressionAlgorithms[i].id == compressionAlg) {
3928 compressionAlgorithmIsSupported = PR_TRUE1;
3929 certificateDecodingFunc = ss->ssl3.supportedCertCompressionAlgorithms[i].decode;
3930 }
3931 }
3932
3933 /* Peer selected a compression algorithm we do not support (and did not advertise). */
3934 if (!compressionAlgorithmIsSupported) {
3935 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_CERTIFICATE_COMPRESSION_ALGORITHM_NOT_SUPPORTED);
3936 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"
, 3936); PORT_SetError_Util(PORT_GetError_Util()); } while (0
); tls13_FatalError(ss, PORT_GetError_Util(), illegal_parameter
); } while (0)
;
3937 return SECFailure;
3938 }
3939
3940 /* The algorithm does not support decoding. */
3941 if (certificateDecodingFunc == NULL((void*)0)) {
3942 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
3943 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"
, 3943); PORT_SetError_Util(PORT_GetError_Util()); } while (0
); tls13_FatalError(ss, PORT_GetError_Util(), illegal_parameter
); } while (0)
;
3944 return SECFailure;
3945 }
3946
3947 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
))
3948 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
))
3949 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
))
;
3950 PRUint32 decodedCertLen = 0;
3951 rv = ssl3_ConsumeHandshakeNumber(ss, &decodedCertLen, 3, &b, &length);
3952 if (rv != SECSuccess) {
3953 return SECFailure; /* alert has been sent */
3954 }
3955
3956 /* If the received CompressedCertificate message cannot be decompressed,
3957 * he connection MUST be terminated with the "bad_certificate" alert.
3958 */
3959 if (decodedCertLen == 0) {
3960 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
))
3961 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
))
3962 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
))
;
3963 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", 3963); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CERTIFICATE
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE
, bad_certificate); } while (0)
;
3964 return SECFailure;
3965 }
3966
3967 /* opaque compressed_certificate_message<1..2^24-1>; */
3968 PRUint32 compressedCertLen = 0;
3969 rv = ssl3_ConsumeHandshakeNumber(ss, &compressedCertLen, 3, &b, &length);
3970 if (rv != SECSuccess) {
3971 return SECFailure; /* alert has been sent */
3972 }
3973
3974 if (compressedCertLen == 0 || compressedCertLen != length) {
3975 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", 3975); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CERTIFICATE
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE
, bad_certificate); } while (0)
;
3976 return SECFailure;
3977 }
3978
3979 /* Decoding received certificate. */
3980 PRUint8 *decodedCert = PORT_ZAllocPORT_ZAlloc_Util(decodedCertLen);
3981 if (!decodedCert) {
3982 return SECFailure;
3983 }
3984
3985 size_t actualCertLen = 0;
3986
3987 SECItem encodedCertAsSecItem = { siBuffer, b, compressedCertLen };
3988 rv = certificateDecodingFunc(&encodedCertAsSecItem,
3989 decodedCert, decodedCertLen, &actualCertLen);
3990
3991 if (rv != SECSuccess) {
3992 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
))
3993 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
))
3994 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
))
;
3995 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", 3995); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CERTIFICATE
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE
, bad_certificate); } while (0)
;
3996 goto loser;
3997 }
3998 PRINT_BUF(60, (ss, "consume bytes:", b, compressedCertLen))if (ssl_trace >= (60)) ssl_PrintBuf (ss, "consume bytes:",
b, compressedCertLen)
;
3999 *b += compressedCertLen;
4000 length -= compressedCertLen;
4001
4002 /* If, after decompression, the specified length does not match the actual length,
4003 * the party receiving the invalid message MUST abort the connection
4004 * with the "bad_certificate" alert.
4005 */
4006 if (actualCertLen != decodedCertLen) {
4007 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
))
4008 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
))
4009 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
))
;
4010 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", 4010); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CERTIFICATE
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE
, bad_certificate); } while (0)
;
4011 goto loser;
4012 }
4013
4014 PRINT_BUF(50, (NULL, "Decoded certificate",if (ssl_trace >= (50)) ssl_PrintBuf (((void*)0), "Decoded certificate"
, decodedCert, decodedCertLen)
4015 decodedCert, decodedCertLen))if (ssl_trace >= (50)) ssl_PrintBuf (((void*)0), "Decoded certificate"
, decodedCert, decodedCertLen)
;
4016
4017 /* compressed_certificate_message: The result of applying the indicated
4018 * compression algorithm to the encoded Certificate message that
4019 * would have been sent if certificate compression was not in use.
4020 *
4021 * After decompression, the Certificate message MUST be processed as if
4022 * it were encoded without being compressed. This way, the parsing and
4023 * the verification have the same security properties as they would have
4024 * in TLS normally.
4025 */
4026 rv = tls13_HandleCertificate(ss, decodedCert, decodedCertLen, PR_TRUE1);
4027 if (rv != SECSuccess) {
4028 goto loser;
4029 }
4030 /* We allow only one compressed certificate to be handled after each
4031 certificate compression advertisement.
4032 See test CertificateCompression_TwoEncodedCertificateRequests. */
4033 ss->xtnData.certificateCompressionAdvertised = PR_FALSE0;
4034 PORT_FreePORT_Free_Util(decodedCert);
4035 return SECSuccess;
4036
4037loser:
4038 PORT_FreePORT_Free_Util(decodedCert);
4039 return SECFailure;
4040}
4041
4042/* Called from tls13_CompleteHandleHandshakeMessage() when it has deciphered a complete
4043 * tls13 Certificate message.
4044 * Caller must hold Handshake and RecvBuf locks.
4045 */
4046static SECStatus
4047tls13_HandleCertificate(sslSocket *ss, PRUint8 *b, PRUint32 length, PRBool alreadyHashed)
4048{
4049 SECStatus rv;
4050 SECItem context = { siBuffer, NULL((void*)0), 0 };
4051 SECItem certList;
4052 PRBool first = PR_TRUE1;
4053 ssl3CertNode *lastCert = NULL((void*)0);
4054
4055 SSL_TRC(3, ("%d: TLS13[%d]: handle certificate handshake",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: handle certificate handshake"
, getpid(), ss->fd)
4056 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: handle certificate handshake"
, getpid(), ss->fd)
;
4057 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",4057))
;
4058 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",4058))
;
4059
4060 rv = tls13_EnsureCerticateExpected(ss);
4061 if (rv != SECSuccess) {
4062 return SECFailure; /* Code already set. */
4063 }
4064
4065 /* We can ignore any other cleartext from the client. */
4066 if (ss->sec.isServer && IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
4067 ssl_CipherSpecReleaseByEpoch(ss, ssl_secret_read, TrafficKeyClearText);
4068 dtls_ReceivedFirstMessageInFlight(ss);
4069 }
4070
4071 /* AlreadyHashed is true only when Certificate Compression is used. */
4072 if (ss->firstHsDone && !alreadyHashed) {
4073 rv = ssl_HashPostHandshakeMessage(ss, ssl_hs_certificate, b, length);
4074 if (rv != SECSuccess) {
4075 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
4076 return SECFailure;
4077 }
4078 }
4079
4080 if (!ss->firstHsDone && ss->sec.isServer) {
4081 /* Our first shot an getting an RTT estimate. If the client took extra
4082 * time to fetch a certificate, this will be bad, but we can't do much
4083 * about that. */
4084 ss->ssl3.hs.rttEstimate = ssl_Time(ss) - ss->ssl3.hs.rttEstimate;
4085 }
4086
4087 /* Process the context string */
4088 rv = ssl3_ConsumeHandshakeVariable(ss, &context, 1, &b, &length);
4089 if (rv != SECSuccess)
4090 return SECFailure;
4091
4092 if (ss->ssl3.clientCertRequested) {
4093 PORT_Assert(ss->sec.isServer)((ss->sec.isServer)?((void)0):PR_Assert("ss->sec.isServer"
,"tls13con.c",4093))
;
4094 if (SECITEM_CompareItemSECITEM_CompareItem_Util(&context, &ss->xtnData.certReqContext) != 0) {
4095 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", 4095); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CERTIFICATE
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE
, illegal_parameter); } while (0)
;
4096 return SECFailure;
4097 }
4098 }
4099 rv = ssl3_ConsumeHandshakeVariable(ss, &certList, 3, &b, &length);
4100 if (rv != SECSuccess) {
4101 return SECFailure;
4102 }
4103 if (length) {
4104 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", 4104); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CERTIFICATE
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE
, illegal_parameter); } while (0)
;
4105 return SECFailure;
4106 }
4107
4108 if (!certList.len) {
4109 if (!ss->sec.isServer) {
4110 /* Servers always need to send some cert. */
4111 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", 4111); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CERTIFICATE
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE
, bad_certificate); } while (0)
;
4112 return SECFailure;
4113 } else {
4114 /* This is TLS's version of a no_certificate alert. */
4115 /* I'm a server. I've requested a client cert. He hasn't got one. */
4116 rv = ssl3_HandleNoCertificate(ss);
4117 if (rv != SECSuccess) {
4118 return SECFailure;
4119 }
4120
4121 TLS13_SET_HS_STATE(ss, wait_finished)tls13_SetHsState(ss, wait_finished, __func__, "tls13con.c", 4121
)
;
4122 return SECSuccess;
4123 }
4124 }
4125
4126 /* Now clean up. */
4127 ssl3_CleanupPeerCerts(ss);
4128 ss->ssl3.peerCertArena = PORT_NewArenaPORT_NewArena_Util(DER_DEFAULT_CHUNKSIZE(2048));
4129 if (ss->ssl3.peerCertArena == NULL((void*)0)) {
4130 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"
, 4130); PORT_SetError_Util(SEC_ERROR_NO_MEMORY); } while (0)
; tls13_FatalError(ss, SEC_ERROR_NO_MEMORY, internal_error); }
while (0)
;
4131 return SECFailure;
4132 }
4133
4134 while (certList.len) {
4135 CERTCertificate *cert;
4136
4137 rv = tls13_HandleCertificateEntry(ss, &certList, first,
4138 &cert);
4139 if (rv != SECSuccess) {
4140 ss->xtnData.signedCertTimestamps.len = 0;
4141 return SECFailure;
4142 }
4143
4144 if (first) {
4145 ss->sec.peerCert = cert;
4146
4147 if (ss->xtnData.signedCertTimestamps.len) {
4148 sslSessionID *sid = ss->sec.ci.sid;
4149 rv = SECITEM_CopyItemSECITEM_CopyItem_Util(NULL((void*)0), &sid->u.ssl3.signedCertTimestamps,
4150 &ss->xtnData.signedCertTimestamps);
4151 ss->xtnData.signedCertTimestamps.len = 0;
4152 if (rv != SECSuccess) {
4153 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"
, 4153); PORT_SetError_Util(SEC_ERROR_NO_MEMORY); } while (0)
; tls13_FatalError(ss, SEC_ERROR_NO_MEMORY, internal_error); }
while (0)
;
4154 return SECFailure;
4155 }
4156 }
4157 } else {
4158 ssl3CertNode *c = PORT_ArenaNew(ss->ssl3.peerCertArena,(ssl3CertNode *)PORT_ArenaAlloc_Util(ss->ssl3.peerCertArena
, sizeof(ssl3CertNode))
4159 ssl3CertNode)(ssl3CertNode *)PORT_ArenaAlloc_Util(ss->ssl3.peerCertArena
, sizeof(ssl3CertNode))
;
4160 if (!c) {
4161 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"
, 4161); PORT_SetError_Util(SEC_ERROR_NO_MEMORY); } while (0)
; tls13_FatalError(ss, SEC_ERROR_NO_MEMORY, internal_error); }
while (0)
;
4162 return SECFailure;
4163 }
4164 c->cert = cert;
4165 c->next = NULL((void*)0);
4166
4167 if (lastCert) {
4168 lastCert->next = c;
4169 } else {
4170 ss->ssl3.peerCertChain = c;
4171 }
4172 lastCert = c;
4173 }
4174
4175 first = PR_FALSE0;
4176 }
4177 SECKEY_UpdateCertPQG(ss->sec.peerCert);
4178
4179 return ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
4180}
4181
4182/* Add context to the hash functions as described in
4183 [draft-ietf-tls-tls13; Section 4.9.1] */
4184SECStatus
4185tls13_AddContextToHashes(sslSocket *ss, const SSL3Hashes *hashes,
4186 SSLHashType algorithm, PRBool sending,
4187 SSL3Hashes *tbsHash)
4188{
4189 SECStatus rv = SECSuccess;
4190 PK11Context *ctx;
4191 const unsigned char context_padding[] = {
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 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
4198 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
4199 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20
4200 };
4201
4202 const char *client_cert_verify_string = "TLS 1.3, client CertificateVerify";
4203 const char *server_cert_verify_string = "TLS 1.3, server CertificateVerify";
4204 const char *context_string = (sending ^ ss->sec.isServer) ? client_cert_verify_string
4205 : server_cert_verify_string;
4206 unsigned int hashlength;
4207
4208 /* Double check that we are doing the same hash.*/
4209 PORT_Assert(hashes->len == tls13_GetHashSize(ss))((hashes->len == tls13_GetHashSize(ss))?((void)0):PR_Assert
("hashes->len == tls13_GetHashSize(ss)","tls13con.c",4209)
)
;
4210
4211 ctx = PK11_CreateDigestContext(ssl3_HashTypeToOID(algorithm));
4212 if (!ctx) {
4213 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_NO_MEMORY);
4214 goto loser;
4215 }
4216
4217 PORT_Assert(SECFailure)((SECFailure)?((void)0):PR_Assert("SECFailure","tls13con.c",4217
))
;
4218 PORT_Assert(!SECSuccess)((!SECSuccess)?((void)0):PR_Assert("!SECSuccess","tls13con.c"
,4218))
;
4219
4220 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)
;
4221 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))
;
4222 rv |= PK11_DigestBegin(ctx);
4223 rv |= PK11_DigestOp(ctx, context_padding, sizeof(context_padding));
4224 rv |= PK11_DigestOp(ctx, (unsigned char *)context_string,
4225 strlen(context_string) + 1); /* +1 includes the terminating 0 */
4226 rv |= PK11_DigestOp(ctx, hashes->u.raw, hashes->len);
4227 /* Update the hash in-place */
4228 rv |= PK11_DigestFinal(ctx, tbsHash->u.raw, &hashlength, sizeof(tbsHash->u.raw));
4229 PK11_DestroyContext(ctx, PR_TRUE1);
4230 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)
;
4231
4232 tbsHash->len = hashlength;
4233 tbsHash->hashAlg = algorithm;
4234
4235 if (rv) {
4236 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4237 goto loser;
4238 }
4239 return SECSuccess;
4240
4241loser:
4242 return SECFailure;
4243}
4244
4245/*
4246 * Derive-Secret(Secret, Label, Messages) =
4247 * HKDF-Expand-Label(Secret, Label,
4248 * Hash(Messages) + Hash(resumption_context), L))
4249 */
4250SECStatus
4251tls13_DeriveSecret(sslSocket *ss, PK11SymKey *key,
4252 const char *label,
4253 unsigned int labelLen,
4254 const SSL3Hashes *hashes,
4255 PK11SymKey **dest,
4256 SSLHashType hash)
4257{
4258 SECStatus rv;
4259
4260 rv = tls13_HkdfExpandLabel(key, hash, hashes->u.raw, hashes->len,
4261 label, labelLen, CKM_HKDF_DERIVE0x0000402aUL,
4262 tls13_GetHashSizeForHash(hash),
4263 ss->protocolVariant, dest);
4264 if (rv != SECSuccess) {
4265 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"
, 4265); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0)
;
4266 return SECFailure;
4267 }
4268 return SECSuccess;
4269}
4270
4271/* Convenience wrapper for the empty hash. */
4272SECStatus
4273tls13_DeriveSecretNullHash(sslSocket *ss, PK11SymKey *key,
4274 const char *label,
4275 unsigned int labelLen,
4276 PK11SymKey **dest,
4277 SSLHashType hash)
4278{
4279 SSL3Hashes hashes;
4280 SECStatus rv;
4281 PRUint8 buf[] = { 0 };
4282
4283 rv = tls13_ComputeHash(ss, &hashes, buf, 0, hash);
4284 if (rv != SECSuccess) {
4285 return SECFailure;
4286 }
4287
4288 return tls13_DeriveSecret(ss, key, label, labelLen, &hashes, dest, hash);
4289}
4290
4291/* Convenience wrapper that lets us supply a separate prefix and suffix. */
4292static SECStatus
4293tls13_DeriveSecretWrap(sslSocket *ss, PK11SymKey *key,
4294 const char *prefix,
4295 const char *suffix,
4296 const char *keylogLabel,
4297 PK11SymKey **dest)
4298{
4299 SECStatus rv;
4300 SSL3Hashes hashes;
4301 char buf[100];
4302 const char *label;
4303
4304 if (prefix) {
4305 if ((strlen(prefix) + strlen(suffix) + 2) > sizeof(buf)) {
4306 PORT_Assert(0)((0)?((void)0):PR_Assert("0","tls13con.c",4306));
4307 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
4308 return SECFailure;
4309 }
4310 (void)PR_snprintf(buf, sizeof(buf), "%s %s",
4311 prefix, suffix);
4312 label = buf;
4313 } else {
4314 label = suffix;
4315 }
4316
4317 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)
4318 SSL_GETPID(), ss->fd, label))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: deriving secret '%s'"
, getpid(), ss->fd, label)
;
4319 rv = tls13_ComputeHandshakeHashes(ss, &hashes);
4320 if (rv != SECSuccess) {
4321 PORT_Assert(0)((0)?((void)0):PR_Assert("0","tls13con.c",4321)); /* Should never fail */
4322 ssl_MapLowLevelError(SEC_ERROR_LIBRARY_FAILURE);
4323 return SECFailure;
4324 }
4325
4326 rv = tls13_DeriveSecret(ss, key, label, strlen(label),
4327 &hashes, dest, tls13_GetHash(ss));
4328 if (rv != SECSuccess) {
4329 return SECFailure;
4330 }
4331
4332 if (keylogLabel) {
4333 ssl3_RecordKeyLog(ss, keylogLabel, *dest);
4334 }
4335 return SECSuccess;
4336}
4337
4338SECStatus
4339SSLExp_SecretCallback(PRFileDesc *fd, SSLSecretCallback cb, void *arg)
4340{
4341 sslSocket *ss = ssl_FindSocket(fd);
4342 if (!ss) {
4343 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)
4344 SSL_GETPID(), fd))if (ssl_debug) ssl_Trace ("%d: SSL[%d]: bad socket in SSL_SecretCallback"
, getpid(), fd)
;
4345 return SECFailure;
4346 }
4347
4348 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",4348)); PR_EnterMonitor(((ss)->firstHandshakeLock
)); } }
;
4349 ssl_GetSSL3HandshakeLock(ss){ if (!ss->opt.noLocks) { ((!((PR_GetMonitorEntryCount(((ss
)->xmitBufLock)) > 0)))?((void)0):PR_Assert("!ssl_HaveXmitBufLock(ss)"
,"tls13con.c",4349)); PR_EnterMonitor(((ss)->ssl3HandshakeLock
)); } }
;
4350 ss->secretCallback = cb;
4351 ss->secretCallbackArg = arg;
4352 ssl_ReleaseSSL3HandshakeLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->ssl3HandshakeLock
)); }
;
4353 ssl_Release1stHandshakeLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->firstHandshakeLock
)); }
;
4354 return SECSuccess;
4355}
4356
4357/* Derive traffic keys for the next cipher spec in the queue. */
4358static SECStatus
4359tls13_DeriveTrafficKeys(sslSocket *ss, ssl3CipherSpec *spec,
4360 TrafficKeyType type,
4361 PRBool deleteSecret)
4362{
4363 size_t keySize = spec->cipherDef->key_size;
4364 size_t ivSize = spec->cipherDef->iv_size +
4365 spec->cipherDef->explicit_nonce_size; /* This isn't always going to
4366 * work, but it does for
4367 * AES-GCM */
4368 CK_MECHANISM_TYPE bulkAlgorithm = ssl3_Alg2Mech(spec->cipherDef->calg);
4369 PK11SymKey **prkp = NULL((void*)0);
4370 PK11SymKey *prk = NULL((void*)0);
4371 PRBool clientSecret;
4372 SECStatus rv;
4373 /* These labels are just used for debugging. */
4374 static const char kHkdfPhaseEarlyApplicationDataKeys[] = "early application data";
4375 static const char kHkdfPhaseHandshakeKeys[] = "handshake data";
4376 static const char kHkdfPhaseApplicationDataKeys[] = "application data";
4377
4378 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",4378))
;
4379
4380 clientSecret = !tls13_UseServerSecret(ss, spec->direction);
4381 switch (type) {
4382 case TrafficKeyEarlyApplicationData:
4383 PORT_Assert(clientSecret)((clientSecret)?((void)0):PR_Assert("clientSecret","tls13con.c"
,4383))
;
4384 prkp = &ss->ssl3.hs.clientEarlyTrafficSecret;
4385 spec->phase = kHkdfPhaseEarlyApplicationDataKeys;
4386 break;
4387 case TrafficKeyHandshake:
4388 prkp = clientSecret ? &ss->ssl3.hs.clientHsTrafficSecret
4389 : &ss->ssl3.hs.serverHsTrafficSecret;
4390 spec->phase = kHkdfPhaseHandshakeKeys;
4391 break;
4392 case TrafficKeyApplicationData:
4393 prkp = clientSecret ? &ss->ssl3.hs.clientTrafficSecret
4394 : &ss->ssl3.hs.serverTrafficSecret;
4395 spec->phase = kHkdfPhaseApplicationDataKeys;
4396 break;
4397 default:
4398 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"
, 4398); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0)
;
4399 PORT_Assert(0)((0)?((void)0):PR_Assert("0","tls13con.c",4399));
4400 return SECFailure;
4401 }
4402 PORT_Assert(prkp != NULL)((prkp != ((void*)0))?((void)0):PR_Assert("prkp != NULL","tls13con.c"
,4402))
;
4403 prk = *prkp;
4404
4405 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)
4406 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)
4407 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)
;
4408
4409 rv = tls13_HkdfExpandLabel(prk, tls13_GetHash(ss),
4410 NULL((void*)0), 0,
4411 kHkdfPurposeKey, strlen(kHkdfPurposeKey),
4412 bulkAlgorithm, keySize,
4413 ss->protocolVariant,
4414 &spec->keyMaterial.key);
4415 if (rv != SECSuccess) {
4416 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"
, 4416); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0)
;
4417 PORT_Assert(0)((0)?((void)0):PR_Assert("0","tls13con.c",4417));
4418 goto loser;
4419 }
4420
4421 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram) && spec->epoch > 0) {
4422 rv = ssl_CreateMaskingContextInner(spec->version, ss->ssl3.hs.cipher_suite,
4423 ss->protocolVariant, prk, kHkdfPurposeSn,
4424 strlen(kHkdfPurposeSn), &spec->maskContext);
4425 if (rv != SECSuccess) {
4426 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"
, 4426); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0)
;
4427 PORT_Assert(0)((0)?((void)0):PR_Assert("0","tls13con.c",4427));
4428 goto loser;
4429 }
4430 }
4431
4432 rv = tls13_HkdfExpandLabelRaw(prk, tls13_GetHash(ss),
4433 NULL((void*)0), 0,
4434 kHkdfPurposeIv, strlen(kHkdfPurposeIv),
4435 ss->protocolVariant,
4436 spec->keyMaterial.iv, ivSize);
4437 if (rv != SECSuccess) {
4438 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"
, 4438); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0)
;
4439 PORT_Assert(0)((0)?((void)0):PR_Assert("0","tls13con.c",4439));
4440 goto loser;
4441 }
4442
4443 if (deleteSecret) {
4444 PK11_FreeSymKey(prk);
4445 *prkp = NULL((void*)0);
4446 }
4447 return SECSuccess;
4448
4449loser:
4450 return SECFailure;
4451}
4452
4453void
4454tls13_SetSpecRecordVersion(sslSocket *ss, ssl3CipherSpec *spec)
4455{
4456 /* Set the record version to pretend to be (D)TLS 1.2. */
4457 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
4458 spec->recordVersion = SSL_LIBRARY_VERSION_DTLS_1_2_WIRE((~0x0102) & 0xffff);
4459 } else {
4460 spec->recordVersion = SSL_LIBRARY_VERSION_TLS_1_20x0303;
4461 }
4462 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)
4463 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)
;
4464}
4465
4466static SECStatus
4467tls13_SetupPendingCipherSpec(sslSocket *ss, ssl3CipherSpec *spec)
4468{
4469 ssl3CipherSuite suite = ss->ssl3.hs.cipher_suite;
4470
4471 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",4471))
;
4472 PORT_Assert(spec->epoch)((spec->epoch)?((void)0):PR_Assert("spec->epoch","tls13con.c"
,4472))
;
4473
4474 /* Version isn't set when we send 0-RTT data. */
4475 spec->version = PR_MAX(SSL_LIBRARY_VERSION_TLS_1_3, ss->version)((0x0304)>(ss->version)?(0x0304):(ss->version));
4476
4477 ssl_SaveCipherSpec(ss, spec);
4478 /* We want to keep read cipher specs around longer because
4479 * there are cases where we might get either epoch N or
4480 * epoch N+1. */
4481 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram) && spec->direction == ssl_secret_read) {
4482 ssl_CipherSpecAddRef(spec);
4483 }
4484
4485 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)
4486 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)
;
4487
4488 spec->cipherDef = ssl_GetBulkCipherDef(ssl_LookupCipherSuiteDef(suite));
4489
4490 if (spec->epoch == TrafficKeyEarlyApplicationData) {
4491 if (ss->xtnData.selectedPsk &&
4492 ss->xtnData.selectedPsk->zeroRttSuite != TLS_NULL_WITH_NULL_NULL0x0000) {
4493 spec->earlyDataRemaining = ss->xtnData.selectedPsk->maxEarlyData;
4494 }
4495 }
4496
4497 tls13_SetSpecRecordVersion(ss, spec);
4498
4499 /* The record size limit is reduced by one so that the remainder of the
4500 * record handling code can use the same checks for all versions. */
4501 if (ssl3_ExtensionNegotiated(ss, ssl_record_size_limit_xtn)) {
4502 spec->recordSizeLimit = ((spec->direction == ssl_secret_read)
4503 ? ss->opt.recordSizeLimit
4504 : ss->xtnData.recordSizeLimit) -
4505 1;
4506 } else {
4507 spec->recordSizeLimit = MAX_FRAGMENT_LENGTH16384;
4508 }
4509 return SECSuccess;
4510}
4511
4512/*
4513 * Initialize the cipher context. All TLS 1.3 operations are AEAD,
4514 * so they are all message contexts.
4515 */
4516static SECStatus
4517tls13_InitPendingContext(sslSocket *ss, ssl3CipherSpec *spec)
4518{
4519 CK_MECHANISM_TYPE encMechanism;
4520 CK_ATTRIBUTE_TYPE encMode;
4521 SECItem iv;
4522 SSLCipherAlgorithm calg;
4523
4524 calg = spec->cipherDef->calg;
4525
4526 encMechanism = ssl3_Alg2Mech(calg);
4527 encMode = CKA_NSS_MESSAGE0x82000000L | ((spec->direction == ssl_secret_write) ? CKA_ENCRYPT0x00000104UL : CKA_DECRYPT0x00000105UL);
4528 iv.data = NULL((void*)0);
4529 iv.len = 0;
4530
4531 /*
4532 * build the context
4533 */
4534 spec->cipherContext = PK11_CreateContextBySymKey(encMechanism, encMode,
4535 spec->keyMaterial.key,
4536 &iv);
4537 if (!spec->cipherContext) {
4538 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
4539 return SECFailure;
4540 }
4541 return SECSuccess;
4542}
4543
4544/*
4545 * Called before sending alerts to set up the right key on the client.
4546 * We might encounter errors during the handshake where the current
4547 * key is ClearText or EarlyApplicationData. This
4548 * function switches to the Handshake key if possible.
4549 */
4550SECStatus
4551tls13_SetAlertCipherSpec(sslSocket *ss)
4552{
4553 SECStatus rv;
4554
4555 if (ss->sec.isServer) {
4556 return SECSuccess;
4557 }
4558 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_30x0304) {
4559 return SECSuccess;
4560 }
4561 if (TLS13_IN_HS_STATE(ss, wait_server_hello)tls13_InHsState(ss, wait_server_hello, wait_invalid)) {
4562 return SECSuccess;
4563 }
4564 if ((ss->ssl3.cwSpec->epoch != TrafficKeyClearText) &&
4565 (ss->ssl3.cwSpec->epoch != TrafficKeyEarlyApplicationData)) {
4566 return SECSuccess;
4567 }
4568
4569 rv = tls13_SetCipherSpec(ss, TrafficKeyHandshake,
4570 ssl_secret_write, PR_FALSE0);
4571 if (rv != SECSuccess) {
4572 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
4573 return SECFailure;
4574 }
4575 return SECSuccess;
4576}
4577
4578/* Install a new cipher spec for this direction.
4579 *
4580 * During the handshake, the values for |epoch| take values from the
4581 * TrafficKeyType enum. Afterwards, key update increments them.
4582 */
4583static SECStatus
4584tls13_SetCipherSpec(sslSocket *ss, PRUint16 epoch,
4585 SSLSecretDirection direction, PRBool deleteSecret)
4586{
4587 TrafficKeyType type;
4588 SECStatus rv;
4589 ssl3CipherSpec *spec = NULL((void*)0);
4590 ssl3CipherSpec **specp;
4591
4592 /* Flush out old handshake data. */
4593 ssl_GetXmitBufLock(ss){ if (!ss->opt.noLocks) PR_EnterMonitor(((ss)->xmitBufLock
)); }
;
4594 rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER0x40000000);
4595 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
;
4596 if (rv != SECSuccess) {
4597 return SECFailure;
4598 }
4599
4600 /* Create the new spec. */
4601 spec = ssl_CreateCipherSpec(ss, direction);
4602 if (!spec) {
4603 return SECFailure;
4604 }
4605 spec->epoch = epoch;
4606 spec->nextSeqNum = 0;
4607 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
4608 dtls_InitRecvdRecords(&spec->recvdRecords);
4609 }
4610
4611 /* This depends on spec having a valid direction and epoch. */
4612 rv = tls13_SetupPendingCipherSpec(ss, spec);
4613 if (rv != SECSuccess) {
4614 goto loser;
4615 }
4616
4617 type = (TrafficKeyType)PR_MIN(TrafficKeyApplicationData, epoch)((TrafficKeyApplicationData)<(epoch)?(TrafficKeyApplicationData
):(epoch))
;
4618 rv = tls13_DeriveTrafficKeys(ss, spec, type, deleteSecret);
4619 if (rv != SECSuccess) {
4620 goto loser;
4621 }
4622
4623 rv = tls13_InitPendingContext(ss, spec);
4624 if (rv != SECSuccess) {
4625 goto loser;
4626 }
4627
4628 /* Now that we've set almost everything up, finally cut over. */
4629 specp = (direction == ssl_secret_read) ? &ss->ssl3.crSpec : &ss->ssl3.cwSpec;
4630 ssl_GetSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_LockWrite_Util((ss)->
specLock); }
;
4631 ssl_CipherSpecRelease(*specp); /* May delete old cipher. */
4632 *specp = spec; /* Overwrite. */
4633 ssl_ReleaseSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockWrite_Util((ss)->
specLock); }
;
4634
4635 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"))
4636 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"))
4637 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"))
;
4638 return SECSuccess;
4639
4640loser:
4641 ssl_CipherSpecRelease(spec);
4642 return SECFailure;
4643}
4644
4645SECStatus
4646tls13_ComputeHandshakeHashes(sslSocket *ss, SSL3Hashes *hashes)
4647{
4648 SECStatus rv;
4649 PK11Context *ctx = NULL((void*)0);
4650 PRBool useEchInner;
4651 sslBuffer *transcript;
4652
4653 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",4653))
;
4654 if (ss->ssl3.hs.hashType == handshake_hash_unknown) {
4655 /* Backup: if we haven't done any hashing, then hash now.
4656 * This happens when we are doing 0-RTT on the client. */
4657 ctx = PK11_CreateDigestContext(ssl3_HashTypeToOID(tls13_GetHash(ss)));
4658 if (!ctx) {
4659 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4660 return SECFailure;
4661 }
4662
4663 if (PK11_DigestBegin(ctx) != SECSuccess) {
4664 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4665 goto loser;
4666 }
4667
4668 /* One might expect this to use ss->ssl3.hs.echAccepted,
4669 * but with 0-RTT we don't know that yet. */
4670 useEchInner = ss->sec.isServer ? PR_FALSE0 : !!ss->ssl3.hs.echHpkeCtx;
4671 transcript = useEchInner ? &ss->ssl3.hs.echInnerMessages : &ss->ssl3.hs.messages;
4672
4673 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)
4674 transcript->buf,if (ssl_trace >= (10)) ssl_PrintBuf (ss, "Handshake hash computed over saved messages"
, transcript->buf, transcript->len)
4675 transcript->len))if (ssl_trace >= (10)) ssl_PrintBuf (ss, "Handshake hash computed over saved messages"
, transcript->buf, transcript->len)
;
4676
4677 if (PK11_DigestOp(ctx,
4678 transcript->buf,
4679 transcript->len) != SECSuccess) {
4680 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4681 goto loser;
4682 }
4683 } else {
4684 if (ss->firstHsDone) {
4685 ctx = PK11_CloneContext(ss->ssl3.hs.shaPostHandshake);
4686 } else {
4687 ctx = PK11_CloneContext(ss->ssl3.hs.sha);
4688 }
4689 if (!ctx) {
4690 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
4691 return SECFailure;
4692 }
4693 }
4694
4695 rv = PK11_DigestFinal(ctx, hashes->u.raw,
4696 &hashes->len,
4697 sizeof(hashes->u.raw));
4698 if (rv != SECSuccess) {
4699 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
4700 goto loser;
4701 }
4702
4703 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)
;
4704 PORT_Assert(hashes->len == tls13_GetHashSize(ss))((hashes->len == tls13_GetHashSize(ss))?((void)0):PR_Assert
("hashes->len == tls13_GetHashSize(ss)","tls13con.c",4704)
)
;
4705 PK11_DestroyContext(ctx, PR_TRUE1);
4706
4707 return SECSuccess;
4708
4709loser:
4710 PK11_DestroyContext(ctx, PR_TRUE1);
4711 return SECFailure;
4712}
4713
4714TLS13KeyShareEntry *
4715tls13_CopyKeyShareEntry(TLS13KeyShareEntry *o)
4716{
4717 TLS13KeyShareEntry *n;
4718
4719 PORT_Assert(o)((o)?((void)0):PR_Assert("o","tls13con.c",4719));
4720 n = PORT_ZNew(TLS13KeyShareEntry)(TLS13KeyShareEntry *)PORT_ZAlloc_Util(sizeof(TLS13KeyShareEntry
))
;
4721 if (!n) {
4722 return NULL((void*)0);
4723 }
4724
4725 if (SECSuccess != SECITEM_CopyItemSECITEM_CopyItem_Util(NULL((void*)0), &n->key_exchange, &o->key_exchange)) {
4726 PORT_FreePORT_Free_Util(n);
4727 return NULL((void*)0);
4728 }
4729 n->group = o->group;
4730 return n;
4731}
4732
4733void
4734tls13_DestroyKeyShareEntry(TLS13KeyShareEntry *offer)
4735{
4736 if (!offer) {
4737 return;
4738 }
4739 SECITEM_ZfreeItemSECITEM_ZfreeItem_Util(&offer->key_exchange, PR_FALSE0);
4740 PORT_ZFreePORT_ZFree_Util(offer, sizeof(*offer));
4741}
4742
4743void
4744tls13_DestroyKeyShares(PRCList *list)
4745{
4746 PRCList *cur_p;
4747
4748 /* The list must be initialized. */
4749 PORT_Assert(PR_LIST_HEAD(list))(((list)->next)?((void)0):PR_Assert("PR_LIST_HEAD(list)","tls13con.c"
,4749))
;
4750
4751 while (!PR_CLIST_IS_EMPTY(list)((list)->next == (list))) {
4752 cur_p = PR_LIST_TAIL(list)(list)->prev;
4753 PR_REMOVE_LINK(cur_p)do { (cur_p)->prev->next = (cur_p)->next; (cur_p)->
next->prev = (cur_p)->prev; } while (0)
;
4754 tls13_DestroyKeyShareEntry((TLS13KeyShareEntry *)cur_p);
4755 }
4756}
4757
4758void
4759tls13_DestroyEarlyData(PRCList *list)
4760{
4761 PRCList *cur_p;
4762
4763 while (!PR_CLIST_IS_EMPTY(list)((list)->next == (list))) {
4764 TLS13EarlyData *msg;
4765
4766 cur_p = PR_LIST_TAIL(list)(list)->prev;
4767 msg = (TLS13EarlyData *)cur_p;
4768
4769 PR_REMOVE_LINK(cur_p)do { (cur_p)->prev->next = (cur_p)->next; (cur_p)->
next->prev = (cur_p)->prev; } while (0)
;
4770 SECITEM_ZfreeItemSECITEM_ZfreeItem_Util(&msg->data, PR_FALSE0);
4771 PORT_ZFreePORT_ZFree_Util(msg, sizeof(*msg));
4772 }
4773}
4774
4775/* draft-ietf-tls-tls13 Section 5.2.2 specifies the following
4776 * nonce algorithm:
4777 *
4778 * The length of the per-record nonce (iv_length) is set to max(8 bytes,
4779 * N_MIN) for the AEAD algorithm (see [RFC5116] Section 4). An AEAD
4780 * algorithm where N_MAX is less than 8 bytes MUST NOT be used with TLS.
4781 * The per-record nonce for the AEAD construction is formed as follows:
4782 *
4783 * 1. The 64-bit record sequence number is padded to the left with
4784 * zeroes to iv_length.
4785 *
4786 * 2. The padded sequence number is XORed with the static
4787 * client_write_iv or server_write_iv, depending on the role.
4788 *
4789 * The resulting quantity (of length iv_length) is used as the per-
4790 * record nonce.
4791 *
4792 * Existing suites have the same nonce size: N_MIN = N_MAX = 12 bytes
4793 *
4794 * See RFC 5288 and https://tools.ietf.org/html/draft-ietf-tls-chacha20-poly1305-04#section-2
4795 */
4796static void
4797tls13_WriteNonce(const unsigned char *ivIn, unsigned int ivInLen,
4798 const unsigned char *nonce, unsigned int nonceLen,
4799 unsigned char *ivOut, unsigned int ivOutLen)
4800{
4801 size_t i;
4802 unsigned int offset = ivOutLen - nonceLen;
4803
4804 PORT_Assert(ivInLen <= ivOutLen)((ivInLen <= ivOutLen)?((void)0):PR_Assert("ivInLen <= ivOutLen"
,"tls13con.c",4804))
;
4805 PORT_Assert(nonceLen <= ivOutLen)((nonceLen <= ivOutLen)?((void)0):PR_Assert("nonceLen <= ivOutLen"
,"tls13con.c",4805))
;
4806 PORT_Memsetmemset(ivOut, 0, ivOutLen);
4807 PORT_Memcpymemcpy(ivOut, ivIn, ivInLen);
4808
4809 /* XOR the last n bytes of the IV with the nonce (should be a counter). */
4810 for (i = 0; i < nonceLen; ++i) {
4811 ivOut[offset + i] ^= nonce[i];
4812 }
4813 PRINT_BUF(50, (NULL, "Nonce", ivOut, ivOutLen))if (ssl_trace >= (50)) ssl_PrintBuf (((void*)0), "Nonce", ivOut
, ivOutLen)
;
4814}
4815
4816/* Setup the IV for AEAD encrypt. The PKCS #11 module will add the
4817 * counter, but it doesn't know about the DTLS epic, so we add it here.
4818 */
4819unsigned int
4820tls13_SetupAeadIv(PRBool isDTLS, SSL3ProtocolVersion v, unsigned char *ivOut, unsigned char *ivIn,
4821 unsigned int offset, unsigned int ivLen, DTLSEpoch epoch)
4822{
4823 PORT_Memcpymemcpy(ivOut, ivIn, ivLen);
4824 if (isDTLS && v < SSL_LIBRARY_VERSION_TLS_1_30x0304) {
4825 /* handle the tls 1.2 counter mode case, the epoc is copied
4826 * instead of xored. We accomplish this by clearing ivOut
4827 * before running xor. */
4828 if (offset >= ivLen) {
4829 ivOut[offset] = ivOut[offset + 1] = 0;
4830 }
4831 ivOut[offset] ^= (unsigned char)(epoch >> BPB8) & 0xff;
4832 ivOut[offset + 1] ^= (unsigned char)(epoch)&0xff;
4833 offset += 2;
4834 }
4835
4836 return offset;
4837}
4838
4839/*
4840 * Do a single AEAD for TLS. This differs from PK11_AEADOp in the following
4841 * ways.
4842 * 1) If context is not supplied, it treats the operation as a single shot
4843 * and creates a context from symKey and mech.
4844 * 2) It always assumes the tag will be at the end of the buffer
4845 * (in on decrypt, out on encrypt) just like the old single shot.
4846 * 3) If we aren't generating an IV, it uses tls13_WriteNonce to create the
4847 * nonce.
4848 * NOTE is context is supplied, symKey and mech are ignored
4849 */
4850SECStatus
4851tls13_AEAD(PK11Context *context, PRBool decrypt,
4852 CK_GENERATOR_FUNCTION ivGen, unsigned int fixedbits,
4853 const unsigned char *ivIn, unsigned char *ivOut, unsigned int ivLen,
4854 const unsigned char *nonceIn, unsigned int nonceLen,
4855 const unsigned char *aad, unsigned int aadLen,
4856 unsigned char *out, unsigned int *outLen, unsigned int maxout,
4857 unsigned int tagLen, const unsigned char *in, unsigned int inLen)
4858{
4859 unsigned char *tag;
4860 unsigned char iv[MAX_IV_LENGTH24];
4861 unsigned char tagbuf[HASH_LENGTH_MAX64];
4862 SECStatus rv;
4863
4864 /* must have either context or the symKey set */
4865 if (!context) {
4866 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
4867 return SECFailure;
4868 }
4869
4870 PORT_Assert(ivLen <= MAX_IV_LENGTH)((ivLen <= 24)?((void)0):PR_Assert("ivLen <= MAX_IV_LENGTH"
,"tls13con.c",4870))
;
4871 PORT_Assert(tagLen <= HASH_LENGTH_MAX)((tagLen <= 64)?((void)0):PR_Assert("tagLen <= HASH_LENGTH_MAX"
,"tls13con.c",4871))
;
4872 if (!ivOut) {
4873 ivOut = iv; /* caller doesn't need a returned, iv */
4874 }
4875
4876 if (ivGen == CKG_NO_GENERATE0x00000000UL) {
4877 tls13_WriteNonce(ivIn, ivLen, nonceIn, nonceLen, ivOut, ivLen);
4878 } else if (ivIn != ivOut) {
4879 PORT_Memcpymemcpy(ivOut, ivIn, ivLen);
4880 }
4881 if (decrypt) {
4882 inLen = inLen - tagLen;
4883 tag = (unsigned char *)in + inLen;
4884 /* tag is const on decrypt, but returned on encrypt */
4885 } else {
4886 /* tag is written to a separate buffer, then added to the end
4887 * of the actual output buffer. This allows output buffer to be larger
4888 * than the input buffer and everything still work */
4889 tag = tagbuf;
4890 }
4891 rv = PK11_AEADOp(context, ivGen, fixedbits, ivOut, ivLen, aad, aadLen,
4892 out, (int *)outLen, maxout, tag, tagLen, in, inLen);
4893 /* on encrypt SSL always puts the tag at the end of the buffer */
4894 if ((rv == SECSuccess) && !(decrypt)) {
4895 unsigned int len = *outLen;
4896 /* make sure there is still space */
4897 if (len + tagLen > maxout) {
4898 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_OUTPUT_LEN);
4899 return SECFailure;
4900 }
4901 PORT_Memcpymemcpy(out + len, tag, tagLen);
4902 *outLen += tagLen;
4903 }
4904 return rv;
4905}
4906
4907static SECStatus
4908tls13_HandleEncryptedExtensions(sslSocket *ss, PRUint8 *b, PRUint32 length)
4909{
4910 SECStatus rv;
4911 PRUint32 innerLength;
4912 SECItem oldAlpn = { siBuffer, NULL((void*)0), 0 };
4913
4914 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",4914))
;
4915 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",4915))
;
4916
4917 SSL_TRC(3, ("%d: TLS13[%d]: handle encrypted extensions",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: handle encrypted extensions"
, getpid(), ss->fd)
4918 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: handle encrypted extensions"
, getpid(), ss->fd)
;
4919
4920 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"
, 4921, wait_encrypted_extensions, wait_invalid)
4921 wait_encrypted_extensions)tls13_CheckHsState(ss, SSL_ERROR_RX_UNEXPECTED_ENCRYPTED_EXTENSIONS
, "SSL_ERROR_RX_UNEXPECTED_ENCRYPTED_EXTENSIONS", __func__, "tls13con.c"
, 4921, wait_encrypted_extensions, wait_invalid)
;
4922 if (rv != SECSuccess) {
4923 return SECFailure;
4924 }
4925
4926 rv = ssl3_ConsumeHandshakeNumber(ss, &innerLength, 2, &b, &length);
4927 if (rv != SECSuccess) {
4928 return SECFailure; /* Alert already sent. */
4929 }
4930 if (innerLength != length) {
4931 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", 4932); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS
, illegal_parameter); } while (0)
4932 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", 4932); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS
, illegal_parameter); } while (0)
;
4933 return SECFailure;
4934 }
4935
4936 /* If we are doing 0-RTT, then we already have an ALPN value. Stash
4937 * it for comparison. */
4938 if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent &&
4939 ss->xtnData.nextProtoState == SSL_NEXT_PROTO_EARLY_VALUE) {
4940 oldAlpn = ss->xtnData.nextProto;
4941 ss->xtnData.nextProto.data = NULL((void*)0);
4942 ss->xtnData.nextProtoState = SSL_NEXT_PROTO_NO_SUPPORT;
4943 }
4944
4945 rv = ssl3_ParseExtensions(ss, &b, &length);
4946 if (rv != SECSuccess) {
4947 return SECFailure; /* Error code set below */
4948 }
4949
4950 /* Handle the rest of the extensions. */
4951 rv = ssl3_HandleParsedExtensions(ss, ssl_hs_encrypted_extensions);
4952 if (rv != SECSuccess) {
4953 return SECFailure; /* Error code set below */
4954 }
4955
4956 /* We can only get here if we offered 0-RTT. */
4957 if (ssl3_ExtensionNegotiated(ss, ssl_tls13_early_data_xtn)) {
4958 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",
4958))
;
4959 if (!ss->xtnData.selectedPsk) {
4960 /* Illegal to accept 0-RTT without also accepting PSK. */
4961 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", 4962); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS
, illegal_parameter); } while (0)
4962 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", 4962); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS
, illegal_parameter); } while (0)
;
4963 }
4964 ss->ssl3.hs.zeroRttState = ssl_0rtt_accepted;
4965
4966 /* Check that the server negotiated the same ALPN (if any). */
4967 if (SECITEM_CompareItemSECITEM_CompareItem_Util(&oldAlpn, &ss->xtnData.nextProto)) {
4968 SECITEM_FreeItemSECITEM_FreeItem_Util(&oldAlpn, PR_FALSE0);
4969 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", 4970); PORT_SetError_Util(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID
); } while (0); tls13_FatalError(ss, SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID
, illegal_parameter); } while (0)
4970 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", 4970); PORT_SetError_Util(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID
); } while (0); tls13_FatalError(ss, SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID
, illegal_parameter); } while (0)
;
4971 return SECFailure;
4972 }
4973 /* Check that the server negotiated the same cipher suite. */
4974 if (ss->ssl3.hs.cipher_suite != ss->ssl3.hs.zeroRttSuite) {
4975 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", 4976); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS
, illegal_parameter); } while (0)
4976 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", 4976); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS
, illegal_parameter); } while (0)
;
4977 return SECFailure;
4978 }
4979 } else if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent) {
4980 /* Though we sent 0-RTT, the early_data extension wasn't present so the
4981 * state is unmodified; the server must have rejected 0-RTT. */
4982 ss->ssl3.hs.zeroRttState = ssl_0rtt_ignored;
4983 ss->ssl3.hs.zeroRttIgnore = ssl_0rtt_ignore_trial;
4984 } else {
4985 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",4987))
4986 (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",4987))
4987 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",4987))
;
4988 }
4989
4990 SECITEM_FreeItemSECITEM_FreeItem_Util(&oldAlpn, PR_FALSE0);
4991 if (ss->ssl3.hs.kea_def->authKeyType == ssl_auth_psk) {
4992 TLS13_SET_HS_STATE(ss, wait_finished)tls13_SetHsState(ss, wait_finished, __func__, "tls13con.c", 4992
)
;
4993 } else {
4994 TLS13_SET_HS_STATE(ss, wait_cert_request)tls13_SetHsState(ss, wait_cert_request, __func__, "tls13con.c"
, 4994)
;
4995 }
4996
4997 /* Client is done with any PSKs */
4998 tls13_DestroyPskList(&ss->ssl3.hs.psks);
4999 ss->xtnData.selectedPsk = NULL((void*)0);
5000
5001 return SECSuccess;
5002}
5003
5004static SECStatus
5005tls13_SendEncryptedExtensions(sslSocket *ss)
5006{
5007 sslBuffer extensions = SSL_BUFFER_EMPTY{ ((void*)0), 0, 0, 0 };
5008 SECStatus rv;
5009
5010 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)
5011 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: send encrypted extensions handshake"
, getpid(), ss->fd)
;
5012
5013 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",5013))
;
5014 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",5014))
;
5015
5016 rv = ssl_ConstructExtensions(ss, &extensions, ssl_hs_encrypted_extensions);
5017 if (rv != SECSuccess) {
5018 return SECFailure;
5019 }
5020
5021 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_encrypted_extensions,
5022 SSL_BUFFER_LEN(&extensions)((&extensions)->len) + 2);
5023 if (rv != SECSuccess) {
5024 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"
, 5024); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0)
;
5025 goto loser;
5026 }
5027 rv = ssl3_AppendBufferToHandshakeVariable(ss, &extensions, 2);
5028 if (rv != SECSuccess) {
5029 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"
, 5029); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0)
;
5030 goto loser;
5031 }
5032 sslBuffer_Clear(&extensions);
5033 return SECSuccess;
5034
5035loser:
5036 sslBuffer_Clear(&extensions);
5037 return SECFailure;
5038}
5039
5040SECStatus
5041tls13_SendCertificateVerify(sslSocket *ss, SECKEYPrivateKey *privKey)
5042{
5043 SECStatus rv = SECFailure;
5044 SECItem buf = { siBuffer, NULL((void*)0), 0 };
5045 unsigned int len;
5046 SSLHashType hashAlg;
5047 SSL3Hashes hash;
5048 SSL3Hashes tbsHash; /* The hash "to be signed". */
5049
5050 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",5050))
;
5051 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",5051))
;
5052
5053 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)
5054 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: send certificate_verify handshake"
, getpid(), ss->fd)
;
5055
5056 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",5056))
;
5057 rv = tls13_ComputeHandshakeHashes(ss, &hash);
5058 if (rv != SECSuccess) {
5059 return SECFailure;
5060 }
5061
5062 /* We should have picked a signature scheme when we received a
5063 * CertificateRequest, or when we picked a server certificate. */
5064 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"
,5064))
;
5065 if (ss->ssl3.hs.signatureScheme == ssl_sig_none) {
5066 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
5067 return SECFailure;
5068 }
5069 hashAlg = ssl_SignatureSchemeToHashType(ss->ssl3.hs.signatureScheme);
5070 rv = tls13_AddContextToHashes(ss, &hash, hashAlg,
5071 PR_TRUE1, &tbsHash);
5072 if (rv != SECSuccess) {
5073 return SECFailure;
5074 }
5075
5076 rv = ssl3_SignHashes(ss, &tbsHash, privKey, &buf);
5077 if (rv == SECSuccess && !ss->sec.isServer) {
5078 /* Remember the info about the slot that did the signing.
5079 * Later, when doing an SSL restart handshake, verify this.
5080 * These calls are mere accessors, and can't fail.
5081 */
5082 PK11SlotInfo *slot;
5083 sslSessionID *sid = ss->sec.ci.sid;
5084
5085 slot = PK11_GetSlotFromPrivateKey(privKey);
5086 sid->u.ssl3.clAuthSeries = PK11_GetSlotSeries(slot);
5087 sid->u.ssl3.clAuthSlotID = PK11_GetSlotID(slot);
5088 sid->u.ssl3.clAuthModuleID = PK11_GetModuleID(slot);
5089 sid->u.ssl3.clAuthValid = PR_TRUE1;
5090 PK11_FreeSlot(slot);
5091 }
5092 if (rv != SECSuccess) {
5093 goto done; /* err code was set by ssl3_SignHashes */
5094 }
5095
5096 len = buf.len + 2 + 2;
5097
5098 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_verify, len);
5099 if (rv != SECSuccess) {
5100 goto done; /* error code set by AppendHandshake */
5101 }
5102
5103 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.signatureScheme, 2);
5104 if (rv != SECSuccess) {
5105 goto done; /* err set by AppendHandshakeNumber */
5106 }
5107
5108 rv = ssl3_AppendHandshakeVariable(ss, buf.data, buf.len, 2);
5109 if (rv != SECSuccess) {
5110 goto done; /* error code set by AppendHandshake */
5111 }
5112
5113done:
5114 /* For parity with the allocation functions, which don't use
5115 * SECITEM_AllocItem(). */
5116 if (buf.data)
5117 PORT_FreePORT_Free_Util(buf.data);
5118 return rv;
5119}
5120
5121/* Called from tls13_CompleteHandleHandshakeMessage() when it has deciphered a complete
5122 * tls13 CertificateVerify message
5123 * Caller must hold Handshake and RecvBuf locks.
5124 */
5125SECStatus
5126tls13_HandleCertificateVerify(sslSocket *ss, PRUint8 *b, PRUint32 length)
5127{
5128 sslDelegatedCredential *dc = ss->xtnData.peerDelegCred;
5129 CERTSubjectPublicKeyInfo *spki;
5130 SECKEYPublicKey *pubKey = NULL((void*)0);
5131 SECItem signed_hash = { siBuffer, NULL((void*)0), 0 };
5132 SECStatus rv;
5133 SSLSignatureScheme sigScheme;
5134 SSLHashType hashAlg;
5135 SSL3Hashes tbsHash;
5136 SSL3Hashes hashes;
5137
5138 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)
5139 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: handle certificate_verify handshake"
, getpid(), ss->fd)
;
5140 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",5140))
;
5141 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",5141))
;
5142
5143 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", 5144, wait_cert_verify, wait_invalid
)
5144 wait_cert_verify)tls13_CheckHsState(ss, SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY, "SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY"
, __func__, "tls13con.c", 5144, wait_cert_verify, wait_invalid
)
;
5145 if (rv != SECSuccess) {
5146 return SECFailure;
5147 }
5148
5149 rv = tls13_ComputeHandshakeHashes(ss, &hashes);
5150 if (rv != SECSuccess) {
5151 return SECFailure;
5152 }
5153
5154 if (ss->firstHsDone) {
5155 rv = ssl_HashPostHandshakeMessage(ss, ssl_hs_certificate_verify, b, length);
5156 } else {
5157 rv = ssl_HashHandshakeMessage(ss, ssl_hs_certificate_verify, b, length);
5158 }
5159 if (rv != SECSuccess) {
5160 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
5161 return SECFailure;
5162 }
5163
5164 rv = ssl_ConsumeSignatureScheme(ss, &b, &length, &sigScheme);
5165 if (rv != SECSuccess) {
5166 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", 5166); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CERT_VERIFY
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_CERT_VERIFY
, illegal_parameter); } while (0)
;
5167 return SECFailure;
5168 }
5169
5170 /* Set the |spki| used to verify the handshake. When verifying with a
5171 * delegated credential (DC), this corresponds to the DC public key;
5172 * otherwise it correspond to the public key of the peer's end-entity
5173 * certificate.
5174 */
5175 if (tls13_IsVerifyingWithDelegatedCredential(ss)) {
5176 /* DelegatedCredential.cred.expected_cert_verify_algorithm is expected
5177 * to match CertificateVerify.scheme.
5178 * DelegatedCredential.cred.expected_cert_verify_algorithm must also be
5179 * the same as was reported in ssl3_AuthCertificate.
5180 */
5181 if (sigScheme != dc->expectedCertVerifyAlg || sigScheme != ss->sec.signatureScheme) {
5182 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", 5182); 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)
;
5183 return SECFailure;
5184 }
5185
5186 /* Verify the DC has three steps: (1) use the peer's end-entity
5187 * certificate to verify DelegatedCredential.signature, (2) check that
5188 * the certificate has the correct key usage, and (3) check that the DC
5189 * hasn't expired.
5190 */
5191 rv = tls13_VerifyDelegatedCredential(ss, dc);
5192 if (rv != SECSuccess) { /* Calls FATAL_ERROR() */
5193 return SECFailure;
5194 }
5195
5196 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)
5197 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: Verifying with delegated credential"
, getpid(), ss->fd)
;
5198 spki = dc->spki;
5199 } else {
5200 spki = &ss->sec.peerCert->subjectPublicKeyInfo;
5201 }
5202
5203 rv = ssl_CheckSignatureSchemeConsistency(ss, sigScheme, spki);
5204 if (rv != SECSuccess) {
5205 /* Error set already */
5206 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"
, 5206); PORT_SetError_Util(PORT_GetError_Util()); } while (0
); tls13_FatalError(ss, PORT_GetError_Util(), illegal_parameter
); } while (0)
;
5207 return SECFailure;
5208 }
5209 hashAlg = ssl_SignatureSchemeToHashType(sigScheme);
5210
5211 rv = tls13_AddContextToHashes(ss, &hashes, hashAlg, PR_FALSE0, &tbsHash);
5212 if (rv != SECSuccess) {
5213 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"
, 5213); PORT_SetError_Util(SSL_ERROR_DIGEST_FAILURE); } while
(0); tls13_FatalError(ss, SSL_ERROR_DIGEST_FAILURE, internal_error
); } while (0)
;
5214 return SECFailure;
5215 }
5216
5217 rv = ssl3_ConsumeHandshakeVariable(ss, &signed_hash, 2, &b, &length);
5218 if (rv != SECSuccess) {
5219 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CERT_VERIFY);
5220 return SECFailure;
5221 }
5222
5223 if (length != 0) {
5224 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", 5224); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CERT_VERIFY
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_CERT_VERIFY
, decode_error); } while (0)
;
5225 return SECFailure;
5226 }
5227
5228 pubKey = SECKEY_ExtractPublicKey(spki);
5229 if (pubKey == NULL((void*)0)) {
5230 ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
5231 return SECFailure;
5232 }
5233
5234 rv = ssl_VerifySignedHashesWithPubKey(ss, pubKey, sigScheme,
5235 &tbsHash, &signed_hash);
5236 if (rv != SECSuccess) {
5237 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"
, 5237); PORT_SetError_Util(PORT_GetError_Util()); } while (0
); tls13_FatalError(ss, PORT_GetError_Util(), decrypt_error);
} while (0)
;
5238 goto loser;
5239 }
5240
5241 /* Set the auth type and verify it is what we captured in ssl3_AuthCertificate */
5242 if (!ss->sec.isServer) {
5243 ss->sec.authType = ssl_SignatureSchemeToAuthType(sigScheme);
5244
5245 uint32_t prelimAuthKeyBits = ss->sec.authKeyBits;
5246 rv = ssl_SetAuthKeyBits(ss, pubKey);
5247 if (rv != SECSuccess) {
5248 goto loser; /* Alert sent and code set. */
5249 }
5250
5251 if (prelimAuthKeyBits != ss->sec.authKeyBits) {
5252 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", 5252); 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)
;
5253 goto loser;
5254 }
5255 }
5256
5257 /* Request a client certificate now if one was requested. */
5258 if (ss->ssl3.hs.clientCertRequested) {
5259 PORT_Assert(!ss->sec.isServer)((!ss->sec.isServer)?((void)0):PR_Assert("!ss->sec.isServer"
,"tls13con.c",5259))
;
5260 rv = ssl3_BeginHandleCertificateRequest(
5261 ss, ss->xtnData.sigSchemes, ss->xtnData.numSigSchemes,
5262 &ss->xtnData.certReqAuthorities);
5263 if (rv != SECSuccess) {
5264 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"
, 5264); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0); tls13_FatalError(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error
); } while (0)
;
5265 goto loser;
5266 }
5267 }
5268
5269 SECKEY_DestroyPublicKey(pubKey);
5270 TLS13_SET_HS_STATE(ss, wait_finished)tls13_SetHsState(ss, wait_finished, __func__, "tls13con.c", 5270
)
;
5271 return SECSuccess;
5272
5273loser:
5274 SECKEY_DestroyPublicKey(pubKey);
5275 return SECFailure;
5276}
5277
5278/* Compute the PSK binder hash over:
5279 * Client HRR prefix, if present in ss->ssl3.hs.messages or ss->ssl3.hs.echInnerMessages,
5280 * |len| bytes of |buf| */
5281static SECStatus
5282tls13_ComputePskBinderHash(sslSocket *ss, PRUint8 *b, size_t length,
5283 SSL3Hashes *hashes, SSLHashType hashType)
5284{
5285 SECStatus rv;
5286 PK11Context *ctx = NULL((void*)0);
5287 sslBuffer *clientResidual = NULL((void*)0);
5288 if (!ss->sec.isServer) {
5289 /* On the server, HRR residual is already buffered. */
5290 clientResidual = ss->ssl3.hs.echHpkeCtx ? &ss->ssl3.hs.echInnerMessages : &ss->ssl3.hs.messages;
5291 }
5292 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",5292))
;
5293 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",5293))
;
5294
5295 PRINT_BUF(10, (NULL, "Binder computed over ClientHello",if (ssl_trace >= (10)) ssl_PrintBuf (((void*)0), "Binder computed over ClientHello"
, b, length)
5296 b, length))if (ssl_trace >= (10)) ssl_PrintBuf (((void*)0), "Binder computed over ClientHello"
, b, length)
;
5297
5298 ctx = PK11_CreateDigestContext(ssl3_HashTypeToOID(hashType));
5299 if (!ctx) {
5300 goto loser;
5301 }
5302 rv = PK11_DigestBegin(ctx);
5303 if (rv != SECSuccess) {
5304 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
5305 goto loser;
5306 }
5307
5308 if (clientResidual && clientResidual->len) {
5309 PRINT_BUF(10, (NULL, " with HRR prefix", clientResidual->buf,if (ssl_trace >= (10)) ssl_PrintBuf (((void*)0), " with HRR prefix"
, clientResidual->buf, clientResidual->len)
5310 clientResidual->len))if (ssl_trace >= (10)) ssl_PrintBuf (((void*)0), " with HRR prefix"
, clientResidual->buf, clientResidual->len)
;
5311 rv = PK11_DigestOp(ctx, clientResidual->buf, clientResidual->len);
5312 if (rv != SECSuccess) {
5313 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
5314 goto loser;
5315 }
5316 }
5317
5318 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram) && !ss->sec.isServer) {
5319 /* Removing the unnecessary header fields.
5320 * See ssl3_AppendHandshakeHeader.*/
5321 PORT_Assert(length >= 12)((length >= 12)?((void)0):PR_Assert("length >= 12","tls13con.c"
,5321))
;
5322 rv = PK11_DigestOp(ctx, b, 4);
5323 if (rv != SECSuccess) {
5324 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
5325 goto loser;
5326 }
5327 rv = PK11_DigestOp(ctx, b + 12, length - 12);
5328 } else {
5329 rv = PK11_DigestOp(ctx, b, length);
5330 }
5331 if (rv != SECSuccess) {
5332 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
5333 goto loser;
5334 }
5335 rv = PK11_DigestFinal(ctx, hashes->u.raw, &hashes->len, sizeof(hashes->u.raw));
5336 if (rv != SECSuccess) {
5337 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
5338 goto loser;
5339 }
5340
5341 PK11_DestroyContext(ctx, PR_TRUE1);
5342 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)
;
5343 return SECSuccess;
5344
5345loser:
5346 if (ctx) {
5347 PK11_DestroyContext(ctx, PR_TRUE1);
5348 }
5349 return SECFailure;
5350}
5351
5352/* Compute and inject the PSK Binder for sending.
5353 *
5354 * When sending a ClientHello, we construct all the extensions with a dummy
5355 * value for the binder. To construct the binder, we commit the entire message
5356 * up to the point where the binders start. Then we calculate the hash using
5357 * the saved message (in ss->ssl3.hs.messages). This is written over the dummy
5358 * binder, after which we write the remainder of the binder extension. */
5359SECStatus
5360tls13_WriteExtensionsWithBinder(sslSocket *ss, sslBuffer *extensions, sslBuffer *chBuf)
5361{
5362 SSL3Hashes hashes;
5363 SECStatus rv;
5364
5365 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",5365))
;
5366 sslPsk *psk = (sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks)(&ss->ssl3.hs.psks)->next;
5367 unsigned int size = tls13_GetHashSizeForHash(psk->hash);
5368 unsigned int prefixLen = extensions->len - size - 3;
5369 unsigned int finishedLen;
5370
5371 PORT_Assert(extensions->len >= size + 3)((extensions->len >= size + 3)?((void)0):PR_Assert("extensions->len >= size + 3"
,"tls13con.c",5371))
;
5372
5373 rv = sslBuffer_AppendNumber(chBuf, extensions->len, 2);
5374 if (rv != SECSuccess) {
5375 return SECFailure;
5376 }
5377
5378 /* Only write the extension up to the point before the binders. Assume that
5379 * the pre_shared_key extension is at the end of the buffer. Don't write
5380 * the binder, or the lengths that precede it (a 2 octet length for the list
5381 * of all binders, plus a 1 octet length for the binder length). */
5382 rv = sslBuffer_Append(chBuf, extensions->buf, prefixLen);
5383 if (rv != SECSuccess) {
5384 return SECFailure;
5385 }
5386
5387 /* Calculate the binder based on what has been written out. */
5388 rv = tls13_ComputePskBinderHash(ss, chBuf->buf, chBuf->len, &hashes, psk->hash);
5389 if (rv != SECSuccess) {
5390 return SECFailure;
5391 }
5392
5393 /* Write the binder into the extensions buffer, over the zeros we reserved
5394 * previously. This avoids an allocation and means that we don't need a
5395 * separate write for the extra bits that precede the binder. */
5396 PORT_Assert(psk->binderKey)((psk->binderKey)?((void)0):PR_Assert("psk->binderKey",
"tls13con.c",5396))
;
5397 rv = tls13_ComputeFinished(ss, psk->binderKey,
5398 psk->hash, &hashes, PR_TRUE1,
5399 extensions->buf + extensions->len - size,
5400 &finishedLen, size);
5401 if (rv != SECSuccess) {
5402 return SECFailure;
5403 }
5404 PORT_Assert(finishedLen == size)((finishedLen == size)?((void)0):PR_Assert("finishedLen == size"
,"tls13con.c",5404))
;
5405
5406 /* Write out the remainder of the extension. */
5407 rv = sslBuffer_Append(chBuf, extensions->buf + prefixLen,
5408 extensions->len - prefixLen);
5409 if (rv != SECSuccess) {
5410 return SECFailure;
5411 }
5412
5413 return SECSuccess;
5414}
5415
5416static SECStatus
5417tls13_ComputeFinished(sslSocket *ss, PK11SymKey *baseKey,
5418 SSLHashType hashType, const SSL3Hashes *hashes,
5419 PRBool sending, PRUint8 *output, unsigned int *outputLen,
5420 unsigned int maxOutputLen)
5421{
5422 SECStatus rv;
5423 PK11Context *hmacCtx = NULL((void*)0);
5424 CK_MECHANISM_TYPE macAlg = tls13_GetHmacMechanismFromHash(hashType);
5425 SECItem param = { siBuffer, NULL((void*)0), 0 };
5426 unsigned int outputLenUint;
5427 const char *label = kHkdfLabelFinishedSecret;
5428 PK11SymKey *secret = NULL((void*)0);
5429
5430 PORT_Assert(baseKey)((baseKey)?((void)0):PR_Assert("baseKey","tls13con.c",5430));
5431 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"
))
5432 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"
))
;
5433 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)
;
5434
5435 /* Now derive the appropriate finished secret from the base secret. */
5436 rv = tls13_HkdfExpandLabel(baseKey, hashType,
5437 NULL((void*)0), 0, label, strlen(label),
5438 tls13_GetHmacMechanismFromHash(hashType),
5439 tls13_GetHashSizeForHash(hashType),
5440 ss->protocolVariant, &secret);
5441 if (rv != SECSuccess) {
5442 goto abort;
5443 }
5444
5445 PORT_Assert(hashes->len == tls13_GetHashSizeForHash(hashType))((hashes->len == tls13_GetHashSizeForHash(hashType))?((void
)0):PR_Assert("hashes->len == tls13_GetHashSizeForHash(hashType)"
,"tls13con.c",5445))
;
5446 hmacCtx = PK11_CreateContextBySymKey(macAlg, CKA_SIGN0x00000108UL,
5447 secret, &param);
5448 if (!hmacCtx) {
5449 goto abort;
5450 }
5451
5452 rv = PK11_DigestBegin(hmacCtx);
5453 if (rv != SECSuccess)
5454 goto abort;
5455
5456 rv = PK11_DigestOp(hmacCtx, hashes->u.raw, hashes->len);
5457 if (rv != SECSuccess)
5458 goto abort;
5459
5460 PORT_Assert(maxOutputLen >= tls13_GetHashSizeForHash(hashType))((maxOutputLen >= tls13_GetHashSizeForHash(hashType))?((void
)0):PR_Assert("maxOutputLen >= tls13_GetHashSizeForHash(hashType)"
,"tls13con.c",5460))
;
5461 rv = PK11_DigestFinal(hmacCtx, output, &outputLenUint, maxOutputLen);
5462 if (rv != SECSuccess)
5463 goto abort;
5464 *outputLen = outputLenUint;
5465
5466 PK11_FreeSymKey(secret);
5467 PK11_DestroyContext(hmacCtx, PR_TRUE1);
5468 PRINT_BUF(50, (ss, "finished value", output, outputLenUint))if (ssl_trace >= (50)) ssl_PrintBuf (ss, "finished value",
output, outputLenUint)
;
5469 return SECSuccess;
5470
5471abort:
5472 if (secret) {
5473 PK11_FreeSymKey(secret);
5474 }
5475
5476 if (hmacCtx) {
5477 PK11_DestroyContext(hmacCtx, PR_TRUE1);
5478 }
5479
5480 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
5481 return SECFailure;
5482}
5483
5484static SECStatus
5485tls13_SendFinished(sslSocket *ss, PK11SymKey *baseKey)
5486{
5487 SECStatus rv;
5488 PRUint8 finishedBuf[TLS13_MAX_FINISHED_SIZE64];
5489 unsigned int finishedLen;
5490 SSL3Hashes hashes;
5491
5492 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)
;
5493
5494 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",5494))
;
5495 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",5495))
;
5496
5497 rv = tls13_ComputeHandshakeHashes(ss, &hashes);
5498 if (rv != SECSuccess) {
5499 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"
, 5499); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0)
;
5500 return SECFailure;
5501 }
5502
5503 ssl_GetSpecReadLock(ss){ if (!ss->opt.noLocks) NSSRWLock_LockRead_Util((ss)->specLock
); }
;
5504 rv = tls13_ComputeFinished(ss, baseKey, tls13_GetHash(ss), &hashes, PR_TRUE1,
5505 finishedBuf, &finishedLen, sizeof(finishedBuf));
5506 ssl_ReleaseSpecReadLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockRead_Util((ss)->
specLock); }
;
5507 if (rv != SECSuccess) {
5508 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"
, 5508); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0)
;
5509 return SECFailure;
5510 }
5511
5512 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_finished, finishedLen);
5513 if (rv != SECSuccess) {
5514 return SECFailure; /* Error code already set. */
5515 }
5516
5517 rv = ssl3_AppendHandshake(ss, finishedBuf, finishedLen);
5518 if (rv != SECSuccess) {
5519 return SECFailure; /* Error code already set. */
5520 }
5521
5522 /* TODO(ekr@rtfm.com): Record key log */
5523 return SECSuccess;
5524}
5525
5526static SECStatus
5527tls13_VerifyFinished(sslSocket *ss, SSLHandshakeType message,
5528 PK11SymKey *secret,
5529 PRUint8 *b, PRUint32 length,
5530 const SSL3Hashes *hashes)
5531{
5532 SECStatus rv;
5533 PRUint8 finishedBuf[TLS13_MAX_FINISHED_SIZE64];
5534 unsigned int finishedLen;
5535
5536 if (!hashes) {
5537 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"
, 5537); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0); tls13_FatalError(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error
); } while (0)
;
5538 return SECFailure;
5539 }
5540
5541 rv = tls13_ComputeFinished(ss, secret, tls13_GetHash(ss), hashes, PR_FALSE0,
5542 finishedBuf, &finishedLen, sizeof(finishedBuf));
5543 if (rv != SECSuccess) {
5544 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"
, 5544); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0); tls13_FatalError(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error
); } while (0)
;
5545 return SECFailure;
5546 }
5547
5548 if (length != finishedLen) {
5549#ifndef UNSAFE_FUZZER_MODE
5550 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"
, 5550); 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)
;
5551 return SECFailure;
5552#endif
5553 }
5554
5555 if (NSS_SecureMemcmp(b, finishedBuf, finishedLen) != 0) {
5556#ifndef UNSAFE_FUZZER_MODE
5557 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", 5558); PORT_SetError_Util(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE
); } while (0); tls13_FatalError(ss, SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE
, decrypt_error); } while (0)
5558 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", 5558); PORT_SetError_Util(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE
); } while (0); tls13_FatalError(ss, SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE
, decrypt_error); } while (0)
;
5559 return SECFailure;
5560#endif
5561 }
5562
5563 return SECSuccess;
5564}
5565
5566static SECStatus
5567tls13_CommonHandleFinished(sslSocket *ss, PK11SymKey *key,
5568 PRUint8 *b, PRUint32 length)
5569{
5570 SECStatus rv;
5571 SSL3Hashes hashes;
5572
5573 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", 5574, wait_finished, wait_invalid)
5574 wait_finished)tls13_CheckHsState(ss, SSL_ERROR_RX_UNEXPECTED_FINISHED, "SSL_ERROR_RX_UNEXPECTED_FINISHED"
, __func__, "tls13con.c", 5574, wait_finished, wait_invalid)
;
5575 if (rv != SECSuccess) {
5576 return SECFailure;
5577 }
5578 ss->ssl3.hs.endOfFlight = PR_TRUE1;
5579
5580 rv = tls13_ComputeHandshakeHashes(ss, &hashes);
5581 if (rv != SECSuccess) {
5582 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"
, 5582); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0)
;
5583 return SECFailure;
5584 }
5585
5586 if (ss->firstHsDone) {
5587 rv = ssl_HashPostHandshakeMessage(ss, ssl_hs_finished, b, length);
5588 } else {
5589 rv = ssl_HashHandshakeMessage(ss, ssl_hs_finished, b, length);
5590 }
5591 if (rv != SECSuccess) {
5592 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
5593 return SECFailure;
5594 }
5595
5596 return tls13_VerifyFinished(ss, ssl_hs_finished,
5597 key, b, length, &hashes);
5598}
5599
5600static SECStatus
5601tls13_ClientHandleFinished(sslSocket *ss, PRUint8 *b, PRUint32 length)
5602{
5603 SECStatus rv;
5604
5605 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",5605))
;
5606 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",5606))
;
5607
5608 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)
5609 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: client handle finished handshake"
, getpid(), ss->fd)
;
5610
5611 rv = tls13_CommonHandleFinished(ss, ss->ssl3.hs.serverHsTrafficSecret,
5612 b, length);
5613 if (rv != SECSuccess) {
5614 return SECFailure;
5615 }
5616
5617 return tls13_SendClientSecondRound(ss);
5618}
5619
5620static SECStatus
5621tls13_ServerHandleFinished(sslSocket *ss, PRUint8 *b, PRUint32 length)
5622{
5623 SECStatus rv;
5624
5625 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",5625))
;
5626 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",5626))
;
5627
5628 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)
5629 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: server handle finished handshake"
, getpid(), ss->fd)
;
5630
5631 if (!tls13_ShouldRequestClientAuth(ss)) {
5632 /* Receiving this message might be the first sign we have that
5633 * early data is over, so pretend we received EOED. */
5634 rv = tls13_MaybeHandleSuppressedEndOfEarlyData(ss);
5635 if (rv != SECSuccess) {
5636 return SECFailure; /* Code already set. */
5637 }
5638
5639 if (!tls13_IsPostHandshake(ss)) {
5640 /* Finalize the RTT estimate. */
5641 ss->ssl3.hs.rttEstimate = ssl_Time(ss) - ss->ssl3.hs.rttEstimate;
5642 }
5643 }
5644
5645 rv = tls13_CommonHandleFinished(ss,
5646 ss->firstHsDone ? ss->ssl3.hs.clientTrafficSecret : ss->ssl3.hs.clientHsTrafficSecret,
5647 b, length);
5648 if (rv != SECSuccess) {
5649 return SECFailure;
5650 }
5651
5652 if (ss->firstHsDone) {
5653 TLS13_SET_HS_STATE(ss, idle_handshake)tls13_SetHsState(ss, idle_handshake, __func__, "tls13con.c", 5653
)
;
5654
5655 PORT_Assert(ss->ssl3.hs.shaPostHandshake != NULL)((ss->ssl3.hs.shaPostHandshake != ((void*)0))?((void)0):PR_Assert
("ss->ssl3.hs.shaPostHandshake != NULL","tls13con.c",5655)
)
;
5656 PK11_DestroyContext(ss->ssl3.hs.shaPostHandshake, PR_TRUE1);
5657 ss->ssl3.hs.shaPostHandshake = NULL((void*)0);
5658
5659 ss->ssl3.clientCertRequested = PR_FALSE0;
5660
5661 if (ss->ssl3.hs.keyUpdateDeferred) {
5662 rv = tls13_SendKeyUpdate(ss, ss->ssl3.hs.deferredKeyUpdateRequest,
5663 PR_FALSE0);
5664 if (rv != SECSuccess) {
5665 return SECFailure; /* error is set. */
5666 }
5667 ss->ssl3.hs.keyUpdateDeferred = PR_FALSE0;
5668 }
5669
5670 return SECSuccess;
5671 }
5672
5673 if (!tls13_ShouldRequestClientAuth(ss) &&
5674 (ss->ssl3.hs.zeroRttState != ssl_0rtt_done)) {
5675 dtls_ReceivedFirstMessageInFlight(ss);
5676 }
5677
5678 rv = tls13_SetCipherSpec(ss, TrafficKeyApplicationData,
5679 ssl_secret_read, PR_FALSE0);
5680 if (rv != SECSuccess) {
5681 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"
, 5681); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0); tls13_FatalError(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error
); } while (0)
;
5682 return SECFailure;
5683 }
5684
5685 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
5686 ssl_CipherSpecReleaseByEpoch(ss, ssl_secret_read, TrafficKeyClearText);
5687 /* We need to keep the handshake cipher spec so we can
5688 * read re-transmitted client Finished. */
5689 rv = dtls_StartTimer(ss, ss->ssl3.hs.hdTimer,
5690 DTLS_RETRANSMIT_FINISHED_MS30000,
5691 dtls13_HolddownTimerCb);
5692 if (rv != SECSuccess) {
5693 return SECFailure;
5694 }
5695 }
5696
5697 rv = tls13_ComputeFinalSecrets(ss);
5698 if (rv != SECSuccess) {
5699 return SECFailure;
5700 }
5701
5702 rv = tls13_FinishHandshake(ss);
5703 if (rv != SECSuccess) {
5704 return SECFailure;
5705 }
5706
5707 ssl_GetXmitBufLock(ss){ if (!ss->opt.noLocks) PR_EnterMonitor(((ss)->xmitBufLock
)); }
;
5708 /* If resumption, authType is the original value and not ssl_auth_psk. */
5709 if (ss->opt.enableSessionTickets && ss->sec.authType != ssl_auth_psk) {
5710 rv = tls13_SendNewSessionTicket(ss, NULL((void*)0), 0);
5711 if (rv != SECSuccess) {
5712 goto loser;
5713 }
5714 rv = ssl3_FlushHandshake(ss, 0);
5715 if (rv != SECSuccess) {
5716 goto loser;
5717 }
5718 }
5719 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
;
5720 return SECSuccess;
5721
5722loser:
5723 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
;
5724 return SECFailure;
5725}
5726
5727static SECStatus
5728tls13_FinishHandshake(sslSocket *ss)
5729{
5730 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",5730))
;
5731 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",5731))
;
5732 PORT_Assert(ss->ssl3.hs.restartTarget == NULL)((ss->ssl3.hs.restartTarget == ((void*)0))?((void)0):PR_Assert
("ss->ssl3.hs.restartTarget == NULL","tls13con.c",5732))
;
5733
5734 /* The first handshake is now completed. */
5735 ss->handshake = NULL((void*)0);
5736
5737 /* Don't need this. */
5738 PK11_FreeSymKey(ss->ssl3.hs.clientHsTrafficSecret);
5739 ss->ssl3.hs.clientHsTrafficSecret = NULL((void*)0);
5740 PK11_FreeSymKey(ss->ssl3.hs.serverHsTrafficSecret);
5741 ss->ssl3.hs.serverHsTrafficSecret = NULL((void*)0);
5742
5743 TLS13_SET_HS_STATE(ss, idle_handshake)tls13_SetHsState(ss, idle_handshake, __func__, "tls13con.c", 5743
)
;
5744
5745 return ssl_FinishHandshake(ss);
5746}
5747
5748/* Do the parts of sending the client's second round that require
5749 * the XmitBuf lock. */
5750static SECStatus
5751tls13_SendClientSecondFlight(sslSocket *ss)
5752{
5753 SECStatus rv;
5754 unsigned int offset = 0;
5755
5756 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",5756))
;
5757 PORT_Assert(!ss->ssl3.hs.clientCertificatePending)((!ss->ssl3.hs.clientCertificatePending)?((void)0):PR_Assert
("!ss->ssl3.hs.clientCertificatePending","tls13con.c",5757
))
;
5758
5759 PRBool sendClientCert = !ss->ssl3.sendEmptyCert &&
5760 ss->ssl3.clientCertChain != NULL((void*)0) &&
5761 ss->ssl3.clientPrivateKey != NULL((void*)0);
5762
5763 if (ss->firstHsDone) {
5764 offset = SSL_BUFFER_LEN(&ss->sec.ci.sendBuf)((&ss->sec.ci.sendBuf)->len);
5765 }
5766
5767 if (ss->ssl3.sendEmptyCert) {
5768 ss->ssl3.sendEmptyCert = PR_FALSE0;
5769 rv = ssl3_SendEmptyCertificate(ss);
5770 /* Don't send verify */
5771 if (rv != SECSuccess) {
5772 goto alert_error; /* error code is set. */
5773 }
5774 } else if (sendClientCert) {
5775 rv = tls13_SendCertificate(ss);
5776 if (rv != SECSuccess) {
5777 goto alert_error; /* err code was set. */
5778 }
5779 }
5780
5781 if (ss->firstHsDone) {
5782 rv = ssl3_UpdatePostHandshakeHashes(ss,
5783 SSL_BUFFER_BASE(&ss->sec.ci.sendBuf)((&ss->sec.ci.sendBuf)->buf) + offset,
5784 SSL_BUFFER_LEN(&ss->sec.ci.sendBuf)((&ss->sec.ci.sendBuf)->len) - offset);
5785 if (rv != SECSuccess) {
5786 goto alert_error; /* err code was set. */
5787 }
5788 }
5789
5790 if (ss->ssl3.hs.clientCertRequested) {
5791 SECITEM_FreeItemSECITEM_FreeItem_Util(&ss->xtnData.certReqContext, PR_FALSE0);
5792 if (ss->xtnData.certReqAuthorities.arena) {
5793 PORT_FreeArenaPORT_FreeArena_Util(ss->xtnData.certReqAuthorities.arena, PR_FALSE0);
5794 ss->xtnData.certReqAuthorities.arena = NULL((void*)0);
5795 }
5796 PORT_Memsetmemset(&ss->xtnData.certReqAuthorities, 0,
5797 sizeof(ss->xtnData.certReqAuthorities));
5798 ss->ssl3.hs.clientCertRequested = PR_FALSE0;
5799 }
5800
5801 if (sendClientCert) {
5802 if (ss->firstHsDone) {
5803 offset = SSL_BUFFER_LEN(&ss->sec.ci.sendBuf)((&ss->sec.ci.sendBuf)->len);
5804 }
5805
5806 rv = tls13_SendCertificateVerify(ss, ss->ssl3.clientPrivateKey);
5807 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
5808 ss->ssl3.clientPrivateKey = NULL((void*)0);
5809 if (rv != SECSuccess) {
5810 goto alert_error; /* err code was set. */
5811 }
5812
5813 if (ss->firstHsDone) {
5814 rv = ssl3_UpdatePostHandshakeHashes(ss,
5815 SSL_BUFFER_BASE(&ss->sec.ci.sendBuf)((&ss->sec.ci.sendBuf)->buf) + offset,
5816 SSL_BUFFER_LEN(&ss->sec.ci.sendBuf)((&ss->sec.ci.sendBuf)->len) - offset);
5817 if (rv != SECSuccess) {
5818 goto alert_error; /* err code was set. */
5819 }
5820 }
5821 }
5822
5823 rv = tls13_SendFinished(ss, ss->firstHsDone ? ss->ssl3.hs.clientTrafficSecret : ss->ssl3.hs.clientHsTrafficSecret);
5824 if (rv != SECSuccess) {
5825 goto alert_error; /* err code was set. */
5826 }
5827 rv = ssl3_FlushHandshake(ss, 0);
5828 if (rv != SECSuccess) {
5829 /* No point in sending an alert here because we're not going to
5830 * be able to send it if we couldn't flush the handshake. */
5831 goto error;
5832 }
5833
5834 return SECSuccess;
5835
5836alert_error:
5837 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"
, 5837); PORT_SetError_Util(PORT_GetError_Util()); } while (0
); tls13_FatalError(ss, PORT_GetError_Util(), internal_error)
; } while (0)
;
5838 return SECFailure;
5839error:
5840 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"
, 5840); PORT_SetError_Util(PORT_GetError_Util()); } while (0
)
;
5841 return SECFailure;
5842}
5843
5844static SECStatus
5845tls13_SendClientSecondRound(sslSocket *ss)
5846{
5847 SECStatus rv;
5848
5849 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",5849))
;
5850 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",5850))
;
5851
5852 /* Defer client authentication sending if we are still waiting for server
5853 * authentication. This avoids unnecessary disclosure of client credentials
5854 * to an unauthenticated server.
5855 */
5856 if (ss->ssl3.hs.restartTarget) {
5857 PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget")PR_Assert("unexpected ss->ssl3.hs.restartTarget","tls13con.c"
,5857)
;
5858 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
5859 return SECFailure;
5860 }
5861 if (ss->ssl3.hs.authCertificatePending || ss->ssl3.hs.clientCertificatePending) {
5862 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)
5863 " 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)
5864 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)
;
5865 ss->ssl3.hs.restartTarget = tls13_SendClientSecondRound;
5866 PORT_SetErrorPORT_SetError_Util(PR_WOULD_BLOCK_ERROR(-5998L));
5867 return SECFailure;
5868 }
5869
5870 rv = tls13_ComputeApplicationSecrets(ss);
5871 if (rv != SECSuccess) {
5872 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"
, 5872); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0); tls13_FatalError(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error
); } while (0)
;
5873 return SECFailure;
5874 }
5875
5876 if (ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) {
5877 ssl_GetXmitBufLock(ss){ if (!ss->opt.noLocks) PR_EnterMonitor(((ss)->xmitBufLock
)); }
; /*******************************/
5878 rv = tls13_SendEndOfEarlyData(ss);
5879 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
; /*******************************/
5880 if (rv != SECSuccess) {
5881 return SECFailure; /* Error code already set. */
5882 }
5883 } else if (ss->opt.enableTls13CompatMode && !IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram) &&
5884 ss->ssl3.hs.zeroRttState == ssl_0rtt_none &&
5885 !ss->ssl3.hs.helloRetry) {
5886 ssl_GetXmitBufLock(ss){ if (!ss->opt.noLocks) PR_EnterMonitor(((ss)->xmitBufLock
)); }
; /*******************************/
5887 rv = ssl3_SendChangeCipherSpecsInt(ss);
5888 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
; /*******************************/
5889 if (rv != SECSuccess) {
5890 return rv;
5891 }
5892 }
5893
5894 rv = tls13_SetCipherSpec(ss, TrafficKeyHandshake,
5895 ssl_secret_write, PR_FALSE0);
5896 if (rv != SECSuccess) {
5897 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", 5897); PORT_SetError_Util(SSL_ERROR_INIT_CIPHER_SUITE_FAILURE
); } while (0); tls13_FatalError(ss, SSL_ERROR_INIT_CIPHER_SUITE_FAILURE
, internal_error); } while (0)
;
5898 return SECFailure;
5899 }
5900
5901 rv = tls13_SetCipherSpec(ss, TrafficKeyApplicationData,
5902 ssl_secret_read, PR_FALSE0);
5903 if (rv != SECSuccess) {
5904 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"
, 5904); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0); tls13_FatalError(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error
); } while (0)
;
5905 return SECFailure;
5906 }
5907
5908 ssl_GetXmitBufLock(ss){ if (!ss->opt.noLocks) PR_EnterMonitor(((ss)->xmitBufLock
)); }
; /*******************************/
5909 /* This call can't block, as clientAuthCertificatePending is checked above */
5910 rv = tls13_SendClientSecondFlight(ss);
5911 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
; /*******************************/
5912 if (rv != SECSuccess) {
5913 return SECFailure;
5914 }
5915 rv = tls13_SetCipherSpec(ss, TrafficKeyApplicationData,
5916 ssl_secret_write, PR_FALSE0);
5917 if (rv != SECSuccess) {
5918 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
5919 return SECFailure;
5920 }
5921
5922 rv = tls13_ComputeFinalSecrets(ss);
5923 if (rv != SECSuccess) {
5924 return SECFailure;
5925 }
5926
5927 /* The handshake is now finished */
5928 return tls13_FinishHandshake(ss);
5929}
5930
5931/*
5932 * enum { (65535) } TicketExtensionType;
5933 *
5934 * struct {
5935 * TicketExtensionType extension_type;
5936 * opaque extension_data<0..2^16-1>;
5937 * } TicketExtension;
5938 *
5939 * struct {
5940 * uint32 ticket_lifetime;
5941 * uint32 ticket_age_add;
5942 * opaque ticket_nonce<1..255>;
5943 * opaque ticket<1..2^16-1>;
5944 * TicketExtension extensions<0..2^16-2>;
5945 * } NewSessionTicket;
5946 */
5947
5948static SECStatus
5949tls13_SendNewSessionTicket(sslSocket *ss, const PRUint8 *appToken,
5950 unsigned int appTokenLen)
5951{
5952 PRUint16 message_length;
5953 PK11SymKey *secret;
5954 SECItem ticket_data = { 0, NULL((void*)0), 0 };
5955 SECStatus rv;
5956 NewSessionTicket ticket = { 0 };
5957 PRUint32 max_early_data_size_len = 0;
5958 PRUint32 greaseLen = 0;
5959 PRUint8 ticketNonce[sizeof(ss->ssl3.hs.ticketNonce)];
5960 sslBuffer ticketNonceBuf = SSL_BUFFER(ticketNonce){ ticketNonce, 0, sizeof(ticketNonce), 1 };
5961
5962 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)
5963 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)
;
5964
5965 ticket.flags = 0;
5966 if (ss->opt.enable0RttData) {
5967 ticket.flags |= ticket_allow_early_data;
5968 max_early_data_size_len = 8; /* type + len + value. */
5969 }
5970 ticket.ticket_lifetime_hint = ssl_ticket_lifetime;
5971
5972 if (ss->opt.enableGrease) {
5973 greaseLen = 4; /* type + len + 0 (empty) */
5974 }
5975
5976 /* The ticket age obfuscator. */
5977 rv = PK11_GenerateRandom((PRUint8 *)&ticket.ticket_age_add,
5978 sizeof(ticket.ticket_age_add));
5979 if (rv != SECSuccess)
5980 goto loser;
5981
5982 rv = sslBuffer_AppendNumber(&ticketNonceBuf, ss->ssl3.hs.ticketNonce,
5983 sizeof(ticketNonce));
5984 if (rv != SECSuccess) {
5985 goto loser;
5986 }
5987 ++ss->ssl3.hs.ticketNonce;
5988 rv = tls13_HkdfExpandLabel(ss->ssl3.hs.resumptionMasterSecret,
5989 tls13_GetHash(ss),
5990 ticketNonce, sizeof(ticketNonce),
5991 kHkdfLabelResumption,
5992 strlen(kHkdfLabelResumption),
5993 CKM_HKDF_DERIVE0x0000402aUL,
5994 tls13_GetHashSize(ss),
5995 ss->protocolVariant, &secret);
5996 if (rv != SECSuccess) {
5997 goto loser;
5998 }
5999
6000 rv = ssl3_EncodeSessionTicket(ss, &ticket, appToken, appTokenLen,
6001 secret, &ticket_data);
6002 PK11_FreeSymKey(secret);
6003 if (rv != SECSuccess)
6004 goto loser;
6005
6006 message_length =
6007 4 + /* lifetime */
6008 4 + /* ticket_age_add */
6009 1 + sizeof(ticketNonce) + /* ticket_nonce */
6010 2 + /* extensions lentgh */
6011 max_early_data_size_len + /* max_early_data_size extension length */
6012 greaseLen + /* GREASE extension length */
6013 2 + /* ticket length */
6014 ticket_data.len;
6015
6016 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_new_session_ticket,
6017 message_length);
6018 if (rv != SECSuccess)
6019 goto loser;
6020
6021 /* This is a fixed value. */
6022 rv = ssl3_AppendHandshakeNumber(ss, ssl_ticket_lifetime, 4);
6023 if (rv != SECSuccess)
6024 goto loser;
6025
6026 rv = ssl3_AppendHandshakeNumber(ss, ticket.ticket_age_add, 4);
6027 if (rv != SECSuccess)
6028 goto loser;
6029
6030 /* The ticket nonce. */
6031 rv = ssl3_AppendHandshakeVariable(ss, ticketNonce, sizeof(ticketNonce), 1);
6032 if (rv != SECSuccess)
6033 goto loser;
6034
6035 /* Encode the ticket. */
6036 rv = ssl3_AppendHandshakeVariable(
6037 ss, ticket_data.data, ticket_data.len, 2);
6038 if (rv != SECSuccess)
6039 goto loser;
6040
6041 /* Extensions */
6042 rv = ssl3_AppendHandshakeNumber(ss, max_early_data_size_len + greaseLen, 2);
6043 if (rv != SECSuccess)
6044 goto loser;
6045
6046 /* GREASE NewSessionTicket:
6047 * When sending a NewSessionTicket message in TLS 1.3, a server MAY select
6048 * one or more GREASE extension values and advertise them as extensions
6049 * with varying length and contents [RFC8701, SEction 4.1]. */
6050 if (ss->opt.enableGrease) {
6051 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",6051))
;
6052
6053 PRUint16 grease;
6054 rv = tls13_RandomGreaseValue(&grease);
6055 if (rv != SECSuccess)
6056 goto loser;
6057 /* Extension type */
6058 rv = ssl3_AppendHandshakeNumber(ss, grease, 2);
6059 if (rv != SECSuccess)
6060 goto loser;
6061 /* Extension length */
6062 rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
6063 if (rv != SECSuccess)
6064 goto loser;
6065 }
6066
6067 /* Max early data size extension. */
6068 if (max_early_data_size_len) {
6069 rv = ssl3_AppendHandshakeNumber(
6070 ss, ssl_tls13_early_data_xtn, 2);
6071 if (rv != SECSuccess)
6072 goto loser;
6073
6074 /* Length */
6075 rv = ssl3_AppendHandshakeNumber(ss, 4, 2);
6076 if (rv != SECSuccess)
6077 goto loser;
6078
6079 rv = ssl3_AppendHandshakeNumber(ss, ss->opt.maxEarlyDataSize, 4);
6080 if (rv != SECSuccess)
6081 goto loser;
6082 }
6083
6084 SECITEM_FreeItemSECITEM_FreeItem_Util(&ticket_data, PR_FALSE0);
6085 return SECSuccess;
6086
6087loser:
6088 if (ticket_data.data) {
6089 SECITEM_FreeItemSECITEM_FreeItem_Util(&ticket_data, PR_FALSE0);
6090 }
6091 return SECFailure;
6092}
6093
6094SECStatus
6095SSLExp_SendSessionTicket(PRFileDesc *fd, const PRUint8 *token,
6096 unsigned int tokenLen)
6097{
6098 sslSocket *ss;
6099 SECStatus rv;
6100
6101 ss = ssl_FindSocket(fd);
6102 if (!ss) {
6103 return SECFailure;
6104 }
6105
6106 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
6107 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_VERSION);
6108 return SECFailure;
6109 }
6110
6111 if (!ss->sec.isServer || !tls13_IsPostHandshake(ss) ||
6112 tokenLen > 0xffff) {
6113 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_INVALID_ARGS);
6114 return SECFailure;
6115 }
6116
6117 /* Disable tickets if we can trace this connection back to a PSK.
6118 * We aren't able to issue tickets (currently) without a certificate.
6119 * As PSK =~ resumption, there is no reason to do this. */
6120 if (ss->sec.authType == ssl_auth_psk) {
6121 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_FEATURE_DISABLED);
6122 return SECFailure;
6123 }
6124
6125 ssl_GetSSL3HandshakeLock(ss){ if (!ss->opt.noLocks) { ((!((PR_GetMonitorEntryCount(((ss
)->xmitBufLock)) > 0)))?((void)0):PR_Assert("!ssl_HaveXmitBufLock(ss)"
,"tls13con.c",6125)); PR_EnterMonitor(((ss)->ssl3HandshakeLock
)); } }
;
6126 ssl_GetXmitBufLock(ss){ if (!ss->opt.noLocks) PR_EnterMonitor(((ss)->xmitBufLock
)); }
;
6127 rv = tls13_SendNewSessionTicket(ss, token, tokenLen);
6128 if (rv == SECSuccess) {
6129 rv = ssl3_FlushHandshake(ss, 0);
6130 }
6131 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
;
6132 ssl_ReleaseSSL3HandshakeLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->ssl3HandshakeLock
)); }
;
6133
6134 return rv;
6135}
6136
6137static SECStatus
6138tls13_HandleNewSessionTicket(sslSocket *ss, PRUint8 *b, PRUint32 length)
6139{
6140 SECStatus rv;
6141 PRUint32 utmp;
6142 NewSessionTicket ticket = { 0 };
6143 SECItem data;
6144 SECItem ticket_nonce;
6145 SECItem ticket_data;
6146
6147 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)
6148 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: handle new session ticket message"
, getpid(), ss->fd)
;
6149
6150 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"
, 6151, idle_handshake, wait_invalid)
6151 idle_handshake)tls13_CheckHsState(ss, SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET
, "SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET", __func__, "tls13con.c"
, 6151, idle_handshake, wait_invalid)
;
6152 if (rv != SECSuccess) {
6153 return SECFailure;
6154 }
6155 if (!tls13_IsPostHandshake(ss) || ss->sec.isServer) {
6156 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", 6157); 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)
6157 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", 6157); 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)
;
6158 return SECFailure;
6159 }
6160
6161 ticket.received_timestamp = ssl_Time(ss);
6162 rv = ssl3_ConsumeHandshakeNumber(ss, &ticket.ticket_lifetime_hint, 4, &b,
6163 &length);
6164 if (rv != SECSuccess) {
6165 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", 6166); 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)
6166 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", 6166); 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)
;
6167 return SECFailure;
6168 }
6169 ticket.ticket.type = siBuffer;
6170
6171 rv = ssl3_ConsumeHandshake(ss, &utmp, sizeof(utmp),
6172 &b, &length);
6173 if (rv != SECSuccess) {
6174 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
6175 return SECFailure;
6176 }
6177 ticket.ticket_age_add = PR_ntohl(utmp);
6178
6179 /* The nonce. */
6180 rv = ssl3_ConsumeHandshakeVariable(ss, &ticket_nonce, 1, &b, &length);
6181 if (rv != SECSuccess) {
6182 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", 6183); 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)
6183 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", 6183); 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)
;
6184 return SECFailure;
6185 }
6186
6187 /* Get the ticket value. */
6188 rv = ssl3_ConsumeHandshakeVariable(ss, &ticket_data, 2, &b, &length);
6189 if (rv != SECSuccess || !ticket_data.len) {
6190 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", 6191); 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)
6191 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", 6191); 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)
;
6192 return SECFailure;
6193 }
6194
6195 /* Parse extensions. */
6196 rv = ssl3_ConsumeHandshakeVariable(ss, &data, 2, &b, &length);
6197 if (rv != SECSuccess || length) {
6198 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", 6199); 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)
6199 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", 6199); 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)
;
6200 return SECFailure;
6201 }
6202
6203 rv = ssl3_HandleExtensions(ss, &data.data,
6204 &data.len, ssl_hs_new_session_ticket);
6205 if (rv != SECSuccess) {
6206 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", 6207); 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)
6207 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", 6207); 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)
;
6208 return SECFailure;
6209 }
6210 if (ss->xtnData.max_early_data_size) {
6211 ticket.flags |= ticket_allow_early_data;
6212 ticket.max_early_data_size = ss->xtnData.max_early_data_size;
6213 }
6214
6215 if (!ss->opt.noCache) {
6216 PK11SymKey *secret;
6217
6218 PORT_Assert(ss->sec.ci.sid)((ss->sec.ci.sid)?((void)0):PR_Assert("ss->sec.ci.sid",
"tls13con.c",6218))
;
6219 rv = SECITEM_CopyItemSECITEM_CopyItem_Util(NULL((void*)0), &ticket.ticket, &ticket_data);
6220 if (rv != SECSuccess) {
6221 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"
, 6221); PORT_SetError_Util(SEC_ERROR_NO_MEMORY); } while (0)
; tls13_FatalError(ss, SEC_ERROR_NO_MEMORY, internal_error); }
while (0)
;
6222 return SECFailure;
6223 }
6224 PRINT_BUF(50, (ss, "Caching session ticket",if (ssl_trace >= (50)) ssl_PrintBuf (ss, "Caching session ticket"
, ticket.ticket.data, ticket.ticket.len)
6225 ticket.ticket.data,if (ssl_trace >= (50)) ssl_PrintBuf (ss, "Caching session ticket"
, ticket.ticket.data, ticket.ticket.len)
6226 ticket.ticket.len))if (ssl_trace >= (50)) ssl_PrintBuf (ss, "Caching session ticket"
, ticket.ticket.data, ticket.ticket.len)
;
6227
6228 /* Replace a previous session ticket when
6229 * we receive a second NewSessionTicket message. */
6230 if (ss->sec.ci.sid->cached == in_client_cache ||
6231 ss->sec.ci.sid->cached == in_external_cache) {
6232 /* Create a new session ID. */
6233 sslSessionID *sid = ssl3_NewSessionID(ss, PR_FALSE0);
6234 if (!sid) {
6235 return SECFailure;
6236 }
6237
6238 /* Copy over the peerCert. */
6239 PORT_Assert(ss->sec.ci.sid->peerCert)((ss->sec.ci.sid->peerCert)?((void)0):PR_Assert("ss->sec.ci.sid->peerCert"
,"tls13con.c",6239))
;
6240 sid->peerCert = CERT_DupCertificate(ss->sec.ci.sid->peerCert);
6241 if (!sid->peerCert) {
6242 ssl_FreeSID(sid);
6243 return SECFailure;
6244 }
6245
6246 /* Destroy the old SID. */
6247 ssl_UncacheSessionID(ss);
6248 ssl_FreeSID(ss->sec.ci.sid);
6249 ss->sec.ci.sid = sid;
6250 }
6251
6252 ssl3_SetSIDSessionTicket(ss->sec.ci.sid, &ticket);
6253 PORT_Assert(!ticket.ticket.data)((!ticket.ticket.data)?((void)0):PR_Assert("!ticket.ticket.data"
,"tls13con.c",6253))
;
6254
6255 rv = tls13_HkdfExpandLabel(ss->ssl3.hs.resumptionMasterSecret,
6256 tls13_GetHash(ss),
6257 ticket_nonce.data, ticket_nonce.len,
6258 kHkdfLabelResumption,
6259 strlen(kHkdfLabelResumption),
6260 CKM_HKDF_DERIVE0x0000402aUL,
6261 tls13_GetHashSize(ss),
6262 ss->protocolVariant, &secret);
6263 if (rv != SECSuccess) {
6264 return SECFailure;
6265 }
6266
6267 rv = ssl3_FillInCachedSID(ss, ss->sec.ci.sid, secret);
6268 PK11_FreeSymKey(secret);
6269 if (rv != SECSuccess) {
6270 return SECFailure;
6271 }
6272
6273 /* Cache the session. */
6274 ssl_CacheSessionID(ss);
6275 }
6276
6277 return SECSuccess;
6278}
6279
6280#define _M_NONE0 0
6281#define _M(a) (1 << PR_MIN(a, 31)((a)<(31)?(a):(31)))
6282#define _M1(a) (_M(ssl_hs_##a))
6283#define _M2(a, b) (_M1(a) | _M1(b))
6284#define _M3(a, b, c) (_M1(a) | _M2(b, c))
6285
6286static const struct {
6287 PRUint16 ex_value;
6288 PRUint32 messages;
6289} KnownExtensions[] = {
6290 { ssl_server_name_xtn, _M2(client_hello, encrypted_extensions) },
6291 { ssl_supported_groups_xtn, _M2(client_hello, encrypted_extensions) },
6292 { ssl_signature_algorithms_xtn, _M2(client_hello, certificate_request) },
6293 { ssl_signature_algorithms_cert_xtn, _M2(client_hello,
6294 certificate_request) },
6295 { ssl_use_srtp_xtn, _M2(client_hello, encrypted_extensions) },
6296 { ssl_app_layer_protocol_xtn, _M2(client_hello, encrypted_extensions) },
6297 { ssl_padding_xtn, _M1(client_hello) },
6298 { ssl_tls13_key_share_xtn, _M3(client_hello, server_hello,
6299 hello_retry_request) },
6300 { ssl_tls13_pre_shared_key_xtn, _M2(client_hello, server_hello) },
6301 { ssl_tls13_psk_key_exchange_modes_xtn, _M1(client_hello) },
6302 { ssl_tls13_early_data_xtn, _M3(client_hello, encrypted_extensions,
6303 new_session_ticket) },
6304 { ssl_signed_cert_timestamp_xtn, _M3(client_hello, certificate_request,
6305 certificate) },
6306 { ssl_cert_status_xtn, _M3(client_hello, certificate_request,
6307 certificate) },
6308 { ssl_delegated_credentials_xtn, _M2(client_hello, certificate) },
6309 { ssl_tls13_cookie_xtn, _M2(client_hello, hello_retry_request) },
6310 { ssl_tls13_certificate_authorities_xtn, _M2(client_hello, certificate_request) },
6311 { ssl_tls13_supported_versions_xtn, _M3(client_hello, server_hello,
6312 hello_retry_request) },
6313 { ssl_record_size_limit_xtn, _M2(client_hello, encrypted_extensions) },
6314 { ssl_tls13_encrypted_client_hello_xtn, _M3(client_hello, encrypted_extensions, hello_retry_request) },
6315 { ssl_tls13_outer_extensions_xtn, _M_NONE0 /* Encoding/decoding only */ },
6316 { ssl_tls13_post_handshake_auth_xtn, _M1(client_hello) },
6317 { ssl_certificate_compression_xtn, _M2(client_hello, certificate_request) }
6318};
6319
6320tls13ExtensionStatus
6321tls13_ExtensionStatus(PRUint16 extension, SSLHandshakeType message)
6322{
6323 unsigned int i;
6324
6325 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",6331))
6326 (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",6331))
6327 (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",6331))
6328 (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",6331))
6329 (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",6331))
6330 (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",6331))
6331 (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",6331))
;
6332
6333 for (i = 0; i < PR_ARRAY_SIZE(KnownExtensions)(sizeof(KnownExtensions)/sizeof((KnownExtensions)[0])); i++) {
6334 /* Hacky check for message numbers > 30. */
6335 PORT_Assert(!(KnownExtensions[i].messages & (1U << 31)))((!(KnownExtensions[i].messages & (1U << 31)))?((void
)0):PR_Assert("!(KnownExtensions[i].messages & (1U << 31))"
,"tls13con.c",6335))
;
6336 if (KnownExtensions[i].ex_value == extension) {
6337 break;
6338 }
6339 }
6340 if (i >= PR_ARRAY_SIZE(KnownExtensions)(sizeof(KnownExtensions)/sizeof((KnownExtensions)[0]))) {
6341 return tls13_extension_unknown;
6342 }
6343
6344 /* Return "disallowed" if the message mask bit isn't set. */
6345 if (!(_M(message) & KnownExtensions[i].messages)) {
6346 return tls13_extension_disallowed;
6347 }
6348
6349 return tls13_extension_allowed;
6350}
6351
6352#undef _M
6353#undef _M1
6354#undef _M2
6355#undef _M3
6356
6357/* We cheat a bit on additional data because the AEAD interface
6358 * which doesn't have room for the record number. The AAD we
6359 * format is serialized record number followed by the true AD
6360 * (i.e., the record header) plus the serialized record number. */
6361static SECStatus
6362tls13_FormatAdditionalData(
6363 sslSocket *ss,
6364 const PRUint8 *header, unsigned int headerLen,
6365 DTLSEpoch epoch, sslSequenceNumber seqNum,
6366 PRUint8 *aad, unsigned int *aadLength, unsigned int maxLength)
6367{
6368 SECStatus rv;
6369 sslBuffer buf = SSL_BUFFER_FIXED(aad, maxLength){ aad, 0, maxLength, 1 };
6370
6371 if (IS_DTLS_1_OR_12(ss)((ss->protocolVariant == ssl_variant_datagram) && ss
->version < 0x0304)
) {
6372 rv = sslBuffer_AppendNumber(&buf, epoch, 2);
6373 if (rv != SECSuccess) {
6374 return SECFailure;
6375 }
6376 }
6377 rv = sslBuffer_AppendNumber(&buf, seqNum, IS_DTLS_1_OR_12(ss)((ss->protocolVariant == ssl_variant_datagram) && ss
->version < 0x0304)
? 6 : 8);
6378 if (rv != SECSuccess) {
6379 return SECFailure;
6380 }
6381
6382 rv = sslBuffer_Append(&buf, header, headerLen);
6383 if (rv != SECSuccess) {
6384 return SECFailure;
6385 }
6386
6387 *aadLength = buf.len;
6388
6389 return SECSuccess;
6390}
6391
6392PRInt32
6393tls13_LimitEarlyData(sslSocket *ss, SSLContentType type, PRInt32 toSend)
6394{
6395 PRInt32 reduced;
6396
6397 PORT_Assert(type == ssl_ct_application_data)((type == ssl_ct_application_data)?((void)0):PR_Assert("type == ssl_ct_application_data"
,"tls13con.c",6397))
;
6398 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",6398))
;
6399 PORT_Assert(!ss->firstHsDone)((!ss->firstHsDone)?((void)0):PR_Assert("!ss->firstHsDone"
,"tls13con.c",6399))
;
6400 if (ss->ssl3.cwSpec->epoch != TrafficKeyEarlyApplicationData) {
6401 return toSend;
6402 }
6403
6404 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram) && toSend > ss->ssl3.cwSpec->earlyDataRemaining) {
6405 /* Don't split application data records in DTLS. */
6406 return 0;
6407 }
6408
6409 reduced = PR_MIN(toSend, ss->ssl3.cwSpec->earlyDataRemaining)((toSend)<(ss->ssl3.cwSpec->earlyDataRemaining)?(toSend
):(ss->ssl3.cwSpec->earlyDataRemaining))
;
6410 ss->ssl3.cwSpec->earlyDataRemaining -= reduced;
6411 return reduced;
6412}
6413
6414SECStatus
6415tls13_ProtectRecord(sslSocket *ss,
6416 ssl3CipherSpec *cwSpec,
6417 SSLContentType type,
6418 const PRUint8 *pIn,
6419 PRUint32 contentLen,
6420 sslBuffer *wrBuf)
6421{
6422 const ssl3BulkCipherDef *cipher_def = cwSpec->cipherDef;
6423 const int tagLen = cipher_def->tag_size;
6424 SECStatus rv;
6425
6426 PORT_Assert(cwSpec->direction == ssl_secret_write)((cwSpec->direction == ssl_secret_write)?((void)0):PR_Assert
("cwSpec->direction == ssl_secret_write","tls13con.c",6426
))
;
6427 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)
6428 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)
6429 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)
;
6430
6431 if (contentLen + 1 + tagLen > SSL_BUFFER_SPACE(wrBuf)((wrBuf)->space - (wrBuf)->len)) {
6432 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
6433 return SECFailure;
6434 }
6435
6436 /* Copy the data into the wrBuf. We're going to encrypt in-place
6437 * in the AEAD branch anyway */
6438 PORT_Memcpymemcpy(SSL_BUFFER_NEXT(wrBuf)((wrBuf)->buf + (wrBuf)->len), pIn, contentLen);
6439
6440 if (cipher_def->calg == ssl_calg_null) {
6441 /* Shortcut for plaintext */
6442 rv = sslBuffer_Skip(wrBuf, contentLen, NULL((void*)0));
6443 PORT_Assert(rv == SECSuccess)((rv == SECSuccess)?((void)0):PR_Assert("rv == SECSuccess","tls13con.c"
,6443))
;
6444 } else {
6445 PRUint8 hdr[13];
6446 sslBuffer buf = SSL_BUFFER_FIXED(hdr, sizeof(hdr)){ hdr, 0, sizeof(hdr), 1 };
6447 PRBool needsLength;
6448 PRUint8 aad[21];
6449 const int ivLen = cipher_def->iv_size + cipher_def->explicit_nonce_size;
6450 unsigned int ivOffset = ivLen - sizeof(sslSequenceNumber);
6451 unsigned char ivOut[MAX_IV_LENGTH24];
6452
6453 unsigned int aadLen;
6454 unsigned int len;
6455
6456 PORT_Assert(cipher_def->type == type_aead)((cipher_def->type == type_aead)?((void)0):PR_Assert("cipher_def->type == type_aead"
,"tls13con.c",6456))
;
6457
6458 /* If the following condition holds, we can skip the padding logic for
6459 * DTLS 1.3 (4.2.3). This will be the case until we support a cipher
6460 * with tag length < 15B. */
6461 PORT_Assert(tagLen + 1 /* cType */ >= 16)((tagLen + 1 >= 16)?((void)0):PR_Assert("tagLen + 1 >= 16"
,"tls13con.c",6461))
;
6462
6463 /* Add the content type at the end. */
6464 *(SSL_BUFFER_NEXT(wrBuf)((wrBuf)->buf + (wrBuf)->len) + contentLen) = type;
6465
6466 /* Create the header (ugly that we have to do it twice). */
6467 rv = ssl_InsertRecordHeader(ss, cwSpec, ssl_ct_application_data,
6468 &buf, &needsLength);
6469 if (rv != SECSuccess) {
6470 return SECFailure;
6471 }
6472 if (needsLength) {
6473 rv = sslBuffer_AppendNumber(&buf, contentLen + 1 + tagLen, 2);
6474 if (rv != SECSuccess) {
6475 return SECFailure;
6476 }
6477 }
6478 rv = tls13_FormatAdditionalData(ss, SSL_BUFFER_BASE(&buf)((&buf)->buf), SSL_BUFFER_LEN(&buf)((&buf)->len),
6479 cwSpec->epoch, cwSpec->nextSeqNum,
6480 aad, &aadLen, sizeof(aad));
6481 if (rv != SECSuccess) {
6482 return SECFailure;
6483 }
6484 /* set up initial IV value */
6485 ivOffset = tls13_SetupAeadIv(IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram), cwSpec->version, ivOut, cwSpec->keyMaterial.iv,
6486 ivOffset, ivLen, cwSpec->epoch);
6487 rv = tls13_AEAD(cwSpec->cipherContext, PR_FALSE0,
6488 CKG_GENERATE_COUNTER_XOR0x00000004UL, ivOffset * BPB8,
6489 ivOut, ivOut, ivLen, /* iv */
6490 NULL((void*)0), 0, /* nonce */
6491 aad + sizeof(sslSequenceNumber), /* aad */
6492 aadLen - sizeof(sslSequenceNumber),
6493 SSL_BUFFER_NEXT(wrBuf)((wrBuf)->buf + (wrBuf)->len), /* output */
6494 &len, /* out len */
6495 SSL_BUFFER_SPACE(wrBuf)((wrBuf)->space - (wrBuf)->len), /* max out */
6496 tagLen,
6497 SSL_BUFFER_NEXT(wrBuf)((wrBuf)->buf + (wrBuf)->len), /* input */
6498 contentLen + 1); /* input len */
6499 if (rv != SECSuccess) {
6500 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_ENCRYPTION_FAILURE);
6501 return SECFailure;
6502 }
6503 rv = sslBuffer_Skip(wrBuf, len, NULL((void*)0));
6504 PORT_Assert(rv == SECSuccess)((rv == SECSuccess)?((void)0):PR_Assert("rv == SECSuccess","tls13con.c"
,6504))
;
6505 }
6506
6507 return SECSuccess;
6508}
6509
6510/* Unprotect a TLS 1.3 record and leave the result in plaintext.
6511 *
6512 * Called by ssl3_HandleRecord. Caller must hold the spec read lock.
6513 * Therefore, we MUST not call SSL3_SendAlert().
6514 *
6515 * If SECFailure is returned, we:
6516 * 1. Set |*alert| to the alert to be sent.
6517 * 2. Call PORT_SetError() with an appropriate code.
6518 */
6519SECStatus
6520tls13_UnprotectRecord(sslSocket *ss,
6521 ssl3CipherSpec *spec,
6522 SSL3Ciphertext *cText,
6523 sslBuffer *plaintext,
6524 SSLContentType *innerType,
6525 SSL3AlertDescription *alert)
6526{
6527 const ssl3BulkCipherDef *cipher_def = spec->cipherDef;
6528 const int ivLen = cipher_def->iv_size + cipher_def->explicit_nonce_size;
6529 const int tagLen = cipher_def->tag_size;
6530 const int innerTypeLen = 1;
6531
6532 PRUint8 aad[21];
6533 unsigned int aadLen;
6534 SECStatus rv;
6535
6536 *alert = bad_record_mac; /* Default alert for most issues. */
6537
6538 PORT_Assert(spec->direction == ssl_secret_read)((spec->direction == ssl_secret_read)?((void)0):PR_Assert(
"spec->direction == ssl_secret_read","tls13con.c",6538))
;
6539 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)
6540 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)
6541 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)
;
6542
6543 /* Verify that the outer content type is right.
6544 *
6545 * For the inner content type as well as lower TLS versions this is checked
6546 * in ssl3con.c/ssl3_HandleNonApllicationData().
6547 *
6548 * For DTLS 1.3 this is checked in ssl3gthr.c/dtls_GatherData(). DTLS drops
6549 * invalid records silently [RFC6347, Section 4.1.2.7].
6550 *
6551 * Also allow the DTLS short header in TLS 1.3. */
6552 if (!(cText->hdr[0] == ssl_ct_application_data ||
6553 (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram) &&
6554 ss->version >= SSL_LIBRARY_VERSION_TLS_1_30x0304 &&
6555 (cText->hdr[0] & 0xe0) == 0x20))) {
6556 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])
6557 ("%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])
6558 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])
;
6559 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_UNEXPECTED_RECORD_TYPE);
6560 *alert = unexpected_message;
6561 return SECFailure;
6562 }
6563
6564 /* We can perform this test in variable time because the record's total
6565 * length and the ciphersuite are both public knowledge. */
6566 if (cText->buf->len < tagLen) {
6567 SSL_TRC(3,if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: record too short to contain valid AEAD data"
, getpid(), ss->fd)
6568 ("%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)
6569 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: record too short to contain valid AEAD data"
, getpid(), ss->fd)
;
6570 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_BAD_MAC_READ);
6571 return SECFailure;
6572 }
6573
6574 /* Check if the ciphertext can be valid if we assume maximum plaintext and
6575 * add the specific ciphersuite expansion.
6576 * This way we detect overlong plaintexts/padding before decryption.
6577 * This check enforces size limitations more strict than the RFC.
6578 * (see RFC8446, Section 5.2) */
6579 if (cText->buf->len > (spec->recordSizeLimit + innerTypeLen + tagLen)) {
6580 *alert = record_overflow;
6581 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_RECORD_TOO_LONG);
6582 return SECFailure;
6583 }
6584
6585 /* Check the version number in the record. Stream only. */
6586 if (!IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
6587 SSL3ProtocolVersion version =
6588 ((SSL3ProtocolVersion)cText->hdr[1] << 8) |
6589 (SSL3ProtocolVersion)cText->hdr[2];
6590 if (version != spec->recordVersion) {
6591 /* Do we need a better error here? */
6592 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)
6593 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: record has bogus version"
, getpid(), ss->fd)
;
6594 return SECFailure;
6595 }
6596 }
6597
6598 /* Decrypt */
6599 PORT_Assert(cipher_def->type == type_aead)((cipher_def->type == type_aead)?((void)0):PR_Assert("cipher_def->type == type_aead"
,"tls13con.c",6599))
;
6600 rv = tls13_FormatAdditionalData(ss, cText->hdr, cText->hdrLen,
6601 spec->epoch, cText->seqNum,
6602 aad, &aadLen, sizeof(aad));
6603 if (rv != SECSuccess) {
6604
6605 return SECFailure;
6606 }
6607 rv = tls13_AEAD(spec->cipherContext, PR_TRUE1,
6608 CKG_NO_GENERATE0x00000000UL, 0, /* ignored for decrypt */
6609 spec->keyMaterial.iv, NULL((void*)0), ivLen, /* iv */
6610 aad, sizeof(sslSequenceNumber), /* nonce */
6611 aad + sizeof(sslSequenceNumber), /* aad */
6612 aadLen - sizeof(sslSequenceNumber),
6613 plaintext->buf, /* output */
6614 &plaintext->len, /* outlen */
6615 plaintext->space, /* maxout */
6616 tagLen,
6617 cText->buf->buf, /* in */
6618 cText->buf->len); /* inlen */
6619 if (rv != SECSuccess) {
6620 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
6621 spec->deprotectionFailures++;
6622 }
6623
6624 SSL_TRC(3,if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: record has bogus MAC"
, getpid(), ss->fd)
6625 ("%d: TLS13[%d]: record has bogus MAC",if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: record has bogus MAC"
, getpid(), ss->fd)
6626 SSL_GETPID(), ss->fd))if (ssl_trace >= (3)) ssl_Trace ("%d: TLS13[%d]: record has bogus MAC"
, getpid(), ss->fd)
;
6627 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_BAD_MAC_READ);
6628 return SECFailure;
6629 }
6630
6631 /* There is a similar test in ssl3_HandleRecord, but this test is needed to
6632 * account for padding. */
6633 if (plaintext->len > spec->recordSizeLimit + innerTypeLen) {
6634 *alert = record_overflow;
6635 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_RECORD_TOO_LONG);
6636 return SECFailure;
6637 }
6638
6639 /* The record is right-padded with 0s, followed by the true
6640 * content type, so read from the right until we receive a
6641 * nonzero byte. */
6642 while (plaintext->len > 0 && !(plaintext->buf[plaintext->len - 1])) {
6643 --plaintext->len;
6644 }
6645
6646 /* Bogus padding. */
6647 if (plaintext->len < 1) {
6648 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)
;
6649 /* It's safe to report this specifically because it happened
6650 * after the MAC has been verified. */
6651 *alert = unexpected_message;
6652 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_BAD_BLOCK_PADDING);
6653 return SECFailure;
6654 }
6655
6656 /* Record the type. */
6657 *innerType = (SSLContentType)plaintext->buf[plaintext->len - 1];
6658 --plaintext->len;
6659
6660 /* Check for zero-length encrypted Alert and Handshake fragments
6661 * (zero-length + inner content type byte).
6662 *
6663 * Implementations MUST NOT send Handshake and Alert records that have a
6664 * zero-length TLSInnerPlaintext.content; if such a message is received,
6665 * the receiving implementation MUST terminate the connection with an
6666 * "unexpected_message" alert [RFC8446, Section 5.4]. */
6667 if (!plaintext->len && ((!IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram) && cText->hdr[0] == ssl_ct_application_data) ||
6668 (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram) && dtls_IsDtls13Ciphertext(spec->version, cText->hdr[0])))) {
6669 switch (*innerType) {
6670 case ssl_ct_alert:
6671 *alert = unexpected_message;
6672 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_MALFORMED_ALERT);
6673 return SECFailure;
6674 case ssl_ct_handshake:
6675 *alert = unexpected_message;
6676 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_MALFORMED_HANDSHAKE);
6677 return SECFailure;
6678 default:
6679 break;
6680 }
6681 }
6682
6683 /* Check that we haven't received too much 0-RTT data. */
6684 if (spec->epoch == TrafficKeyEarlyApplicationData &&
6685 *innerType == ssl_ct_application_data) {
6686 if (plaintext->len > spec->earlyDataRemaining) {
6687 *alert = unexpected_message;
6688 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_TOO_MUCH_EARLY_DATA);
6689 return SECFailure;
6690 }
6691 spec->earlyDataRemaining -= plaintext->len;
6692 }
6693
6694 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)
6695 ("%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)
6696 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)
;
6697
6698 return SECSuccess;
6699}
6700
6701/* 0-RTT is only permitted if:
6702 *
6703 * 1. We are doing TLS 1.3
6704 * 2. This isn't a second ClientHello (in response to HelloRetryRequest)
6705 * 3. The 0-RTT option is set.
6706 * 4. We have a valid ticket or an External PSK.
6707 * 5. If resuming:
6708 * 5a. The server is willing to accept 0-RTT.
6709 * 5b. We have not changed our ALPN settings to disallow the ALPN tag
6710 * in the ticket.
6711 *
6712 * Called from tls13_ClientSendEarlyDataXtn().
6713 */
6714PRBool
6715tls13_ClientAllow0Rtt(const sslSocket *ss, const sslSessionID *sid)
6716{
6717 /* We checked that the cipher suite was still allowed back in
6718 * ssl3_SendClientHello. */
6719 if (sid->version < SSL_LIBRARY_VERSION_TLS_1_30x0304) {
6720 return PR_FALSE0;
6721 }
6722 if (ss->ssl3.hs.helloRetry) {
6723 return PR_FALSE0;
6724 }
6725 if (!ss->opt.enable0RttData) {
6726 return PR_FALSE0;
6727 }
6728 if (PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks)((&ss->ssl3.hs.psks)->next == (&ss->ssl3.hs.
psks))
) {
6729 return PR_FALSE0;
6730 }
6731 sslPsk *psk = (sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks)(&ss->ssl3.hs.psks)->next;
6732
6733 if (psk->zeroRttSuite == TLS_NULL_WITH_NULL_NULL0x0000) {
6734 return PR_FALSE0;
6735 }
6736 if (!psk->maxEarlyData) {
6737 return PR_FALSE0;
6738 }
6739
6740 if (psk->type == ssl_psk_external) {
6741 return psk->hash == tls13_GetHashForCipherSuite(psk->zeroRttSuite);
6742 }
6743 if (psk->type == ssl_psk_resume) {
6744 if (!ss->statelessResume)
6745 return PR_FALSE0;
6746 if ((sid->u.ssl3.locked.sessionTicket.flags & ticket_allow_early_data) == 0)
6747 return PR_FALSE0;
6748 return ssl_AlpnTagAllowed(ss, &sid->u.ssl3.alpnSelection);
6749 }
6750 PORT_Assert(0)((0)?((void)0):PR_Assert("0","tls13con.c",6750));
6751 return PR_FALSE0;
6752}
6753
6754SECStatus
6755tls13_MaybeDo0RTTHandshake(sslSocket *ss)
6756{
6757 SECStatus rv;
6758
6759 /* Don't do anything if there is no early_data xtn, which means we're
6760 * not doing early data. */
6761 if (!ssl3_ExtensionAdvertised(ss, ssl_tls13_early_data_xtn)) {
6762 return SECSuccess;
6763 }
6764
6765 ss->ssl3.hs.zeroRttState = ssl_0rtt_sent;
6766 ss->ssl3.hs.zeroRttSuite = ss->ssl3.hs.cipher_suite;
6767 /* Note: Reset the preliminary info here rather than just add 0-RTT. We are
6768 * only guessing what might happen at this point.*/
6769 ss->ssl3.hs.preliminaryInfo = ssl_preinfo_0rtt_cipher_suite(1U << 2);
6770
6771 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)
;
6772
6773 /* Set the ALPN data as if it was negotiated. We check in the ServerHello
6774 * handler that the server negotiates the same value. */
6775 if (ss->sec.ci.sid->u.ssl3.alpnSelection.len) {
6776 ss->xtnData.nextProtoState = SSL_NEXT_PROTO_EARLY_VALUE;
6777 rv = SECITEM_CopyItemSECITEM_CopyItem_Util(NULL((void*)0), &ss->xtnData.nextProto,
6778 &ss->sec.ci.sid->u.ssl3.alpnSelection);
6779 if (rv != SECSuccess) {
6780 return SECFailure;
6781 }
6782 }
6783
6784 if (ss->opt.enableTls13CompatMode && !IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
6785 /* Pretend that this is a proper ChangeCipherSpec even though it is sent
6786 * before receiving the ServerHello. */
6787 ssl_GetSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_LockWrite_Util((ss)->
specLock); }
;
6788 tls13_SetSpecRecordVersion(ss, ss->ssl3.cwSpec);
6789 ssl_ReleaseSpecWriteLock(ss){ if (!ss->opt.noLocks) NSSRWLock_UnlockWrite_Util((ss)->
specLock); }
;
6790 ssl_GetXmitBufLock(ss){ if (!ss->opt.noLocks) PR_EnterMonitor(((ss)->xmitBufLock
)); }
;
6791 rv = ssl3_SendChangeCipherSpecsInt(ss);
6792 ssl_ReleaseXmitBufLock(ss){ if (!ss->opt.noLocks) PR_ExitMonitor(((ss)->xmitBufLock
)); }
;
6793 if (rv != SECSuccess) {
6794 return SECFailure;
6795 }
6796 }
6797
6798 /* If we have any message that was saved for later hashing.
6799 * The updated hash is then used in tls13_DeriveEarlySecrets. */
6800 rv = ssl3_MaybeUpdateHashWithSavedRecord(ss);
6801 if (rv != SECSuccess) {
6802 return SECFailure;
6803 }
6804
6805 /* If we're trying 0-RTT, derive from the first PSK */
6806 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",6806))
;
6807 ss->xtnData.selectedPsk = (sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks)(&ss->ssl3.hs.psks)->next;
6808 rv = tls13_DeriveEarlySecrets(ss);
6809 if (rv != SECSuccess) {
6810 return SECFailure;
6811 }
6812
6813 /* Save cwSpec in case we get a HelloRetryRequest and have to send another
6814 * ClientHello. */
6815 ssl_CipherSpecAddRef(ss->ssl3.cwSpec);
6816
6817 rv = tls13_SetCipherSpec(ss, TrafficKeyEarlyApplicationData,
6818 ssl_secret_write, PR_TRUE1);
6819 ss->xtnData.selectedPsk = NULL((void*)0);
6820 if (rv != SECSuccess) {
6821 return SECFailure;
6822 }
6823
6824 return SECSuccess;
6825}
6826
6827PRInt32
6828tls13_Read0RttData(sslSocket *ss, PRUint8 *buf, PRInt32 len)
6829{
6830 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",6830))
;
6831 PRInt32 offset = 0;
6832 while (!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.bufferedEarlyData)((&ss->ssl3.hs.bufferedEarlyData)->next == (&ss
->ssl3.hs.bufferedEarlyData))
) {
6833 TLS13EarlyData *msg =
6834 (TLS13EarlyData *)PR_NEXT_LINK(&ss->ssl3.hs.bufferedEarlyData)((&ss->ssl3.hs.bufferedEarlyData)->next);
6835 unsigned int tocpy = msg->data.len - msg->consumed;
6836
6837 if (tocpy > (len - offset)) {
6838 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
6839 /* In DTLS, we only return entire records.
6840 * So offset and consumed are always zero. */
6841 PORT_Assert(offset == 0)((offset == 0)?((void)0):PR_Assert("offset == 0","tls13con.c"
,6841))
;
6842 PORT_Assert(msg->consumed == 0)((msg->consumed == 0)?((void)0):PR_Assert("msg->consumed == 0"
,"tls13con.c",6842))
;
6843 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_RX_SHORT_DTLS_READ);
6844 return -1;
6845 }
6846
6847 tocpy = len - offset;
6848 }
6849
6850 PORT_Memcpymemcpy(buf + offset, msg->data.data + msg->consumed, tocpy);
6851 offset += tocpy;
6852 msg->consumed += tocpy;
6853
6854 if (msg->consumed == msg->data.len) {
6855 PR_REMOVE_LINK(&msg->link)do { (&msg->link)->prev->next = (&msg->link
)->next; (&msg->link)->next->prev = (&msg
->link)->prev; } while (0)
;
6856 SECITEM_ZfreeItemSECITEM_ZfreeItem_Util(&msg->data, PR_FALSE0);
6857 PORT_ZFreePORT_ZFree_Util(msg, sizeof(*msg));
6858 }
6859
6860 /* We are done after one record for DTLS; otherwise, when the buffer fills up. */
6861 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram) || offset == len) {
6862 break;
6863 }
6864 }
6865
6866 return offset;
6867}
6868
6869static SECStatus
6870tls13_SendEndOfEarlyData(sslSocket *ss)
6871{
6872 SECStatus rv;
6873
6874 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",6874))
;
6875
6876 if (!ss->opt.suppressEndOfEarlyData) {
6877 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)
;
6878 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_end_of_early_data, 0);
6879 if (rv != SECSuccess) {
6880 return rv; /* err set by AppendHandshake. */
6881 }
6882 }
6883
6884 ss->ssl3.hs.zeroRttState = ssl_0rtt_done;
6885 return SECSuccess;
6886}
6887
6888static SECStatus
6889tls13_HandleEndOfEarlyData(sslSocket *ss, const PRUint8 *b, PRUint32 length)
6890{
6891 SECStatus rv;
6892
6893 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",6893))
;
6894
6895 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"
, 6896, wait_end_of_early_data, wait_invalid)
6896 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"
, 6896, wait_end_of_early_data, wait_invalid)
;
6897 if (rv != SECSuccess) {
6898 return SECFailure;
6899 }
6900
6901 /* We shouldn't be getting any more early data, and if we do,
6902 * it is because of reordering and we drop it. */
6903 if (IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram)) {
6904 ssl_CipherSpecReleaseByEpoch(ss, ssl_secret_read,
6905 TrafficKeyEarlyApplicationData);
6906 dtls_ReceivedFirstMessageInFlight(ss);
6907 }
6908
6909 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",6909))
;
6910
6911 if (length) {
6912 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", 6912); 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)
;
6913 return SECFailure;
6914 }
6915
6916 rv = tls13_SetCipherSpec(ss, TrafficKeyHandshake,
6917 ssl_secret_read, PR_FALSE0);
6918 if (rv != SECSuccess) {
6919 PORT_SetErrorPORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE);
6920 return SECFailure;
6921 }
6922
6923 ss->ssl3.hs.zeroRttState = ssl_0rtt_done;
6924 if (tls13_ShouldRequestClientAuth(ss)) {
6925 TLS13_SET_HS_STATE(ss, wait_client_cert)tls13_SetHsState(ss, wait_client_cert, __func__, "tls13con.c"
, 6925)
;
6926 } else {
6927 TLS13_SET_HS_STATE(ss, wait_finished)tls13_SetHsState(ss, wait_finished, __func__, "tls13con.c", 6927
)
;
6928 }
6929 return SECSuccess;
6930}
6931
6932static SECStatus
6933tls13_MaybeHandleSuppressedEndOfEarlyData(sslSocket *ss)
6934{
6935 PORT_Assert(ss->sec.isServer)((ss->sec.isServer)?((void)0):PR_Assert("ss->sec.isServer"
,"tls13con.c",6935))
;
6936 if (!ss->opt.suppressEndOfEarlyData ||
6937 ss->ssl3.hs.zeroRttState != ssl_0rtt_accepted) {
6938 return SECSuccess;
6939 }
6940
6941 return tls13_HandleEndOfEarlyData(ss, NULL((void*)0), 0);
6942}
6943
6944SECStatus
6945tls13_HandleEarlyApplicationData(sslSocket *ss, sslBuffer *origBuf)
6946{
6947 TLS13EarlyData *ed;
6948 SECItem it = { siBuffer, NULL((void*)0), 0 };
6949
6950 PORT_Assert(ss->sec.isServer)((ss->sec.isServer)?((void)0):PR_Assert("ss->sec.isServer"
,"tls13con.c",6950))
;
6951 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",6951))
;
6952 if (ss->ssl3.hs.zeroRttState != ssl_0rtt_accepted) {
6953 /* Belt and suspenders. */
6954 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"
, 6954); PORT_SetError_Util(SEC_ERROR_LIBRARY_FAILURE); } while
(0); tls13_FatalError(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error
); } while (0)
;
6955 return SECFailure;
6956 }
6957
6958 PRINT_BUF(3, (NULL, "Received early application data",if (ssl_trace >= (3)) ssl_PrintBuf (((void*)0), "Received early application data"
, origBuf->buf, origBuf->len)
6959 origBuf->buf, origBuf->len))if (ssl_trace >= (3)) ssl_PrintBuf (((void*)0), "Received early application data"
, origBuf->buf, origBuf->len)
;
6960 ed = PORT_ZNew(TLS13EarlyData)(TLS13EarlyData *)PORT_ZAlloc_Util(sizeof(TLS13EarlyData));
6961 if (!ed) {
6962 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"
, 6962); PORT_SetError_Util(SEC_ERROR_NO_MEMORY); } while (0)
; tls13_FatalError(ss, SEC_ERROR_NO_MEMORY, internal_error); }
while (0)
;
6963 return SECFailure;
6964 }
6965 it.data = origBuf->buf;
6966 it.len = origBuf->len;
6967 if (SECITEM_CopyItemSECITEM_CopyItem_Util(NULL((void*)0), &ed->data, &it) != SECSuccess) {
6968 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"
, 6968); PORT_SetError_Util(SEC_ERROR_NO_MEMORY); } while (0)
; tls13_FatalError(ss, SEC_ERROR_NO_MEMORY, internal_error); }
while (0)
;
6969 return SECFailure;
6970 }
6971 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)
;
6972
6973 origBuf->len = 0; /* So ssl3_GatherAppDataRecord will keep looping. */
6974
6975 return SECSuccess;
6976}
6977
6978PRUint16
6979tls13_EncodeVersion(SSL3ProtocolVersion version, SSLProtocolVariant variant)
6980{
6981 if (variant == ssl_variant_datagram) {
6982 return dtls_TLSVersionToDTLSVersion(version);
6983 }
6984 /* Stream-variant encodings do not change. */
6985 return (PRUint16)version;
6986}
6987
6988SECStatus
6989tls13_ClientReadSupportedVersion(sslSocket *ss)
6990{
6991 PRUint32 temp;
6992 TLSExtension *versionExtension;
6993 SECItem it;
6994 SECStatus rv;
6995
6996 /* Update the version based on the extension, as necessary. */
6997 versionExtension = ssl3_FindExtension(ss, ssl_tls13_supported_versions_xtn);
6998 if (!versionExtension) {
6999 return SECSuccess;
7000 }
7001
7002 /* Struct copy so we don't damage the extension. */
7003 it = versionExtension->data;
7004
7005 rv = ssl3_ConsumeHandshakeNumber(ss, &temp, 2, &it.data, &it.len);
7006 if (rv != SECSuccess) {
7007 return SECFailure;
7008 }
7009 if (it.len) {
7010 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", 7010); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_SERVER_HELLO
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_SERVER_HELLO
, illegal_parameter); } while (0)
;
7011 return SECFailure;
7012 }
7013
7014 if (temp != tls13_EncodeVersion(SSL_LIBRARY_VERSION_TLS_1_30x0304,
7015 ss->protocolVariant)) {
7016 /* You cannot negotiate < TLS 1.3 with supported_versions. */
7017 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", 7017); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_SERVER_HELLO
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_SERVER_HELLO
, illegal_parameter); } while (0)
;
7018 return SECFailure;
7019 }
7020
7021 /* Any endpoint receiving a Hello message with...ServerHello.legacy_version
7022 * set to 0x0300 (SSL3) MUST abort the handshake with a "protocol_version"
7023 * alert. [RFC8446, Section D.5]
7024 *
7025 * The ServerHello.legacy_version is read into the ss->version field by
7026 * ssl_ClientReadVersion(). */
7027 if (ss->version == SSL_LIBRARY_VERSION_3_00x0300) {
7028 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", 7028); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_SERVER_HELLO
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_SERVER_HELLO
, protocol_version); } while (0)
;
7029 return SECFailure;
7030 }
7031
7032 ss->version = SSL_LIBRARY_VERSION_TLS_1_30x0304;
7033 return SECSuccess;
7034}
7035
7036/* Pick the highest version we support that is also advertised. */
7037SECStatus
7038tls13_NegotiateVersion(sslSocket *ss, const TLSExtension *supportedVersions)
7039{
7040 PRUint16 version;
7041 /* Make a copy so we're nondestructive. */
7042 SECItem data = supportedVersions->data;
7043 SECItem versions;
7044 SECStatus rv;
7045
7046 rv = ssl3_ConsumeHandshakeVariable(ss, &versions, 1,
7047 &data.data, &data.len);
7048 if (rv != SECSuccess) {
7049 return SECFailure;
7050 }
7051 if (data.len || !versions.len || (versions.len & 1)) {
7052 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", 7052); PORT_SetError_Util(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO
); } while (0); tls13_FatalError(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO
, illegal_parameter); } while (0)
;
7053 return SECFailure;
7054 }
7055 for (version = ss->vrange.max; version >= ss->vrange.min; --version) {
7056 if (version < SSL_LIBRARY_VERSION_TLS_1_30x0304 &&
7057 (ss->ssl3.hs.helloRetry || ss->ssl3.hs.echAccepted)) {
7058 /* Prevent negotiating to a lower version after 1.3 HRR or ECH
7059 * When accepting ECH, a different alert is generated.
7060 */
7061 SSL3AlertDescription alert = ss->ssl3.hs.echAccepted ? illegal_parameter : protocol_version;
7062 PORT_SetErrorPORT_SetError_Util(SSL_ERROR_UNSUPPORTED_VERSION);
7063 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", 7063); PORT_SetError_Util(SSL_ERROR_UNSUPPORTED_VERSION
); } while (0); tls13_FatalError(ss, SSL_ERROR_UNSUPPORTED_VERSION
, alert); } while (0)
;
7064 return SECFailure;
7065 }
7066
7067 PRUint16 wire = tls13_EncodeVersion(version, ss->protocolVariant);
7068 unsigned long offset;
7069
7070 for (offset = 0; offset < versions.len; offset += 2) {
7071 PRUint16 supported =
7072 (versions.data[offset] << 8) | versions.data[offset + 1];
7073 if (supported == wire) {
7074 ss->version = version;
7075 return SECSuccess;
7076 }
7077 }
7078 }
7079
7080 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", 7080); PORT_SetError_Util(SSL_ERROR_UNSUPPORTED_VERSION
); } while (0); tls13_FatalError(ss, SSL_ERROR_UNSUPPORTED_VERSION
, protocol_version); } while (0)
;
7081 return SECFailure;
7082}
7083
7084/* This is TLS 1.3 or might negotiate to it. */
7085PRBool
7086tls13_MaybeTls13(sslSocket *ss)
7087{
7088 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_30x0304) {
7089 return PR_TRUE1;
7090 }
7091
7092 if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_30x0304) {
7093 return PR_FALSE0;
7094 }
7095
7096 if (!(ss->ssl3.hs.preliminaryInfo & ssl_preinfo_version(1U << 0))) {
7097 return PR_TRUE1;
7098 }
7099
7100 return PR_FALSE0;
7101}
7102
7103/* Setup random client GREASE values according to RFC8701. State must be kept
7104 * so an equal ClientHello might be send on HelloRetryRequest. */
7105SECStatus
7106tls13_ClientGreaseSetup(sslSocket *ss)
7107{
7108 if (!ss->opt.enableGrease) {
7109 return SECSuccess;
7110 }
7111
7112 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",7112))
;
7113
7114 if (ss->ssl3.hs.grease) {
7115 return SECFailure;
7116 }
7117 ss->ssl3.hs.grease = PORT_AllocPORT_Alloc_Util(sizeof(tls13ClientGrease));
7118 if (!ss->ssl3.hs.grease) {
7119 return SECFailure;
7120 }
7121
7122 tls13ClientGrease *grease = ss->ssl3.hs.grease;
7123 /* We require eight GREASE values and randoms. */
7124 PRUint8 random[8];
7125
7126 /* Generate random GREASE values. */
7127 if (PK11_GenerateRandom(random, sizeof(random)) != SECSuccess) {
7128 return SECFailure;
7129 }
7130 for (size_t i = 0; i < PR_ARRAY_SIZE(grease->idx)(sizeof(grease->idx)/sizeof((grease->idx)[0])); i++) {
7131 random[i] = ((random[i] & 0xf0) | 0x0a);
7132 grease->idx[i] = ((random[i] << 8) | random[i]);
7133 }
7134 /* Specific PskKeyExchangeMode GREASE value. */
7135 grease->pskKem = 0x0b + ((random[8 - 1] >> 5) * 0x1f);
7136
7137 /* Duplicate extensions are not allowed. */
7138 if (grease->idx[grease_extension1] == grease->idx[grease_extension2]) {
7139 grease->idx[grease_extension2] ^= 0x1010;
7140 }
7141
7142 return SECSuccess;
7143}
7144
7145/* Destroy client GREASE state. */
7146void
7147tls13_ClientGreaseDestroy(sslSocket *ss)
7148{
7149 if (ss->ssl3.hs.grease) {
7150 PORT_FreePORT_Free_Util(ss->ssl3.hs.grease);
7151 ss->ssl3.hs.grease = NULL((void*)0);
7152 }
7153}
7154
7155/* Generate a random GREASE value according to RFC8701.
7156 * This function does not provide valid PskKeyExchangeMode GREASE values! */
7157SECStatus
7158tls13_RandomGreaseValue(PRUint16 *out)
7159{
7160 PRUint8 random;
7161
7162 if (PK11_GenerateRandom(&random, sizeof(random)) != SECSuccess) {
7163 return SECFailure;
7164 }
7165
7166 random = ((random & 0xf0) | 0x0a);
7167 *out = ((random << 8) | random);
7168
7169 return SECSuccess;
7170}
7171
7172/* Set TLS 1.3 GREASE Extension random GREASE type. */
7173SECStatus
7174tls13_MaybeGreaseExtensionType(const sslSocket *ss,
7175 const SSLHandshakeType message,
7176 PRUint16 *exType)
7177{
7178 if (*exType != ssl_tls13_grease_xtn) {
7179 return SECSuccess;
7180 }
7181
7182 PR_ASSERT(ss->opt.enableGrease)((ss->opt.enableGrease)?((void)0):PR_Assert("ss->opt.enableGrease"
,"tls13con.c",7182))
;
7183 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",7184))
7184 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",7184))
;
7185
7186 /* GREASE ClientHello:
7187 * A client MAY select one or more GREASE extension values and
7188 * advertise them as extensions with varying length and contents
7189 * [RFC8701, Section 3.1]. */
7190 if (message == ssl_hs_client_hello) {
7191 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",7191))
;
7192 /* Check if the first GREASE extension was already added. */
7193 if (!ssl3_ExtensionAdvertised(ss, ss->ssl3.hs.grease->idx[grease_extension1])) {
7194 *exType = ss->ssl3.hs.grease->idx[grease_extension1];
7195 } else {
7196 *exType = ss->ssl3.hs.grease->idx[grease_extension2];
7197 }
7198 }
7199 /* GREASE CertificateRequest:
7200 * When sending a CertificateRequest in TLS 1.3, a server MAY behave as
7201 * follows: A server MAY select one or more GREASE extension values and
7202 * advertise them as extensions with varying length and contents
7203 * [RFC8701, Section 4.1]. */
7204 else if (message == ssl_hs_certificate_request) {
7205 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",7205))
;
7206 /* Get random grease extension type. */
7207 SECStatus rv = tls13_RandomGreaseValue(exType);
7208 if (rv != SECSuccess) {
7209 return SECFailure;
7210 }
7211 }
7212
7213 return SECSuccess;
7214}