Coverage Report

Created: 2026-11-12 06:38

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/wolfssl/src/tls13.c
Line
Count
Source
1
/* tls13.c
2
 *
3
 * Copyright (C) 2006-2026 wolfSSL Inc.
4
 *
5
 * This file is part of wolfSSL.
6
 *
7
 * wolfSSL is free software; you can redistribute it and/or modify
8
 * it under the terms of the GNU General Public License as published by
9
 * the Free Software Foundation; either version 3 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * wolfSSL is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License
18
 * along with this program; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
20
 */
21
22
#include <wolfssl/wolfcrypt/libwolfssl_sources.h>
23
24
/*
25
 * TLS 1.3-Specific Build Options:
26
 * (See tls.c for generic TLS options: extensions, curves, callbacks, etc.)
27
 *
28
 * Protocol:
29
 * WOLFSSL_TLS13:            Enable TLS 1.3 protocol               default: on
30
 * WOLFSSL_TLS13_DRAFT:      Enable TLS 1.3 draft version support  default: off
31
 * WOLFSSL_QUIC:             Enable QUIC protocol support (TLS 1.3) default: off
32
 * WOLFSSL_DTLS13_NO_HRR_ON_RESUME: Skip HRR on DTLS 1.3 resume   default: off
33
 * WOLFSSL_DTLS_CH_FRAG:     Enable DTLS 1.3 ClientHello frag     default: off
34
 *
35
 * Handshake:
36
 * WOLFSSL_TLS13_MIDDLEBOX_COMPAT: Client-side middlebox compatibility
37
 *                            default: off
38
 *                            Makes the client send a fake session id and its
39
 *                            own ChangeCipherSpec. The server always answers
40
 *                            a non-empty client session id with a
41
 *                            ChangeCipherSpec, as RFC 8446 Appendix D.4
42
 *                            requires, whether or not this is defined.
43
 * WOLFSSL_SEND_HRR_COOKIE:  Send cookie in HelloRetryRequest     default: off
44
 *                            for stateless ClientHello tracking. A client
45
 *                            always echoes back a cookie it is sent.
46
 * WOLFSSL_MAX_TLS13_COOKIE_SZ: Largest cookie a client accepts  default: 4096
47
 *                            in a HelloRetryRequest.
48
 * WOLFSSL_EARLY_DATA:       Allow 0-RTT early data                default: off
49
 * WOLFSSL_EARLY_DATA_GROUP: Group early data with ClientHello     default: off
50
 * WOLFSSL_POST_HANDSHAKE_AUTH: Post-handshake client auth         default: off
51
 * WOLFSSL_TLS13_TICKET_BEFORE_FINISHED: Send NewSessionTicket     default: off
52
 *                            before client Finished message. Violates the
53
 *                            RFC 8446 Section 4.6.1 ordering requirement; for
54
 *                            interop with peers that expect the early ticket.
55
 * WOLFSSL_DTLS13_ECHO_LEGACY_SESSION_ID: Echo legacy_session_id   default: off
56
 *                            in DTLS 1.3. Violates RFC 9147 Section 5 ("DTLS
57
 *                            servers MUST NOT echo the legacy_session_id
58
 *                            value from the client"). A server built with this
59
 *                            option echoes the session ID, which a compliant
60
 *                            client rejects, so enable it only where the peer
61
 *                            is wolfSSL <= 5.9.0 or shares this option.
62
 * WOLFSSL_NO_CLIENT_AUTH:   Disable TLS 1.3 client authentication default: off
63
 * WOLFSSL_NO_CLIENT_CERT_ERROR: TLS 1.3 client aborts the         default: off
64
 *                            handshake when the server requests a
65
 *                            certificate it cannot provide, instead of
66
 *                            sending an empty Certificate message
67
 * WOLFSSL_CERT_SETUP_CB:    Certificate setup callback            default: off
68
 * WOLFSSL_ALLOW_BAD_TLS_LEGACY_VERSION: Allow bad legacy version  default: off
69
 *
70
 * Security:
71
 * WOLFSSL_BLIND_PRIVATE_KEY: Blind private key during signing     default: off
72
 * WOLFSSL_CHECK_SIG_FAULTS: Verify signature after ECC signing    default: off
73
 *                            to detect fault injection attacks
74
 * WOLFSSL_CIPHER_TEXT_CHECK: Verify ciphertext integrity          default: off
75
 * WOLFSSL_TLS13_NULL_CIPHER_IN_DEFAULT: Include RFC 9150 suites   default: off
76
 *                            in the default cipher suite list (requires
77
 *                            HAVE_NULL_CIPHER). Without it the integrity-only
78
 *                            suites must be requested explicitly in the
79
 *                            cipher list, by name or with "eNULL".
80
 *
81
 * TLS 1.3 PSK:
82
 * WOLFSSL_PSK_ONE_ID:       Single PSK identity per connect       default: off
83
 * WOLFSSL_PSK_MULTI_ID_PER_CS: Multiple PSK IDs per cipher suite default: off
84
 * WOLFSSL_PRIORITIZE_PSK:   Prioritize PSK over ciphersuite order default: off
85
 *
86
 * TLS 1.3 Session Tickets:
87
 * WOLFSSL_TICKET_HAVE_ID:   Session tickets include ID            default: off
88
 *                            Forced on when WOLFSSL_EARLY_DATA is set.
89
 * WOLFSSL_TICKET_NONCE_MALLOC: Dynamically allocate ticket nonce  default: off
90
 * WOLFSSL_TLS13_TICKET_CHECK_PSK_MODES: Withhold NewSessionTicket default: off
91
 *                            when the ClientHello advertised no usable
92
 *                            psk_key_exchange_modes, as RFC 9846 Sections
93
 *                            4.3.9 and 4.7.1 require. Off by default: a peer
94
 *                            that omits the extension but expects a ticket
95
 *                            stops getting one.
96
 *
97
 * TLS 1.3 Key Exchange:
98
 * HAVE_KEYING_MATERIAL:     Export keying material (RFC 8446 7.5) default: off
99
 * WOLFSSL_HAVE_TLS_UNIQUE:  Enable tls-unique channel binding     default: off
100
 *
101
 * TLS 1.3 Hash/Signature:
102
 * WOLFSSL_TLS13_SHA512:     Allow SHA-512 in TLS 1.3 handshake   default: off
103
 *                            (no ciphersuite requires it currently)
104
 * WOLFSSL_ERROR_CODE_OPENSSL: Use OpenSSL-compatible error codes  default: off
105
 * WOLFSSL_SSLKEYLOGFILE_OUTPUT: Set key log output file path      default: off
106
 * WOLFSSL_SSLKEYLOGFILE_USE_ENV: Use SSLKEYLOGFILE env var path   default: off
107
 * WOLFSSL_RW_THREADED:      Enable read/write threading support   default: off
108
 * WOLFSSL_ASYNC_IO:         Enable async I/O operations           default: off
109
 * WOLFSSL_NONBLOCK_OCSP:    Non-blocking OCSP processing          default: off
110
 * WOLFSSL_TLS_OCSP_MULTI:   Multiple OCSP responses               default: off
111
 * WOLFSSL_WOLFSENTRY_HOOKS: wolfSentry integration hooks          default: off
112
 */
113
114
#if !defined(NO_TLS) && defined(WOLFSSL_TLS13)
115
116
/* 0-RTT anti-replay eviction needs the session cache. */
117
#if defined(WOLFSSL_EARLY_DATA) && defined(HAVE_SESSION_TICKET) && \
118
    defined(NO_SESSION_CACHE) && !defined(NO_WOLFSSL_SERVER) && \
119
    !defined(WOLFSSL_EARLY_DATA_NO_ANTI_REPLAY)
120
#error "WOLFSSL_EARLY_DATA with tickets requires !NO_SESSION_CACHE, or " \
121
       "define WOLFSSL_EARLY_DATA_NO_ANTI_REPLAY to opt out."
122
#endif
123
124
#ifndef WOLFCRYPT_ONLY
125
126
#ifdef HAVE_ERRNO_H
127
    #include <errno.h>
128
#endif
129
130
#if defined(__MACH__) || defined(__FreeBSD__) || \
131
    defined(__INCLUDE_NUTTX_CONFIG_H) || defined(WOLFSSL_RIOT_OS)
132
#include <sys/time.h>
133
#endif /* __MACH__ || __FreeBSD__ ||
134
          __INCLUDE_NUTTX_CONFIG_H || WOLFSSL_RIOT_OS */
135
136
137
#include <wolfssl/internal.h>
138
#include <wolfssl/error-ssl.h>
139
#include <wolfssl/wolfcrypt/asn.h>
140
#include <wolfssl/wolfcrypt/dh.h>
141
#include <wolfssl/wolfcrypt/kdf.h>
142
#include <wolfssl/wolfcrypt/signature.h>
143
#ifdef NO_INLINE
144
    #include <wolfssl/wolfcrypt/misc.h>
145
#else
146
    #define WOLFSSL_MISC_INCLUDED
147
    #include <wolfcrypt/src/misc.c>
148
#endif
149
150
#ifdef __sun
151
    #include <sys/filio.h>
152
#endif
153
154
#ifndef TRUE
155
    #define TRUE  1
156
#endif
157
#ifndef FALSE
158
    #define FALSE 0
159
#endif
160
161
#ifndef HAVE_AEAD
162
    #if !defined(_MSC_VER) && !defined(__TASKING__)
163
        #error "The build option HAVE_AEAD is required for TLS 1.3"
164
    #else
165
        #pragma \
166
        message("error: The build option HAVE_AEAD is required for TLS 1.3")
167
    #endif
168
#endif
169
170
#ifndef HAVE_HKDF
171
    #if !defined(_MSC_VER) && !defined(__TASKING__)
172
        #error "The build option HAVE_HKDF is required for TLS 1.3"
173
    #else
174
        #pragma message("error: The build option HAVE_HKDF is required for TLS 1.3")
175
    #endif
176
#endif
177
178
#ifndef HAVE_TLS_EXTENSIONS
179
    #if !defined(_MSC_VER) && !defined(__TASKING__)
180
        #error "The build option HAVE_TLS_EXTENSIONS is required for TLS 1.3"
181
    #else
182
        #pragma message("error: The build option HAVE_TLS_EXTENSIONS is required for TLS 1.3")
183
    #endif
184
#endif
185
186
187
/* Set ret to error value and jump to label.
188
 *
189
 * err     The error value to set.
190
 * eLabel  The label to jump to.
191
 */
192
0
#define ERROR_OUT(err, eLabel) { ret = (err); goto eLabel; }
193
194
/* Senders suspend/resume a pending record build only on the re-invoke path;
195
 * poll-completing backends block inside EncryptTls13() as before. */
196
#if defined(WOLFSSL_ASYNC_REINVOKE) && !defined(WOLF_CRYPTO_CB_ASYNC_POLL)
197
    #define TLS13_HS_ASYNC_OKAY 1
198
#else
199
0
    #define TLS13_HS_ASYNC_OKAY 0
200
#endif
201
202
#ifdef WOLFSSL_ASYNC_REINVOKE
203
/* Arm ssl->kdfAsyncDev for a key-schedule op that may pend, retiring this
204
 * connection's previous KDF event first (re-pushing a queued event would
205
 * self-link the event list). Returns 0 on success. */
206
static int Tls13KdfAsyncInit(WOLFSSL* ssl)
207
{
208
    int ret;
209
210
    if (ssl->asyncDev == &ssl->kdfAsyncDev) {
211
        ret = wolfSSL_AsyncPop(ssl, NULL);
212
        if (ret != 0 && ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E) &&
213
                ret != WC_NO_ERR_TRACE(WC_PENDING_E)) {
214
            return ret;
215
        }
216
    }
217
218
#if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_ASYNC_POLL)
219
    /* Never poll-routed: a zeroed cryptocbDevId would look poll-stamped to
220
     * wolfSSL_AsyncPop() and stop the resume state advancing. */
221
    ssl->kdfAsyncDev.cryptocbDevId = INVALID_DEVID;
222
#endif
223
    return wolfSSL_AsyncInit(ssl, &ssl->kdfAsyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
224
}
225
226
#endif /* WOLFSSL_ASYNC_REINVOKE */
227
228
#ifdef WOLFSSL_ASYNC_CRYPT
229
/* Pop the pending operation of a ClientHello or ServerHello. An X25519 shared
230
 * secret that completed asynchronously reports an all-zero result as
231
 * ECC_OUT_OF_RANGE_E without passing the conversion in
232
 * TLSX_KeyShare_ProcessX25519_ex(), so convert it here to send the same
233
 * illegal_parameter alert. */
234
static int Tls13HelloAsyncPop(WOLFSSL* ssl, byte* state)
235
{
236
#ifdef HAVE_CURVE25519
237
    /* Read before the pop, which clears ssl->asyncDev. */
238
    int x25519 = (ssl->asyncDev != NULL) &&
239
        (ssl->asyncDev->marker == WOLFSSL_ASYNC_MARKER_X25519);
240
#endif
241
    int ret = wolfSSL_AsyncPop(ssl, state);
242
243
#ifdef HAVE_CURVE25519
244
    if (x25519 && (ret == WC_NO_ERR_TRACE(ECC_OUT_OF_RANGE_E))) {
245
        ret = ECC_PEERKEY_ERROR;
246
        WOLFSSL_ERROR_VERBOSE(ret);
247
    }
248
#endif
249
    return ret;
250
}
251
#endif /* WOLFSSL_ASYNC_CRYPT */
252
253
/* Cap on re-invoking a callback for a record the caller cannot resume
254
 * (alerts, asyncOkay = 0 senders); bounds the otherwise unbounded spin. */
255
#ifndef WOLFSSL_ASYNC_MAX_REINVOKE
256
#define WOLFSSL_ASYNC_MAX_REINVOKE 1000
257
#endif
258
259
/* Size of the TLS v1.3 label use when deriving keys. */
260
0
#define TLS13_PROTOCOL_LABEL_SZ    6
261
/* The protocol label for TLS v1.3. */
262
static const byte tls13ProtocolLabel[TLS13_PROTOCOL_LABEL_SZ + 1] = "tls13 ";
263
264
#ifdef WOLFSSL_DTLS13
265
#define DTLS13_PROTOCOL_LABEL_SZ    6
266
static const byte dtls13ProtocolLabel[DTLS13_PROTOCOL_LABEL_SZ + 1] = "dtls13";
267
#endif /* WOLFSSL_DTLS13 */
268
269
#if defined(HAVE_ECH)
270
#define ECH_ACCEPT_CONFIRMATION_LABEL_SZ 23
271
#define ECH_HRR_ACCEPT_CONFIRMATION_LABEL_SZ 27
272
static const byte
273
    echAcceptConfirmationLabel[ECH_ACCEPT_CONFIRMATION_LABEL_SZ + 1] =
274
    "ech accept confirmation";
275
static const byte
276
    echHrrAcceptConfirmationLabel[ECH_HRR_ACCEPT_CONFIRMATION_LABEL_SZ + 1] =
277
    "hrr ech accept confirmation";
278
#endif
279
280
#ifndef NO_CERTS
281
#if !defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
282
    defined(HAVE_ED448) || defined(HAVE_FALCON) || defined(WOLFSSL_HAVE_MLDSA) || \
283
    defined(WOLFSSL_HAVE_SLHDSA)
284
285
static WC_INLINE int GetMsgHash(WOLFSSL* ssl, byte* hash);
286
287
#endif
288
#endif
289
290
/* Expand data using HMAC, salt and label and info.
291
 * TLS v1.3 defines this function. Use callback if available. */
292
static int Tls13HKDFExpandLabel(WOLFSSL* ssl, byte* okm, word32 okmLen,
293
                                const byte* prk, word32 prkLen,
294
                                const byte* protocol, word32 protocolLen,
295
                                const byte* label, word32 labelLen,
296
                                const byte* info, word32 infoLen,
297
                                int digest)
298
0
{
299
0
    int ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN);
300
#ifdef WOLFSSL_ASYNC_REINVOKE
301
    int aret;
302
303
    /* Armed before the provider runs so a pending from the PK callback or
304
     * wolfCrypt path falls through to the single push below. */
305
    aret = Tls13KdfAsyncInit(ssl);
306
    if (aret != 0)
307
        return aret;
308
#endif
309
310
#if defined(HAVE_PK_CALLBACKS)
311
    if (ssl->ctx && ssl->ctx->HKDFExpandLabelCb) {
312
        ret = ssl->ctx->HKDFExpandLabelCb(okm, okmLen, prk, prkLen,
313
                                          protocol, protocolLen,
314
                                          label, labelLen,
315
                                          info, infoLen, digest,
316
                                          WOLFSSL_CLIENT_END /* ignored */);
317
    }
318
319
    if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN))
320
#endif
321
0
    {
322
0
    PRIVATE_KEY_UNLOCK();
323
0
#if !defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(6,0))
324
0
    ret = wc_Tls13_HKDF_Expand_Label_ex(okm, okmLen, prk, prkLen,
325
0
                                     protocol, protocolLen,
326
0
                                     label, labelLen,
327
0
                                     info, infoLen, digest,
328
0
                                     ssl->heap, ssl->devId);
329
#else
330
    (void)ssl;
331
    ret = wc_Tls13_HKDF_Expand_Label(okm, okmLen, prk, prkLen,
332
                                     protocol, protocolLen,
333
                                     label, labelLen,
334
                                     info, infoLen, digest);
335
#endif
336
0
    PRIVATE_KEY_LOCK();
337
0
    }
338
#ifdef WOLFSSL_ASYNC_REINVOKE
339
    /* HKDF has no key object to carry a WC_ASYNC_DEV, so queue the
340
     * SSL-owned KDF device; without it the pop finds nothing pending and
341
     * replays the handshake message. CALL_AGAIN keeps the state put. */
342
    if (ret == WC_NO_ERR_TRACE(WC_PENDING_E))
343
        ret = wolfSSL_AsyncPush(ssl, &ssl->kdfAsyncDev);
344
#endif
345
0
    return ret;
346
0
}
347
348
/* Same as above, but pass in the side we are expanding for:
349
 * side: either WOLFSSL_CLIENT_END or WOLFSSL_SERVER_END.
350
 */
351
static int Tls13HKDFExpandKeyLabel(WOLFSSL* ssl, byte* okm, word32 okmLen,
352
                                   const byte* prk, word32 prkLen,
353
                                   const byte* protocol, word32 protocolLen,
354
                                   const byte* label, word32 labelLen,
355
                                   const byte* info, word32 infoLen,
356
                                   int digest, int side)
357
0
{
358
0
    int ret;
359
#ifdef WOLFSSL_ASYNC_REINVOKE
360
    ret = Tls13KdfAsyncInit(ssl);
361
    if (ret != 0)
362
        return ret;
363
#endif
364
365
#if defined(HAVE_PK_CALLBACKS)
366
    ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN);
367
    if (ssl->ctx && ssl->ctx->HKDFExpandLabelCb) {
368
        ret = ssl->ctx->HKDFExpandLabelCb(okm, okmLen, prk, prkLen,
369
                                         protocol, protocolLen,
370
                                         label, labelLen,
371
                                         info, infoLen,
372
                                         digest, side);
373
    }
374
    /* No early return: a pending here must reach the push at the end. */
375
    if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN))
376
#endif
377
0
    {
378
379
0
#if !defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(6,0))
380
0
    ret = wc_Tls13_HKDF_Expand_Label_ex(okm, okmLen, prk, prkLen,
381
0
                                      protocol, protocolLen,
382
0
                                      label, labelLen,
383
0
                                      info, infoLen, digest,
384
0
                                      ssl->heap, ssl->devId);
385
386
#elif defined(HAVE_FIPS) && defined(wc_Tls13_HKDF_Expand_Label)
387
    ret = wc_Tls13_HKDF_Expand_Label_fips(okm, okmLen, prk, prkLen,
388
                                      protocol, protocolLen,
389
                                      label, labelLen,
390
                                      info, infoLen, digest);
391
#else
392
    ret = wc_Tls13_HKDF_Expand_Label(okm, okmLen, prk, prkLen,
393
                                      protocol, protocolLen,
394
                                      label, labelLen,
395
                                      info, infoLen, digest);
396
#endif
397
0
    }
398
#ifdef WOLFSSL_ASYNC_REINVOKE
399
    /* HKDF has no key object to carry a WC_ASYNC_DEV, so queue the
400
     * SSL-owned KDF device; without it the pop finds nothing pending and
401
     * replays the handshake message. CALL_AGAIN keeps the state put. */
402
    if (ret == WC_NO_ERR_TRACE(WC_PENDING_E))
403
        ret = wolfSSL_AsyncPush(ssl, &ssl->kdfAsyncDev);
404
#endif
405
0
    (void)ssl;
406
0
    (void)side;
407
0
    return ret;
408
0
}
409
410
411
/* Derive a key from a message.
412
 *
413
 * ssl        The SSL/TLS object.
414
 * output     The buffer to hold the derived key.
415
 * outputLen  The length of the derived key.
416
 * secret     The secret used to derive the key (HMAC secret).
417
 * label      The label used to distinguish the context.
418
 * labelLen   The length of the label.
419
 * msg        The message data to derive key from.
420
 * msgLen     The length of the message data to derive key from.
421
 * hashAlgo   The hash algorithm to use in the HMAC.
422
 * returns 0 on success, otherwise failure.
423
 */
424
static int DeriveKeyMsg(WOLFSSL* ssl, byte* output, int outputLen,
425
                        const byte* secret, const byte* label, word32 labelLen,
426
                        byte* msg, int msgLen, int hashAlgo)
427
0
{
428
0
    byte        hash[WC_MAX_DIGEST_SIZE];
429
0
    Digest      digest;
430
0
    word32      hashSz = 0;
431
0
    const byte* protocol;
432
0
    word32      protocolLen;
433
0
    int         digestAlg = -1;
434
0
    int         ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG);
435
436
0
    switch (hashAlgo) {
437
0
#ifndef NO_SHA256
438
0
        case sha256_mac:
439
0
            ret = wc_InitSha256_ex(&digest.sha256, ssl->heap, ssl->devId);
440
0
            if (ret == 0) {
441
0
                    ret = wc_Sha256Update(&digest.sha256, msg, (word32)msgLen);
442
0
                if (ret == 0)
443
0
                    ret = wc_Sha256Final(&digest.sha256, hash);
444
0
                wc_Sha256Free(&digest.sha256);
445
0
            }
446
0
            hashSz = WC_SHA256_DIGEST_SIZE;
447
0
            digestAlg = WC_SHA256;
448
0
            break;
449
0
#endif
450
0
#ifdef WOLFSSL_SHA384
451
0
        case sha384_mac:
452
0
            ret = wc_InitSha384_ex(&digest.sha384, ssl->heap, ssl->devId);
453
0
            if (ret == 0) {
454
0
                ret = wc_Sha384Update(&digest.sha384, msg, (word32)msgLen);
455
0
                if (ret == 0)
456
0
                    ret = wc_Sha384Final(&digest.sha384, hash);
457
0
                wc_Sha384Free(&digest.sha384);
458
0
            }
459
0
            hashSz = WC_SHA384_DIGEST_SIZE;
460
0
            digestAlg = WC_SHA384;
461
0
            break;
462
0
#endif
463
#ifdef WOLFSSL_TLS13_SHA512
464
        case sha512_mac:
465
            ret = wc_InitSha512_ex(&digest.sha512, ssl->heap, ssl->devId);
466
            if (ret == 0) {
467
                ret = wc_Sha512Update(&digest.sha512, msg, (word32)msgLen);
468
                if (ret == 0)
469
                    ret = wc_Sha512Final(&digest.sha512, hash);
470
                wc_Sha512Free(&digest.sha512);
471
            }
472
            hashSz = WC_SHA512_DIGEST_SIZE;
473
            digestAlg = WC_SHA512;
474
            break;
475
#endif
476
#ifdef WOLFSSL_SM3
477
        case sm3_mac:
478
            ret = wc_InitSm3(&digest.sm3, ssl->heap, ssl->devId);
479
            if (ret == 0) {
480
                ret = wc_Sm3Update(&digest.sm3, msg, (word32)msgLen);
481
                if (ret == 0)
482
                    ret = wc_Sm3Final(&digest.sm3, hash);
483
                wc_Sm3Free(&digest.sm3);
484
            }
485
            hashSz = WC_SM3_DIGEST_SIZE;
486
            digestAlg = WC_SM3;
487
            break;
488
#endif
489
0
        default:
490
0
            ret = BAD_FUNC_ARG;
491
0
            digestAlg = -1;
492
0
            break;
493
0
    }
494
495
0
    if (digestAlg < 0)
496
0
        return HASH_TYPE_E;
497
498
0
    if (ret != 0)
499
0
        return ret;
500
501
0
    switch (ssl->version.minor) {
502
0
        case TLSv1_3_MINOR:
503
0
            protocol = tls13ProtocolLabel;
504
0
            protocolLen = TLS13_PROTOCOL_LABEL_SZ;
505
0
            break;
506
#ifdef WOLFSSL_DTLS13
507
        case DTLSv1_3_MINOR:
508
            if (!ssl->options.dtls)
509
                return VERSION_ERROR;
510
511
            protocol = dtls13ProtocolLabel;
512
            protocolLen = DTLS13_PROTOCOL_LABEL_SZ;
513
            break;
514
#endif /* WOLFSSL_DTLS13 */
515
0
        default:
516
0
            return VERSION_ERROR;
517
0
    }
518
0
    if (outputLen == -1)
519
0
        outputLen = (int)hashSz;
520
521
0
    ret = Tls13HKDFExpandLabel(ssl, output, (word32)outputLen, secret, hashSz,
522
0
                               protocol, protocolLen, label, labelLen,
523
0
                               hash, hashSz, digestAlg);
524
0
    return ret;
525
0
}
526
527
/* Derive a key.
528
 *
529
 * ssl          The SSL/TLS object.
530
 * output       The buffer to hold the derived key.
531
 * outputLen    The length of the derived key.
532
 * secret       The secret used to derive the key (HMAC secret).
533
 * label        The label used to distinguish the context.
534
 * labelLen     The length of the label.
535
 * hashAlgo     The hash algorithm to use in the HMAC.
536
 * includeMsgs  Whether to include a hash of the handshake messages so far.
537
 * side         The side that we are deriving the secret for.
538
 * returns 0 on success, otherwise failure.
539
 */
540
int Tls13DeriveKey(WOLFSSL* ssl, byte* output, int outputLen,
541
                   const byte* secret, const byte* label, word32 labelLen,
542
                   int hashAlgo, int includeMsgs, int side)
543
0
{
544
0
    int         ret = 0;
545
0
    byte        hash[WC_MAX_DIGEST_SIZE];
546
0
    word32      hashSz = 0;
547
0
    word32      hashOutSz = 0;
548
0
    const byte* protocol;
549
0
    word32      protocolLen;
550
0
    int         digestAlg = 0;
551
552
553
0
    switch (hashAlgo) {
554
0
    #ifndef NO_SHA256
555
0
        case sha256_mac:
556
0
            hashSz    = WC_SHA256_DIGEST_SIZE;
557
0
            digestAlg = WC_SHA256;
558
0
            if (includeMsgs)
559
0
                ret = wc_Sha256GetHash(&ssl->hsHashes->hashSha256, hash);
560
0
            break;
561
0
    #endif
562
563
0
    #ifdef WOLFSSL_SHA384
564
0
        case sha384_mac:
565
0
            hashSz    = WC_SHA384_DIGEST_SIZE;
566
0
            digestAlg = WC_SHA384;
567
0
            if (includeMsgs)
568
0
                ret = wc_Sha384GetHash(&ssl->hsHashes->hashSha384, hash);
569
0
            break;
570
0
    #endif
571
572
    #ifdef WOLFSSL_TLS13_SHA512
573
        case sha512_mac:
574
            hashSz    = WC_SHA512_DIGEST_SIZE;
575
            digestAlg = WC_SHA512;
576
            if (includeMsgs)
577
                ret = wc_Sha512GetHash(&ssl->hsHashes->hashSha512, hash);
578
            break;
579
    #endif
580
581
    #ifdef WOLFSSL_SM3
582
        case sm3_mac:
583
            hashSz    = WC_SM3_DIGEST_SIZE;
584
            digestAlg = WC_SM3;
585
            if (includeMsgs)
586
                ret = wc_Sm3GetHash(&ssl->hsHashes->hashSm3, hash);
587
            break;
588
    #endif
589
590
0
        default:
591
0
            ret = HASH_TYPE_E;
592
0
            break;
593
0
    }
594
0
    if (ret != 0)
595
0
        return ret;
596
597
0
    protocol = tls13ProtocolLabel;
598
0
    protocolLen = TLS13_PROTOCOL_LABEL_SZ;
599
600
#ifdef WOLFSSL_DTLS13
601
    if (ssl->options.dtls) {
602
         protocol = dtls13ProtocolLabel;
603
         protocolLen = DTLS13_PROTOCOL_LABEL_SZ;
604
    }
605
#endif /* WOLFSSL_DTLS13 */
606
607
0
    if (outputLen == -1) {
608
0
        outputLen = (int)hashSz;
609
0
    }
610
0
    if (includeMsgs) {
611
0
        hashOutSz = hashSz;
612
0
    }
613
0
    else {
614
        /* Appease static analyzers by making sure hash is cleared, since it is
615
         * passed into expand key label where older wc_Tls13_HKDF_Expand_Label
616
         * will unconditionally try to call a memcpy on it, however length will
617
         * always be 0. */
618
0
        XMEMSET(hash, 0, sizeof(hash));
619
0
        hashOutSz = 0;
620
0
    }
621
622
0
    PRIVATE_KEY_UNLOCK();
623
0
    ret = Tls13HKDFExpandKeyLabel(ssl, output, (word32)outputLen, secret, hashSz,
624
0
                                  protocol, protocolLen, label, labelLen,
625
0
                                  hash, hashOutSz, digestAlg, side);
626
0
    PRIVATE_KEY_LOCK();
627
628
#ifdef WOLFSSL_CHECK_MEM_ZERO
629
    wc_MemZero_Add("TLS 1.3 derived key", output, outputLen);
630
#endif
631
0
    return ret;
632
0
}
633
634
/* Convert TLS mac ID to a hash algorithm ID
635
 *
636
 * mac Mac ID to convert
637
 * returns hash ID on success, or the NONE type.
638
 */
639
static WC_INLINE int mac2hash(int mac)
640
0
{
641
0
    int hash;
642
0
    switch (mac) {
643
0
        #ifndef NO_SHA256
644
0
        case sha256_mac:
645
0
            hash = WC_SHA256;
646
0
            break;
647
0
        #endif
648
649
0
        #ifdef WOLFSSL_SHA384
650
0
        case sha384_mac:
651
0
            hash = WC_SHA384;
652
0
            break;
653
0
        #endif
654
655
        #ifdef WOLFSSL_TLS13_SHA512
656
        case sha512_mac:
657
            hash = WC_SHA512;
658
            break;
659
        #endif
660
661
        #ifdef WOLFSSL_SM3
662
        case sm3_mac:
663
            hash = WC_SM3;
664
            break;
665
        #endif
666
667
0
    default:
668
0
        hash = WC_HASH_TYPE_NONE;
669
0
    }
670
0
    return hash;
671
0
}
672
673
#ifndef NO_PSK
674
/* The length of the binder key label. */
675
#define BINDER_KEY_LABEL_SZ         10
676
/* The binder key label. */
677
static const byte binderKeyLabel[BINDER_KEY_LABEL_SZ + 1] =
678
    "ext binder";
679
680
/* Derive the binder key.
681
 *
682
 * ssl  The SSL/TLS object.
683
 * key  The derived key.
684
 * returns 0 on success, otherwise failure.
685
 */
686
static int DeriveBinderKey(WOLFSSL* ssl, byte* key)
687
{
688
    WOLFSSL_MSG("Derive Binder Key");
689
    if (ssl == NULL || ssl->arrays == NULL) {
690
        return BAD_FUNC_ARG;
691
    }
692
    return DeriveKeyMsg(ssl, key, -1, ssl->arrays->secret,
693
                        binderKeyLabel, BINDER_KEY_LABEL_SZ,
694
                        NULL, 0, ssl->specs.mac_algorithm);
695
}
696
#endif /* !NO_PSK */
697
698
#if defined(HAVE_SESSION_TICKET) && \
699
    (!defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER))
700
/* The length of the binder key resume label. */
701
#define BINDER_KEY_RESUME_LABEL_SZ  10
702
/* The binder key resume label. */
703
static const byte binderKeyResumeLabel[BINDER_KEY_RESUME_LABEL_SZ + 1] =
704
    "res binder";
705
706
/* Derive the binder resumption key.
707
 *
708
 * ssl  The SSL/TLS object.
709
 * key  The derived key.
710
 * returns 0 on success, otherwise failure.
711
 */
712
static int DeriveBinderKeyResume(WOLFSSL* ssl, byte* key)
713
{
714
    WOLFSSL_MSG("Derive Binder Key - Resumption");
715
    if (ssl == NULL || ssl->arrays == NULL) {
716
        return BAD_FUNC_ARG;
717
    }
718
    return DeriveKeyMsg(ssl, key, -1, ssl->arrays->secret,
719
                        binderKeyResumeLabel, BINDER_KEY_RESUME_LABEL_SZ,
720
                        NULL, 0, ssl->specs.mac_algorithm);
721
}
722
#endif /* HAVE_SESSION_TICKET && (!NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER) */
723
724
#ifdef WOLFSSL_EARLY_DATA
725
726
/* The length of the early traffic label. */
727
#define EARLY_TRAFFIC_LABEL_SZ      11
728
/* The early traffic label. */
729
static const byte earlyTrafficLabel[EARLY_TRAFFIC_LABEL_SZ + 1] =
730
    "c e traffic";
731
732
/* Derive the early traffic key.
733
 *
734
 * ssl  The SSL/TLS object.
735
 * key  The derived key.
736
 * side The side that we are deriving the secret for.
737
 * returns 0 on success, otherwise failure.
738
 */
739
static int DeriveEarlyTrafficSecret(WOLFSSL* ssl, byte* key, int side)
740
{
741
    int ret;
742
    WOLFSSL_MSG("Derive Early Traffic Secret");
743
    if (ssl == NULL || ssl->arrays == NULL) {
744
        return BAD_FUNC_ARG;
745
    }
746
747
#if defined(WOLFSSL_SNIFFER) && defined(WOLFSSL_SNIFFER_KEYLOGFILE)
748
    /* If this is called from a sniffer session with keylog file support,
749
     * obtain the appropriate secret from the callback */
750
    if (ssl->snifferSecretCb != NULL) {
751
        return ssl->snifferSecretCb(ssl->arrays->clientRandom,
752
                                    SNIFFER_SECRET_CLIENT_EARLY_TRAFFIC_SECRET,
753
                                    key);
754
    }
755
#endif /* WOLFSSL_SNIFFER && WOLFSSL_SNIFFER_KEYLOGFILE */
756
757
    ret = Tls13DeriveKey(ssl, key, -1, ssl->arrays->secret,
758
                    earlyTrafficLabel, EARLY_TRAFFIC_LABEL_SZ,
759
                    ssl->specs.mac_algorithm, 1, side);
760
#ifdef HAVE_SECRET_CALLBACK
761
    if (ret == 0 && ssl->tls13SecretCb != NULL) {
762
        ret = ssl->tls13SecretCb(ssl, CLIENT_EARLY_TRAFFIC_SECRET, key,
763
                                 ssl->specs.hash_size, ssl->tls13SecretCtx);
764
        if (ret != 0) {
765
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
766
            return TLS13_SECRET_CB_E;
767
        }
768
    }
769
#ifdef OPENSSL_EXTRA
770
    if (ret == 0 && ssl->tls13KeyLogCb != NULL) {
771
        ret = ssl->tls13KeyLogCb(ssl, CLIENT_EARLY_TRAFFIC_SECRET, key,
772
                                ssl->specs.hash_size, NULL);
773
        if (ret != 0) {
774
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
775
            return TLS13_SECRET_CB_E;
776
        }
777
    }
778
#endif /* OPENSSL_EXTRA */
779
#endif /* HAVE_SECRET_CALLBACK */
780
    return ret;
781
}
782
783
#endif
784
785
/* The length of the client handshake label. */
786
0
#define CLIENT_HANDSHAKE_LABEL_SZ   12
787
/* The client handshake label. */
788
static const byte clientHandshakeLabel[CLIENT_HANDSHAKE_LABEL_SZ + 1] =
789
    "c hs traffic";
790
791
/* Derive the client handshake key.
792
 *
793
 * ssl  The SSL/TLS object.
794
 * key  The derived key.
795
 * returns 0 on success, otherwise failure.
796
 */
797
static int DeriveClientHandshakeSecret(WOLFSSL* ssl, byte* key)
798
0
{
799
0
    int ret;
800
0
    WOLFSSL_MSG("Derive Client Handshake Secret");
801
0
    if (ssl == NULL || ssl->arrays == NULL) {
802
0
        return BAD_FUNC_ARG;
803
0
    }
804
805
#if defined(WOLFSSL_SNIFFER) && defined(WOLFSSL_SNIFFER_KEYLOGFILE)
806
    /* If this is called from a sniffer session with keylog file support,
807
     * obtain the appropriate secret from the callback */
808
    if (ssl->snifferSecretCb != NULL) {
809
        return ssl->snifferSecretCb(ssl->arrays->clientRandom,
810
                               SNIFFER_SECRET_CLIENT_HANDSHAKE_TRAFFIC_SECRET,
811
                               key);
812
    }
813
#endif /* WOLFSSL_SNIFFER && WOLFSSL_SNIFFER_KEYLOGFILE */
814
815
0
    ret = Tls13DeriveKey(ssl, key, -1, ssl->arrays->preMasterSecret,
816
0
                    clientHandshakeLabel, CLIENT_HANDSHAKE_LABEL_SZ,
817
0
                    ssl->specs.mac_algorithm, 1, WOLFSSL_CLIENT_END);
818
#ifdef HAVE_SECRET_CALLBACK
819
    if (ret == 0 && ssl->tls13SecretCb != NULL) {
820
        ret = ssl->tls13SecretCb(ssl, CLIENT_HANDSHAKE_TRAFFIC_SECRET, key,
821
                                 ssl->specs.hash_size, ssl->tls13SecretCtx);
822
        if (ret != 0) {
823
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
824
            return TLS13_SECRET_CB_E;
825
        }
826
    }
827
#ifdef OPENSSL_EXTRA
828
    if (ret == 0 && ssl->tls13KeyLogCb != NULL) {
829
        ret = ssl->tls13KeyLogCb(ssl, CLIENT_HANDSHAKE_TRAFFIC_SECRET, key,
830
                                ssl->specs.hash_size, NULL);
831
        if (ret != 0) {
832
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
833
            return TLS13_SECRET_CB_E;
834
        }
835
    }
836
#endif /* OPENSSL_EXTRA */
837
#endif /* HAVE_SECRET_CALLBACK */
838
0
    return ret;
839
0
}
840
841
/* The length of the server handshake label. */
842
0
#define SERVER_HANDSHAKE_LABEL_SZ   12
843
/* The server handshake label. */
844
static const byte serverHandshakeLabel[SERVER_HANDSHAKE_LABEL_SZ + 1] =
845
    "s hs traffic";
846
847
/* Derive the server handshake key.
848
 *
849
 * ssl  The SSL/TLS object.
850
 * key  The derived key.
851
 * returns 0 on success, otherwise failure.
852
 */
853
static int DeriveServerHandshakeSecret(WOLFSSL* ssl, byte* key)
854
0
{
855
0
    int ret;
856
0
    WOLFSSL_MSG("Derive Server Handshake Secret");
857
0
    if (ssl == NULL || ssl->arrays == NULL) {
858
0
        return BAD_FUNC_ARG;
859
0
    }
860
861
#if defined(WOLFSSL_SNIFFER) && defined(WOLFSSL_SNIFFER_KEYLOGFILE)
862
    /* If this is called from a sniffer session with keylog file support,
863
     * obtain the appropriate secret from the callback */
864
    if (ssl->snifferSecretCb != NULL) {
865
        return ssl->snifferSecretCb(ssl->arrays->clientRandom,
866
                                SNIFFER_SECRET_SERVER_HANDSHAKE_TRAFFIC_SECRET,
867
                                key);
868
    }
869
#endif /* WOLFSSL_SNIFFER && WOLFSSL_SNIFFER_KEYLOGFILE */
870
871
0
    ret = Tls13DeriveKey(ssl, key, -1, ssl->arrays->preMasterSecret,
872
0
                    serverHandshakeLabel, SERVER_HANDSHAKE_LABEL_SZ,
873
0
                    ssl->specs.mac_algorithm, 1, WOLFSSL_SERVER_END);
874
875
#ifdef HAVE_SECRET_CALLBACK
876
    if (ret == 0 && ssl->tls13SecretCb != NULL) {
877
        ret = ssl->tls13SecretCb(ssl, SERVER_HANDSHAKE_TRAFFIC_SECRET, key,
878
                                 ssl->specs.hash_size, ssl->tls13SecretCtx);
879
        if (ret != 0) {
880
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
881
            return TLS13_SECRET_CB_E;
882
        }
883
    }
884
#ifdef OPENSSL_EXTRA
885
    if (ret == 0 && ssl->tls13KeyLogCb != NULL) {
886
        ret = ssl->tls13KeyLogCb(ssl, SERVER_HANDSHAKE_TRAFFIC_SECRET, key,
887
                                ssl->specs.hash_size, NULL);
888
        if (ret != 0) {
889
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
890
            return TLS13_SECRET_CB_E;
891
        }
892
    }
893
#endif /* OPENSSL_EXTRA */
894
#endif /* HAVE_SECRET_CALLBACK */
895
0
    return ret;
896
0
}
897
898
/* The length of the client application traffic label. */
899
0
#define CLIENT_APP_LABEL_SZ         12
900
/* The client application traffic label. */
901
static const byte clientAppLabel[CLIENT_APP_LABEL_SZ + 1] =
902
    "c ap traffic";
903
904
/* Derive the client application traffic key.
905
 *
906
 * ssl  The SSL/TLS object.
907
 * key  The derived key.
908
 * returns 0 on success, otherwise failure.
909
 */
910
static int DeriveClientTrafficSecret(WOLFSSL* ssl, byte* key)
911
0
{
912
0
    int ret;
913
0
    WOLFSSL_MSG("Derive Client Traffic Secret");
914
0
    if (ssl == NULL || ssl->arrays == NULL) {
915
0
        return BAD_FUNC_ARG;
916
0
    }
917
918
#if defined(WOLFSSL_SNIFFER) && defined(WOLFSSL_SNIFFER_KEYLOGFILE)
919
    /* If this is called from a sniffer session with keylog file support,
920
     * obtain the appropriate secret from the callback */
921
    if (ssl->snifferSecretCb != NULL) {
922
        return ssl->snifferSecretCb(ssl->arrays->clientRandom,
923
                                    SNIFFER_SECRET_CLIENT_TRAFFIC_SECRET,
924
                                    key);
925
    }
926
#endif /* WOLFSSL_SNIFFER && WOLFSSL_SNIFFER_KEYLOGFILE */
927
928
0
    ret = Tls13DeriveKey(ssl, key, -1, ssl->arrays->masterSecret,
929
0
                    clientAppLabel, CLIENT_APP_LABEL_SZ,
930
0
                    ssl->specs.mac_algorithm, 1, WOLFSSL_CLIENT_END);
931
932
#ifdef HAVE_SECRET_CALLBACK
933
    if (ret == 0 && ssl->tls13SecretCb != NULL) {
934
        ret = ssl->tls13SecretCb(ssl, CLIENT_TRAFFIC_SECRET, key,
935
                                 ssl->specs.hash_size, ssl->tls13SecretCtx);
936
        if (ret != 0) {
937
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
938
            return TLS13_SECRET_CB_E;
939
        }
940
    }
941
#ifdef OPENSSL_EXTRA
942
    if (ret == 0 && ssl->tls13KeyLogCb != NULL) {
943
        ret = ssl->tls13KeyLogCb(ssl, CLIENT_TRAFFIC_SECRET, key,
944
                                ssl->specs.hash_size, NULL);
945
        if (ret != 0) {
946
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
947
            return TLS13_SECRET_CB_E;
948
        }
949
    }
950
#endif /* OPENSSL_EXTRA */
951
#endif /* HAVE_SECRET_CALLBACK */
952
0
    return ret;
953
0
}
954
955
/* The length of the server application traffic label. */
956
0
#define SERVER_APP_LABEL_SZ         12
957
/* The  server application traffic label. */
958
static const byte serverAppLabel[SERVER_APP_LABEL_SZ + 1] =
959
    "s ap traffic";
960
961
/* Derive the server application traffic key.
962
 *
963
 * ssl  The SSL/TLS object.
964
 * key  The derived key.
965
 * returns 0 on success, otherwise failure.
966
 */
967
static int DeriveServerTrafficSecret(WOLFSSL* ssl, byte* key)
968
0
{
969
0
    int ret;
970
0
    WOLFSSL_MSG("Derive Server Traffic Secret");
971
0
    if (ssl == NULL || ssl->arrays == NULL) {
972
0
        return BAD_FUNC_ARG;
973
0
    }
974
975
#if defined(WOLFSSL_SNIFFER) && defined(WOLFSSL_SNIFFER_KEYLOGFILE)
976
    /* If this is called from a sniffer session with keylog file support,
977
     * obtain the appropriate secret from the callback */
978
    if (ssl->snifferSecretCb != NULL) {
979
        return ssl->snifferSecretCb(ssl->arrays->clientRandom,
980
                                    SNIFFER_SECRET_SERVER_TRAFFIC_SECRET,
981
                                    key);
982
    }
983
#endif /* WOLFSSL_SNIFFER && WOLFSSL_SNIFFER_KEYLOGFILE */
984
985
0
    ret = Tls13DeriveKey(ssl, key, -1, ssl->arrays->masterSecret,
986
0
                    serverAppLabel, SERVER_APP_LABEL_SZ,
987
0
                    ssl->specs.mac_algorithm, 1, WOLFSSL_SERVER_END);
988
989
#ifdef HAVE_SECRET_CALLBACK
990
    if (ret == 0 && ssl->tls13SecretCb != NULL) {
991
        ret = ssl->tls13SecretCb(ssl, SERVER_TRAFFIC_SECRET, key,
992
                                 ssl->specs.hash_size, ssl->tls13SecretCtx);
993
        if (ret != 0) {
994
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
995
            return TLS13_SECRET_CB_E;
996
        }
997
    }
998
#ifdef OPENSSL_EXTRA
999
    if (ret == 0 && ssl->tls13KeyLogCb != NULL) {
1000
        ret = ssl->tls13KeyLogCb(ssl, SERVER_TRAFFIC_SECRET, key,
1001
                                ssl->specs.hash_size, NULL);
1002
        if (ret != 0) {
1003
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
1004
            return TLS13_SECRET_CB_E;
1005
        }
1006
    }
1007
#endif /* OPENSSL_EXTRA */
1008
#endif /* HAVE_SECRET_CALLBACK */
1009
0
    return ret;
1010
0
}
1011
1012
#ifdef HAVE_KEYING_MATERIAL
1013
/* The length of the exporter master secret label. */
1014
#define EXPORTER_MASTER_LABEL_SZ    10
1015
/* The exporter master secret label. */
1016
static const byte exporterMasterLabel[EXPORTER_MASTER_LABEL_SZ + 1] =
1017
    "exp master";
1018
1019
/* Derive the exporter secret.
1020
 *
1021
 * ssl  The SSL/TLS object.
1022
 * key  The derived key.
1023
 * returns 0 on success, otherwise failure.
1024
 */
1025
static int DeriveExporterSecret(WOLFSSL* ssl, byte* key)
1026
{
1027
    int ret;
1028
    WOLFSSL_ENTER("Derive Exporter Secret");
1029
    if (ssl == NULL || ssl->arrays == NULL) {
1030
        return BAD_FUNC_ARG;
1031
    }
1032
    ret = Tls13DeriveKey(ssl, key, -1, ssl->arrays->masterSecret,
1033
                        exporterMasterLabel, EXPORTER_MASTER_LABEL_SZ,
1034
                        ssl->specs.mac_algorithm, 1, 0 /* Unused */);
1035
#ifdef HAVE_SECRET_CALLBACK
1036
    if (ret == 0 && ssl->tls13SecretCb != NULL) {
1037
        ret = ssl->tls13SecretCb(ssl, EXPORTER_SECRET, key,
1038
                                 ssl->specs.hash_size, ssl->tls13SecretCtx);
1039
        if (ret != 0) {
1040
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
1041
            return TLS13_SECRET_CB_E;
1042
        }
1043
    }
1044
#ifdef OPENSSL_EXTRA
1045
    if (ret == 0 && ssl->tls13KeyLogCb != NULL) {
1046
        ret = ssl->tls13KeyLogCb(ssl, EXPORTER_SECRET, key,
1047
                                ssl->specs.hash_size, NULL);
1048
        if (ret != 0) {
1049
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
1050
            return TLS13_SECRET_CB_E;
1051
        }
1052
    }
1053
#endif /* OPENSSL_EXTRA */
1054
#endif /* HAVE_SECRET_CALLBACK */
1055
    return ret;
1056
}
1057
1058
/* The length of the exporter label. */
1059
#define EXPORTER_LABEL_SZ    8
1060
/* The exporter label. */
1061
static const byte exporterLabel[EXPORTER_LABEL_SZ + 1] =
1062
    "exporter";
1063
/* Hash("") */
1064
#ifndef NO_SHA256
1065
static const byte emptySHA256Hash[] = {
1066
    0xE3, 0xB0, 0xC4, 0x42, 0x98, 0xFC, 0x1C, 0x14, 0x9A, 0xFB, 0xF4, 0xC8,
1067
    0x99, 0x6F, 0xB9, 0x24, 0x27, 0xAE, 0x41, 0xE4, 0x64, 0x9B, 0x93, 0x4C,
1068
    0xA4, 0x95, 0x99, 0x1B, 0x78, 0x52, 0xB8, 0x55
1069
};
1070
#endif
1071
#ifdef WOLFSSL_SHA384
1072
static const byte emptySHA384Hash[] = {
1073
    0x38, 0xB0, 0x60, 0xA7, 0x51, 0xAC, 0x96, 0x38, 0x4C, 0xD9, 0x32, 0x7E,
1074
    0xB1, 0xB1, 0xE3, 0x6A, 0x21, 0xFD, 0xB7, 0x11, 0x14, 0xBE, 0x07, 0x43,
1075
    0x4C, 0x0C, 0xC7, 0xBF, 0x63, 0xF6, 0xE1, 0xDA, 0x27, 0x4E, 0xDE, 0xBF,
1076
    0xE7, 0x6F, 0x65, 0xFB, 0xD5, 0x1A, 0xD2, 0xF1, 0x48, 0x98, 0xB9, 0x5B
1077
};
1078
#endif
1079
#ifdef WOLFSSL_TLS13_SHA512
1080
static const byte emptySHA512Hash[] = {
1081
    0xCF, 0x83, 0xE1, 0x35, 0x7E, 0xEF, 0xB8, 0xBD, 0xF1, 0x54, 0x28, 0x50,
1082
    0xD6, 0x6D, 0x80, 0x07, 0xD6, 0x20, 0xE4, 0x05, 0x0B, 0x57, 0x15, 0xDC,
1083
    0x83, 0xF4, 0xA9, 0x21, 0xD3, 0x6C, 0xE9, 0xCE, 0x47, 0xD0, 0xD1, 0x3C,
1084
    0x5D, 0x85, 0xF2, 0xB0, 0xFF, 0x83, 0x18, 0xD2, 0x87, 0x7E, 0xEC, 0x2F,
1085
    0x63, 0xB9, 0x31, 0xBD, 0x47, 0x41, 0x7A, 0x81, 0xA5, 0x38, 0x32, 0x7A,
1086
    0xF9, 0x27, 0xDA, 0x3E
1087
};
1088
#endif
1089
#ifdef WOLFSSL_SM3
1090
static const byte emptySM3Hash[] = {
1091
    0x1A, 0xB2, 0x1D, 0x83, 0x55, 0xCF, 0xA1, 0x7F, 0x8E, 0x61, 0x19, 0x48,
1092
    0x31, 0xE8, 0x1A, 0x8F, 0x22, 0xBE, 0xC8, 0xC7, 0x28, 0xFE, 0xFB, 0x74,
1093
    0x7E, 0xD0, 0x35, 0xEB, 0x50, 0x82, 0xAA, 0x2B
1094
};
1095
#endif
1096
/**
1097
 * Implement section 7.5 of RFC 8446
1098
 * @return  0 on success
1099
 *         <0 on failure
1100
 */
1101
int Tls13_Exporter(WOLFSSL* ssl, unsigned char *out, size_t outLen,
1102
        const char *label, size_t labelLen,
1103
        const unsigned char *context, size_t contextLen)
1104
{
1105
    int                 ret;
1106
    enum wc_HashType    hashType = WC_HASH_TYPE_NONE;
1107
    word32              hashLen = 0;
1108
    byte                hashOut[WC_MAX_DIGEST_SIZE];
1109
    const byte*         emptyHash = NULL;
1110
    byte                firstExpand[WC_MAX_DIGEST_SIZE];
1111
    const byte*         protocol = tls13ProtocolLabel;
1112
    word32              protocolLen = TLS13_PROTOCOL_LABEL_SZ;
1113
1114
    if (ssl->options.dtls && ssl->version.minor != DTLSv1_3_MINOR)
1115
        return VERSION_ERROR;
1116
1117
    if (!ssl->options.dtls && ssl->version.minor != TLSv1_3_MINOR)
1118
        return VERSION_ERROR;
1119
1120
#ifdef WOLFSSL_DTLS13
1121
    if (ssl->options.dtls) {
1122
        protocol = dtls13ProtocolLabel;
1123
        protocolLen = DTLS13_PROTOCOL_LABEL_SZ;
1124
    }
1125
#endif /* WOLFSSL_DTLS13 */
1126
1127
    /* Sanity check contextLen to prevent truncation when cast to word32. */
1128
    if (contextLen > WOLFSSL_MAX_32BIT)
1129
        return BAD_FUNC_ARG;
1130
    /* RFC 8446 HkdfLabel encodes the output length as a uint16, so requested
1131
     * lengths > 65535 cannot be represented and must be rejected. */
1132
    if (outLen > WOLFSSL_MAX_16BIT)
1133
        return BAD_FUNC_ARG;
1134
    /* RFC 8446 HkdfLabel encodes the label length in a single byte, so
1135
     * anything > 255 cannot be represented and must be rejected.
1136
     * The protocol length is included in the label. */
1137
    if ((labelLen +  protocolLen) > WOLFSSL_MAX_8BIT)
1138
        return BAD_FUNC_ARG;
1139
1140
    switch (ssl->specs.mac_algorithm) {
1141
        #ifndef NO_SHA256
1142
        case sha256_mac:
1143
            hashType  = WC_HASH_TYPE_SHA256;
1144
            hashLen   = WC_SHA256_DIGEST_SIZE;
1145
            emptyHash = emptySHA256Hash;
1146
            break;
1147
        #endif
1148
1149
        #ifdef WOLFSSL_SHA384
1150
        case sha384_mac:
1151
            hashType  = WC_HASH_TYPE_SHA384;
1152
            hashLen   = WC_SHA384_DIGEST_SIZE;
1153
            emptyHash = emptySHA384Hash;
1154
            break;
1155
        #endif
1156
1157
        #ifdef WOLFSSL_TLS13_SHA512
1158
        case sha512_mac:
1159
            hashType  = WC_HASH_TYPE_SHA512;
1160
            hashLen   = WC_SHA512_DIGEST_SIZE;
1161
            emptyHash = emptySHA512Hash;
1162
            break;
1163
        #endif
1164
1165
        #ifdef WOLFSSL_SM3
1166
        case sm3_mac:
1167
            hashType  = WC_HASH_TYPE_SM3;
1168
            hashLen   = WC_SM3_DIGEST_SIZE;
1169
            emptyHash = emptySM3Hash;
1170
            break;
1171
        #endif
1172
1173
        default:
1174
            return BAD_FUNC_ARG;
1175
    }
1176
1177
#ifdef WOLFSSL_CHECK_MEM_ZERO
1178
    /* Poison and register firstExpand before it is written so that any path
1179
     * below (all of which funnel through cleanup) is covered. */
1180
    XMEMSET(firstExpand, 0xff, sizeof(firstExpand));
1181
    wc_MemZero_Add("Tls13_Exporter firstExpand", firstExpand,
1182
                   sizeof(firstExpand));
1183
#endif
1184
1185
    /* Derive-Secret(Secret, label, "") */
1186
    ret = Tls13HKDFExpandLabel(ssl, firstExpand, hashLen,
1187
            ssl->arrays->exporterSecret, hashLen,
1188
            protocol, protocolLen, (byte*)label, (word32)labelLen,
1189
            emptyHash, hashLen, (int)hashType);
1190
    if (ret != 0)
1191
        goto cleanup;
1192
1193
    /* Hash(context_value) */
1194
    ret = wc_Hash(hashType, context, (word32)contextLen, hashOut, WC_MAX_DIGEST_SIZE);
1195
    if (ret != 0)
1196
        goto cleanup;
1197
1198
    ret = Tls13HKDFExpandLabel(ssl, out, (word32)outLen, firstExpand, hashLen,
1199
            protocol, protocolLen, exporterLabel, EXPORTER_LABEL_SZ,
1200
            hashOut, hashLen, (int)hashType);
1201
1202
cleanup:
1203
    /* firstExpand is the per-label Derive-Secret PRK and hashOut holds
1204
     * Hash(context_value); wipe both before the stack frame is reclaimed. */
1205
    ForceZero(firstExpand, sizeof(firstExpand));
1206
    ForceZero(hashOut, sizeof(hashOut));
1207
#ifdef WOLFSSL_CHECK_MEM_ZERO
1208
    wc_MemZero_Check(firstExpand, sizeof(firstExpand));
1209
#endif
1210
    return ret;
1211
}
1212
#endif
1213
1214
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
1215
/* The length of the resumption master secret label. */
1216
#define RESUME_MASTER_LABEL_SZ      10
1217
/* The resumption master secret label. */
1218
static const byte resumeMasterLabel[RESUME_MASTER_LABEL_SZ + 1] =
1219
    "res master";
1220
1221
/* Derive the resumption secret.
1222
 *
1223
 * ssl  The SSL/TLS object.
1224
 * key  The derived key.
1225
 * returns 0 on success, otherwise failure.
1226
 */
1227
int DeriveResumptionSecret(WOLFSSL* ssl, byte* key)
1228
{
1229
    byte* masterSecret;
1230
1231
    WOLFSSL_MSG("Derive Resumption Secret");
1232
    if (ssl == NULL) {
1233
        return BAD_FUNC_ARG;
1234
    }
1235
    if (ssl->arrays != NULL) {
1236
        masterSecret = ssl->arrays->masterSecret;
1237
    }
1238
    else {
1239
        masterSecret = ssl->session->masterSecret;
1240
    }
1241
    return Tls13DeriveKey(ssl, key, -1, masterSecret, resumeMasterLabel,
1242
                     RESUME_MASTER_LABEL_SZ, ssl->specs.mac_algorithm, 1,
1243
                     0 /* Unused */);
1244
}
1245
#endif
1246
1247
#ifdef WOLFSSL_SESSION_EXPORT
1248
/* Serialize the TLS 1.3 state the record layer sections of a session export
1249
 * leave out, for a stream and a DTLS session alike: the traffic secrets the
1250
 * next KeyUpdate derives its keys from, the resumption secret the tickets
1251
 * issued or received from here on derive their PSK from, a KeyUpdate response
1252
 * still due from the peer and the nonce of the last ticket issued.
1253
 * Returns the number of bytes written to 'exp' or a negative value. */
1254
int ExportTls13State(WOLFSSL* ssl, byte* exp, word32 len)
1255
{
1256
    word32 idx = 0;
1257
    byte secretSz;
1258
    byte nonceLen = 0;
1259
1260
    WOLFSSL_ENTER("ExportTls13State");
1261
1262
    if (ssl == NULL || exp == NULL)
1263
        return BAD_FUNC_ARG;
1264
1265
    /* the secrets are the traffic ones only once the handshake is done */
1266
    if (!ssl->options.handShakeDone) {
1267
        WOLFSSL_MSG("Can not export before the handshake is done");
1268
        return BAD_STATE_E;
1269
    }
1270
1271
    /* a KeyUpdate response the read side left for the write side to send */
1272
    if (ssl->options.sendKeyUpdate) {
1273
        WOLFSSL_MSG("Can not export with a KeyUpdate response pending");
1274
        return BAD_STATE_E;
1275
    }
1276
1277
    secretSz = ssl->specs.hash_size;
1278
    if (secretSz > SECRET_LEN)
1279
        return BAD_STATE_E;
1280
1281
    /* The nonce of the last ticket issued, the per-connection count that
1282
     * SendTls13NewSessionTicket() steps for every ticket and that has to stay
1283
     * unique on the connection (RFC 8446 Section 4.6.1); unset before the
1284
     * first ticket. A client holds the nonce of the ticket it received, which
1285
     * belongs to the session, not to the connection, so it is not exported. */
1286
#ifdef HAVE_SESSION_TICKET
1287
    if (ssl->options.side == WOLFSSL_SERVER_END)
1288
        nonceLen = ssl->session->ticketNonce.len;
1289
    if (nonceLen > DEF_TICKET_NONCE_SZ)
1290
        return BAD_STATE_E;
1291
#endif
1292
1293
    /* secret length, the three secrets, the KeyUpdate response flag, the nonce
1294
     * length and a fixed DEF_TICKET_NONCE_SZ wide nonce field */
1295
    if (OPAQUE8_LEN + (3u * secretSz) + (2 * OPAQUE8_LEN) + DEF_TICKET_NONCE_SZ
1296
            > len)
1297
        return BUFFER_E;
1298
1299
    exp[idx++] = secretSz;
1300
    XMEMCPY(exp + idx, ssl->clientSecret, secretSz); idx += secretSz;
1301
    XMEMCPY(exp + idx, ssl->serverSecret, secretSz); idx += secretSz;
1302
    XMEMCPY(exp + idx, ssl->session->masterSecret, secretSz); idx += secretSz;
1303
1304
    /* a KeyUpdate that asked for a response the peer has not sent yet */
1305
    exp[idx++] = ssl->keys.updateResponseReq;
1306
1307
    /* the nonce length, then the nonce itself in a DEF_TICKET_NONCE_SZ wide
1308
     * field so the section size does not depend on whether a ticket was sent */
1309
    exp[idx++] = nonceLen;
1310
    XMEMSET(exp + idx, 0, DEF_TICKET_NONCE_SZ);
1311
#ifdef HAVE_SESSION_TICKET
1312
    if (nonceLen > 0)
1313
        XMEMCPY(exp + idx, ssl->session->ticketNonce.data, nonceLen);
1314
#endif
1315
    idx += DEF_TICKET_NONCE_SZ;
1316
1317
    WOLFSSL_LEAVE("ExportTls13State", (int)idx);
1318
    return (int)idx;
1319
}
1320
1321
/* Parse what ExportTls13State() wrote into 'ssl', whose cipher specs and
1322
 * options were imported ahead of it.
1323
 * Returns the number of bytes read from 'exp' or a negative value. */
1324
int ImportTls13State(WOLFSSL* ssl, const byte* exp, word32 len)
1325
{
1326
    word32 idx = 0;
1327
    byte secretSz;
1328
    byte nonceLen;
1329
1330
    WOLFSSL_ENTER("ImportTls13State");
1331
1332
    if (ssl == NULL || exp == NULL)
1333
        return BAD_FUNC_ARG;
1334
1335
    if (OPAQUE8_LEN > len)
1336
        return BUFFER_E;
1337
    secretSz = exp[idx++];
1338
    /* every key is derived over specs.hash_size bytes of the secrets; the
1339
     * three secrets are followed by the KeyUpdate response flag, the nonce
1340
     * length and a DEF_TICKET_NONCE_SZ wide nonce field */
1341
    if (secretSz != ssl->specs.hash_size || secretSz > SECRET_LEN ||
1342
            idx + (3u * secretSz) + (2 * OPAQUE8_LEN) + DEF_TICKET_NONCE_SZ
1343
                > len)
1344
        return BUFFER_E;
1345
    XMEMCPY(ssl->clientSecret, exp + idx, secretSz); idx += secretSz;
1346
    XMEMCPY(ssl->serverSecret, exp + idx, secretSz); idx += secretSz;
1347
    XMEMCPY(ssl->session->masterSecret, exp + idx, secretSz); idx += secretSz;
1348
1349
    /* the KeyUpdate response still due from the peer */
1350
    if (exp[idx] > 1)
1351
        return BUFFER_E;
1352
    ssl->keys.updateResponseReq = exp[idx++];
1353
1354
    /* the nonce the next ticket is numbered after, only meaningful on the
1355
     * server; a client blob carries a zero length here */
1356
    nonceLen = exp[idx++];
1357
    if (nonceLen > DEF_TICKET_NONCE_SZ)
1358
        return BUFFER_E;
1359
#ifdef HAVE_SESSION_TICKET
1360
    if (ssl->options.side == WOLFSSL_SERVER_END) {
1361
        ssl->session->ticketNonce.len = nonceLen;
1362
        XMEMCPY(ssl->session->ticketNonce.data, exp + idx, nonceLen);
1363
    }
1364
#endif
1365
    idx += DEF_TICKET_NONCE_SZ;
1366
1367
    /* The imported connection is past its handshake: received KeyUpdate
1368
     * messages must pass the out-of-order sanity check. */
1369
    if (ssl->options.handShakeDone)
1370
        ssl->msgsReceived.got_finished = 1;
1371
1372
    WOLFSSL_LEAVE("ImportTls13State", (int)idx);
1373
    return (int)idx;
1374
}
1375
#endif /* WOLFSSL_SESSION_EXPORT */
1376
1377
/* Length of the finished label. */
1378
0
#define FINISHED_LABEL_SZ           8
1379
/* Finished label for generating finished key. */
1380
static const byte finishedLabel[FINISHED_LABEL_SZ+1] = "finished";
1381
/* Derive the finished secret.
1382
 *
1383
 * ssl     The SSL/TLS object.
1384
 * key     The key to use with the HMAC.
1385
 * secret  The derived secret.
1386
 * side    The side that we are deriving the secret for.
1387
 * returns 0 on success, otherwise failure.
1388
 */
1389
static int DeriveFinishedSecret(WOLFSSL* ssl, byte* key, byte* secret,
1390
                                int side)
1391
0
{
1392
0
    WOLFSSL_MSG("Derive Finished Secret");
1393
0
    return Tls13DeriveKey(ssl, secret, -1, key, finishedLabel,
1394
0
                          FINISHED_LABEL_SZ,  ssl->specs.mac_algorithm, 0,
1395
0
                          side);
1396
0
}
1397
1398
/* The length of the application traffic label. */
1399
0
#define APP_TRAFFIC_LABEL_SZ        11
1400
/* The application traffic label. */
1401
static const byte appTrafficLabel[APP_TRAFFIC_LABEL_SZ + 1] =
1402
    "traffic upd";
1403
1404
/* Update the traffic secret.
1405
 *
1406
 * ssl     The SSL/TLS object.
1407
 * secret  The previous secret and derived secret.
1408
 * side    The side that we are deriving the secret for.
1409
 * returns 0 on success, otherwise failure.
1410
 */
1411
static int DeriveTrafficSecret(WOLFSSL* ssl, byte* secret, int side)
1412
0
{
1413
0
    WOLFSSL_MSG("Derive New Application Traffic Secret");
1414
0
    return Tls13DeriveKey(ssl, secret, -1, secret,
1415
0
                     appTrafficLabel, APP_TRAFFIC_LABEL_SZ,
1416
0
                     ssl->specs.mac_algorithm, 0, side);
1417
0
}
1418
1419
1420
static int Tls13_HKDF_Extract(WOLFSSL *ssl, byte* prk, const byte* salt,
1421
                              int saltLen, byte* ikm, int ikmLen, int digest)
1422
0
{
1423
0
    int ret;
1424
#ifdef HAVE_PK_CALLBACKS
1425
    void *cb_ctx;
1426
    CallbackHKDFExtract cb;
1427
#endif
1428
1429
#ifdef WOLFSSL_ASYNC_REINVOKE
1430
    ret = Tls13KdfAsyncInit(ssl);
1431
    if (ret != 0)
1432
        return ret;
1433
#endif
1434
1435
#ifdef HAVE_PK_CALLBACKS
1436
    cb_ctx = ssl->HkdfExtractCtx;
1437
    cb = ssl->ctx->HkdfExtractCb;
1438
    if (cb != NULL) {
1439
        ret = cb(prk, salt, (word32)saltLen, ikm, (word32)ikmLen, digest, cb_ctx);
1440
    }
1441
    else
1442
#endif
1443
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
1444
    if ((int)ssl->arrays->psk_keySz < 0) {
1445
        ret = PSK_KEY_ERROR;
1446
    }
1447
    else
1448
#endif
1449
0
    {
1450
0
    #if !defined(HAVE_FIPS) || \
1451
0
        (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(6,0))
1452
0
        ret = wc_Tls13_HKDF_Extract_ex(prk, salt, (word32)saltLen, ikm, (word32)ikmLen, digest,
1453
0
            ssl->heap, ssl->devId);
1454
    #else
1455
        ret = wc_Tls13_HKDF_Extract(prk, salt, saltLen, ikm, ikmLen, digest);
1456
        (void)ssl;
1457
    #endif
1458
0
    }
1459
#ifdef WOLFSSL_ASYNC_REINVOKE
1460
    if (ret == WC_NO_ERR_TRACE(WC_PENDING_E))
1461
        ret = wolfSSL_AsyncPush(ssl, &ssl->kdfAsyncDev);
1462
#endif
1463
0
    return ret;
1464
0
}
1465
1466
/* Derive the early secret using HKDF Extract.
1467
 *
1468
 * ssl  The SSL/TLS object.
1469
 */
1470
int DeriveEarlySecret(WOLFSSL* ssl)
1471
0
{
1472
0
    int ret;
1473
1474
0
    WOLFSSL_MSG("Derive Early Secret");
1475
0
    if (ssl == NULL || ssl->arrays == NULL) {
1476
0
        return BAD_FUNC_ARG;
1477
0
    }
1478
#if defined(WOLFSSL_RENESAS_TSIP_TLS)
1479
    ret = tsip_Tls13DeriveEarlySecret(ssl);
1480
    if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE))
1481
        return ret;
1482
#endif
1483
0
    PRIVATE_KEY_UNLOCK();
1484
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
1485
    ret = Tls13_HKDF_Extract(ssl, ssl->arrays->secret, NULL, 0,
1486
            ssl->arrays->psk_key, (int)ssl->arrays->psk_keySz,
1487
            mac2hash(ssl->specs.mac_algorithm));
1488
#else
1489
0
    ret = Tls13_HKDF_Extract(ssl, ssl->arrays->secret, NULL, 0,
1490
0
            ssl->arrays->masterSecret, 0, mac2hash(ssl->specs.mac_algorithm));
1491
0
#endif
1492
0
    PRIVATE_KEY_LOCK();
1493
0
    return ret;
1494
0
}
1495
1496
/* The length of the derived label. */
1497
0
#define DERIVED_LABEL_SZ        7
1498
/* The derived label. */
1499
static const byte derivedLabel[DERIVED_LABEL_SZ + 1] =
1500
    "derived";
1501
1502
/* Derive the handshake secret using HKDF Extract.
1503
 *
1504
 * ssl  The SSL/TLS object.
1505
 */
1506
int DeriveHandshakeSecret(WOLFSSL* ssl)
1507
0
{
1508
0
    byte key[WC_MAX_DIGEST_SIZE];
1509
0
    int ret;
1510
0
    WOLFSSL_MSG("Derive Handshake Secret");
1511
0
    if (ssl == NULL || ssl->arrays == NULL) {
1512
0
        return BAD_FUNC_ARG;
1513
0
    }
1514
#if defined(WOLFSSL_RENESAS_TSIP_TLS)
1515
    ret = tsip_Tls13DeriveHandshakeSecret(ssl);
1516
    if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE))
1517
        return ret;
1518
#endif
1519
1520
    /* Derive-Secret(., "derived", "") per RFC 8446 Section 7.1.
1521
     * Empty hash (NULL, 0) is required by the TLS 1.3 key schedule. */
1522
0
    ret = DeriveKeyMsg(ssl, key, -1, ssl->arrays->secret,
1523
0
                        derivedLabel, DERIVED_LABEL_SZ,
1524
0
                        NULL, 0, ssl->specs.mac_algorithm);
1525
0
    if (ret == 0) {
1526
0
        PRIVATE_KEY_UNLOCK();
1527
0
        ret = Tls13_HKDF_Extract(ssl, ssl->arrays->preMasterSecret,
1528
0
                key, ssl->specs.hash_size,
1529
0
                ssl->arrays->preMasterSecret, (int)ssl->arrays->preMasterSz,
1530
0
                mac2hash(ssl->specs.mac_algorithm));
1531
0
        PRIVATE_KEY_LOCK();
1532
0
    }
1533
0
    if (ret != WC_NO_ERR_TRACE(WC_PENDING_E)) {
1534
        /* Last use of the early secret and of the PSK it was extracted from -
1535
         * zeroize both. */
1536
0
        ForceZero(ssl->arrays->secret, SECRET_LEN);
1537
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
1538
        ForceZero(ssl->arrays->psk_key, MAX_PSK_KEY_LEN);
1539
#endif
1540
0
    }
1541
1542
#ifdef WOLFSSL_CHECK_MEM_ZERO
1543
    wc_MemZero_Add("DeriveHandshakeSecret key", key, WC_MAX_DIGEST_SIZE);
1544
#endif
1545
0
    ForceZero(key, sizeof(key));
1546
#ifdef WOLFSSL_CHECK_MEM_ZERO
1547
    wc_MemZero_Check(key, sizeof(key));
1548
#endif
1549
0
    return ret;
1550
0
}
1551
1552
/* Derive the master secret using HKDF Extract.
1553
 *
1554
 * ssl  The SSL/TLS object.
1555
 */
1556
int DeriveMasterSecret(WOLFSSL* ssl)
1557
0
{
1558
0
    byte key[WC_MAX_DIGEST_SIZE];
1559
0
    int ret;
1560
0
    WOLFSSL_MSG("Derive Master Secret");
1561
0
    if (ssl == NULL || ssl->arrays == NULL) {
1562
0
        return BAD_FUNC_ARG;
1563
0
    }
1564
1565
#if defined(WOLFSSL_RENESAS_TSIP_TLS)
1566
    ret = tsip_Tls13DeriveMasterSecret(ssl);
1567
    if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE))
1568
        return ret;
1569
#endif
1570
1571
    /* Derive-Secret(., "derived", "") per RFC 8446 Section 7.1.
1572
     * Empty hash (NULL, 0) is required by the TLS 1.3 key schedule. */
1573
0
    ret = DeriveKeyMsg(ssl, key, -1, ssl->arrays->preMasterSecret,
1574
0
                        derivedLabel, DERIVED_LABEL_SZ,
1575
0
                        NULL, 0, ssl->specs.mac_algorithm);
1576
0
    if (ret == 0) {
1577
0
        PRIVATE_KEY_UNLOCK();
1578
0
        ret = Tls13_HKDF_Extract(ssl, ssl->arrays->masterSecret,
1579
0
                                 key, ssl->specs.hash_size,
1580
0
                                 ssl->arrays->masterSecret, 0,
1581
0
                                 mac2hash(ssl->specs.mac_algorithm));
1582
0
        PRIVATE_KEY_LOCK();
1583
0
    }
1584
1585
#ifdef WOLFSSL_CHECK_MEM_ZERO
1586
    wc_MemZero_Add("DeriveMasterSecret key", key, WC_MAX_DIGEST_SIZE);
1587
#endif
1588
0
    ForceZero(key, sizeof(key));
1589
#ifdef WOLFSSL_CHECK_MEM_ZERO
1590
    wc_MemZero_Check(key, sizeof(key));
1591
#endif
1592
1593
#ifdef HAVE_KEYING_MATERIAL
1594
    if (ret != 0)
1595
        return ret;
1596
    /* Calculate exporter secret only when saving arrays */
1597
    if (ssl->options.saveArrays)
1598
        ret = DeriveExporterSecret(ssl, ssl->arrays->exporterSecret);
1599
#endif
1600
1601
0
    return ret;
1602
0
}
1603
1604
#if defined(HAVE_SESSION_TICKET)
1605
/* Length of the resumption label. */
1606
#define RESUMPTION_LABEL_SZ         10
1607
/* Resumption label for generating PSK associated with the ticket. */
1608
static const byte resumptionLabel[RESUMPTION_LABEL_SZ+1] = "resumption";
1609
1610
/* Derive the PSK associated with the ticket.
1611
 *
1612
 * ssl       The SSL/TLS object.
1613
 * nonce     The nonce to derive with.
1614
 * nonceLen  The length of the nonce to derive with.
1615
 * secret    The derived secret.
1616
 * returns 0 on success, otherwise failure.
1617
 */
1618
int DeriveResumptionPSK(WOLFSSL* ssl, byte* nonce, byte nonceLen, byte* secret)
1619
{
1620
    int         digestAlg;
1621
    /* Only one protocol version defined at this time. */
1622
    const byte* protocol    = tls13ProtocolLabel;
1623
    word32      protocolLen = TLS13_PROTOCOL_LABEL_SZ;
1624
    int         ret;
1625
1626
    WOLFSSL_MSG("Derive Resumption PSK");
1627
1628
#ifdef WOLFSSL_DTLS13
1629
    if (ssl->options.dtls) {
1630
        protocol = dtls13ProtocolLabel;
1631
        protocolLen = DTLS13_PROTOCOL_LABEL_SZ;
1632
    }
1633
#endif /* WOLFSSL_DTLS13 */
1634
1635
    switch (ssl->specs.mac_algorithm) {
1636
        #ifndef NO_SHA256
1637
        case sha256_mac:
1638
            digestAlg = WC_SHA256;
1639
            break;
1640
        #endif
1641
1642
        #ifdef WOLFSSL_SHA384
1643
        case sha384_mac:
1644
            digestAlg = WC_SHA384;
1645
            break;
1646
        #endif
1647
1648
        #ifdef WOLFSSL_TLS13_SHA512
1649
        case sha512_mac:
1650
            digestAlg = WC_SHA512;
1651
            break;
1652
        #endif
1653
1654
        #ifdef WOLFSSL_SM3
1655
        case sm3_mac:
1656
            digestAlg = WC_SM3;
1657
            break;
1658
        #endif
1659
1660
        default:
1661
            return BAD_FUNC_ARG;
1662
    }
1663
1664
#if defined(WOLFSSL_TICKET_NONCE_MALLOC) &&                                    \
1665
    (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
1666
    PRIVATE_KEY_UNLOCK();
1667
    ret = wc_Tls13_HKDF_Expand_Label_Alloc(secret, ssl->specs.hash_size,
1668
        ssl->session->masterSecret, ssl->specs.hash_size, protocol, protocolLen,
1669
        resumptionLabel, RESUMPTION_LABEL_SZ, nonce, nonceLen, digestAlg,
1670
        ssl->heap);
1671
    PRIVATE_KEY_LOCK();
1672
#else
1673
    ret = Tls13HKDFExpandLabel(ssl, secret, ssl->specs.hash_size,
1674
                               ssl->session->masterSecret, ssl->specs.hash_size,
1675
                               protocol, protocolLen, resumptionLabel,
1676
                               RESUMPTION_LABEL_SZ, nonce, nonceLen, digestAlg);
1677
#endif /* !defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3) */
1678
    return ret;
1679
}
1680
#endif /* HAVE_SESSION_TICKET */
1681
1682
1683
/* Calculate the HMAC of message data to this point.
1684
 *
1685
 * ssl   The SSL/TLS object.
1686
 * key   The HMAC key.
1687
 * hash  The hash result - verify data.
1688
 * returns length of verify data generated.
1689
 */
1690
#if defined(WOLFSSL_ASYNC_REINVOKE) && !defined(NO_HMAC)
1691
/* Release the held transcript Hmac and its resume state. */
1692
void Tls13FreeHsHmac(WOLFSSL* ssl)
1693
{
1694
    if (ssl->hsHmac != NULL) {
1695
        wc_HmacFree(ssl->hsHmac);
1696
        XFREE(ssl->hsHmac, ssl->heap, DYNAMIC_TYPE_HMAC);
1697
        ssl->hsHmac = NULL;
1698
    }
1699
    ssl->hsHmacStep = 0;
1700
    ssl->hsHmacOut = NULL;
1701
}
1702
#endif /* WOLFSSL_ASYNC_REINVOKE && !NO_HMAC */
1703
1704
static int BuildTls13HandshakeHmac(WOLFSSL* ssl, byte* key, byte* hash,
1705
    word32* pHashSz)
1706
0
{
1707
0
#ifndef WOLFSSL_ASYNC_REINVOKE
1708
0
    WC_DECLARE_VAR(verifyHmac, Hmac, 1, 0);
1709
0
#endif
1710
0
    int  hashType = WC_SHA256;
1711
0
    int  hashSz = WC_SHA256_DIGEST_SIZE;
1712
0
    int  ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG);
1713
1714
0
    if (ssl == NULL || key == NULL || hash == NULL) {
1715
0
        return BAD_FUNC_ARG;
1716
0
    }
1717
1718
    /* Get the hash of the previous handshake messages. */
1719
0
    switch (ssl->specs.mac_algorithm) {
1720
0
    #ifndef NO_SHA256
1721
0
        case sha256_mac:
1722
0
            hashType = WC_SHA256;
1723
0
            hashSz = WC_SHA256_DIGEST_SIZE;
1724
0
            ret = wc_Sha256GetHash(&ssl->hsHashes->hashSha256, hash);
1725
0
            break;
1726
0
    #endif /* !NO_SHA256 */
1727
0
    #ifdef WOLFSSL_SHA384
1728
0
        case sha384_mac:
1729
0
            hashType = WC_SHA384;
1730
0
            hashSz = WC_SHA384_DIGEST_SIZE;
1731
0
            ret = wc_Sha384GetHash(&ssl->hsHashes->hashSha384, hash);
1732
0
            break;
1733
0
    #endif /* WOLFSSL_SHA384 */
1734
    #ifdef WOLFSSL_TLS13_SHA512
1735
        case sha512_mac:
1736
            hashType = WC_SHA512;
1737
            hashSz = WC_SHA512_DIGEST_SIZE;
1738
            ret = wc_Sha512GetHash(&ssl->hsHashes->hashSha512, hash);
1739
            break;
1740
    #endif /* WOLFSSL_TLS13_SHA512 */
1741
    #ifdef WOLFSSL_SM3
1742
        case sm3_mac:
1743
            hashType = WC_SM3;
1744
            hashSz = WC_SM3_DIGEST_SIZE;
1745
            ret = wc_Sm3GetHash(&ssl->hsHashes->hashSm3, hash);
1746
            break;
1747
    #endif /* WOLFSSL_SM3 */
1748
0
        default:
1749
0
            ret = BAD_FUNC_ARG;
1750
0
            break;
1751
0
    }
1752
0
    if (ret != 0)
1753
0
        return ret;
1754
1755
#ifdef WOLFSSL_DEBUG_TLS
1756
    WOLFSSL_MSG("  Key");
1757
    WOLFSSL_BUFFER(key, ssl->specs.hash_size);
1758
    WOLFSSL_MSG("  Msg Hash");
1759
    WOLFSSL_BUFFER(hash, hashSz);
1760
#endif
1761
1762
#ifdef WOLFSSL_ASYNC_REINVOKE
1763
    /* Held on the SSL object so a crypto callback WC_PENDING_E resumes by
1764
     * re-invoking the same Hmac with identical arguments; the transcript
1765
     * hash input is recomputed deterministically by the caller's retry.
1766
     * Bound to the output buffer: a replayed caller that computes several
1767
     * HMACs (the PSK binder list) must not resume one request against
1768
     * another's key, so a different output discards the held state. */
1769
    if (ssl->hsHmac != NULL && ssl->hsHmacOut != hash)
1770
        Tls13FreeHsHmac(ssl);
1771
    if (ssl->hsHmac == NULL) {
1772
        ssl->hsHmac = (Hmac*)XMALLOC(sizeof(Hmac), ssl->heap,
1773
                                     DYNAMIC_TYPE_HMAC);
1774
        if (ssl->hsHmac == NULL)
1775
            return MEMORY_E;
1776
        ret = wc_HmacInit(ssl->hsHmac, ssl->heap, ssl->devId);
1777
        if (ret != 0) {
1778
            Tls13FreeHsHmac(ssl);
1779
            return ret;
1780
        }
1781
        ssl->hsHmacStep = 0;
1782
        ssl->hsHmacOut = hash;
1783
    }
1784
    /* Armed before the operations, matching the HKDF helpers. */
1785
    ret = Tls13KdfAsyncInit(ssl);
1786
    if (ret != 0) {
1787
        Tls13FreeHsHmac(ssl);
1788
        return ret;
1789
    }
1790
    if (ssl->hsHmacStep == 0) {
1791
        ret = wc_HmacSetKey(ssl->hsHmac, hashType, key,
1792
                            ssl->specs.hash_size);
1793
        if (ret == 0)
1794
            ssl->hsHmacStep = 1;
1795
    }
1796
    if (ret == 0 && ssl->hsHmacStep == 1) {
1797
        ret = wc_HmacUpdate(ssl->hsHmac, hash, (word32)hashSz);
1798
        if (ret == 0)
1799
            ssl->hsHmacStep = 2;
1800
    }
1801
    if (ret == 0 && ssl->hsHmacStep == 2)
1802
        ret = wc_HmacFinal(ssl->hsHmac, hash);
1803
    if (ret == WC_NO_ERR_TRACE(WC_PENDING_E))
1804
        return wolfSSL_AsyncPush(ssl, &ssl->kdfAsyncDev);
1805
    Tls13FreeHsHmac(ssl);
1806
#else
1807
0
    WC_ALLOC_VAR_EX(verifyHmac, Hmac, 1, NULL, DYNAMIC_TYPE_HMAC,
1808
0
        return MEMORY_E);
1809
1810
    /* Calculate the verify data. */
1811
0
    ret = wc_HmacInit(verifyHmac, ssl->heap, ssl->devId);
1812
0
    if (ret == 0) {
1813
0
        ret = wc_HmacSetKey(verifyHmac, hashType, key, ssl->specs.hash_size);
1814
0
        if (ret == 0)
1815
0
            ret = wc_HmacUpdate(verifyHmac, hash, (word32)hashSz);
1816
0
        if (ret == 0)
1817
0
            ret = wc_HmacFinal(verifyHmac, hash);
1818
0
        wc_HmacFree(verifyHmac);
1819
0
    }
1820
1821
0
    WC_FREE_VAR_EX(verifyHmac, NULL, DYNAMIC_TYPE_HMAC);
1822
0
#endif /* WOLFSSL_ASYNC_REINVOKE */
1823
1824
#ifdef WOLFSSL_DEBUG_TLS
1825
    WOLFSSL_MSG("  Hash");
1826
    WOLFSSL_BUFFER(hash, hashSz);
1827
#endif
1828
1829
0
    if (pHashSz)
1830
0
        *pHashSz = (word32)hashSz;
1831
1832
0
    return ret;
1833
0
}
1834
1835
/* The length of the label to use when deriving keys. */
1836
0
#define WRITE_KEY_LABEL_SZ     3
1837
/* The length of the label to use when deriving IVs. */
1838
0
#define WRITE_IV_LABEL_SZ      2
1839
/* The label to use when deriving keys. */
1840
static const byte writeKeyLabel[WRITE_KEY_LABEL_SZ+1] = "key";
1841
/* The label to use when deriving IVs. */
1842
static const byte writeIVLabel[WRITE_IV_LABEL_SZ+1]   = "iv";
1843
1844
/* Expand the traffic secrets held in ssl->clientSecret/serverSecret into the
1845
 * record layer key and IV of ssl->keys, and, for DTLS 1.3, into the record
1846
 * number key. RFC 8446 Section 7.3 and RFC 9147 Section 4.2.3.
1847
 *
1848
 * ssl        The SSL/TLS object.
1849
 * provision  PROVISION_CLIENT, PROVISION_SERVER or both, naming the
1850
 *            direction(s) whose secret is expanded.
1851
 * returns 0 on success, otherwise failure.
1852
 */
1853
int Tls13DeriveRecordKeys(WOLFSSL* ssl, int provision)
1854
0
{
1855
0
    int   ret = 0;
1856
0
    int   i = 0;
1857
0
    WC_DECLARE_VAR(key_dig, byte, MAX_PRF_DIG, 0);
1858
1859
0
    WC_ALLOC_VAR_EX(key_dig, byte, MAX_PRF_DIG, ssl->heap,
1860
0
        DYNAMIC_TYPE_DIGEST, return MEMORY_E);
1861
1862
#ifdef WOLFSSL_CHECK_MEM_ZERO
1863
    XMEMSET(key_dig, 0xff, MAX_PRF_DIG);
1864
    wc_MemZero_Add("Tls13DeriveRecordKeys key_dig", key_dig, MAX_PRF_DIG);
1865
#endif
1866
1867
    /* Key data = client key | server key | client IV | server IV */
1868
1869
0
    if (provision & PROVISION_CLIENT) {
1870
        /* Derive the client key.  */
1871
0
        WOLFSSL_MSG("Derive Client Key");
1872
0
        ret = Tls13DeriveKey(ssl, &key_dig[i], ssl->specs.key_size,
1873
0
                        ssl->clientSecret, writeKeyLabel,
1874
0
                        WRITE_KEY_LABEL_SZ, ssl->specs.mac_algorithm, 0,
1875
0
                        WOLFSSL_CLIENT_END);
1876
0
        if (ret != 0)
1877
0
            goto end;
1878
0
        i += ssl->specs.key_size;
1879
0
    }
1880
1881
0
    if (provision & PROVISION_SERVER) {
1882
        /* Derive the server key.  */
1883
0
        WOLFSSL_MSG("Derive Server Key");
1884
0
        ret = Tls13DeriveKey(ssl, &key_dig[i], ssl->specs.key_size,
1885
0
                        ssl->serverSecret, writeKeyLabel,
1886
0
                        WRITE_KEY_LABEL_SZ, ssl->specs.mac_algorithm, 0,
1887
0
                        WOLFSSL_SERVER_END);
1888
0
        if (ret != 0)
1889
0
            goto end;
1890
0
        i += ssl->specs.key_size;
1891
0
    }
1892
1893
0
    if (provision & PROVISION_CLIENT) {
1894
        /* Derive the client IV.  */
1895
0
        WOLFSSL_MSG("Derive Client IV");
1896
0
        ret = Tls13DeriveKey(ssl, &key_dig[i], ssl->specs.iv_size,
1897
0
                        ssl->clientSecret, writeIVLabel,
1898
0
                        WRITE_IV_LABEL_SZ, ssl->specs.mac_algorithm, 0,
1899
0
                        WOLFSSL_CLIENT_END);
1900
0
        if (ret != 0)
1901
0
            goto end;
1902
0
        i += ssl->specs.iv_size;
1903
0
    }
1904
1905
0
    if (provision & PROVISION_SERVER) {
1906
        /* Derive the server IV.  */
1907
0
        WOLFSSL_MSG("Derive Server IV");
1908
0
        ret = Tls13DeriveKey(ssl, &key_dig[i], ssl->specs.iv_size,
1909
0
                        ssl->serverSecret, writeIVLabel,
1910
0
                        WRITE_IV_LABEL_SZ, ssl->specs.mac_algorithm, 0,
1911
0
                        WOLFSSL_SERVER_END);
1912
0
        if (ret != 0)
1913
0
            goto end;
1914
        /* Server IV is the last key material written to key_dig, so i is not
1915
         * advanced here; the whole buffer is zeroed at end regardless. */
1916
0
    }
1917
1918
    /* Store keys and IVs but don't activate them. */
1919
0
    ret = StoreKeys(ssl, key_dig, provision);
1920
1921
#ifdef WOLFSSL_DTLS13
1922
    if (ret == 0 && ssl->options.dtls)
1923
        ret = Dtls13DeriveSnKeys(ssl, provision);
1924
#endif
1925
1926
0
end:
1927
    /* Zero the whole key_dig buffer (not just the i bytes derived) so no
1928
     * key-schedule material can linger in the unused tail. */
1929
0
    ForceZero(key_dig, MAX_PRF_DIG);
1930
#ifdef WOLFSSL_SMALL_STACK
1931
    XFREE(key_dig, ssl->heap, DYNAMIC_TYPE_DIGEST);
1932
#elif defined(WOLFSSL_CHECK_MEM_ZERO)
1933
    wc_MemZero_Check(key_dig, MAX_PRF_DIG);
1934
#endif
1935
1936
0
    return ret;
1937
0
}
1938
1939
/* Derive the keys and IVs for TLS v1.3.
1940
 *
1941
 * ssl      The SSL/TLS object.
1942
 * secret   early_data_key when deriving the key and IV for encrypting early
1943
 *          data application data and end_of_early_data messages.
1944
 *          handshake_key when deriving keys and IVs for encrypting handshake
1945
 *          messages.
1946
 *          traffic_key when deriving first keys and IVs for encrypting
1947
 *          traffic messages.
1948
 *          update_traffic_key when deriving next keys and IVs for encrypting
1949
 *          traffic messages.
1950
 *          no_key when deriving keys and IVs from existing secrets without
1951
 *          re-deriving the secrets. Used during early data transitions.
1952
 * side     ENCRYPT_SIDE_ONLY when only encryption secret needs to be derived.
1953
 *          DECRYPT_SIDE_ONLY when only decryption secret needs to be derived.
1954
 *          ENCRYPT_AND_DECRYPT_SIDE when both secret needs to be derived.
1955
 * store    1 indicates to derive the keys and IVs from derived secret and
1956
 *          store ready for provisioning.
1957
 * returns 0 on success, otherwise failure.
1958
 */
1959
int DeriveTls13Keys(WOLFSSL* ssl, int secret, int side, int store)
1960
0
{
1961
0
    int   ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); /* Assume failure */
1962
0
    int   provision;
1963
1964
#if defined(WOLFSSL_RENESAS_TSIP_TLS)
1965
    ret = tsip_Tls13DeriveKeys(ssl, secret, side);
1966
    if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
1967
        return ret;
1968
    }
1969
    ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); /* Assume failure */
1970
#endif
1971
1972
0
    if (side == ENCRYPT_AND_DECRYPT_SIDE) {
1973
0
        provision = PROVISION_CLIENT_SERVER;
1974
0
    }
1975
0
    else {
1976
0
        provision = ((ssl->options.side != WOLFSSL_CLIENT_END) ^
1977
0
                     (side == ENCRYPT_SIDE_ONLY)) ? PROVISION_CLIENT :
1978
0
                                                    PROVISION_SERVER;
1979
0
    }
1980
1981
    /* Derive the appropriate secret to use in the HKDF. */
1982
0
    switch (secret) {
1983
#ifdef WOLFSSL_EARLY_DATA
1984
        case early_data_key:
1985
            ret = DeriveEarlyTrafficSecret(ssl, ssl->clientSecret,
1986
                                           WOLFSSL_CLIENT_END);
1987
            if (ret != 0)
1988
                goto end;
1989
            break;
1990
#endif
1991
1992
0
        case handshake_key:
1993
0
            if (provision & PROVISION_CLIENT) {
1994
0
                ret = DeriveClientHandshakeSecret(ssl,
1995
0
                                                  ssl->clientSecret);
1996
0
                if (ret != 0)
1997
0
                    goto end;
1998
0
            }
1999
0
            if (provision & PROVISION_SERVER) {
2000
0
                ret = DeriveServerHandshakeSecret(ssl,
2001
0
                                                  ssl->serverSecret);
2002
0
                if (ret != 0)
2003
0
                    goto end;
2004
0
            }
2005
0
            break;
2006
2007
0
        case traffic_key:
2008
0
            if (provision & PROVISION_CLIENT) {
2009
0
                ret = DeriveClientTrafficSecret(ssl, ssl->clientSecret);
2010
0
                if (ret != 0)
2011
0
                    goto end;
2012
0
            }
2013
0
            if (provision & PROVISION_SERVER) {
2014
0
                ret = DeriveServerTrafficSecret(ssl, ssl->serverSecret);
2015
0
                if (ret != 0)
2016
0
                    goto end;
2017
0
            }
2018
0
            break;
2019
2020
0
        case update_traffic_key:
2021
0
            if (provision & PROVISION_CLIENT) {
2022
0
                ret = DeriveTrafficSecret(ssl, ssl->clientSecret,
2023
0
                                          WOLFSSL_CLIENT_END);
2024
0
                if (ret != 0)
2025
0
                    goto end;
2026
0
            }
2027
0
            if (provision & PROVISION_SERVER) {
2028
0
                ret = DeriveTrafficSecret(ssl, ssl->serverSecret,
2029
0
                                          WOLFSSL_SERVER_END);
2030
0
                if (ret != 0)
2031
0
                    goto end;
2032
0
            }
2033
0
            break;
2034
2035
0
        case no_key:
2036
            /* Called with early data to derive keys from existing secrets
2037
             * without re-deriving the secrets themselves. */
2038
0
            ret = 0;
2039
0
            break;
2040
2041
0
        default:
2042
0
            ret = BAD_FUNC_ARG;
2043
0
            break;
2044
0
    }
2045
2046
#ifdef WOLFSSL_QUIC
2047
    if (WOLFSSL_IS_QUIC(ssl)) {
2048
        ret = wolfSSL_quic_forward_secrets(ssl, secret, side);
2049
        if (ret != 0)
2050
            goto end;
2051
    }
2052
#endif /* WOLFSSL_QUIC */
2053
2054
0
    if (!store)
2055
0
        goto end;
2056
2057
0
    ret = Tls13DeriveRecordKeys(ssl, provision);
2058
2059
#ifdef WOLFSSL_DTLS13
2060
    if (ret != 0)
2061
      goto end;
2062
2063
    if (ssl->options.dtls) {
2064
        w64wrapper epochNumber;
2065
2066
        switch (secret) {
2067
            case early_data_key:
2068
                epochNumber = w64From32(0, DTLS13_EPOCH_EARLYDATA);
2069
                break;
2070
            case handshake_key:
2071
                epochNumber = w64From32(0, DTLS13_EPOCH_HANDSHAKE);
2072
                break;
2073
            case traffic_key:
2074
            case no_key:
2075
                epochNumber = w64From32(0, DTLS13_EPOCH_TRAFFIC0);
2076
                break;
2077
            case update_traffic_key:
2078
                if (side == ENCRYPT_SIDE_ONLY) {
2079
                    epochNumber = ssl->dtls13Epoch;
2080
                }
2081
                else if (side == DECRYPT_SIDE_ONLY) {
2082
                    epochNumber = ssl->dtls13PeerEpoch;
2083
                }
2084
                else {
2085
                    ret = BAD_STATE_E;
2086
                    goto end;
2087
                }
2088
                w64Increment(&epochNumber);
2089
                break;
2090
            default:
2091
                ret = BAD_STATE_E;
2092
                goto end;
2093
        }
2094
        ret = Dtls13NewEpoch(ssl, epochNumber, side);
2095
        if (ret != 0)
2096
            goto end;
2097
    }
2098
2099
#endif /* WOLFSSL_DTLS13 */
2100
2101
0
end:
2102
0
    if (ret != 0) {
2103
0
        WOLFSSL_ERROR_VERBOSE(ret);
2104
0
    }
2105
2106
0
    return ret;
2107
0
}
2108
2109
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK) || defined(WOLFSSL_DTLS13)
2110
#ifdef WOLFSSL_32BIT_MILLI_TIME
2111
#ifndef NO_ASN_TIME
2112
#if defined(USER_TICKS)
2113
#if 0
2114
    word32 TimeNowInMilliseconds(void)
2115
    {
2116
        /*
2117
        write your own clock tick function if don't want gettimeofday()
2118
        needs millisecond accuracy but doesn't have to correlated to EPOCH
2119
        */
2120
    }
2121
#endif
2122
2123
#elif defined(WOLFSSL_OPTEE)
2124
    word32 TimeNowInMilliseconds(void)
2125
    {
2126
        TEE_Time now;
2127
2128
        /* Monotonic within the TA, and not the normal world's clock. */
2129
        TEE_GetSystemTime(&now);
2130
2131
        return (word32)((now.seconds * 1000) + now.millis);
2132
    }
2133
2134
#elif defined(TIME_OVERRIDES)
2135
#if !defined(NO_ASN) && !defined(NO_ASN_TIME)
2136
    word32 TimeNowInMilliseconds(void)
2137
    {
2138
        return (word32) wc_Time(0) * 1000;
2139
    }
2140
#else
2141
    #ifndef HAVE_TIME_T_TYPE
2142
        typedef long time_t;
2143
    #endif
2144
    extern time_t XTIME(time_t * timer);
2145
2146
    /* The time in milliseconds.
2147
     * Used for tickets to represent difference between when first seen and when
2148
     * sending.
2149
     *
2150
     * returns the time in milliseconds as a 32-bit value.
2151
     */
2152
    word32 TimeNowInMilliseconds(void)
2153
    {
2154
        return (word32) XTIME(0) * 1000;
2155
    }
2156
#endif
2157
2158
#elif defined(XTIME_MS)
2159
    word32 TimeNowInMilliseconds(void)
2160
    {
2161
        return (word32)XTIME_MS(0);
2162
    }
2163
2164
#elif defined(USE_WINDOWS_API)
2165
    /* The time in milliseconds.
2166
     * Used for tickets to represent difference between when first seen and when
2167
     * sending.
2168
     *
2169
     * returns the time in milliseconds as a 32-bit value.
2170
     */
2171
    word32 TimeNowInMilliseconds(void)
2172
    {
2173
        static int           init = 0;
2174
        static LARGE_INTEGER freq;
2175
        LARGE_INTEGER        count;
2176
2177
        if (!init) {
2178
            QueryPerformanceFrequency(&freq);
2179
            init = 1;
2180
        }
2181
2182
        QueryPerformanceCounter(&count);
2183
2184
        return (word32)(count.QuadPart / (freq.QuadPart / 1000));
2185
    }
2186
2187
#elif defined(HAVE_RTP_SYS)
2188
    #include "rtptime.h"
2189
2190
    /* The time in milliseconds.
2191
     * Used for tickets to represent difference between when first seen and when
2192
     * sending.
2193
     *
2194
     * returns the time in milliseconds as a 32-bit value.
2195
     */
2196
    word32 TimeNowInMilliseconds(void)
2197
    {
2198
        return (word32)rtp_get_system_sec() * 1000;
2199
    }
2200
#elif defined(WOLFSSL_DEOS)
2201
    word32 TimeNowInMilliseconds(void)
2202
    {
2203
        const word32 systemTickTimeInHz = 1000000 / systemTickInMicroseconds();
2204
        word32 *systemTickPtr = systemTickPointer();
2205
2206
        return (word32) (*systemTickPtr/systemTickTimeInHz) * 1000;
2207
    }
2208
#elif defined(MICRIUM)
2209
    /* The time in milliseconds.
2210
     * Used for tickets to represent difference between when first seen and when
2211
     * sending.
2212
     *
2213
     * returns the time in milliseconds as a 32-bit value.
2214
     */
2215
    word32 TimeNowInMilliseconds(void)
2216
    {
2217
        OS_TICK ticks = 0;
2218
        OS_ERR  err;
2219
2220
        ticks = OSTimeGet(&err);
2221
2222
        return (word32) (ticks / OSCfg_TickRate_Hz) * 1000;
2223
    }
2224
#elif defined(MICROCHIP_TCPIP_V5)
2225
    /* The time in milliseconds.
2226
     * Used for tickets to represent difference between when first seen and when
2227
     * sending.
2228
     *
2229
     * returns the time in milliseconds as a 32-bit value.
2230
     */
2231
    word32 TimeNowInMilliseconds(void)
2232
    {
2233
        return (word32) (TickGet() / (TICKS_PER_SECOND / 1000));
2234
    }
2235
#elif defined(MICROCHIP_TCPIP)
2236
    #if defined(MICROCHIP_MPLAB_HARMONY)
2237
        #include <system/tmr/sys_tmr.h>
2238
2239
    /* The time in milliseconds.
2240
     * Used for tickets to represent difference between when first seen and when
2241
     * sending.
2242
     *
2243
     * returns the time in milliseconds as a 32-bit value.
2244
     */
2245
    word32 TimeNowInMilliseconds(void)
2246
    {
2247
        return (word32)(SYS_TMR_TickCountGet() /
2248
                        (SYS_TMR_TickCounterFrequencyGet() / 1000));
2249
    }
2250
    #else
2251
    /* The time in milliseconds.
2252
     * Used for tickets to represent difference between when first seen and when
2253
     * sending.
2254
     *
2255
     * returns the time in milliseconds as a 32-bit value.
2256
     */
2257
    word32 TimeNowInMilliseconds(void)
2258
    {
2259
        return (word32)(SYS_TICK_Get() / (SYS_TICK_TicksPerSecondGet() / 1000));
2260
    }
2261
2262
    #endif
2263
2264
#elif defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX)
2265
    /* The time in milliseconds.
2266
     * Used for tickets to represent difference between when first seen and when
2267
     * sending.
2268
     *
2269
     * returns the time in milliseconds as a 32-bit value.
2270
     */
2271
    word32 TimeNowInMilliseconds(void)
2272
    {
2273
        TIME_STRUCT mqxTime;
2274
2275
        _time_get_elapsed(&mqxTime);
2276
2277
        return (word32) mqxTime.SECONDS * 1000;
2278
    }
2279
#elif defined(FREESCALE_FREE_RTOS) || defined(FREESCALE_KSDK_FREERTOS)
2280
    #include "include/task.h"
2281
2282
    /* The time in milliseconds.
2283
     * Used for tickets to represent difference between when first seen and when
2284
     * sending.
2285
     *
2286
     * returns the time in milliseconds as a 32-bit value.
2287
     */
2288
    word32 TimeNowInMilliseconds(void)
2289
    {
2290
        return (unsigned int)(((float)xTaskGetTickCount()) /
2291
                              (configTICK_RATE_HZ / 1000));
2292
    }
2293
#elif defined(FREESCALE_KSDK_BM)
2294
    #include "lwip/sys.h" /* lwIP */
2295
2296
    /* The time in milliseconds.
2297
     * Used for tickets to represent difference between when first seen and when
2298
     * sending.
2299
     *
2300
     * returns the time in milliseconds as a 32-bit value.
2301
     */
2302
    word32 TimeNowInMilliseconds(void)
2303
    {
2304
        return sys_now();
2305
    }
2306
2307
#elif defined(WOLFSSL_CMSIS_RTOS) || defined(WOLFSSL_CMSIS_RTOSv2)
2308
2309
    word32 TimeNowInMilliseconds(void)
2310
    {
2311
        return (word32)osKernelGetTickCount();
2312
    }
2313
2314
#elif defined(WOLFSSL_TIRTOS)
2315
    /* The time in milliseconds.
2316
     * Used for tickets to represent difference between when first seen and when
2317
     * sending.
2318
     *
2319
     * returns the time in milliseconds as a 32-bit value.
2320
     */
2321
    word32 TimeNowInMilliseconds(void)
2322
    {
2323
        return (word32) Seconds_get() * 1000;
2324
    }
2325
#elif defined(WOLFSSL_UTASKER)
2326
    /* The time in milliseconds.
2327
     * Used for tickets to represent difference between when first seen and when
2328
     * sending.
2329
     *
2330
     * returns the time in milliseconds as a 32-bit value.
2331
     */
2332
    word32 TimeNowInMilliseconds(void)
2333
    {
2334
        return (word32)(uTaskerSystemTick / (TICK_RESOLUTION / 1000));
2335
    }
2336
#elif defined(WOLFSSL_LINUXKM)
2337
    word32 TimeNowInMilliseconds(void)
2338
    {
2339
        return (word32)wc_linuxkm_time_epoch_msecs();
2340
    }
2341
#elif defined(WOLFSSL_QNX_CAAM)
2342
    word32 TimeNowInMilliseconds(void)
2343
    {
2344
        struct timespec now;
2345
        clock_gettime(CLOCK_REALTIME, &now);
2346
        return (word32)(now.tv_sec * 1000 + now.tv_nsec / 1000000);
2347
    }
2348
#elif defined(FUSION_RTOS)
2349
    /* The time in milliseconds.
2350
     * Used for tickets to represent difference between when first seen and when
2351
     * sending.
2352
     *
2353
     * returns the time in milliseconds as a 32-bit value.
2354
     */
2355
    word32 TimeNowInMilliseconds(void)
2356
    {
2357
        struct timeval now;
2358
        if (FCL_GETTIMEOFDAY(&now, 0) < 0)
2359
            return 0;
2360
2361
        /* Convert to milliseconds number. */
2362
        return (word32)(now.tv_sec * 1000 + now.tv_usec / 1000);
2363
    }
2364
#elif defined(WOLFSSL_ZEPHYR)
2365
    word32 TimeNowInMilliseconds(void)
2366
    {
2367
        int64_t t;
2368
    #if defined(CONFIG_ARCH_POSIX)
2369
        k_cpu_idle();
2370
    #endif
2371
        t = k_uptime_get(); /* returns current uptime in milliseconds */
2372
        return (word32)t;
2373
    }
2374
#elif defined(FREERTOS)
2375
    word32 TimeNowInMilliseconds(void)
2376
    {
2377
        return (word32)((uint64_t)(xTaskGetTickCount() * 1000) /
2378
            configTICK_RATE_HZ);
2379
    }
2380
#else
2381
    /* The time in milliseconds.
2382
     * Used for tickets to represent difference between when first seen and when
2383
     * sending.
2384
     *
2385
     * returns the time in milliseconds as a 32-bit value.
2386
     */
2387
    word32 TimeNowInMilliseconds(void)
2388
    {
2389
        struct timeval now;
2390
2391
        if (gettimeofday(&now, 0) < 0)
2392
            return 0;
2393
2394
        /* Convert to milliseconds number. */
2395
        return (word32)(now.tv_sec * 1000 + now.tv_usec / 1000);
2396
    }
2397
#endif
2398
#else
2399
    /* user must supply time in milliseconds function:
2400
     *   word32 TimeNowInMilliseconds(void);
2401
     * The response is milliseconds elapsed
2402
     */
2403
#endif /* !NO_ASN_TIME */
2404
#else
2405
#ifndef NO_ASN_TIME
2406
#if defined(USER_TICKS)
2407
#if 0
2408
    sword64 TimeNowInMilliseconds(void)
2409
    {
2410
        /*
2411
        write your own clock tick function if don't want gettimeofday()
2412
        needs millisecond accuracy but doesn't have to correlated to EPOCH
2413
        */
2414
    }
2415
#endif
2416
2417
#elif defined(WOLFSSL_OPTEE)
2418
    sword64 TimeNowInMilliseconds(void)
2419
    {
2420
        TEE_Time now;
2421
2422
        /* Monotonic within the TA, and not the normal world's clock. */
2423
        TEE_GetSystemTime(&now);
2424
2425
        return ((sword64)now.seconds * 1000) + (sword64)now.millis;
2426
    }
2427
2428
#elif defined(TIME_OVERRIDES)
2429
#if !defined(NO_ASN) && !defined(NO_ASN_TIME)
2430
    sword64 TimeNowInMilliseconds(void)
2431
    {
2432
        return (sword64) wc_Time(0) * 1000;
2433
    }
2434
#else
2435
    #ifndef HAVE_TIME_T_TYPE
2436
        typedef long time_t;
2437
    #endif
2438
    extern time_t XTIME(time_t * timer);
2439
2440
    /* The time in milliseconds.
2441
     * Used for tickets to represent difference between when first seen and when
2442
     * sending.
2443
     *
2444
     * returns the time in milliseconds as a 32-bit value.
2445
     */
2446
    sword64 TimeNowInMilliseconds(void)
2447
    {
2448
        return (sword64) XTIME(0) * 1000;
2449
    }
2450
#endif
2451
2452
#elif defined(XTIME_MS)
2453
    sword64 TimeNowInMilliseconds(void)
2454
    {
2455
        return (sword64)XTIME_MS(0);
2456
    }
2457
2458
#elif defined(USE_WINDOWS_API)
2459
    /* The time in milliseconds.
2460
     * Used for tickets to represent difference between when first seen and when
2461
     * sending.
2462
     *
2463
     * returns the time in milliseconds as a 64-bit value.
2464
     */
2465
    sword64 TimeNowInMilliseconds(void)
2466
    {
2467
        static int           init = 0;
2468
        static LARGE_INTEGER freq;
2469
        LARGE_INTEGER        count;
2470
2471
        if (!init) {
2472
            QueryPerformanceFrequency(&freq);
2473
            init = 1;
2474
        }
2475
2476
        QueryPerformanceCounter(&count);
2477
2478
        return (sword64)(count.QuadPart / (freq.QuadPart / 1000));
2479
    }
2480
2481
#elif defined(HAVE_RTP_SYS)
2482
    #include "rtptime.h"
2483
2484
    /* The time in milliseconds.
2485
     * Used for tickets to represent difference between when first seen and when
2486
     * sending.
2487
     *
2488
     * returns the time in milliseconds as a 64-bit value.
2489
     */
2490
    sword64 TimeNowInMilliseconds(void)
2491
    {
2492
        return (sword64)rtp_get_system_sec() * 1000;
2493
    }
2494
#elif defined(WOLFSSL_DEOS)
2495
    sword64 TimeNowInMilliseconds(void)
2496
    {
2497
        const word32 systemTickTimeInHz = 1000000 / systemTickInMicroseconds();
2498
        word32 *systemTickPtr = systemTickPointer();
2499
2500
        return (sword64) (*systemTickPtr/systemTickTimeInHz) * 1000;
2501
    }
2502
#elif defined(MICRIUM)
2503
    /* The time in milliseconds.
2504
     * Used for tickets to represent difference between when first seen and when
2505
     * sending.
2506
     *
2507
     * returns the time in milliseconds as a 64-bit value.
2508
     */
2509
    sword64 TimeNowInMilliseconds(void)
2510
    {
2511
        OS_TICK ticks = 0;
2512
        OS_ERR  err;
2513
2514
        ticks = OSTimeGet(&err);
2515
2516
        return (sword64) (ticks / OSCfg_TickRate_Hz) * 1000;
2517
    }
2518
#elif defined(MICROCHIP_TCPIP_V5)
2519
    /* The time in milliseconds.
2520
     * Used for tickets to represent difference between when first seen and when
2521
     * sending.
2522
     *
2523
     * returns the time in milliseconds as a 64-bit value.
2524
     */
2525
    sword64 TimeNowInMilliseconds(void)
2526
    {
2527
        return (sword64) (TickGet() / (TICKS_PER_SECOND / 1000));
2528
    }
2529
#elif defined(MICROCHIP_TCPIP)
2530
    #if defined(MICROCHIP_MPLAB_HARMONY)
2531
        #include <system/tmr/sys_tmr.h>
2532
2533
    /* The time in milliseconds.
2534
     * Used for tickets to represent difference between when first seen and when
2535
     * sending.
2536
     *
2537
     * returns the time in milliseconds as a 64-bit value.
2538
     */
2539
    sword64 TimeNowInMilliseconds(void)
2540
    {
2541
        return (sword64)SYS_TMR_TickCountGet() /
2542
                        (SYS_TMR_TickCounterFrequencyGet() / 1000);
2543
    }
2544
    #else
2545
    /* The time in milliseconds.
2546
     * Used for tickets to represent difference between when first seen and when
2547
     * sending.
2548
     *
2549
     * returns the time in milliseconds as a 64-bit value.
2550
     */
2551
    sword64 TimeNowInMilliseconds(void)
2552
    {
2553
        return (sword64)SYS_TICK_Get() / (SYS_TICK_TicksPerSecondGet() / 1000);
2554
    }
2555
2556
    #endif
2557
2558
#elif defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX)
2559
    /* The time in milliseconds.
2560
     * Used for tickets to represent difference between when first seen and when
2561
     * sending.
2562
     *
2563
     * returns the time in milliseconds as a 64-bit value.
2564
     */
2565
    sword64 TimeNowInMilliseconds(void)
2566
    {
2567
        TIME_STRUCT mqxTime;
2568
2569
        _time_get_elapsed(&mqxTime);
2570
2571
        return (sword64) mqxTime.SECONDS * 1000;
2572
    }
2573
#elif defined(FREESCALE_FREE_RTOS) || defined(FREESCALE_KSDK_FREERTOS)
2574
    #include "include/task.h"
2575
2576
    /* The time in milliseconds.
2577
     * Used for tickets to represent difference between when first seen and when
2578
     * sending.
2579
     *
2580
     * returns the time in milliseconds as a 64-bit value.
2581
     */
2582
    sword64 TimeNowInMilliseconds(void)
2583
    {
2584
        return (sword64)xTaskGetTickCount() / (configTICK_RATE_HZ / 1000);
2585
    }
2586
#elif defined(FREESCALE_KSDK_BM)
2587
    #include "lwip/sys.h" /* lwIP */
2588
2589
    /* The time in milliseconds.
2590
     * Used for tickets to represent difference between when first seen and when
2591
     * sending.
2592
     *
2593
     * returns the time in milliseconds as a 64-bit value.
2594
     */
2595
    sword64 TimeNowInMilliseconds(void)
2596
    {
2597
        return sys_now();
2598
    }
2599
2600
#elif defined(WOLFSSL_CMSIS_RTOS) || defined(WOLFSSL_CMSIS_RTOSv2)
2601
2602
    sword64 TimeNowInMilliseconds(void)
2603
    {
2604
        return (sword64)osKernelGetTickCount();
2605
    }
2606
2607
#elif defined(WOLFSSL_TIRTOS)
2608
    /* The time in milliseconds.
2609
     * Used for tickets to represent difference between when first seen and when
2610
     * sending.
2611
     *
2612
     * returns the time in milliseconds as a 64-bit value.
2613
     */
2614
    sword64 TimeNowInMilliseconds(void)
2615
    {
2616
        return (sword64) Seconds_get() * 1000;
2617
    }
2618
#elif defined(WOLFSSL_UTASKER)
2619
    /* The time in milliseconds.
2620
     * Used for tickets to represent difference between when first seen and when
2621
     * sending.
2622
     *
2623
     * returns the time in milliseconds as a 64-bit value.
2624
     */
2625
    sword64 TimeNowInMilliseconds(void)
2626
    {
2627
        return (sword64)(uTaskerSystemTick / (TICK_RESOLUTION / 1000));
2628
    }
2629
#elif defined(WOLFSSL_LINUXKM)
2630
    sword64 TimeNowInMilliseconds(void)
2631
    {
2632
        s64 t;
2633
#if LINUX_VERSION_CODE < KERNEL_VERSION(4, 0, 0)
2634
        struct timespec ts;
2635
        getnstimeofday(&ts);
2636
        t = ts.tv_sec * (s64)1000;
2637
        t += ts.tv_nsec / (s64)1000000;
2638
#else
2639
        struct timespec64 ts;
2640
#if LINUX_VERSION_CODE < KERNEL_VERSION(5, 0, 0)
2641
        ts = current_kernel_time64();
2642
#else
2643
        ktime_get_coarse_real_ts64(&ts);
2644
#endif
2645
        t = ts.tv_sec * 1000L;
2646
        t += ts.tv_nsec / 1000000L;
2647
#endif
2648
        return (sword64)t;
2649
    }
2650
#elif defined(WOLFSSL_QNX_CAAM)
2651
    sword64 TimeNowInMilliseconds(void)
2652
    {
2653
        struct timespec now;
2654
        clock_gettime(CLOCK_REALTIME, &now);
2655
        return (sword64)(now.tv_sec * 1000 + now.tv_nsec / 1000000);
2656
    }
2657
#elif defined(FUSION_RTOS)
2658
    /* The time in milliseconds.
2659
     * Used for tickets to represent difference between when first seen and when
2660
     * sending.
2661
     *
2662
     * returns the time in milliseconds as a 64-bit value.
2663
     */
2664
    sword64 TimeNowInMilliseconds(void)
2665
    {
2666
        struct timeval now;
2667
        if (FCL_GETTIMEOFDAY(&now, 0) < 0)
2668
            return 0;
2669
2670
        /* Convert to milliseconds number. */
2671
        return (sword64)now.tv_sec * 1000 + now.tv_usec / 1000;
2672
    }
2673
#elif defined(WOLFSSL_ZEPHYR)
2674
    sword64 TimeNowInMilliseconds(void)
2675
    {
2676
        int64_t t;
2677
    #if defined(CONFIG_ARCH_POSIX)
2678
        k_cpu_idle();
2679
    #endif
2680
        t = k_uptime_get(); /* returns current uptime in milliseconds */
2681
        return (sword64)t;
2682
    }
2683
#elif defined(FREERTOS)
2684
    sword64 TimeNowInMilliseconds(void)
2685
    {
2686
        return (sword64)((uint64_t)(xTaskGetTickCount() * 1000) /
2687
            configTICK_RATE_HZ);
2688
    }
2689
#else
2690
    /* The time in milliseconds.
2691
     * Used for tickets to represent difference between when first seen and when
2692
     * sending.
2693
     *
2694
     * returns the time in milliseconds as a 64-bit value.
2695
     */
2696
    sword64 TimeNowInMilliseconds(void)
2697
    {
2698
        struct timeval now;
2699
2700
        if (gettimeofday(&now, 0) < 0)
2701
            return 0;
2702
2703
        /* Convert to milliseconds number. */
2704
        return (sword64)now.tv_sec * 1000 + now.tv_usec / 1000;
2705
    }
2706
#endif
2707
#else
2708
    /* user must supply time in milliseconds function:
2709
     *   sword64 TimeNowInMilliseconds(void);
2710
     * The response is milliseconds elapsed
2711
     */
2712
#endif /* !NO_ASN_TIME */
2713
#endif /* WOLFSSL_32BIT_MILLI_TIME */
2714
#endif /* HAVE_SESSION_TICKET || !NO_PSK || WOLFSSL_DTLS13 */
2715
2716
/* Add record layer header to message.
2717
 *
2718
 * output  The buffer to write the record layer header into.
2719
 * length  The length of the record data.
2720
 * type    The type of record message.
2721
 * ssl     The SSL/TLS object.
2722
 */
2723
static void AddTls13RecordHeader(byte* output, word32 length, byte type,
2724
                                 WOLFSSL* ssl)
2725
0
{
2726
0
    RecordLayerHeader* rl;
2727
2728
0
    rl = (RecordLayerHeader*)output;
2729
0
    rl->type    = type;
2730
0
    rl->pvMajor = ssl->version.major;
2731
    /* NOTE: May be TLSv1_MINOR when sending first ClientHello. */
2732
0
    rl->pvMinor = TLSv1_2_MINOR;
2733
0
    c16toa((word16)length, rl->length);
2734
0
}
2735
2736
/* Add handshake header to message.
2737
 *
2738
 * output      The buffer to write the handshake header into.
2739
 * length      The length of the handshake data.
2740
 * fragOffset  The offset of the fragment data. (DTLS)
2741
 * fragLength  The length of the fragment data. (DTLS)
2742
 * type        The type of handshake message.
2743
 * ssl         The SSL/TLS object. (DTLS)
2744
 */
2745
static void AddTls13HandShakeHeader(byte* output, word32 length,
2746
                                    word32 fragOffset, word32 fragLength,
2747
                                    byte type, WOLFSSL* ssl)
2748
0
{
2749
0
    HandShakeHeader* hs;
2750
0
    (void)fragOffset;
2751
0
    (void)fragLength;
2752
0
    (void)ssl;
2753
2754
#ifdef WOLFSSL_DTLS13
2755
    /* message_hash type is used for a synthetic message that replaces the first
2756
       ClientHello in the hash transcript when using HelloRetryRequest. It will
2757
       never be transmitted and, as the DTLS-only fields must not be considered
2758
       when computing the hash transcript, we can avoid to use the DTLS
2759
       handshake header. */
2760
    if (ssl->options.dtls && type != message_hash) {
2761
        Dtls13HandshakeAddHeader(ssl, output, (enum HandShakeType)type, length);
2762
        return;
2763
    }
2764
#endif /* WOLFSSL_DTLS13 */
2765
2766
    /* handshake header */
2767
0
    hs = (HandShakeHeader*)output;
2768
0
    hs->type = type;
2769
0
    c32to24(length, hs->length);
2770
0
}
2771
2772
2773
/* Add both record layer and handshake header to message.
2774
 *
2775
 * output      The buffer to write the headers into.
2776
 * length      The length of the handshake data.
2777
 * type        The type of record layer message.
2778
 * ssl         The SSL/TLS object. (DTLS)
2779
 */
2780
static void AddTls13Headers(byte* output, word32 length, byte type,
2781
                            WOLFSSL* ssl)
2782
0
{
2783
0
    word32 lengthAdj = HANDSHAKE_HEADER_SZ;
2784
0
    word32 outputAdj = RECORD_HEADER_SZ;
2785
2786
#ifdef WOLFSSL_DTLS13
2787
    if (ssl->options.dtls) {
2788
        Dtls13AddHeaders(output, length, (enum HandShakeType)type, ssl);
2789
        return;
2790
    }
2791
#endif /* WOLFSSL_DTLS13 */
2792
2793
0
    AddTls13RecordHeader(output, length + lengthAdj, handshake, ssl);
2794
0
    AddTls13HandShakeHeader(output + outputAdj, length, 0, length, type, ssl);
2795
0
}
2796
2797
#if (!defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER)) \
2798
    && !defined(NO_CERTS)
2799
/* Add both record layer and fragment handshake header to message.
2800
 *
2801
 * output      The buffer to write the headers into.
2802
 * fragOffset  The offset of the fragment data. (DTLS)
2803
 * fragLength  The length of the fragment data. (DTLS)
2804
 * length      The length of the handshake data.
2805
 * type        The type of record layer message.
2806
 * ssl         The SSL/TLS object. (DTLS)
2807
 */
2808
static void AddTls13FragHeaders(byte* output, word32 fragSz, word32 fragOffset,
2809
                                word32 length, byte type, WOLFSSL* ssl)
2810
0
{
2811
0
    word32 lengthAdj = HANDSHAKE_HEADER_SZ;
2812
0
    word32 outputAdj = RECORD_HEADER_SZ;
2813
0
    (void)fragSz;
2814
2815
#ifdef WOLFSSL_DTLS13
2816
    /* we ignore fragmentation fields here because fragmentation logic for
2817
       DTLS1.3 is inside dtls13_handshake_send(). */
2818
    if (ssl->options.dtls) {
2819
        Dtls13AddHeaders(output, length, (enum HandShakeType)type, ssl);
2820
        return;
2821
    }
2822
#endif /* WOLFSSL_DTLS13 */
2823
2824
0
    AddTls13RecordHeader(output, fragSz + lengthAdj, handshake, ssl);
2825
0
    AddTls13HandShakeHeader(output + outputAdj, length, fragOffset, fragSz,
2826
0
                            type, ssl);
2827
0
}
2828
#endif /* (!NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER) && !NO_CERTS */
2829
2830
/* Write the sequence number into the buffer.
2831
 * No DTLS v1.3 support.
2832
 *
2833
 * ssl          The SSL/TLS object.
2834
 * verifyOrder  Which set of sequence numbers to use.
2835
 * out          The buffer to write into.
2836
 */
2837
static WC_INLINE void WriteSEQTls13(WOLFSSL* ssl, int verifyOrder, byte* out)
2838
0
{
2839
0
    word32 seq[2] = {0, 0};
2840
2841
0
    if (ssl->options.dtls) {
2842
#ifdef WOLFSSL_DTLS13
2843
        Dtls13GetSeq(ssl, verifyOrder, seq, 1);
2844
#endif /* WOLFSSL_DTLS13 */
2845
0
    }
2846
0
    else if (verifyOrder == PEER_ORDER) {
2847
0
        seq[0] = ssl->keys.peer_sequence_number_hi;
2848
0
        seq[1] = ssl->keys.peer_sequence_number_lo++;
2849
        /* handle rollover */
2850
0
        if (seq[1] > ssl->keys.peer_sequence_number_lo)
2851
0
            ssl->keys.peer_sequence_number_hi++;
2852
0
    }
2853
0
    else {
2854
0
        seq[0] = ssl->keys.sequence_number_hi;
2855
0
        seq[1] = ssl->keys.sequence_number_lo++;
2856
        /* handle rollover */
2857
0
        if (seq[1] > ssl->keys.sequence_number_lo)
2858
0
            ssl->keys.sequence_number_hi++;
2859
0
    }
2860
#ifdef WOLFSSL_DEBUG_TLS
2861
    WOLFSSL_MSG_EX("TLS 1.3 Write Sequence %d %d", seq[0], seq[1]);
2862
#endif
2863
2864
0
    c32toa(seq[0], out);
2865
0
    c32toa(seq[1], out + OPAQUE32_LEN);
2866
0
}
2867
2868
/* Build the nonce for TLS v1.3 encryption and decryption.
2869
 *
2870
 * ssl    The SSL/TLS object.
2871
 * nonce  The nonce data to use when encrypting or decrypting.
2872
 * iv     The derived IV.
2873
 * order  The side on which the message is to be or was sent.
2874
 */
2875
static WC_INLINE void BuildTls13Nonce(WOLFSSL* ssl, byte* nonce, const byte* iv,
2876
                                   int ivSz, int order)
2877
0
{
2878
0
    int seq_offset;
2879
    /* Ensure minimum nonce size for standard AEAD ciphers */
2880
0
    if (ivSz < AEAD_NONCE_SZ)
2881
0
        ivSz = AEAD_NONCE_SZ;
2882
0
    seq_offset = ivSz - SEQ_SZ;
2883
    /* The nonce is the IV with the sequence XORed into the last bytes. */
2884
0
    WriteSEQTls13(ssl, order, nonce + seq_offset);
2885
0
    XMEMCPY(nonce, iv, seq_offset);
2886
0
    xorbuf(nonce + seq_offset, iv + seq_offset, SEQ_SZ);
2887
0
}
2888
2889
#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
2890
/* Encrypt with ChaCha20 and create authentication tag with Poly1305.
2891
 *
2892
 * ssl     The SSL/TLS object.
2893
 * output  The buffer to write encrypted data and authentication tag into.
2894
 *         May be the same pointer as input.
2895
 * input   The data to encrypt.
2896
 * sz      The number of bytes to encrypt.
2897
 * nonce   The nonce to use with ChaCha20.
2898
 * aad     The additional authentication data.
2899
 * aadSz   The size of the addition authentication data.
2900
 * tag     The authentication tag buffer.
2901
 * returns 0 on success, otherwise failure.
2902
 */
2903
static int ChaCha20Poly1305_Encrypt(WOLFSSL* ssl, byte* output,
2904
                                    const byte* input, word16 sz, byte* nonce,
2905
                                    const byte* aad, word16 aadSz, byte* tag)
2906
0
{
2907
    /* Persistent-key stitched helper: derives the per-record Poly1305 key from
2908
     * the keyed ChaCha, then encrypts and authenticates in one pass (the IFMA
2909
     * stitch for large records, else two-pass).  TLS 1.3 is always RFC 8439. */
2910
0
    return wc_ChaCha20Poly1305_Encrypt_ex(ssl->encrypt.chacha,
2911
0
        ssl->auth.poly1305, output, input, sz, nonce, tag, aad, aadSz);
2912
0
}
2913
#endif
2914
2915
#ifdef HAVE_NULL_CIPHER
2916
/* Create authentication tag and copy data over input.
2917
 *
2918
 * ssl     The SSL/TLS object.
2919
 * output  The buffer to copy data into.
2920
 *         May be the same pointer as input.
2921
 * input   The data.
2922
 * sz      The number of bytes of data.
2923
 * nonce   The nonce to use with authentication.
2924
 * aad     The additional authentication data.
2925
 * aadSz   The size of the addition authentication data.
2926
 * tag     The authentication tag buffer.
2927
 * returns 0 on success, otherwise failure.
2928
 */
2929
static int Tls13IntegrityOnly_Encrypt(WOLFSSL* ssl, byte* output,
2930
                                      const byte* input, word16 sz,
2931
                                      const byte* nonce,
2932
                                      const byte* aad, word16 aadSz, byte* tag)
2933
{
2934
    int ret;
2935
2936
    /* HMAC: nonce | aad | input  */
2937
    ret = wc_HmacUpdate(ssl->encrypt.hmac, nonce, ssl->specs.iv_size);
2938
    if (ret == 0)
2939
        ret = wc_HmacUpdate(ssl->encrypt.hmac, aad, aadSz);
2940
    if (ret == 0)
2941
        ret = wc_HmacUpdate(ssl->encrypt.hmac, input, sz);
2942
    if (ret == 0)
2943
        ret = wc_HmacFinal(ssl->encrypt.hmac, tag);
2944
    /* Copy the input to output if not the same buffer */
2945
    if (ret == 0 && output != input)
2946
        XMEMCPY(output, input, sz);
2947
    return ret;
2948
}
2949
#endif
2950
2951
/* Encrypt data for TLS v1.3.
2952
 *
2953
 * ssl     The SSL/TLS object.
2954
 * output  The buffer to write encrypted data and authentication tag into.
2955
 *         May be the same pointer as input.
2956
 * input   The record header and data to encrypt.
2957
 * sz      The number of bytes to encrypt.
2958
 * aad     The additional authentication data.
2959
 * aadSz   The size of the addition authentication data.
2960
 * asyncOkay If non-zero can return WC_PENDING_E, otherwise blocks on crypto
2961
 * returns 0 on success, otherwise failure.
2962
 */
2963
static int EncryptTls13(WOLFSSL* ssl, byte* output, const byte* input,
2964
                        word16 sz, const byte* aad, word16 aadSz, int asyncOkay)
2965
0
{
2966
0
    int    ret    = 0;
2967
0
    word16 dataSz;
2968
0
    word16 macSz  = ssl->specs.aead_mac_size;
2969
0
    word32 nonceSz = 0;
2970
#ifdef WOLFSSL_ASYNC_CRYPT
2971
    /* Only AES-GCM/AES-CCM assign asyncDev, so only they may pend under a
2972
     * poll-completing device; the crypto-callback re-invoke path returns
2973
     * before the push and is not limited this way. */
2974
    WC_ASYNC_DEV* asyncDev = NULL;
2975
    word32 event_flags = WC_ASYNC_FLAG_CALL_AGAIN;
2976
#endif
2977
2978
0
    WOLFSSL_ENTER("EncryptTls13");
2979
0
    if (sz < ssl->specs.aead_mac_size)
2980
0
        return BUFFER_E;
2981
0
    dataSz = sz - ssl->specs.aead_mac_size;
2982
2983
0
    (void)output;
2984
0
    (void)input;
2985
0
    (void)sz;
2986
0
    (void)dataSz;
2987
0
    (void)macSz;
2988
0
    (void)asyncOkay;
2989
0
    (void)nonceSz;
2990
2991
#ifdef WOLFSSL_ASYNC_CRYPT
2992
    if (ssl->error == WC_NO_ERR_TRACE(WC_PENDING_E)) {
2993
        ssl->error = 0; /* clear async */
2994
    }
2995
#endif
2996
#if defined(WOLFSSL_RENESAS_TSIP_TLS)
2997
    ret = tsip_Tls13AesEncrypt(ssl, output, input, dataSz);
2998
    if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
2999
        if (ret > 0) {
3000
            ret = 0; /* tsip_Tls13AesEncrypt returns output size */
3001
        }
3002
        return ret;
3003
    }
3004
    ret = 0;
3005
#endif /* WOLFSSL_RENESAS_TSIP_TLS */
3006
3007
0
    switch (ssl->encrypt.state) {
3008
0
        case CIPHER_STATE_BEGIN:
3009
0
        {
3010
        #ifdef WOLFSSL_DEBUG_TLS
3011
            WOLFSSL_MSG("Data to encrypt");
3012
            WOLFSSL_BUFFER(input, dataSz);
3013
            WOLFSSL_MSG("Additional Authentication Data");
3014
            WOLFSSL_BUFFER(aad, aadSz);
3015
        #endif
3016
3017
        #ifdef WOLFSSL_CIPHER_TEXT_CHECK
3018
            if (ssl->specs.bulk_cipher_algorithm != wolfssl_cipher_null &&
3019
                    dataSz >= sizeof(ssl->encrypt.sanityCheck)) {
3020
                XMEMCPY(ssl->encrypt.sanityCheck, input,
3021
                    sizeof(ssl->encrypt.sanityCheck));
3022
            }
3023
        #endif
3024
3025
0
        #ifdef CIPHER_NONCE
3026
0
            if (ssl->encrypt.nonce == NULL) {
3027
0
                ssl->encrypt.nonce = (byte*)XMALLOC(AEAD_MAX_IMP_SZ,
3028
0
                                                ssl->heap, DYNAMIC_TYPE_CIPHER);
3029
            #ifdef WOLFSSL_CHECK_MEM_ZERO
3030
                if (ssl->encrypt.nonce != NULL) {
3031
                    wc_MemZero_Add("EncryptTls13 nonce", ssl->encrypt.nonce,
3032
                        ssl->specs.iv_size);
3033
                }
3034
            #endif
3035
0
            }
3036
0
            if (ssl->encrypt.nonce == NULL)
3037
0
                return MEMORY_E;
3038
3039
0
            BuildTls13Nonce(ssl, ssl->encrypt.nonce, ssl->keys.aead_enc_imp_IV,
3040
0
                            ssl->specs.iv_size, CUR_ORDER);
3041
0
        #endif
3042
3043
            /* Advance state and proceed */
3044
0
            ssl->encrypt.state = CIPHER_STATE_DO;
3045
0
        }
3046
0
        FALL_THROUGH;
3047
3048
0
        case CIPHER_STATE_DO:
3049
0
        {
3050
0
            switch (ssl->specs.bulk_cipher_algorithm) {
3051
0
            #ifdef BUILD_AESGCM
3052
0
                case wolfssl_aes_gcm:
3053
                #ifdef WOLFSSL_ASYNC_CRYPT
3054
                    /* initialize event */
3055
                    asyncDev = &ssl->encrypt.aes->asyncDev;
3056
                    ret = wolfSSL_AsyncInit(ssl, asyncDev, event_flags);
3057
                    if (ret != 0)
3058
                        break;
3059
                #endif
3060
3061
0
                    nonceSz = AESGCM_NONCE_SZ;
3062
3063
                #if defined(HAVE_PK_CALLBACKS)
3064
                    ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN);
3065
                    if (ssl->ctx && ssl->ctx->PerformTlsRecordProcessingCb) {
3066
                        ret = ssl->ctx->PerformTlsRecordProcessingCb(ssl, 1,
3067
                                  output, input, dataSz,
3068
                                  ssl->encrypt.nonce, nonceSz,
3069
                                  output + dataSz, macSz,
3070
                                  aad, aadSz);
3071
                    }
3072
                    if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN))
3073
                #endif
3074
0
                    {
3075
3076
                #if ((defined(HAVE_FIPS) || defined(HAVE_SELFTEST)) && \
3077
                    (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2)))
3078
                        ret = wc_AesGcmEncrypt(ssl->encrypt.aes, output, input,
3079
                            dataSz, ssl->encrypt.nonce, nonceSz,
3080
                            output + dataSz, macSz, aad, aadSz);
3081
                #else
3082
0
                        ret = wc_AesGcmSetExtIV(ssl->encrypt.aes,
3083
0
                                ssl->encrypt.nonce, nonceSz);
3084
0
                        if (ret == 0) {
3085
0
                            ret = wc_AesGcmEncrypt_ex(ssl->encrypt.aes, output,
3086
0
                                    input, dataSz, ssl->encrypt.nonce, nonceSz,
3087
0
                                    output + dataSz, macSz, aad, aadSz);
3088
0
                        }
3089
0
                #endif
3090
0
                    }
3091
0
                    break;
3092
0
            #endif
3093
3094
            #ifdef HAVE_AESCCM
3095
                case wolfssl_aes_ccm:
3096
                #ifdef WOLFSSL_ASYNC_CRYPT
3097
                    /* initialize event */
3098
                    asyncDev = &ssl->encrypt.aes->asyncDev;
3099
                    ret = wolfSSL_AsyncInit(ssl, asyncDev, event_flags);
3100
                    if (ret != 0)
3101
                        break;
3102
                #endif
3103
3104
                    nonceSz = AESCCM_NONCE_SZ;
3105
                #if defined(HAVE_PK_CALLBACKS)
3106
                    ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN);
3107
                    if (ssl->ctx && ssl->ctx->PerformTlsRecordProcessingCb) {
3108
                        ret = ssl->ctx->PerformTlsRecordProcessingCb(ssl, 1,
3109
                                  output, input, dataSz,
3110
                                  ssl->encrypt.nonce, nonceSz,
3111
                                  output + dataSz, macSz,
3112
                                  aad, aadSz);
3113
                    }
3114
                    if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN))
3115
                #endif
3116
                    {
3117
                #if ((defined(HAVE_FIPS) || defined(HAVE_SELFTEST)) && \
3118
                    (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2)))
3119
                        ret = wc_AesCcmEncrypt(ssl->encrypt.aes, output, input,
3120
                            dataSz, ssl->encrypt.nonce, nonceSz,
3121
                            output + dataSz, macSz, aad, aadSz);
3122
                #else
3123
                        ret = wc_AesCcmSetNonce(ssl->encrypt.aes,
3124
                                ssl->encrypt.nonce, nonceSz);
3125
                        if (ret == 0) {
3126
                            ret = wc_AesCcmEncrypt_ex(ssl->encrypt.aes, output,
3127
                                    input, dataSz, ssl->encrypt.nonce, nonceSz,
3128
                                    output + dataSz, macSz, aad, aadSz);
3129
                        }
3130
                #endif
3131
                    }
3132
                    break;
3133
            #endif
3134
3135
0
            #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
3136
0
                case wolfssl_chacha:
3137
0
                    ret = ChaCha20Poly1305_Encrypt(ssl, output, input, dataSz,
3138
0
                        ssl->encrypt.nonce, aad, aadSz, output + dataSz);
3139
0
                    break;
3140
0
            #endif
3141
3142
            #ifdef WOLFSSL_SM4_GCM
3143
                case wolfssl_sm4_gcm:
3144
                    nonceSz = SM4_GCM_NONCE_SZ;
3145
                    ret = wc_Sm4GcmEncrypt(ssl->encrypt.sm4, output, input,
3146
                        dataSz, ssl->encrypt.nonce, nonceSz, output + dataSz,
3147
                        macSz, aad, aadSz);
3148
                    break;
3149
            #endif
3150
3151
            #ifdef WOLFSSL_SM4_CCM
3152
                case wolfssl_sm4_ccm:
3153
                    nonceSz = SM4_CCM_NONCE_SZ;
3154
                    ret = wc_Sm4CcmEncrypt(ssl->encrypt.sm4, output, input,
3155
                        dataSz, ssl->encrypt.nonce, nonceSz, output + dataSz,
3156
                        macSz, aad, aadSz);
3157
                    break;
3158
            #endif
3159
3160
            #ifdef HAVE_NULL_CIPHER
3161
                case wolfssl_cipher_null:
3162
                    ret = Tls13IntegrityOnly_Encrypt(ssl, output, input, dataSz,
3163
                        ssl->encrypt.nonce, aad, aadSz, output + dataSz);
3164
                    break;
3165
            #endif
3166
3167
0
                default:
3168
0
                    WOLFSSL_MSG("wolfSSL Encrypt programming error");
3169
0
                    return ENCRYPT_ERROR;
3170
0
            }
3171
3172
        #ifdef WOLFSSL_ASYNC_CRYPT
3173
            if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
3174
                /* if async is not okay, then block */
3175
                if (!asyncOkay) {
3176
                #if defined(WOLFSSL_ASYNC_REINVOKE) && \
3177
                    !defined(WOLF_CRYPTO_CB_ASYNC_POLL)
3178
                    /* wc_AsyncWait() never runs a callback: leave the state
3179
                     * at CIPHER_STATE_DO for the caller to re-invoke. */
3180
                    return ret;
3181
                #else
3182
                    ret = wc_AsyncWait(ret, asyncDev, event_flags);
3183
                #endif
3184
                }
3185
                else {
3186
                #if !defined(WOLFSSL_ASYNC_REINVOKE) || \
3187
                    defined(WOLF_CRYPTO_CB_ASYNC_POLL)
3188
                    /* Poll completes into output; the resume must skip the
3189
                     * in-place AEAD or it would encrypt its own output. */
3190
                    ssl->encrypt.state = CIPHER_STATE_END;
3191
                #endif
3192
                    /* Else stay at CIPHER_STATE_DO: the retry must re-invoke
3193
                     * the callback or the record goes out unencrypted. */
3194
                    return wolfSSL_AsyncPush(ssl, asyncDev);
3195
                }
3196
            }
3197
        #endif
3198
3199
            /* Advance state */
3200
0
            ssl->encrypt.state = CIPHER_STATE_END;
3201
0
        }
3202
0
        FALL_THROUGH;
3203
3204
0
        case CIPHER_STATE_END:
3205
0
        {
3206
        #ifdef WOLFSSL_DEBUG_TLS
3207
            #ifdef CIPHER_NONCE
3208
                WOLFSSL_MSG("Nonce");
3209
                WOLFSSL_BUFFER(ssl->encrypt.nonce, ssl->specs.iv_size);
3210
            #endif
3211
                WOLFSSL_MSG("Encrypted data");
3212
                WOLFSSL_BUFFER(output, dataSz);
3213
                WOLFSSL_MSG("Authentication Tag");
3214
                WOLFSSL_BUFFER(output + dataSz, macSz);
3215
        #endif
3216
3217
        #ifdef WOLFSSL_CIPHER_TEXT_CHECK
3218
            if (ssl->specs.bulk_cipher_algorithm != wolfssl_cipher_null &&
3219
                    dataSz >= sizeof(ssl->encrypt.sanityCheck) &&
3220
                XMEMCMP(output, ssl->encrypt.sanityCheck,
3221
                    sizeof(ssl->encrypt.sanityCheck)) == 0) {
3222
3223
                WOLFSSL_MSG("EncryptTls13 sanity check failed! Glitch?");
3224
                return ENCRYPT_ERROR;
3225
            }
3226
            ForceZero(ssl->encrypt.sanityCheck,
3227
                sizeof(ssl->encrypt.sanityCheck));
3228
        #endif
3229
        #ifdef WOLFSSL_CHECK_MEM_ZERO
3230
            if ((ssl->specs.bulk_cipher_algorithm != wolfssl_cipher_null) &&
3231
                    (output != input) && (ret == 0)) {
3232
                wc_MemZero_Add("TLS 1.3 Encrypt plaintext", input, sz);
3233
            }
3234
        #endif
3235
3236
0
        #ifdef CIPHER_NONCE
3237
0
            ForceZero(ssl->encrypt.nonce, ssl->specs.iv_size);
3238
0
        #endif
3239
3240
0
            break;
3241
0
        }
3242
3243
0
        default:
3244
0
            break;
3245
0
    }
3246
3247
3248
    /* Reset state */
3249
0
    ssl->encrypt.state = CIPHER_STATE_BEGIN;
3250
3251
0
    return ret;
3252
0
}
3253
3254
#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
3255
/* Decrypt with ChaCha20 and check authentication tag with Poly1305.
3256
 *
3257
 * ssl     The SSL/TLS object.
3258
 * output  The buffer to write decrypted data into.
3259
 *         May be the same pointer as input.
3260
 * input   The data to decrypt.
3261
 * sz      The number of bytes to decrypt.
3262
 * nonce   The nonce to use with ChaCha20.
3263
 * aad     The additional authentication data.
3264
 * aadSz   The size of the addition authentication data.
3265
 * tagIn   The authentication tag data from packet.
3266
 * returns 0 on success, otherwise failure.
3267
 */
3268
static int ChaCha20Poly1305_Decrypt(WOLFSSL* ssl, byte* output,
3269
                                    const byte* input, word16 sz, byte* nonce,
3270
                                    const byte* aad, word16 aadSz,
3271
                                    const byte* tagIn)
3272
0
{
3273
0
    int ret;
3274
3275
    /* Persistent-key stitched helper: verifies the Poly1305 tag over
3276
     * aad+ciphertext and decrypts in one pass (the IFMA decrypt stitch for
3277
     * large records, else two-pass); it zeroes output on tag mismatch. */
3278
0
    ret = wc_ChaCha20Poly1305_Decrypt_ex(ssl->decrypt.chacha,
3279
0
        ssl->auth.poly1305, output, input, sz, nonce, tagIn, aad, aadSz);
3280
0
    if (ret == WC_NO_ERR_TRACE(MAC_CMP_FAILED_E)) {
3281
0
        WOLFSSL_MSG("MAC did not match");
3282
0
        ret = VERIFY_MAC_ERROR;
3283
0
    }
3284
3285
0
    return ret;
3286
0
}
3287
#endif
3288
3289
#ifdef HAVE_NULL_CIPHER
3290
/* Check HMAC tag and copy over input.
3291
 *
3292
 * ssl     The SSL/TLS object.
3293
 * output  The buffer to copy data into.
3294
 *         May be the same pointer as input.
3295
 * input   The data.
3296
 * sz      The number of bytes of data.
3297
 * nonce   The nonce to use with authentication.
3298
 * aad     The additional authentication data.
3299
 * aadSz   The size of the addition authentication data.
3300
 * tagIn   The authentication tag data from packet.
3301
 * returns 0 on success, otherwise failure.
3302
 */
3303
static int Tls13IntegrityOnly_Decrypt(WOLFSSL* ssl, byte* output,
3304
                                      const byte* input, word16 sz,
3305
                                      const byte* nonce,
3306
                                      const byte* aad, word16 aadSz,
3307
                                      const byte* tagIn)
3308
{
3309
    int ret;
3310
    byte hmac[WC_MAX_DIGEST_SIZE];
3311
3312
    /* HMAC: nonce | aad | input  */
3313
    ret = wc_HmacUpdate(ssl->decrypt.hmac, nonce, ssl->specs.iv_size);
3314
    if (ret == 0)
3315
        ret = wc_HmacUpdate(ssl->decrypt.hmac, aad, aadSz);
3316
    if (ret == 0)
3317
        ret = wc_HmacUpdate(ssl->decrypt.hmac, input, sz);
3318
    if (ret == 0)
3319
        ret = wc_HmacFinal(ssl->decrypt.hmac, hmac);
3320
    /* Check authentication tag matches */
3321
    if (ret == 0 && ConstantCompare(tagIn, hmac, ssl->specs.hash_size) != 0)
3322
        ret = DECRYPT_ERROR;
3323
    /* Copy the input to output if not the same buffer */
3324
    if (ret == 0 && output != input)
3325
        XMEMCPY(output, input, sz);
3326
    ForceZero(hmac, sizeof(hmac));
3327
    return ret;
3328
}
3329
#endif
3330
3331
/* Decrypt data for TLS v1.3.
3332
 *
3333
 * ssl     The SSL/TLS object.
3334
 * output  The buffer to write decrypted data into.
3335
 *         May be the same pointer as input.
3336
 * input   The data to decrypt and authentication tag.
3337
 * sz      The length of the encrypted data plus authentication tag.
3338
 * aad     The additional authentication data.
3339
 * aadSz   The size of the addition authentication data.
3340
 * returns 0 on success, otherwise failure.
3341
 */
3342
int DecryptTls13(WOLFSSL* ssl, byte* output, const byte* input, word16 sz,
3343
                 const byte* aad, word16 aadSz)
3344
0
{
3345
0
    int    ret    = 0;
3346
0
    word16 dataSz;
3347
0
    word16 macSz  = ssl->specs.aead_mac_size;
3348
0
    word32 nonceSz = 0;
3349
3350
0
    WOLFSSL_ENTER("DecryptTls13");
3351
0
    if (sz < ssl->specs.aead_mac_size) {
3352
0
        return BAD_FUNC_ARG;
3353
0
    }
3354
0
    dataSz = sz - ssl->specs.aead_mac_size;
3355
3356
#if defined(WOLFSSL_RENESAS_TSIP_TLS)
3357
    ret = tsip_Tls13AesDecrypt(ssl, output, input, sz);
3358
3359
    if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
3360
        #ifndef WOLFSSL_EARLY_DATA
3361
        if (ret < 0) {
3362
            ret = VERIFY_MAC_ERROR;
3363
            WOLFSSL_ERROR_VERBOSE(ret);
3364
        }
3365
        #endif
3366
        return ret;
3367
    }
3368
#endif
3369
3370
#ifdef WOLFSSL_ASYNC_CRYPT
3371
    ret = wolfSSL_AsyncPop(ssl, &ssl->decrypt.state);
3372
    if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) {
3373
        /* check for still pending */
3374
        if (ret == WC_NO_ERR_TRACE(WC_PENDING_E))
3375
            return ret;
3376
3377
        ssl->error = 0; /* clear async */
3378
3379
        /* let failures through so CIPHER_STATE_END logic is run */
3380
    }
3381
    else
3382
#endif
3383
0
    {
3384
        /* Reset state */
3385
0
        ret = 0;
3386
0
        ssl->decrypt.state = CIPHER_STATE_BEGIN;
3387
0
    }
3388
3389
0
    (void)output;
3390
0
    (void)input;
3391
0
    (void)sz;
3392
0
    (void)dataSz;
3393
0
    (void)macSz;
3394
0
    (void)nonceSz;
3395
3396
0
    switch (ssl->decrypt.state) {
3397
0
        case CIPHER_STATE_BEGIN:
3398
0
        {
3399
        #ifdef WOLFSSL_DEBUG_TLS
3400
            WOLFSSL_MSG("Data to decrypt");
3401
            WOLFSSL_BUFFER(input, dataSz);
3402
            WOLFSSL_MSG("Additional Authentication Data");
3403
            WOLFSSL_BUFFER(aad, aadSz);
3404
            WOLFSSL_MSG("Authentication tag");
3405
            WOLFSSL_BUFFER(input + dataSz, macSz);
3406
        #endif
3407
3408
0
        #ifdef CIPHER_NONCE
3409
0
            if (ssl->decrypt.nonce == NULL) {
3410
0
                ssl->decrypt.nonce = (byte*)XMALLOC(AEAD_MAX_IMP_SZ,
3411
0
                                                ssl->heap, DYNAMIC_TYPE_CIPHER);
3412
            #ifdef WOLFSSL_CHECK_MEM_ZERO
3413
                if (ssl->decrypt.nonce != NULL) {
3414
                    wc_MemZero_Add("DecryptTls13 nonce", ssl->decrypt.nonce,
3415
                        ssl->specs.iv_size);
3416
                }
3417
            #endif
3418
0
            }
3419
0
            if (ssl->decrypt.nonce == NULL)
3420
0
                return MEMORY_E;
3421
3422
0
            BuildTls13Nonce(ssl, ssl->decrypt.nonce, ssl->keys.aead_dec_imp_IV,
3423
0
                            ssl->specs.iv_size, PEER_ORDER);
3424
0
        #endif
3425
3426
            /* Advance state and proceed */
3427
0
            ssl->decrypt.state = CIPHER_STATE_DO;
3428
0
        }
3429
0
        FALL_THROUGH;
3430
3431
0
        case CIPHER_STATE_DO:
3432
0
        {
3433
0
            switch (ssl->specs.bulk_cipher_algorithm) {
3434
0
            #ifdef BUILD_AESGCM
3435
0
                case wolfssl_aes_gcm:
3436
                #ifdef WOLFSSL_ASYNC_CRYPT
3437
                    /* initialize event */
3438
                    ret = wolfSSL_AsyncInit(ssl, &ssl->decrypt.aes->asyncDev,
3439
                        WC_ASYNC_FLAG_NONE);
3440
                    if (ret != 0)
3441
                        break;
3442
                #endif
3443
3444
0
                    nonceSz = AESGCM_NONCE_SZ;
3445
3446
                #if defined(HAVE_PK_CALLBACKS)
3447
                    ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN);
3448
                    if (ssl->ctx && ssl->ctx->PerformTlsRecordProcessingCb) {
3449
                        ret = ssl->ctx->PerformTlsRecordProcessingCb(ssl, 0,
3450
                                  output, input, dataSz,
3451
                                  ssl->decrypt.nonce, nonceSz,
3452
                                  (byte *)(input + dataSz), macSz,
3453
                                  aad, aadSz);
3454
                    }
3455
                    if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN))
3456
                #endif
3457
0
                    {
3458
3459
0
                        ret = wc_AesGcmDecrypt(ssl->decrypt.aes, output, input,
3460
0
                            dataSz, ssl->decrypt.nonce, nonceSz,
3461
0
                            input + dataSz, macSz, aad, aadSz);
3462
3463
                #ifdef WOLFSSL_ASYNC_CRYPT
3464
                        if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
3465
                            ret = wolfSSL_AsyncPush(ssl,
3466
                                &ssl->decrypt.aes->asyncDev);
3467
                        }
3468
                #endif
3469
3470
0
                    }
3471
0
                    break;
3472
0
            #endif
3473
3474
            #ifdef HAVE_AESCCM
3475
                case wolfssl_aes_ccm:
3476
                #ifdef WOLFSSL_ASYNC_CRYPT
3477
                    /* initialize event */
3478
                    ret = wolfSSL_AsyncInit(ssl, &ssl->decrypt.aes->asyncDev,
3479
                        WC_ASYNC_FLAG_NONE);
3480
                    if (ret != 0)
3481
                        break;
3482
                #endif
3483
3484
                    nonceSz = AESCCM_NONCE_SZ;
3485
                #if defined(HAVE_PK_CALLBACKS)
3486
                    ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN);
3487
                    if (ssl->ctx && ssl->ctx->PerformTlsRecordProcessingCb) {
3488
                        ret = ssl->ctx->PerformTlsRecordProcessingCb(ssl, 0,
3489
                                  output, input, dataSz,
3490
                                  ssl->decrypt.nonce, nonceSz,
3491
                                  (byte *)(input + dataSz), macSz,
3492
                                  aad, aadSz);
3493
                    }
3494
                    if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN))
3495
                #endif
3496
                    {
3497
                        ret = wc_AesCcmDecrypt(ssl->decrypt.aes, output, input,
3498
                            dataSz, ssl->decrypt.nonce, nonceSz,
3499
                            input + dataSz, macSz, aad, aadSz);
3500
                #ifdef WOLFSSL_ASYNC_CRYPT
3501
                        if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
3502
                            ret = wolfSSL_AsyncPush(ssl,
3503
                                &ssl->decrypt.aes->asyncDev);
3504
                        }
3505
                #endif
3506
                    }
3507
                    break;
3508
            #endif
3509
3510
0
            #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
3511
0
                case wolfssl_chacha:
3512
0
                    ret = ChaCha20Poly1305_Decrypt(ssl, output, input, dataSz,
3513
0
                        ssl->decrypt.nonce, aad, aadSz, input + dataSz);
3514
0
                    break;
3515
0
            #endif
3516
3517
            #ifdef WOLFSSL_SM4_GCM
3518
                case wolfssl_sm4_gcm:
3519
                    nonceSz = SM4_GCM_NONCE_SZ;
3520
                    ret = wc_Sm4GcmDecrypt(ssl->decrypt.sm4, output, input,
3521
                        dataSz, ssl->decrypt.nonce, nonceSz, input + dataSz,
3522
                        macSz, aad, aadSz);
3523
                    break;
3524
            #endif
3525
3526
            #ifdef WOLFSSL_SM4_CCM
3527
                case wolfssl_sm4_ccm:
3528
                    nonceSz = SM4_CCM_NONCE_SZ;
3529
                    ret = wc_Sm4CcmDecrypt(ssl->decrypt.sm4, output, input,
3530
                        dataSz, ssl->decrypt.nonce, nonceSz, input + dataSz,
3531
                        macSz, aad, aadSz);
3532
                    break;
3533
            #endif
3534
3535
            #ifdef HAVE_NULL_CIPHER
3536
                case wolfssl_cipher_null:
3537
                    ret = Tls13IntegrityOnly_Decrypt(ssl, output, input, dataSz,
3538
                        ssl->decrypt.nonce, aad, aadSz, input + dataSz);
3539
                    break;
3540
            #endif
3541
0
                default:
3542
0
                    WOLFSSL_MSG("wolfSSL Decrypt programming error");
3543
0
                    return DECRYPT_ERROR;
3544
0
            }
3545
3546
        #ifdef WOLFSSL_ASYNC_CRYPT
3547
            if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
3548
            #if !defined(WOLFSSL_ASYNC_REINVOKE) || \
3549
                defined(WOLF_CRYPTO_CB_ASYNC_POLL)
3550
                /* The poll completes the operation into the output buffer,
3551
                 * so the resume must not run the AEAD again: advance past
3552
                 * it now (the pop does not, the event is CALL_AGAIN). */
3553
                ssl->decrypt.state = CIPHER_STATE_END;
3554
            #else
3555
                /* Crypto callback re-invocation: leave the state at
3556
                 * CIPHER_STATE_DO so the retry re-enters the AEAD;
3557
                 * advancing would hand back the undecrypted record. */
3558
            #endif
3559
                return ret;
3560
            }
3561
        #endif
3562
3563
            /* Advance state */
3564
0
            ssl->decrypt.state = CIPHER_STATE_END;
3565
0
        }
3566
0
        FALL_THROUGH;
3567
3568
0
        case CIPHER_STATE_END:
3569
0
        {
3570
        #ifdef WOLFSSL_DEBUG_TLS
3571
            #ifdef CIPHER_NONCE
3572
                WOLFSSL_MSG("Nonce");
3573
                WOLFSSL_BUFFER(ssl->decrypt.nonce, ssl->specs.iv_size);
3574
            #endif
3575
                WOLFSSL_MSG("Decrypted data");
3576
                WOLFSSL_BUFFER(output, dataSz);
3577
        #endif
3578
        #ifdef WOLFSSL_CHECK_MEM_ZERO
3579
            if ((ssl->specs.bulk_cipher_algorithm != wolfssl_cipher_null) &&
3580
                    (ret == 0)) {
3581
                wc_MemZero_Add("TLS 1.3 Decrypted data", output, sz);
3582
            }
3583
        #endif
3584
3585
0
        #ifdef CIPHER_NONCE
3586
0
            ForceZero(ssl->decrypt.nonce, ssl->specs.iv_size);
3587
0
        #endif
3588
3589
0
            break;
3590
0
        }
3591
3592
0
       default:
3593
0
            break;
3594
0
    }
3595
3596
0
    if (ret < 0) {
3597
0
        WOLFSSL_ERROR_VERBOSE(ret);
3598
0
    }
3599
3600
0
    return ret;
3601
0
}
3602
3603
/* Build SSL Message, encrypted.
3604
 * TLS v1.3 encryption is AEAD only.
3605
 *
3606
 * ssl         The SSL/TLS object.
3607
 * output      The buffer to write record message to.
3608
 * outSz       Size of the buffer being written into.
3609
 * input       The record data to encrypt (excluding record header).
3610
 * inSz        The size of the record data.
3611
 * type        The recorder header content type.
3612
 * hashOutput  Whether to hash the unencrypted record data.
3613
 * sizeOnly    Only want the size of the record message.
3614
 * asyncOkay   If non-zero can return WC_PENDING_E, otherwise blocks on crypto
3615
 * returns the size of the encrypted record message or negative value on error.
3616
 */
3617
int BuildTls13Message(WOLFSSL* ssl, byte* output, int outSz, const byte* input,
3618
                int inSz, int type, int hashOutput, int sizeOnly, int asyncOkay)
3619
0
{
3620
0
    int ret;
3621
0
    BuildMsgArgs* args;
3622
0
    BuildMsgArgs  lcl_args;
3623
3624
0
    WOLFSSL_ENTER("BuildTls13Message");
3625
3626
0
    if (ssl == NULL) {
3627
0
        return BAD_FUNC_ARG;
3628
0
    }
3629
3630
#ifdef WOLFSSL_ASYNC_CRYPT
3631
    ret = WC_NO_PENDING_E;
3632
    if (asyncOkay) {
3633
        if (ssl->async == NULL) {
3634
            ssl->async = (struct WOLFSSL_ASYNC*)
3635
                    XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
3636
                            DYNAMIC_TYPE_ASYNC);
3637
            if (ssl->async == NULL)
3638
                return MEMORY_E;
3639
            XMEMSET(ssl->async, 0, sizeof(struct WOLFSSL_ASYNC));
3640
        }
3641
        /* Not ssl->async->args: that buffer belongs to the handler that
3642
         * called down into the record builder. */
3643
        args = &ssl->async->buildArgs;
3644
3645
        ret = wolfSSL_AsyncPop(ssl, &ssl->options.buildMsgState);
3646
        if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) {
3647
            /* Check for error */
3648
            if (ret < 0)
3649
                goto exit_buildmsg;
3650
        }
3651
    }
3652
    else
3653
#endif
3654
0
    {
3655
0
        args = &lcl_args;
3656
0
    }
3657
3658
    /* buildArgs13Set, not the pop result, marks a resume: the handler
3659
     * already popped the pending, and resetting on the pop result would
3660
     * rebuild a half-built record (transcript/sequence advance twice). */
3661
#ifdef WOLFSSL_ASYNC_CRYPT
3662
    if (!asyncOkay || !ssl->options.buildArgs13Set)
3663
#endif
3664
0
    {
3665
        /* Note: these hit ssl->options even for a sizeOnly probe, where every
3666
         * other result goes to lcl_args, so a probe destroys the resume point
3667
         * of a suspended asynchronous build. wolfssl_local_GetRecordSize() is
3668
         * the only sizeOnly caller and restores them; a new one must too. */
3669
0
        ret = 0;
3670
0
        ssl->options.buildMsgState = BUILD_MSG_BEGIN;
3671
        /* A fresh record must not inherit a suspended build's mid-way
3672
         * cipher state. Not for sizeOnly probes: GetRecordSize() does not
3673
         * save this field and rewinding would re-run the AEAD. */
3674
0
        if (!sizeOnly)
3675
0
            ssl->encrypt.state = CIPHER_STATE_BEGIN;
3676
0
        XMEMSET(args, 0, sizeof(BuildMsgArgs));
3677
3678
0
        args->headerSz = RECORD_HEADER_SZ;
3679
#ifdef WOLFSSL_DTLS13
3680
        if (ssl->options.dtls)
3681
            args->headerSz = Dtls13GetRlHeaderLength(ssl, 1);
3682
#endif /* WOLFSSL_DTLS13 */
3683
3684
0
        args->sz = args->headerSz + (word32)inSz;
3685
0
        args->idx  = args->headerSz;
3686
0
    }
3687
3688
#ifdef WOLFSSL_ASYNC_CRYPT
3689
    if (ret == WC_NO_ERR_TRACE(WC_NO_PENDING_E))
3690
        ret = 0;
3691
#endif
3692
3693
0
    switch (ssl->options.buildMsgState) {
3694
0
        case BUILD_MSG_BEGIN:
3695
0
        {
3696
           /* catch mistaken sizeOnly parameter */
3697
0
            if (sizeOnly) {
3698
0
                if (output || input) {
3699
0
                    WOLFSSL_MSG("BuildTls13Message with sizeOnly "
3700
0
                                "doesn't need input or output");
3701
0
                    return BAD_FUNC_ARG;
3702
0
                }
3703
0
            }
3704
0
            else if (output == NULL || input == NULL) {
3705
0
                return BAD_FUNC_ARG;
3706
0
            }
3707
3708
            /* Record layer content type at the end of record data. */
3709
0
            args->sz++;
3710
            /* Authentication data at the end. */
3711
0
            args->sz += ssl->specs.aead_mac_size;
3712
#ifdef WOLFSSL_DTLS13
3713
            /* Pad to minimum length */
3714
            if (ssl->options.dtls &&
3715
                    args->sz < (word32)Dtls13MinimumRecordLength(ssl)) {
3716
                args->pad = Dtls13MinimumRecordLength(ssl) - args->sz;
3717
                args->sz = Dtls13MinimumRecordLength(ssl);
3718
            }
3719
#endif
3720
0
            if (sizeOnly)
3721
0
                return (int)args->sz;
3722
3723
0
            if (args->sz > (word32)outSz) {
3724
0
                WOLFSSL_MSG("Oops, want to write past output buffer size");
3725
0
                return BUFFER_E;
3726
0
            }
3727
3728
            /* Record data length. */
3729
0
            args->size = (word16)(args->sz - args->headerSz);
3730
            /* Write/update the record header with the new size.
3731
             * Always have the content type as application data for encrypted
3732
             * messages in TLS v1.3.
3733
             */
3734
3735
0
            if (ssl->options.dtls) {
3736
#ifdef WOLFSSL_DTLS13
3737
                Dtls13RlAddCiphertextHeader(ssl, output, args->size);
3738
#endif /* WOLFSSL_DTLS13 */
3739
0
            }
3740
0
            else {
3741
0
                AddTls13RecordHeader(output, args->size, application_data, ssl);
3742
0
            }
3743
3744
            /* TLS v1.3 can do in place encryption. */
3745
0
            if (input != output + args->idx)
3746
0
                XMEMCPY(output + args->idx, input, (size_t)inSz);
3747
0
            args->idx += (word32)inSz;
3748
3749
    #ifdef WOLFSSL_ASYNC_CRYPT
3750
            /* Set only after the argument checks above cannot return any
3751
             * more: an early error return must not leave the resume marker
3752
             * set, or the next build would reuse stale args. */
3753
            if (asyncOkay)
3754
                ssl->options.buildArgs13Set = 1;
3755
    #endif
3756
0
            ssl->options.buildMsgState = BUILD_MSG_HASH;
3757
0
        }
3758
0
        FALL_THROUGH;
3759
3760
0
        case BUILD_MSG_HASH:
3761
0
        {
3762
0
            if (hashOutput) {
3763
0
                ret = HashOutput(ssl, output, (int)args->headerSz + inSz, 0);
3764
0
                if (ret != 0)
3765
0
                    goto exit_buildmsg;
3766
0
            }
3767
3768
            /* The real record content type goes at the end of the data. */
3769
0
            output[args->idx++] = (byte)type;
3770
            /* Double check that any necessary padding is zero'd out */
3771
0
            XMEMSET(output + args->idx, 0, args->pad);
3772
0
            args->idx += args->pad;
3773
3774
0
            ssl->options.buildMsgState = BUILD_MSG_ENCRYPT;
3775
0
        }
3776
0
        FALL_THROUGH;
3777
3778
0
        case BUILD_MSG_ENCRYPT:
3779
0
        {
3780
#ifdef WOLFSSL_QUIC
3781
            if (WOLFSSL_IS_QUIC(ssl)) {
3782
                /* QUIC does not use encryption of the TLS Record Layer.
3783
                 * Return the original length + added headers
3784
                 * and restore it in the record header. */
3785
                AddTls13RecordHeader(output, (word32)inSz, (byte)type, ssl);
3786
                ret = (int)args->headerSz + inSz;
3787
                goto exit_buildmsg;
3788
            }
3789
#endif
3790
        #ifdef ATOMIC_USER
3791
            if (ssl->ctx->MacEncryptCb) {
3792
                /* User Record Layer Callback handling */
3793
                byte* mac = output + args->idx;
3794
                output += args->headerSz;
3795
3796
                ret = ssl->ctx->MacEncryptCb(ssl, mac, output, (unsigned int)inSz, (byte)type, 0,
3797
                        output, output, args->size, ssl->MacEncryptCtx);
3798
            }
3799
            else
3800
        #endif
3801
0
            {
3802
0
                const byte* aad = output;
3803
0
                output += args->headerSz;
3804
0
                ret = EncryptTls13(ssl, output, output, args->size, aad,
3805
0
                                   (word16)args->headerSz, asyncOkay);
3806
            #ifdef WOLFSSL_ASYNC_REINVOKE
3807
                /* Non-resumable caller (alerts): finish the encryption by
3808
                 * re-invoking; devices were already waited on above. */
3809
                if (!asyncOkay) {
3810
                    int reinvoke = 0;
3811
3812
                    while (ret == WC_NO_ERR_TRACE(WC_PENDING_E) &&
3813
                            reinvoke++ < WOLFSSL_ASYNC_MAX_REINVOKE) {
3814
                        ret = EncryptTls13(ssl, output, output, args->size,
3815
                                           aad, (word16)args->headerSz,
3816
                                           asyncOkay);
3817
                    }
3818
                    if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
3819
                        /* A device that never completes would otherwise spin
3820
                         * here forever, which is what wc_AsyncWait() used to
3821
                         * do. Report it instead. */
3822
                        WOLFSSL_MSG("Crypto callback still pending after "
3823
                                    "retry limit on a blocking record");
3824
                        ret = WC_HW_WAIT_E;
3825
                    }
3826
                }
3827
            #endif
3828
0
                if (ret != 0) {
3829
                #ifdef WOLFSSL_ASYNC_CRYPT
3830
                    if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
3831
                #endif
3832
0
                    {
3833
                        /* Zeroize plaintext. */
3834
0
                        ForceZero(output, args->size);
3835
0
                    }
3836
0
                }
3837
#ifdef WOLFSSL_DTLS13
3838
                if (ret == 0 && ssl->options.dtls) {
3839
                    /* AAD points to the header. Reuse the variable  */
3840
                    ret = Dtls13EncryptRecordNumber(ssl, (byte*)aad,
3841
                                                    (word16)args->sz);
3842
                }
3843
#endif /* WOLFSSL_DTLS13 */
3844
0
            }
3845
0
            break;
3846
0
        }
3847
3848
0
        default:
3849
0
            break;
3850
0
    }
3851
3852
0
exit_buildmsg:
3853
3854
0
    WOLFSSL_LEAVE("BuildTls13Message", ret);
3855
3856
#ifdef WOLFSSL_ASYNC_CRYPT
3857
    if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
3858
        return ret;
3859
    }
3860
#endif
3861
3862
    /* make sure build message state is reset */
3863
0
    ssl->options.buildMsgState = BUILD_MSG_BEGIN;
3864
3865
    /* return sz on success */
3866
0
    if (ret == 0) {
3867
0
        ret = (int)args->sz;
3868
0
    }
3869
0
    else {
3870
0
        WOLFSSL_ERROR_VERBOSE(ret);
3871
0
    }
3872
3873
    /* Final cleanup */
3874
#ifdef WOLFSSL_ASYNC_CRYPT
3875
    if (asyncOkay)
3876
        ssl->options.buildArgs13Set = 0;
3877
#endif
3878
3879
0
    return ret;
3880
0
}
3881
3882
#if !defined(NO_WOLFSSL_CLIENT) || (!defined(NO_WOLFSSL_SERVER) && \
3883
    (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)) && \
3884
    (defined(WOLFSSL_PSK_ONE_ID) || defined(WOLFSSL_PRIORITIZE_PSK)))
3885
/* Find the cipher suite in the suites set in the SSL.
3886
 *
3887
 * ssl    SSL/TLS object.
3888
 * suite  Cipher suite to look for.
3889
 * returns 1 when suite is found in SSL/TLS object's list and 0 otherwise.
3890
 */
3891
int FindSuiteSSL(const WOLFSSL* ssl, byte* suite)
3892
0
{
3893
0
    word16 i;
3894
0
    const Suites* suites = WOLFSSL_SUITES(ssl);
3895
3896
0
    for (i = 0; i < suites->suiteSz; i += 2) {
3897
0
        if (suites->suites[i+0] == suite[0] &&
3898
0
                suites->suites[i+1] == suite[1]) {
3899
0
            return 1;
3900
0
        }
3901
0
    }
3902
3903
0
    return 0;
3904
0
}
3905
#endif
3906
3907
#ifndef NO_PSK
3908
/* Get the MAC algorithm for the TLS 1.3 cipher suite.
3909
 *
3910
 * @param [in] suite.
3911
 * @return  A value from wc_MACAlgorithm enumeration.
3912
 */
3913
byte SuiteMac(const byte* suite)
3914
{
3915
    byte mac = no_mac;
3916
3917
    if (suite[0] == TLS13_BYTE) {
3918
        switch (suite[1]) {
3919
        #ifdef BUILD_TLS_AES_128_GCM_SHA256
3920
            case TLS_AES_128_GCM_SHA256:
3921
                mac = sha256_mac;
3922
                break;
3923
        #endif
3924
        #ifdef BUILD_TLS_CHACHA20_POLY1305_SHA256
3925
            case TLS_CHACHA20_POLY1305_SHA256:
3926
                mac = sha256_mac;
3927
                break;
3928
        #endif
3929
        #ifdef BUILD_TLS_AES_128_CCM_SHA256
3930
            case TLS_AES_128_CCM_SHA256:
3931
                mac = sha256_mac;
3932
                break;
3933
        #endif
3934
        #ifdef BUILD_TLS_AES_128_CCM_8_SHA256
3935
            case TLS_AES_128_CCM_8_SHA256:
3936
                mac = sha256_mac;
3937
                break;
3938
        #endif
3939
        #ifdef BUILD_TLS_AES_256_GCM_SHA384
3940
            case TLS_AES_256_GCM_SHA384:
3941
                mac = sha384_mac;
3942
                break;
3943
        #endif
3944
            default:
3945
                break;
3946
        }
3947
    }
3948
#if (defined(WOLFSSL_SM4_GCM) || defined(WOLFSSL_SM4_CCM)) && \
3949
     defined(WOLFSSL_SM3)
3950
    else if (suite[0] == CIPHER_BYTE) {
3951
        switch (suite[1]) {
3952
        #ifdef BUILD_TLS_SM4_GCM_SM3
3953
            case TLS_SM4_GCM_SM3:
3954
                mac = sm3_mac;
3955
                break;
3956
        #endif
3957
        #ifdef BUILD_TLS_SM4_CCM_SM3
3958
            case TLS_SM4_CCM_SM3:
3959
                mac = sm3_mac;
3960
                break;
3961
        #endif
3962
            default:
3963
                break;
3964
        }
3965
    }
3966
#endif
3967
#ifdef HAVE_NULL_CIPHER
3968
    else if (suite[0] == ECC_BYTE) {
3969
        switch (suite[1]) {
3970
        #ifdef BUILD_TLS_SHA256_SHA256
3971
            case TLS_SHA256_SHA256:
3972
                mac = sha256_mac;
3973
                break;
3974
        #endif
3975
        #ifdef BUILD_TLS_SHA384_SHA384
3976
            case TLS_SHA384_SHA384:
3977
                mac = sha384_mac;
3978
                break;
3979
        #endif
3980
            default:
3981
                break;
3982
        }
3983
    }
3984
#endif
3985
3986
    return mac;
3987
}
3988
#endif
3989
3990
#if defined(WOLFSSL_SEND_HRR_COOKIE) && !defined(NO_WOLFSSL_SERVER)
3991
/* Create Cookie extension using the hash of the first ClientHello.
3992
 *
3993
 * ssl     SSL/TLS object.
3994
 * hash    The hash data.
3995
 * hashSz  The size of the hash data in bytes.
3996
 * returns 0 on success, otherwise failure.
3997
 */
3998
int CreateCookieExt(const WOLFSSL* ssl, byte* hash, word16 hashSz,
3999
                    TLSX** exts, byte cipherSuite0, byte cipherSuite)
4000
{
4001
    int  ret;
4002
    byte mac[WC_MAX_DIGEST_SIZE] = {0};
4003
    WC_DECLARE_VAR(cookieHmac, Hmac, 1, ssl->heap);
4004
    byte cookieType = 0;
4005
    byte macSz = 0;
4006
    byte cookie[OPAQUE8_LEN + WC_MAX_DIGEST_SIZE + OPAQUE16_LEN * 2];
4007
    TLSX* ext;
4008
    word16 cookieSz = 0;
4009
4010
    if (hash == NULL || hashSz == 0) {
4011
        return BAD_FUNC_ARG;
4012
    }
4013
4014
    if (ssl->buffers.tls13CookieSecret.buffer == NULL ||
4015
            ssl->buffers.tls13CookieSecret.length == 0) {
4016
        WOLFSSL_MSG("Missing DTLS 1.3 cookie secret");
4017
        return COOKIE_ERROR;
4018
    }
4019
4020
    /* Cookie Data = Hash Len | Hash | CS | KeyShare Group */
4021
    cookie[cookieSz++] = (byte)hashSz;
4022
    XMEMCPY(cookie + cookieSz, hash, hashSz);
4023
    cookieSz += hashSz;
4024
    cookie[cookieSz++] = cipherSuite0;
4025
    cookie[cookieSz++] = cipherSuite;
4026
    if ((ext = TLSX_Find(*exts, TLSX_KEY_SHARE)) != NULL) {
4027
        KeyShareEntry* kse = (KeyShareEntry*)ext->data;
4028
        if (kse == NULL) {
4029
            WOLFSSL_MSG("KeyShareEntry can't be empty when negotiating "
4030
                        "parameters");
4031
            return BAD_STATE_E;
4032
        }
4033
        c16toa(kse->group, cookie + cookieSz);
4034
        cookieSz += OPAQUE16_LEN;
4035
    }
4036
4037
#ifndef NO_SHA256
4038
    cookieType = WC_SHA256;
4039
    macSz = WC_SHA256_DIGEST_SIZE;
4040
#elif defined(WOLFSSL_SHA384)
4041
    cookieType = WC_SHA384;
4042
    macSz = WC_SHA384_DIGEST_SIZE;
4043
#elif defined(WOLFSSL_TLS13_SHA512)
4044
    cookieType = WC_SHA512;
4045
    macSz = WC_SHA512_DIGEST_SIZE;
4046
#elif defined(WOLFSSL_SM3)
4047
    cookieType = WC_SM3;
4048
    macSz = WC_SM3_DIGEST_SIZE;
4049
#else
4050
    #error "No digest to available to use with HMAC for cookies."
4051
#endif /* NO_SHA */
4052
4053
    WC_ALLOC_VAR_EX(cookieHmac, Hmac, 1, ssl->heap, DYNAMIC_TYPE_HMAC,
4054
                    return MEMORY_E);
4055
4056
    ret = wc_HmacInit(cookieHmac, ssl->heap, ssl->devId);
4057
    if (ret == 0) {
4058
        ret = wc_HmacSetKey(cookieHmac, cookieType,
4059
                            ssl->buffers.tls13CookieSecret.buffer,
4060
                            ssl->buffers.tls13CookieSecret.length);
4061
    }
4062
    if (ret == 0)
4063
        ret = wc_HmacUpdate(cookieHmac, cookie, cookieSz);
4064
#ifdef WOLFSSL_DTLS13
4065
    /* Tie cookie to peer address */
4066
    if (ret == 0) {
4067
        /* peerLock not necessary. Still in handshake phase. */
4068
        if (ssl->options.dtls && ssl->buffers.dtlsCtx.peer.sz > 0) {
4069
            ret = wc_HmacUpdate(cookieHmac,
4070
                (byte*)ssl->buffers.dtlsCtx.peer.sa,
4071
                ssl->buffers.dtlsCtx.peer.sz);
4072
        }
4073
    }
4074
#endif
4075
    if (ret == 0)
4076
        ret = wc_HmacFinal(cookieHmac, mac);
4077
4078
    wc_HmacFree(cookieHmac);
4079
    WC_FREE_VAR_EX(cookieHmac, ssl->heap, DYNAMIC_TYPE_HMAC);
4080
    if (ret != 0)
4081
        return ret;
4082
4083
    /* The cookie data is the hash and the integrity check. */
4084
    return TLSX_Cookie_Use(ssl, cookie, cookieSz, mac, macSz, 1, exts);
4085
}
4086
#endif
4087
4088
#ifdef WOLFSSL_DTLS13
4089
#define HRR_MAX_HS_HEADER_SZ DTLS_HANDSHAKE_HEADER_SZ
4090
#else
4091
#define HRR_MAX_HS_HEADER_SZ HANDSHAKE_HEADER_SZ
4092
#endif /* WOLFSSL_DTLS13 */
4093
4094
static int CreateCookie(const WOLFSSL* ssl, byte** hash, byte* hashSz,
4095
                            Hashes* hashes, TLSX** exts)
4096
0
{
4097
0
    int    ret = 0;
4098
4099
0
    (void)exts;
4100
4101
0
    *hash = NULL;
4102
0
    switch (ssl->specs.mac_algorithm) {
4103
0
    #ifndef NO_SHA256
4104
0
        case sha256_mac:
4105
0
            *hash = hashes->sha256;
4106
0
            break;
4107
0
    #endif
4108
0
    #ifdef WOLFSSL_SHA384
4109
0
        case sha384_mac:
4110
0
            *hash = hashes->sha384;
4111
0
            break;
4112
0
    #endif
4113
    #ifdef WOLFSSL_TLS13_SHA512
4114
        case sha512_mac:
4115
            *hash = hashes->sha512;
4116
            break;
4117
    #endif
4118
    #ifdef WOLFSSL_SM3
4119
        case sm3_mac:
4120
            *hash = hashes->sm3;
4121
            break;
4122
    #endif
4123
0
    }
4124
0
    *hashSz = ssl->specs.hash_size;
4125
4126
    /* check hash */
4127
0
    if (*hash == NULL && *hashSz > 0)
4128
0
        return BAD_FUNC_ARG;
4129
4130
#if defined(WOLFSSL_SEND_HRR_COOKIE) && !defined(NO_WOLFSSL_SERVER)
4131
    if (ssl->options.sendCookie && ssl->options.side == WOLFSSL_SERVER_END)
4132
        ret = CreateCookieExt(ssl, *hash, *hashSz, exts,
4133
                ssl->options.cipherSuite0, ssl->options.cipherSuite);
4134
#endif
4135
0
    return ret;
4136
0
}
4137
4138
/* Restart the handshake hash with a hash of the previous messages.
4139
 *
4140
 * ssl The SSL/TLS object.
4141
 * returns 0 on success, otherwise failure.
4142
 */
4143
int RestartHandshakeHash(WOLFSSL* ssl)
4144
0
{
4145
0
    int    ret;
4146
0
    byte   header[HANDSHAKE_HEADER_SZ] = {0};
4147
0
    Hashes hashes;
4148
0
    byte*  hash = NULL;
4149
0
    byte   hashSz = 0;
4150
4151
0
    ret = BuildCertHashes(ssl, &hashes);
4152
0
    if (ret != 0)
4153
0
        return ret;
4154
0
    ret = CreateCookie(ssl, &hash, &hashSz, &hashes, &ssl->extensions);
4155
0
    if (ret != 0)
4156
0
        return ret;
4157
#if defined(WOLFSSL_SEND_HRR_COOKIE) && !defined(NO_WOLFSSL_SERVER)
4158
    if (ssl->options.sendCookie && ssl->options.side == WOLFSSL_SERVER_END)
4159
        return 0;
4160
#endif
4161
4162
0
    AddTls13HandShakeHeader(header, hashSz, 0, 0, message_hash, ssl);
4163
4164
#ifdef WOLFSSL_DEBUG_TLS
4165
    WOLFSSL_MSG("Restart Hash");
4166
    WOLFSSL_BUFFER(hash, hashSz);
4167
#endif
4168
4169
0
    ret = InitHandshakeHashes(ssl);
4170
0
    if (ret != 0)
4171
0
        return ret;
4172
0
    ret = HashRaw(ssl, header, sizeof(header));
4173
0
    if (ret != 0)
4174
0
        return ret;
4175
0
    return HashRaw(ssl, hash, hashSz);
4176
0
}
4177
4178
#if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER)
4179
/* The value in the random field of a ServerHello to indicate
4180
 * HelloRetryRequest.
4181
 */
4182
static byte helloRetryRequestRandom[] = {
4183
    0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11,
4184
    0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91,
4185
    0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E,
4186
    0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C
4187
};
4188
#endif
4189
4190
#ifdef HAVE_ECH
4191
/* returns the index of the first supported cipher suite, -1 if none */
4192
int EchConfigGetSupportedCipherSuite(WOLFSSL_EchConfig* config)
4193
{
4194
    int i = 0;
4195
4196
    if (!wc_HpkeKemIsSupported(config->kemId)) {
4197
        WOLFSSL_MSG("ECH config: KEM not supported");
4198
        return WOLFSSL_FATAL_ERROR;
4199
    }
4200
4201
    for (i = 0; i < config->numCipherSuites; i++) {
4202
        if (wc_HpkeKdfIsSupported(config->cipherSuites[i].kdfId) &&
4203
                wc_HpkeAeadIsSupported(config->cipherSuites[i].aeadId)) {
4204
            return i;
4205
        }
4206
    }
4207
4208
    WOLFSSL_MSG("ECH config: KDF or AEAD not supported");
4209
    return WOLFSSL_FATAL_ERROR;
4210
}
4211
4212
/* Hash the inner client hello, initializing the hsHashesEch field if needed.
4213
 * This should receive the client hello without outer_extensions 'encoding'
4214
 *
4215
 * ssl      SSL/TLS object.
4216
 * ech      ECH object.
4217
 * returns 0 on success and otherwise failure.
4218
 */
4219
static int EchHashHelloInner(WOLFSSL* ssl, WOLFSSL_ECH* ech)
4220
{
4221
    int ret = 0;
4222
    int headerSz;
4223
    word32 realSz;
4224
    HS_Hashes* tmpHashes;
4225
#ifndef NO_WOLFSSL_CLIENT
4226
    byte falseHeader[HRR_MAX_HS_HEADER_SZ];
4227
#endif
4228
4229
    if (ssl == NULL || ech == NULL) {
4230
        return BAD_FUNC_ARG;
4231
    }
4232
4233
#ifdef WOLFSSL_DTLS13
4234
    headerSz = ssl->options.dtls ? DTLS13_HANDSHAKE_HEADER_SZ :
4235
                                   HANDSHAKE_HEADER_SZ;
4236
#else
4237
    headerSz = HANDSHAKE_HEADER_SZ;
4238
#endif
4239
4240
    realSz = ech->innerClientHelloLen;
4241
4242
    tmpHashes = ssl->hsHashes;
4243
4244
    ssl->hsHashes = ssl->hsHashesEch;
4245
    if (ssl->hsHashes == NULL) {
4246
        ret = InitHandshakeHashes(ssl);
4247
        if (ret == 0) {
4248
            ssl->hsHashesEch = ssl->hsHashes;
4249
        }
4250
    }
4251
4252
    if (ret == 0) {
4253
#ifndef NO_WOLFSSL_CLIENT
4254
        if (ssl->options.side == WOLFSSL_CLIENT_END) {
4255
            /* client-side: innerClientHello contains body only */
4256
            AddTls13HandShakeHeader(falseHeader, realSz, 0, 0, client_hello,
4257
                                    ssl);
4258
            ret = HashRaw(ssl, falseHeader, headerSz);
4259
            if (ret == 0) {
4260
                ret = HashRaw(ssl, ech->innerClientHello, realSz);
4261
            }
4262
        }
4263
#endif
4264
#ifndef NO_WOLFSSL_SERVER
4265
        if (ssl->options.side == WOLFSSL_SERVER_END) {
4266
            /* server-side: innerClientHello contains header + body */
4267
            ret = HashRaw(ssl, ech->innerClientHello, headerSz + realSz);
4268
        }
4269
#endif
4270
    }
4271
4272
    ssl->hsHashes = tmpHashes;
4273
    return ret;
4274
}
4275
4276
/* Calculate the 8 ECH confirmation bytes.
4277
 *
4278
 * ssl            SSL/TLS object.
4279
 * label          Ascii string describing ECH acceptance or rejection.
4280
 * labelSz        Length of label excluding NULL character.
4281
 * input          The buffer to calculate confirmation off of.
4282
 * acceptOffset   Where the 8 ECH confirmation bytes start.
4283
 * helloSz        Size of hello message.
4284
 * isHrr          Whether message is a HelloRetryRequest or not.
4285
 * acceptExpanded An 8 byte array to store calculated confirmation to.
4286
 * returns 0 on success and otherwise failure.
4287
 */
4288
static int EchCalcAcceptance(WOLFSSL* ssl, byte* label, word16 labelSz,
4289
    const byte* input, int acceptOffset, int helloSz, byte isHrr,
4290
    byte* acceptExpanded)
4291
{
4292
    int ret = 0;
4293
    int digestType = 0;
4294
    int digestSize = 0;
4295
    int hashSz = 0;
4296
    int headerSz;
4297
    HS_Hashes* tmpHashes;
4298
    HS_Hashes* acceptHash = NULL;
4299
    byte zeros[WC_MAX_DIGEST_SIZE];
4300
    byte transcriptEchConf[WC_MAX_DIGEST_SIZE];
4301
    byte clientHelloInnerHash[WC_MAX_DIGEST_SIZE];
4302
    byte expandLabelPrk[WC_MAX_DIGEST_SIZE];
4303
    byte messageHashHeader[HRR_MAX_HS_HEADER_SZ];
4304
4305
    XMEMSET(zeros, 0, sizeof(zeros));
4306
    XMEMSET(transcriptEchConf, 0, sizeof(transcriptEchConf));
4307
    XMEMSET(clientHelloInnerHash, 0, sizeof(clientHelloInnerHash));
4308
    XMEMSET(expandLabelPrk, 0, sizeof(expandLabelPrk));
4309
4310
#ifdef WOLFSSL_CHECK_MEM_ZERO
4311
    wc_MemZero_Add("ECH PRK", expandLabelPrk, sizeof(expandLabelPrk));
4312
#endif
4313
4314
    tmpHashes = ssl->hsHashes;
4315
    ssl->hsHashes = ssl->hsHashesEch;
4316
4317
#ifdef WOLFSSL_DTLS13
4318
    headerSz = ssl->options.dtls ? DTLS13_HANDSHAKE_HEADER_SZ :
4319
                                   HANDSHAKE_HEADER_SZ;
4320
#else
4321
    headerSz = HANDSHAKE_HEADER_SZ;
4322
#endif
4323
4324
    /* input starts at the handshake header, so the confirmation bytes must lie
4325
     * inside the message that follows it */
4326
    if (acceptOffset < headerSz || helloSz < 0 ||
4327
            (helloSz + headerSz) < ECH_ACCEPT_CONFIRMATION_SZ ||
4328
            acceptOffset > (helloSz + headerSz) -
4329
                ECH_ACCEPT_CONFIRMATION_SZ) {
4330
        WOLFSSL_ERROR_VERBOSE(BUFFER_ERROR);
4331
        ret = BUFFER_ERROR;
4332
    }
4333
4334
    if (ret == 0 && isHrr) {
4335
        /* the transcript hash of ClientHelloInner1 */
4336
        ret = GetMsgHash(ssl, clientHelloInnerHash);
4337
        if (ret > 0) {
4338
            hashSz = ret;
4339
            ret = 0;
4340
        }
4341
        else if (ret == 0) {
4342
            ret = HASH_TYPE_E;
4343
        }
4344
4345
        /* restart ECH transcript hash, similar to RestartHandshakeHash but
4346
         * don't add a cookie */
4347
        if (ret == 0) {
4348
            ret = InitHandshakeHashes(ssl);
4349
            ssl->hsHashesEch = ssl->hsHashes;
4350
        }
4351
        if (ret == 0) {
4352
            AddTls13HandShakeHeader(messageHashHeader, (word32)hashSz, 0, 0,
4353
                message_hash, ssl);
4354
            ret = HashRaw(ssl, messageHashHeader, headerSz);
4355
        }
4356
        if (ret == 0) {
4357
            ret = HashRaw(ssl, clientHelloInnerHash, (word32)hashSz);
4358
        }
4359
    }
4360
4361
    /* hash with zeros for confirmation computation */
4362
    if (ret == 0) {
4363
        ret = InitHandshakeHashesAndCopy(ssl, ssl->hsHashesEch, &acceptHash);
4364
    }
4365
    if (ret == 0) {
4366
        ssl->hsHashes = acceptHash;
4367
        ret = HashRaw(ssl, input, acceptOffset);
4368
    }
4369
    if (ret == 0) {
4370
        ret = HashRaw(ssl, zeros, ECH_ACCEPT_CONFIRMATION_SZ);
4371
    }
4372
    if (ret == 0) {
4373
        ret = HashRaw(ssl, input + acceptOffset + ECH_ACCEPT_CONFIRMATION_SZ,
4374
            helloSz + headerSz - (acceptOffset + ECH_ACCEPT_CONFIRMATION_SZ));
4375
    }
4376
4377
    /* get the modified transcript hash */
4378
    if (ret == 0) {
4379
        ret = GetMsgHash(ssl, transcriptEchConf);
4380
        if (ret > 0) {
4381
            ret = 0;
4382
        }
4383
        else if (ret == 0) {
4384
            ret = HASH_TYPE_E;
4385
        }
4386
    }
4387
4388
    /* pick the right type and size based on mac_algorithm */
4389
    if (ret == 0) {
4390
        switch (ssl->specs.mac_algorithm) {
4391
#ifndef NO_SHA256
4392
            case sha256_mac:
4393
                digestType = WC_SHA256;
4394
                digestSize = WC_SHA256_DIGEST_SIZE;
4395
                break;
4396
#endif /* !NO_SHA256 */
4397
#ifdef WOLFSSL_SHA384
4398
            case sha384_mac:
4399
                digestType = WC_SHA384;
4400
                digestSize = WC_SHA384_DIGEST_SIZE;
4401
                break;
4402
#endif /* WOLFSSL_SHA384 */
4403
#ifdef WOLFSSL_TLS13_SHA512
4404
            case sha512_mac:
4405
                digestType = WC_SHA512;
4406
                digestSize = WC_SHA512_DIGEST_SIZE;
4407
                break;
4408
#endif /* WOLFSSL_TLS13_SHA512 */
4409
#ifdef WOLFSSL_SM3
4410
            case sm3_mac:
4411
                digestType = WC_SM3;
4412
                digestSize = WC_SM3_DIGEST_SIZE;
4413
                break;
4414
#endif /* WOLFSSL_SM3 */
4415
            default:
4416
                ret = WOLFSSL_FATAL_ERROR;
4417
                break;
4418
        }
4419
    }
4420
4421
    /* extract clientRandomInner with a key of all zeros */
4422
    if (ret == 0) {
4423
        PRIVATE_KEY_UNLOCK();
4424
    #if !defined(HAVE_FIPS) || \
4425
        (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(6,0))
4426
        ret = wc_HKDF_Extract_ex(digestType, zeros, (word32)digestSize,
4427
            ssl->arrays->clientRandomInner, RAN_LEN, expandLabelPrk,
4428
            ssl->heap, ssl->devId);
4429
    #else
4430
        ret = wc_HKDF_Extract(digestType, zeros, digestSize,
4431
            ssl->arrays->clientRandomInner, RAN_LEN, expandLabelPrk);
4432
    #endif
4433
        PRIVATE_KEY_LOCK();
4434
    }
4435
4436
    /* tls expand with the confirmation label */
4437
    if (ret == 0) {
4438
        PRIVATE_KEY_UNLOCK();
4439
#ifdef WOLFSSL_DTLS13
4440
        if (ssl->options.dtls) {
4441
            ret = Tls13HKDFExpandKeyLabel(ssl, acceptExpanded,
4442
                ECH_ACCEPT_CONFIRMATION_SZ, expandLabelPrk, (word32)digestSize,
4443
                dtls13ProtocolLabel, DTLS13_PROTOCOL_LABEL_SZ, label, labelSz,
4444
                transcriptEchConf, (word32)digestSize, digestType,
4445
                WOLFSSL_SERVER_END);
4446
        }
4447
        else
4448
#endif
4449
        {
4450
            ret = Tls13HKDFExpandKeyLabel(ssl, acceptExpanded,
4451
                ECH_ACCEPT_CONFIRMATION_SZ, expandLabelPrk, (word32)digestSize,
4452
                tls13ProtocolLabel, TLS13_PROTOCOL_LABEL_SZ, label, labelSz,
4453
                transcriptEchConf, (word32)digestSize, digestType,
4454
                WOLFSSL_SERVER_END);
4455
        }
4456
        PRIVATE_KEY_LOCK();
4457
    }
4458
4459
    if (acceptHash != NULL) {
4460
        ssl->hsHashes = acceptHash;
4461
        FreeHandshakeHashes(ssl);
4462
    }
4463
4464
    ssl->hsHashes = tmpHashes;
4465
    ForceZero(expandLabelPrk, sizeof(expandLabelPrk));
4466
#ifdef WOLFSSL_CHECK_MEM_ZERO
4467
    wc_MemZero_Check(expandLabelPrk, sizeof(expandLabelPrk));
4468
#endif
4469
    return ret;
4470
}
4471
#endif
4472
4473
#if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG) && \
4474
    (!defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER))
4475
/* Record whether the peer's advertised algorithms permit SHA-1 signed
4476
 * certificates, and release the peer's signature_algorithms_cert list.
4477
 *
4478
 * RFC 8446 Section 4.2.3 has signature_algorithms cover certificate signatures
4479
 * when signature_algorithms_cert is absent.
4480
 *
4481
 * ssl         The SSL/TLS object.
4482
 * peerSuites  The peer's signature_algorithms list.
4483
 */
4484
static void SetPeerSha1CertOk(WOLFSSL* ssl, const Suites* peerSuites)
4485
0
{
4486
0
    const byte* list = NULL;
4487
0
    word16      listSz = 0;
4488
0
    word16      i;
4489
4490
0
    ssl->options.peerSha1CertOk = 0;
4491
4492
0
    if (ssl->certHashSigAlgoSz > 0) {
4493
0
        list = ssl->certHashSigAlgo;
4494
0
        listSz = ssl->certHashSigAlgoSz;
4495
0
    }
4496
0
    else if (peerSuites != NULL) {
4497
0
        list = peerSuites->hashSigAlgo;
4498
0
        listSz = peerSuites->hashSigAlgoSz;
4499
0
    }
4500
4501
0
    for (i = 0; (list != NULL) && (i + 2 <= listSz); i += 2) {
4502
        /* Only rsa_pkcs1_sha1, dsa_sha1 and ecdsa_sha1 carry sha_mac as the
4503
         * first byte of the signature scheme. */
4504
0
        if (list[i] == sha_mac) {
4505
0
            ssl->options.peerSha1CertOk = 1;
4506
0
            break;
4507
0
        }
4508
0
    }
4509
4510
    /* Post-handshake auth parses its own list. */
4511
0
    XFREE(ssl->certHashSigAlgo, ssl->heap, DYNAMIC_TYPE_TLSX);
4512
0
    ssl->certHashSigAlgo = NULL;
4513
0
    ssl->certHashSigAlgoSz = 0;
4514
0
}
4515
#endif /* !NO_CERTS && !WOLFSSL_NO_SIGALG && (client || server) */
4516
4517
#ifndef NO_WOLFSSL_CLIENT
4518
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
4519
#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_PSK_ONE_ID) && \
4520
    !defined(NO_PSK)
4521
/**
4522
* convert mac algorithm to WOLFSSL_EVP_MD
4523
* @param mac_alg mac algorithm
4524
* @return const WOLFSSL_EVP_MD on successful, otherwise NULL
4525
*/
4526
static const WOLFSSL_EVP_MD* ssl_handshake_md(const byte mac_alg)
4527
{
4528
    switch(mac_alg) {
4529
        case no_mac:
4530
            return NULL;
4531
    #ifndef NO_MD5
4532
        case md5_mac:
4533
            return wolfSSL_EVP_md5();
4534
    #endif
4535
    #ifndef NO_SHA
4536
        case sha_mac:
4537
            return wolfSSL_EVP_sha1();
4538
    #endif
4539
    #ifdef WOLFSSL_SHA224
4540
        case sha224_mac:
4541
            return wolfSSL_EVP_sha224();
4542
    #endif
4543
        case sha256_mac:
4544
            return wolfSSL_EVP_sha256();
4545
    #ifdef WOLFSSL_SHA384
4546
        case sha384_mac:
4547
            return wolfSSL_EVP_sha384();
4548
    #endif
4549
    #ifdef WOLFSSL_SHA512
4550
        case sha512_mac:
4551
            return wolfSSL_EVP_sha512();
4552
    #endif
4553
        case rmd_mac:
4554
        case blake2b_mac:
4555
            WOLFSSL_MSG("no suitable EVP_MD");
4556
            return NULL;
4557
        default:
4558
            WOLFSSL_MSG("Unknown mac algorithm");
4559
            return NULL;
4560
    }
4561
}
4562
#endif
4563
/* Setup pre-shared key based on the details in the extension data.
4564
 *
4565
 * ssl          SSL/TLS object.
4566
 * psk          Pre-shared key extension data.
4567
 * clientHello  Whether called from client_hello construction.
4568
 * returns 0 on success, PSK_KEY_ERROR when the client PSK callback fails and
4569
 * other negative value on failure.
4570
 */
4571
static int SetupPskKey(WOLFSSL* ssl, PreSharedKey* psk, int clientHello)
4572
{
4573
#if defined(HAVE_SESSION_TICKET) || !defined(WOLFSSL_PSK_ONE_ID)
4574
    int ret;
4575
#endif
4576
    byte suite[2];
4577
4578
    if (psk == NULL)
4579
        return BAD_FUNC_ARG;
4580
4581
    if (!HaveUniqueSessionObj(ssl)) {
4582
        WOLFSSL_MSG("Unable to have unique session object");
4583
        WOLFSSL_ERROR_VERBOSE(MEMORY_ERROR);
4584
        return MEMORY_ERROR;
4585
    }
4586
4587
    suite[0] = ssl->options.cipherSuite0;
4588
    suite[1] = ssl->options.cipherSuite;
4589
4590
#ifdef HAVE_SESSION_TICKET
4591
    if (psk->resumption) {
4592
        if (clientHello) {
4593
            suite[0] = psk->cipherSuite0;
4594
            suite[1] = psk->cipherSuite;
4595
4596
            /* Ensure cipher suite is supported or changed suite to one with
4597
             * the same MAC algorithm. */
4598
            if (!FindSuiteSSL(ssl, suite)) {
4599
                WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
4600
                return PSK_KEY_ERROR;
4601
            }
4602
4603
            ssl->options.cipherSuite0 = suite[0];
4604
            ssl->options.cipherSuite = suite[1];
4605
4606
            /* Setting mac for binder and keys for deriving EarlyData. */
4607
            ret = SetCipherSpecs(ssl);
4608
            if (ret != 0)
4609
                return ret;
4610
        }
4611
4612
    #ifdef WOLFSSL_EARLY_DATA
4613
        if (ssl->session->maxEarlyDataSz == 0)
4614
            ssl->earlyData = no_early_data;
4615
    #endif
4616
        /* Resumption PSK is master secret. */
4617
        ssl->arrays->psk_keySz = ssl->specs.hash_size;
4618
        if ((ret = DeriveResumptionPSK(ssl, ssl->session->ticketNonce.data,
4619
                   ssl->session->ticketNonce.len, ssl->arrays->psk_key)) != 0) {
4620
            return ret;
4621
        }
4622
        if (!clientHello) {
4623
            /* CLIENT: using secret in ticket for peer authentication. */
4624
            ssl->options.peerAuthGood = 1;
4625
        }
4626
    }
4627
#endif
4628
#ifndef NO_PSK
4629
    if (!psk->resumption) {
4630
        /* Get the pre-shared key. */
4631
#ifndef WOLFSSL_PSK_ONE_ID
4632
        const char* cipherName = NULL;
4633
    #ifdef OPENSSL_EXTRA
4634
        WOLFSSL_SESSION* psksession = NULL;
4635
    #endif
4636
4637
        /* Set the client identity to use. */
4638
        if (psk->identityLen > MAX_PSK_ID_LEN)
4639
            return PSK_KEY_ERROR;
4640
        XMEMSET(ssl->arrays->client_identity, 0,
4641
            sizeof(ssl->arrays->client_identity));
4642
        XMEMCPY(ssl->arrays->client_identity, psk->identity, psk->identityLen);
4643
4644
    #ifdef WOLFSSL_DEBUG_TLS
4645
        WOLFSSL_MSG("PSK cipher suite:");
4646
        WOLFSSL_MSG(GetCipherNameInternal(psk->cipherSuite0, psk->cipherSuite));
4647
    #endif
4648
4649
        /* Get the pre-shared key. */
4650
    #ifdef OPENSSL_EXTRA
4651
        if (ssl->options.session_psk_cb != NULL) {
4652
            const unsigned char* id = NULL;
4653
            size_t idlen = 0;
4654
            const WOLFSSL_EVP_MD* handshake_md = NULL;
4655
4656
            if (ssl->msgsReceived.got_hello_retry_request >= 1) {
4657
                handshake_md = ssl_handshake_md(ssl->specs.mac_algorithm);
4658
            }
4659
            /* OpenSSL compatible callback that gets cached session. */
4660
            if (ssl->options.session_psk_cb(ssl, handshake_md, &id, &idlen,
4661
                                                            &psksession) == 0) {
4662
                wolfSSL_FreeSession(ssl->ctx, psksession);
4663
                WOLFSSL_MSG("psk session callback failed");
4664
                return PSK_KEY_ERROR;
4665
            }
4666
            if (psksession != NULL) {
4667
                if (idlen > MAX_PSK_KEY_LEN) {
4668
                    wolfSSL_FreeSession(ssl->ctx, psksession);
4669
                    WOLFSSL_MSG("psk key length is too long");
4670
                    WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
4671
                    return PSK_KEY_ERROR;
4672
                }
4673
4674
                ssl->arrays->psk_keySz = (word32)idlen;
4675
                XMEMCPY(ssl->arrays->psk_key, id, idlen);
4676
                suite[0] = psksession->cipherSuite0;
4677
                suite[1] = psksession->cipherSuite;
4678
                /* Not needed anymore. */
4679
                wolfSSL_FreeSession(ssl->ctx, psksession);
4680
                /* Leave pointer not NULL to indicate success with callback. */
4681
            }
4682
        }
4683
        if (psksession != NULL) {
4684
            /* Don't try other callbacks - we have an answer. */
4685
        }
4686
        else
4687
    #endif /* OPENSSL_EXTRA */
4688
        if (ssl->options.client_psk_cs_cb != NULL) {
4689
        #ifdef WOLFSSL_PSK_MULTI_ID_PER_CS
4690
            ssl->arrays->client_identity[0] = 0;
4691
        #endif
4692
            /* Lookup key again for next identity. */
4693
            ssl->arrays->psk_keySz = ssl->options.client_psk_cs_cb(
4694
                ssl, ssl->arrays->server_hint,
4695
                ssl->arrays->client_identity, MAX_PSK_ID_LEN,
4696
                ssl->arrays->psk_key, MAX_PSK_KEY_LEN,
4697
                GetCipherNameInternal(psk->cipherSuite0, psk->cipherSuite));
4698
            if (clientHello) {
4699
                /* Use PSK cipher suite. */
4700
                ssl->options.cipherSuite0 = psk->cipherSuite0;
4701
                ssl->options.cipherSuite  = psk->cipherSuite;
4702
            }
4703
            else {
4704
                byte pskCS[2];
4705
                pskCS[0] = psk->cipherSuite0;
4706
                pskCS[1] = psk->cipherSuite;
4707
4708
                /* Ensure PSK and negotiated cipher suites have same hash. */
4709
                if (SuiteMac(pskCS) != SuiteMac(suite)) {
4710
                    WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
4711
                    return PSK_KEY_ERROR;
4712
                }
4713
                /* Negotiated cipher suite is to be used - update PSK. */
4714
                psk->cipherSuite0 = suite[0];
4715
                psk->cipherSuite  = suite[1];
4716
            }
4717
        }
4718
        else if (ssl->options.client_psk_tls13_cb != NULL) {
4719
            byte cipherSuite0;
4720
            byte cipherSuite;
4721
            int cipherSuiteFlags = WOLFSSL_CIPHER_SUITE_FLAG_NONE;
4722
4723
            ssl->arrays->psk_keySz = ssl->options.client_psk_tls13_cb(ssl,
4724
                    ssl->arrays->server_hint, ssl->arrays->client_identity,
4725
                    MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN,
4726
                    &cipherName);
4727
            if (GetCipherSuiteFromName(cipherName, &cipherSuite0,
4728
                            &cipherSuite, NULL, NULL, &cipherSuiteFlags) != 0) {
4729
                WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
4730
                return PSK_KEY_ERROR;
4731
            }
4732
            ssl->options.cipherSuite0 = cipherSuite0;
4733
            ssl->options.cipherSuite  = cipherSuite;
4734
            (void)cipherSuiteFlags;
4735
        }
4736
        else {
4737
            ssl->arrays->psk_keySz = ssl->options.client_psk_cb(ssl,
4738
                    ssl->arrays->server_hint, ssl->arrays->client_identity,
4739
                    MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN);
4740
            ssl->options.cipherSuite0 = TLS13_BYTE;
4741
            ssl->options.cipherSuite  = WOLFSSL_DEF_PSK_CIPHER;
4742
        }
4743
        if (ssl->arrays->psk_keySz == 0 ||
4744
                (ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN &&
4745
            (int)ssl->arrays->psk_keySz != WC_NO_ERR_TRACE(USE_HW_PSK))) {
4746
            WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
4747
            return PSK_KEY_ERROR;
4748
        }
4749
4750
        ret = SetCipherSpecs(ssl);
4751
        if (ret != 0)
4752
            return ret;
4753
#else
4754
        /* PSK information loaded during setting of default TLS extensions. */
4755
#endif /* !WOLFSSL_PSK_ONE_ID */
4756
4757
        if (!clientHello && (psk->cipherSuite0 != suite[0] ||
4758
                             psk->cipherSuite  != suite[1])) {
4759
            WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
4760
            return PSK_KEY_ERROR;
4761
        }
4762
4763
        if (!clientHello) {
4764
#ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
4765
            if (ssl->options.certWithExternPsk) {
4766
                /* Certificate authentication is still required. */
4767
                ssl->options.peerAuthGood = 0;
4768
            }
4769
            else
4770
#endif
4771
            {
4772
                /* CLIENT: using PSK for peer authentication. */
4773
                ssl->options.peerAuthGood = 1;
4774
            }
4775
        }
4776
    }
4777
#endif
4778
4779
#ifdef HAVE_SUPPORTED_CURVES
4780
    if (!clientHello) {
4781
        TLSX* ext;
4782
        word32 modes;
4783
        KeyShareEntry* kse = NULL;
4784
4785
        /* Get the PSK key exchange modes the client wants to negotiate. */
4786
        ext = TLSX_Find(ssl->extensions, TLSX_PSK_KEY_EXCHANGE_MODES);
4787
        if (ext == NULL) {
4788
            WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
4789
            return PSK_KEY_ERROR;
4790
        }
4791
        modes = ext->val;
4792
4793
        ext = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
4794
        if (ext != NULL) {
4795
            kse = (KeyShareEntry*)ext->data;
4796
        }
4797
        /* Use (EC)DHE for forward-security if possible. */
4798
        if (((modes & (1 << PSK_DHE_KE)) != 0) && (!ssl->options.noPskDheKe) &&
4799
                                                (kse != NULL) && kse->derived) {
4800
            if ((kse->session != 0) && (kse->session != kse->group)) {
4801
                WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
4802
                return PSK_KEY_ERROR;
4803
            }
4804
        }
4805
        else if (ssl->options.onlyPskDheKe ||
4806
                 (ssl->options.failNoPSK && !psk->resumption)) {
4807
            /* A mandatory external PSK (failNoPSK) must be combined with
4808
             * (EC)DHE for forward secrecy, so reject a pure psk_ke
4809
             * negotiation. Session-ticket resumption is exempt. */
4810
            WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
4811
            return PSK_KEY_ERROR;
4812
        }
4813
        else if (ssl->options.noPskDheKe) {
4814
            ssl->arrays->preMasterSz = 0;
4815
        }
4816
    }
4817
    else
4818
#endif
4819
    if (ssl->options.noPskDheKe) {
4820
        ssl->arrays->preMasterSz = 0;
4821
    }
4822
4823
    /* Derive the early secret using the PSK. */
4824
    return DeriveEarlySecret(ssl);
4825
}
4826
4827
/* Derive and write the binders into the ClientHello in space left when
4828
 * writing the Pre-Shared Key extension.
4829
 *
4830
 * ssl     The SSL/TLS object.
4831
 * output  The buffer containing the ClientHello.
4832
 * idx     The index at the end of the completed ClientHello.
4833
 * returns 0 on success and otherwise failure.
4834
 */
4835
static int WritePSKBinders(WOLFSSL* ssl, byte* output, word32 idx)
4836
{
4837
    int           ret;
4838
    TLSX*         ext;
4839
    PreSharedKey* current;
4840
    byte          binderKey[WC_MAX_DIGEST_SIZE];
4841
    word16        len;
4842
4843
    WOLFSSL_ENTER("WritePSKBinders");
4844
4845
    if (idx > WOLFSSL_MAX_16BIT) {
4846
        return INPUT_SIZE_E;
4847
    }
4848
4849
    ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
4850
    if (ext == NULL)
4851
        return SANITY_MSG_E;
4852
4853
    /* Get the size of the binders to determine where to write binders. */
4854
    ret = TLSX_PreSharedKey_GetSizeBinders((PreSharedKey*)ext->data,
4855
                                                            client_hello, &len);
4856
    if (ret < 0)
4857
        return ret;
4858
    idx -= len;
4859
4860
    /* Hash truncated ClientHello - up to binders. */
4861
#ifdef WOLFSSL_DTLS13
4862
    if (ssl->options.dtls)
4863
        ret = Dtls13HashHandshake(ssl, output + Dtls13GetRlHeaderLength(ssl, 0),
4864
                                 (word16)idx - Dtls13GetRlHeaderLength(ssl, 0));
4865
    else
4866
#endif /* WOLFSSL_DTLS13 */
4867
        ret = HashOutput(ssl, output, (int)idx, 0);
4868
4869
    if (ret != 0)
4870
        return ret;
4871
4872
    current = (PreSharedKey*)ext->data;
4873
#ifdef WOLFSSL_CHECK_MEM_ZERO
4874
    if (current != NULL) {
4875
        wc_MemZero_Add("WritePSKBinders binderKey", binderKey,
4876
            sizeof(binderKey));
4877
    }
4878
#endif
4879
    /* Calculate the binder for each identity based on previous handshake data.
4880
     */
4881
    while (current != NULL) {
4882
        if ((ret = SetupPskKey(ssl, current, 1)) != 0)
4883
            break;
4884
4885
    #ifdef HAVE_SESSION_TICKET
4886
        if (current->resumption)
4887
            ret = DeriveBinderKeyResume(ssl, binderKey);
4888
    #endif
4889
    #ifndef NO_PSK
4890
        if (!current->resumption)
4891
            ret = DeriveBinderKey(ssl, binderKey);
4892
    #endif
4893
        if (ret != 0)
4894
            break;
4895
4896
        /* Derive the Finished message secret. */
4897
        ret = DeriveFinishedSecret(ssl, binderKey,
4898
                                   ssl->keys.client_write_MAC_secret,
4899
                                   0 /* neither end */);
4900
        if (ret != 0)
4901
            break;
4902
4903
        /* Build the HMAC of the handshake message data = binder. */
4904
        ret = BuildTls13HandshakeHmac(ssl, ssl->keys.client_write_MAC_secret,
4905
            current->binder, &current->binderLen);
4906
        if (ret != 0)
4907
            break;
4908
4909
        current = current->next;
4910
    }
4911
4912
    ForceZero(binderKey, sizeof(binderKey));
4913
#ifdef WOLFSSL_CHECK_MEM_ZERO
4914
    wc_MemZero_Check(binderKey, sizeof(binderKey));
4915
#endif
4916
    if (ret != 0)
4917
        return ret;
4918
4919
    /* Data entered into extension, now write to message. */
4920
    ret = TLSX_PreSharedKey_WriteBinders((PreSharedKey*)ext->data, output + idx,
4921
                                                            client_hello, &len);
4922
    if (ret < 0)
4923
        return ret;
4924
4925
    /* Hash binders to complete the hash of the ClientHello. */
4926
    ret = HashRaw(ssl, output + idx, len);
4927
    if (ret < 0)
4928
        return ret;
4929
4930
    #ifdef WOLFSSL_EARLY_DATA
4931
    if (ssl->earlyData != no_early_data) {
4932
        if ((ret = SetupPskKey(ssl, (PreSharedKey*)ext->data, 1)) != 0)
4933
            return ret;
4934
4935
        /* Derive early data encryption key. */
4936
        ret = DeriveTls13Keys(ssl, early_data_key, ENCRYPT_SIDE_ONLY, 1);
4937
        if (ret != 0)
4938
            return ret;
4939
        if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
4940
            return ret;
4941
4942
    }
4943
    #endif
4944
4945
    WOLFSSL_LEAVE("WritePSKBinders", ret);
4946
4947
    return ret;
4948
}
4949
#endif
4950
4951
/* Length of the session's ID to send as legacy_session_id. Only the ID of a
4952
 * session being resumed is sent. */
4953
static byte Tls13ClientSessionIdSz(const WOLFSSL* ssl)
4954
0
{
4955
0
    return ssl->options.resuming ? ssl->session->sessionIDSz : 0;
4956
0
}
4957
4958
static void GetTls13SessionId(WOLFSSL* ssl, byte* output, word32* idx)
4959
0
{
4960
0
    if (Tls13ClientSessionIdSz(ssl) > 0) {
4961
        /* Session resumption for old versions of protocol. */
4962
0
        if (ssl->session->sessionIDSz <= ID_LEN) {
4963
0
            if (output != NULL)
4964
0
                output[*idx] = ssl->session->sessionIDSz;
4965
0
            (*idx)++;
4966
0
            if (output != NULL) {
4967
0
                XMEMCPY(output + *idx, ssl->session->sessionID,
4968
0
                    ssl->session->sessionIDSz);
4969
0
            }
4970
0
            *idx += ssl->session->sessionIDSz;
4971
0
        }
4972
0
        else {
4973
            /* Invalid session ID length. Reset it. */
4974
0
            ssl->session->sessionIDSz = 0;
4975
0
            if (output != NULL)
4976
0
                output[*idx] = 0;
4977
0
            (*idx)++;
4978
0
        }
4979
0
    }
4980
0
    else {
4981
    #ifdef WOLFSSL_TLS13_MIDDLEBOX_COMPAT
4982
        if (ssl->options.tls13MiddleBoxCompat) {
4983
            if (output != NULL)
4984
                output[*idx] = ID_LEN;
4985
            (*idx)++;
4986
            if (output != NULL)
4987
                XMEMCPY(output + *idx, ssl->arrays->clientRandom, ID_LEN);
4988
            *idx += ID_LEN;
4989
        }
4990
        else
4991
    #endif /* WOLFSSL_TLS13_MIDDLEBOX_COMPAT */
4992
0
        {
4993
            /* TLS v1.3 does not use session id - 0 length. */
4994
0
            if (output != NULL)
4995
0
                output[*idx] = 0;
4996
0
            (*idx)++;
4997
0
        }
4998
0
    }
4999
0
}
5000
5001
/* handle generation of TLS 1.3 client_hello (1) */
5002
/* Send a ClientHello message to the server.
5003
 * Include the information required to start a handshake with servers using
5004
 * protocol versions less than TLS v1.3.
5005
 * Only a client will send this message.
5006
 *
5007
 * ssl  The SSL/TLS object.
5008
 * returns 0 on success and otherwise failure.
5009
 */
5010
5011
typedef struct Sch13Args {
5012
    byte*  output;
5013
    word32 idx;
5014
    int    sendSz;
5015
    word32 length;
5016
#if defined(HAVE_ECH)
5017
    int clientRandomOffset;
5018
    word32 preXLength;
5019
    word32 expandedInnerLen;
5020
    WOLFSSL_ECH* ech;
5021
#endif
5022
} Sch13Args;
5023
5024
#ifdef WOLFSSL_EARLY_DATA
5025
/* Check if early data can potentially be sent.
5026
 * Returns 1 if early data is possible, 0 otherwise.
5027
 */
5028
static int EarlyDataPossible(WOLFSSL* ssl)
5029
{
5030
    /* Need session resumption OR PSK callback configured */
5031
    if (ssl->options.resuming) {
5032
        return 1;
5033
    }
5034
#ifndef NO_PSK
5035
    if (ssl->options.client_psk_tls13_cb != NULL ||
5036
        ssl->options.client_psk_cb != NULL) {
5037
        return 1;
5038
    }
5039
#endif
5040
    return 0;
5041
}
5042
#endif /* WOLFSSL_EARLY_DATA */
5043
5044
int SendTls13ClientHello(WOLFSSL* ssl)
5045
0
{
5046
0
    int ret;
5047
#ifdef WOLFSSL_ASYNC_CRYPT
5048
    Sch13Args* args = NULL;
5049
    WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
5050
#else
5051
0
    Sch13Args  args[1];
5052
0
#endif
5053
0
    byte major, tls12minor;
5054
0
    const Suites* suites;
5055
5056
0
    WOLFSSL_START(WC_FUNC_CLIENT_HELLO_SEND);
5057
0
    WOLFSSL_ENTER("SendTls13ClientHello");
5058
5059
0
    if (ssl == NULL) {
5060
0
        return BAD_FUNC_ARG;
5061
0
    }
5062
5063
0
#if defined(HAVE_SECURE_RENEGOTIATION) || defined(HAVE_SERVER_RENEGOTIATION_INFO)
5064
    /* Re-establish renegotiation_info advertising for a reused object
5065
     * (wolfSSL_clear frees it) so a TLS 1.2 downgrade still enforces what the
5066
     * ClientHello advertised. Only when absent, to keep any existing state. */
5067
0
    if (ssl->secure_renegotiation == NULL) {
5068
0
        ret = SetupClientSecureRenegotiation(ssl);
5069
0
        if (ret != WOLFSSL_SUCCESS)
5070
0
            return ret;
5071
0
    }
5072
0
#endif
5073
5074
0
    ssl->options.buildingMsg = 1;
5075
0
    major = SSLv3_MAJOR;
5076
0
    tls12minor = TLSv1_2_MINOR;
5077
5078
#ifdef WOLFSSL_DTLS13
5079
    if (ssl->options.dtls) {
5080
        major = DTLS_MAJOR;
5081
        tls12minor = DTLSv1_2_MINOR;
5082
    }
5083
#endif /* WOLFSSL_DTLS */
5084
5085
0
    if (ssl->options.resuming &&
5086
0
            ssl->session->version.major != 0 &&
5087
0
            (ssl->session->version.major != ssl->version.major ||
5088
0
             ssl->session->version.minor != ssl->version.minor)) {
5089
0
    #ifndef WOLFSSL_NO_TLS12
5090
0
        if (ssl->session->version.major == ssl->version.major &&
5091
0
            ssl->session->version.minor < ssl->version.minor) {
5092
            /* Cannot resume with a different protocol version. */
5093
0
            ssl->options.resuming = 0;
5094
0
            ssl->version.major = ssl->session->version.major;
5095
0
            ssl->version.minor = ssl->session->version.minor;
5096
0
            return SendClientHello(ssl);
5097
0
        }
5098
0
        else
5099
0
    #endif
5100
0
        {
5101
0
            WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
5102
0
            return VERSION_ERROR;
5103
0
        }
5104
0
    }
5105
5106
0
    suites = WOLFSSL_SUITES(ssl);
5107
0
    if (suites == NULL) {
5108
0
        WOLFSSL_MSG("Bad suites pointer in SendTls13ClientHello");
5109
0
        return SUITES_ERROR;
5110
0
    }
5111
5112
#ifdef WOLFSSL_ASYNC_CRYPT
5113
    if (ssl->async == NULL) {
5114
        ssl->async = (struct WOLFSSL_ASYNC*)
5115
                XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
5116
                        DYNAMIC_TYPE_ASYNC);
5117
        if (ssl->async == NULL)
5118
            return MEMORY_E;
5119
        ssl->async->freeArgs = NULL;
5120
    }
5121
    args = (Sch13Args*)ssl->async->args;
5122
5123
    ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
5124
    if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) {
5125
        /* Check for error */
5126
        if (ret < 0)
5127
            return ret;
5128
    }
5129
    else
5130
#endif
5131
0
    {
5132
        /* Reset state */
5133
0
        ssl->options.asyncState = TLS_ASYNC_BEGIN;
5134
0
        XMEMSET(args, 0, sizeof(Sch13Args));
5135
0
    }
5136
5137
0
    switch (ssl->options.asyncState) {
5138
0
    case TLS_ASYNC_BEGIN:
5139
0
    {
5140
0
    word32 sessIdSz = 0;
5141
5142
0
    args->idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
5143
5144
#ifdef WOLFSSL_DTLS13
5145
    if (ssl->options.dtls)
5146
        args->idx += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
5147
#endif /* WOLFSSL_DTLS13 */
5148
5149
    /* Version | Random | Cipher Suites | Compression */
5150
0
    args->length = VERSION_SZ + RAN_LEN + suites->suiteSz +
5151
0
            SUITE_LEN + COMP_LEN + ENUM_LEN;
5152
#ifdef WOLFSSL_QUIC
5153
    if (WOLFSSL_IS_QUIC(ssl)) {
5154
        /* RFC 9001 ch. 8.4 sessionID in ClientHello MUST be 0 length */
5155
        ssl->session->sessionIDSz = 0;
5156
        ssl->options.tls13MiddleBoxCompat = 0;
5157
    }
5158
#endif
5159
#ifdef WOLFSSL_DTLS13
5160
    if (ssl->options.dtls) {
5161
        /* RFC 9147 Section 5: DTLS implementations do not use the
5162
         *                     TLS 1.3 "compatibility mode" */
5163
        ssl->options.tls13MiddleBoxCompat = 0;
5164
    }
5165
#endif
5166
0
    GetTls13SessionId(ssl, NULL, &sessIdSz);
5167
0
    args->length += (word16)sessIdSz;
5168
5169
#ifdef WOLFSSL_DTLS13
5170
    if (ssl->options.dtls) {
5171
        /* legacy_cookie_id len */
5172
        args->length += ENUM_LEN;
5173
5174
        /* server sent us an HelloVerifyRequest and we allow downgrade  */
5175
        if (ssl->arrays->cookieSz > 0 && ssl->options.downgrade)
5176
            args->length += ssl->arrays->cookieSz;
5177
    }
5178
#endif /* WOLFSSL_DTLS13 */
5179
5180
    /* Advance state and proceed */
5181
0
    ssl->options.asyncState = TLS_ASYNC_BUILD;
5182
0
    } /* case TLS_ASYNC_BEGIN */
5183
0
    FALL_THROUGH;
5184
5185
0
    case TLS_ASYNC_BUILD:
5186
0
    case TLS_ASYNC_DO:
5187
0
    {
5188
    /* Auto populate extensions supported unless user defined. */
5189
0
    if ((ret = TLSX_PopulateExtensions(ssl, 0)) != 0)
5190
0
        return ret;
5191
5192
    /* Advance state and proceed */
5193
0
    ssl->options.asyncState = TLS_ASYNC_FINALIZE;
5194
0
    } /* case TLS_ASYNC_BUILD */
5195
0
    FALL_THROUGH;
5196
5197
0
    case TLS_ASYNC_FINALIZE:
5198
0
    {
5199
#ifdef WOLFSSL_EARLY_DATA
5200
    if (!EarlyDataPossible(ssl))
5201
        ssl->earlyData = no_early_data;
5202
    if (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST_COMPLETE)
5203
        ssl->earlyData = no_early_data;
5204
    if (ssl->earlyData == no_early_data)
5205
        TLSX_Remove(&ssl->extensions, TLSX_EARLY_DATA, ssl->heap);
5206
    if (ssl->earlyData != no_early_data &&
5207
        (ret = TLSX_EarlyData_Use(ssl, 0, 0)) < 0) {
5208
        return ret;
5209
    }
5210
#endif
5211
#ifdef WOLFSSL_QUIC
5212
    if (WOLFSSL_IS_QUIC(ssl) && IsAtLeastTLSv1_3(ssl->version)) {
5213
        ret = wolfSSL_quic_add_transport_extensions(ssl, client_hello);
5214
        if (ret != 0)
5215
            return ret;
5216
    }
5217
#endif
5218
5219
    /* find length of outer and inner */
5220
#if defined(HAVE_ECH)
5221
    if (!ssl->options.disableECH) {
5222
        TLSX* echX = TLSX_Find(ssl->extensions, TLSX_ECH);
5223
        void* hostName = NULL;
5224
        word16 nameLen;
5225
        if (echX == NULL)
5226
            return WOLFSSL_FATAL_ERROR;
5227
5228
        args->ech = (WOLFSSL_ECH*)echX->data;
5229
        if (args->ech == NULL)
5230
            return WOLFSSL_FATAL_ERROR;
5231
5232
        /* if ECH was rejected by the HRR then the server MUST stop
5233
         * decrypting ECH, so send a GREASE ECH for the follow-up CH */
5234
        if (EchRejected(ssl) &&
5235
                ssl->options.serverState ==
5236
                    SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
5237
            args->ech->state = ECH_WRITE_GREASE;
5238
        }
5239
5240
        /* only prepare if we have a chance at acceptance (real ECH only) */
5241
        if (ssl->echConfigs != NULL &&
5242
                (ssl->options.echAccepted || args->ech->innerCount == 0)) {
5243
            word32 encodedLen;
5244
            byte downgrade;
5245
5246
            /* ensure that a version less than TLS1.3 is never offered  */
5247
            downgrade = ssl->options.downgrade;
5248
            ssl->options.downgrade = 0;
5249
5250
            /* set the type to inner */
5251
            args->ech->type = ECH_TYPE_INNER;
5252
            args->preXLength = args->length;
5253
5254
            /* get expanded inner size (used for transcript) */
5255
            ret = TLSX_GetRequestSize(ssl, client_hello, &args->length);
5256
            if (ret != 0) {
5257
                args->ech->type = ECH_TYPE_OUTER;
5258
                ssl->options.downgrade = downgrade;
5259
                return ret;
5260
            }
5261
5262
            /* args->expandedInnerLen carries the length for the hash */
5263
            args->expandedInnerLen = args->length;
5264
            if (args->expandedInnerLen > 0xFFFF) {
5265
                args->ech->type = ECH_TYPE_OUTER;
5266
                ssl->options.downgrade = downgrade;
5267
                return BUFFER_E;
5268
            }
5269
5270
            /* get encoded inner size */
5271
            args->ech->writeEncoded = 1;
5272
            encodedLen = args->preXLength;
5273
            ret = TLSX_GetRequestSize(ssl, client_hello, &encodedLen);
5274
            args->ech->writeEncoded = 0;
5275
            /* set the type to outer */
5276
            args->ech->type = ECH_TYPE_OUTER;
5277
            ssl->options.downgrade = downgrade;
5278
            if (ret != 0)
5279
                return ret;
5280
5281
            /* calculate padding (RFC 9849, section 6.1.3) */
5282
            nameLen = TLSX_SNI_GetRequest(ssl->extensions,
5283
                WOLFSSL_SNI_HOST_NAME, &hostName, 1);
5284
            if (nameLen == 0 && ssl->ctx != NULL)
5285
                nameLen = TLSX_SNI_GetRequest(ssl->ctx->extensions,
5286
                    WOLFSSL_SNI_HOST_NAME, &hostName, 1);
5287
5288
            if (nameLen != 0) {
5289
                if (nameLen > args->ech->echConfig->maxNameLen)
5290
                    args->ech->paddingLen = 0;
5291
                else
5292
                    args->ech->paddingLen =
5293
                        (word16)args->ech->echConfig->maxNameLen - nameLen;
5294
            }
5295
            else {
5296
                /* maxNameLen + length of the SNI extension */
5297
                args->ech->paddingLen = args->ech->echConfig->maxNameLen + 9;
5298
            }
5299
5300
            /* innerClientHelloLen and padding are based on the
5301
             * encoded (sealed) inner */
5302
            args->ech->paddingLen +=
5303
                ECH_PADDING_TO_32(encodedLen + args->ech->paddingLen);
5304
            args->ech->innerClientHelloLen = encodedLen +
5305
                args->ech->paddingLen + args->ech->hpke->Nt;
5306
5307
            if (args->ech->innerClientHelloLen > 0xFFFF)
5308
                return BUFFER_E;
5309
5310
            /* restore the length to pre-ClientHelloInner computations */
5311
            args->length = args->preXLength;
5312
        }
5313
    }
5314
#endif
5315
5316
0
    {
5317
#ifdef WOLFSSL_DTLS_CH_FRAG
5318
        word16 maxFrag = wolfssl_local_GetMaxPlaintextSize(ssl);
5319
        word16 lenWithoutExts = args->length;
5320
#endif
5321
5322
        /* Include length of TLS extensions. */
5323
0
        ret = TLSX_GetRequestSize(ssl, client_hello, &args->length);
5324
0
        if (ret != 0)
5325
0
            return ret;
5326
5327
        /* Total message size. */
5328
0
        args->sendSz =
5329
0
                (int)(args->length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ);
5330
5331
#ifdef WOLFSSL_DTLS13
5332
        if (ssl->options.dtls)
5333
            args->sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
5334
#endif /* WOLFSSL_DTLS13 */
5335
5336
#ifdef WOLFSSL_DTLS_CH_FRAG
5337
        /* Only empty the key share on the first CH; this avoids first CH
5338
         * fragmentation (wolfSSL refuses them) */
5339
        if (ssl->options.dtls && args->sendSz > maxFrag &&
5340
                ssl->options.serverState !=
5341
                    SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
5342
            /* Try again with an empty key share if we would be fragmenting */
5343
            ret = TLSX_KeyShare_Empty(ssl);
5344
            if (ret != 0)
5345
                return ret;
5346
            args->length = lenWithoutExts;
5347
            ret = TLSX_GetRequestSize(ssl, client_hello, &args->length);
5348
            if (ret != 0)
5349
                return ret;
5350
            args->sendSz = (int)(args->length +
5351
                    DTLS_HANDSHAKE_HEADER_SZ + DTLS_RECORD_HEADER_SZ);
5352
            if (args->sendSz > maxFrag) {
5353
                WOLFSSL_MSG("Can't fit first CH in one fragment.");
5354
                return BUFFER_ERROR;
5355
            }
5356
            WOLFSSL_MSG("Sending empty key share so we don't fragment CH1");
5357
        }
5358
#endif
5359
0
    }
5360
5361
    /* Check buffers are big enough and grow if needed. */
5362
0
    if ((ret = CheckAvailableSize(ssl, args->sendSz)) != 0)
5363
0
        return ret;
5364
5365
    /* Get position in output buffer to write new message to. */
5366
0
    args->output = GetOutputBuffer(ssl);
5367
5368
    /* Put the record and handshake headers on. */
5369
0
    AddTls13Headers(args->output, args->length, client_hello, ssl);
5370
5371
    /* Protocol version - negotiation now in extension: supported_versions. */
5372
0
    args->output[args->idx++] = major;
5373
0
    args->output[args->idx++] = tls12minor;
5374
5375
    /* Keep for downgrade. */
5376
0
    ssl->chVersion = ssl->version;
5377
5378
0
    if (ssl->arrays == NULL) {
5379
0
        return BAD_FUNC_ARG;
5380
0
    }
5381
    /* Client Random */
5382
0
    if (ssl->options.connectState == CONNECT_BEGIN) {
5383
0
        ret = wc_RNG_GenerateBlock(ssl->rng, args->output + args->idx, RAN_LEN);
5384
0
        if (ret != 0)
5385
0
            return ret;
5386
5387
        /* Store random for possible second ClientHello. */
5388
0
        XMEMCPY(ssl->arrays->clientRandom, args->output + args->idx, RAN_LEN);
5389
0
    }
5390
0
    else
5391
0
        XMEMCPY(args->output + args->idx, ssl->arrays->clientRandom, RAN_LEN);
5392
5393
#if defined(HAVE_ECH)
5394
    args->clientRandomOffset = (int)args->idx;
5395
#endif
5396
5397
0
    args->idx += RAN_LEN;
5398
5399
0
    GetTls13SessionId(ssl, args->output, &args->idx);
5400
5401
#ifdef WOLFSSL_DTLS13
5402
    if (ssl->options.dtls) {
5403
        args->output[args->idx++] = ssl->arrays->cookieSz;
5404
5405
        if (ssl->arrays->cookieSz > 0) {
5406
            /* We have a cookie saved, so the server sent us an
5407
             * HelloVerifyRequest, it means it is a v1.2 server */
5408
            if (!ssl->options.downgrade)
5409
                return VERSION_ERROR;
5410
            XMEMCPY(args->output + args->idx, ssl->arrays->cookie,
5411
                ssl->arrays->cookieSz);
5412
            args->idx += ssl->arrays->cookieSz;
5413
        }
5414
    }
5415
#endif /* WOLFSSL_DTLS13 */
5416
5417
    /* Cipher suites */
5418
0
    c16toa(suites->suiteSz, args->output + args->idx);
5419
0
    args->idx += OPAQUE16_LEN;
5420
0
    XMEMCPY(args->output + args->idx, &suites->suites,
5421
0
        suites->suiteSz);
5422
0
    args->idx += suites->suiteSz;
5423
#ifdef WOLFSSL_DEBUG_TLS
5424
    {
5425
        int ii;
5426
        WOLFSSL_MSG("Ciphers:");
5427
        for (ii = 0 ; ii < suites->suiteSz; ii += 2) {
5428
            WOLFSSL_MSG(GetCipherNameInternal(suites->suites[ii+0],
5429
                                              suites->suites[ii+1]));
5430
        }
5431
    }
5432
#endif
5433
5434
    /* Compression not supported in TLS v1.3. */
5435
0
    args->output[args->idx++] = COMP_LEN;
5436
0
    args->output[args->idx++] = NO_COMPRESSION;
5437
5438
#if defined(HAVE_ECH)
5439
    /* Build the expanded inner ClientHello */
5440
    if (ssl->echConfigs != NULL && !ssl->options.disableECH &&
5441
            (ssl->options.echAccepted || args->ech->innerCount == 0)) {
5442
        byte downgrade;
5443
5444
        /* calculate maximum buffer size needed */
5445
        word32 encodedBodyLen = args->ech->innerClientHelloLen -
5446
            args->ech->hpke->Nt;
5447
        word32 innerBufSize = args->expandedInnerLen;
5448
        if (encodedBodyLen > innerBufSize)
5449
            innerBufSize = encodedBodyLen;
5450
5451
        /* set the type to inner */
5452
        args->ech->type = ECH_TYPE_INNER;
5453
        /* innerClientHello may already exist from hrr, free if it does */
5454
        if (args->ech->innerClientHello != NULL) {
5455
            XFREE(args->ech->innerClientHello, ssl->heap,
5456
                DYNAMIC_TYPE_TMP_BUFFER);
5457
        }
5458
        /* allocate the inner */
5459
        args->ech->innerClientHello =
5460
            (byte*)XMALLOC(innerBufSize, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
5461
        if (args->ech->innerClientHello == NULL) {
5462
            args->ech->type = ECH_TYPE_OUTER;
5463
            return MEMORY_E;
5464
        }
5465
        /* copy everything before extensions into the innerClientHello
5466
         * ignore record and handshake headers */
5467
        XMEMCPY(args->ech->innerClientHello,
5468
            args->output + RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ,
5469
            args->preXLength);
5470
        /* copy the client random to inner - only for first CH, not after HRR */
5471
        if (!ssl->options.echAccepted) {
5472
            XMEMCPY(ssl->arrays->clientRandomInner, ssl->arrays->clientRandom,
5473
                RAN_LEN);
5474
        }
5475
        else {
5476
            /* After HRR, use the same inner random as CH1 */
5477
            XMEMCPY(args->ech->innerClientHello + VERSION_SZ,
5478
                ssl->arrays->clientRandomInner, RAN_LEN);
5479
        }
5480
        /* change the outer client random */
5481
        ret = wc_RNG_GenerateBlock(ssl->rng, args->output +
5482
            args->clientRandomOffset, RAN_LEN);
5483
        if (ret != 0) {
5484
            args->ech->type = ECH_TYPE_OUTER;
5485
            return ret;
5486
        }
5487
        /* copy the new client random */
5488
        XMEMCPY(ssl->arrays->clientRandom, args->output +
5489
            args->clientRandomOffset, RAN_LEN);
5490
5491
        /* ensure that a version less than TLS1.3 is never offered  */
5492
        downgrade = ssl->options.downgrade;
5493
        ssl->options.downgrade = 0;
5494
5495
        /* write the expanded extensions into the inner buffer */
5496
        args->length = 0;
5497
        ret = TLSX_WriteRequest(ssl,
5498
            args->ech->innerClientHello + args->preXLength, client_hello,
5499
            &args->length);
5500
        if (ret != 0) {
5501
            args->ech->type = ECH_TYPE_OUTER;
5502
            ssl->options.downgrade = downgrade;
5503
            return ret;
5504
        }
5505
5506
        /* hash expanded form */
5507
        args->ech->innerClientHelloLen = args->expandedInnerLen;
5508
        ret = EchHashHelloInner(ssl, args->ech);
5509
        args->ech->innerClientHelloLen = encodedBodyLen + args->ech->hpke->Nt;
5510
        if (ret != 0) {
5511
            args->ech->type = ECH_TYPE_OUTER;
5512
            ssl->options.downgrade = downgrade;
5513
            return ret;
5514
        }
5515
5516
        /* zero padding bytes sealed with the inner hello */
5517
        XMEMSET(args->ech->innerClientHello +
5518
            args->ech->innerClientHelloLen - args->ech->hpke->Nt -
5519
            args->ech->paddingLen, 0, args->ech->paddingLen);
5520
        /* Rewrite inner buffer with the encoded form for sealing */
5521
        args->ech->writeEncoded = 1;
5522
        args->length = 0;
5523
        ret = TLSX_WriteRequest(ssl,
5524
            args->ech->innerClientHello + args->preXLength, client_hello,
5525
            &args->length);
5526
        args->ech->writeEncoded = 0;
5527
        /* set the type to outer */
5528
        args->ech->type = ECH_TYPE_OUTER;
5529
        ssl->options.downgrade = downgrade;
5530
        if (ret != 0)
5531
            return ret;
5532
    }
5533
#endif
5534
5535
    /* Write out extensions for a request. */
5536
0
    args->length = 0;
5537
0
    ret = TLSX_WriteRequest(ssl, args->output + args->idx, client_hello,
5538
0
        &args->length);
5539
0
    if (ret != 0)
5540
0
        return ret;
5541
5542
0
    args->idx += args->length;
5543
5544
#if defined(HAVE_ECH)
5545
    /* HPKE-seal inner hello and place into outer ECH extension's payload */
5546
    if (ssl->echConfigs != NULL && !ssl->options.disableECH &&
5547
            (ssl->options.echAccepted || args->ech->innerCount == 0)) {
5548
#if defined(WOLFSSL_TEST_ECH)
5549
        if (ssl->echInnerHelloCb != NULL) {
5550
            ret = ssl->echInnerHelloCb(args->ech->innerClientHello,
5551
                args->ech->innerClientHelloLen - args->ech->hpke->Nt);
5552
            if (ret != 0)
5553
                return ret;
5554
        }
5555
#endif
5556
        ret = TLSX_FinalizeEch(ssl, args->ech,
5557
            args->output + RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ,
5558
            (word32)(args->sendSz - (RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ)));
5559
5560
        if (ret != 0)
5561
            return ret;
5562
    }
5563
    /* Mark CH1 done for any ECH extension (real or GREASE) */
5564
    if (args->ech != NULL)
5565
        args->ech->innerCount = 1;
5566
#endif
5567
5568
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
5569
    /* Resumption has a specific set of extensions and binder is calculated
5570
     * for each identity.
5571
     */
5572
    if (TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY)) {
5573
        ret = WritePSKBinders(ssl, args->output, args->idx);
5574
    }
5575
    else
5576
#endif
5577
0
    {
5578
#ifdef WOLFSSL_DTLS13
5579
        if (ssl->options.dtls)
5580
            ret = Dtls13HashHandshake(ssl,
5581
                args->output + Dtls13GetRlHeaderLength(ssl, 0),
5582
                (word16)args->idx - Dtls13GetRlHeaderLength(ssl, 0));
5583
        else
5584
#endif /* WOLFSSL_DTLS13 */
5585
0
        {
5586
            /* compute the outer hash */
5587
0
            ret = HashOutput(ssl, args->output, (int)args->idx, 0);
5588
0
        }
5589
0
    }
5590
0
    if (ret != 0)
5591
0
        return ret;
5592
5593
0
    ssl->options.clientState = CLIENT_HELLO_COMPLETE;
5594
5595
#if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
5596
    if (ssl->hsInfoOn) AddPacketName(ssl, "ClientHello");
5597
    if (ssl->toInfoOn) {
5598
        ret = AddPacketInfo(ssl, "ClientHello", handshake, args->output,
5599
                      args->sendSz, WRITE_PROTO, 0, ssl->heap);
5600
        if (ret != 0)
5601
            return ret;
5602
    }
5603
#endif
5604
5605
0
    ssl->options.buildingMsg = 0;
5606
#ifdef WOLFSSL_DTLS13
5607
    if (ssl->options.dtls) {
5608
        ret = Dtls13HandshakeSend(ssl, args->output, (word16)args->sendSz,
5609
                                  (word16)args->idx, client_hello, 0);
5610
        break;
5611
    }
5612
#endif /* WOLFSSL_DTLS13 */
5613
5614
0
    ssl->buffers.outputBuffer.length += (word32)args->sendSz;
5615
5616
    /* Advance state and proceed */
5617
0
    ssl->options.asyncState = TLS_ASYNC_END;
5618
0
    }
5619
    /* case TLS_ASYNC_BUILD */
5620
0
    FALL_THROUGH;
5621
5622
0
    case TLS_ASYNC_END:
5623
0
    {
5624
#ifdef WOLFSSL_EARLY_DATA_GROUP
5625
    /* QUIC needs to forward records at their encryption level
5626
     * and is therefore unable to group here */
5627
    if (ssl->earlyData == no_early_data || WOLFSSL_IS_QUIC(ssl))
5628
#endif
5629
0
        ret = SendBuffered(ssl);
5630
5631
0
    break;
5632
0
    }
5633
0
    default:
5634
0
        ret = INPUT_CASE_ERROR;
5635
0
    } /* switch (ssl->options.asyncState) */
5636
5637
#ifdef WOLFSSL_ASYNC_CRYPT
5638
    if (ret == 0)
5639
        FreeAsyncCtx(ssl, 0);
5640
#endif
5641
5642
0
    WOLFSSL_LEAVE("SendTls13ClientHello", ret);
5643
0
    WOLFSSL_END(WC_FUNC_CLIENT_HELLO_SEND);
5644
5645
0
    return ret;
5646
0
}
5647
5648
#if defined(WOLFSSL_DTLS13) && !defined(NO_WOLFSSL_CLIENT)
5649
static int Dtls13ClientDoDowngrade(WOLFSSL* ssl)
5650
{
5651
    int ret;
5652
    if (ssl->dtls13ClientHello == NULL)
5653
        return BAD_STATE_E;
5654
5655
    /* v1.3 and v1.2 hash messages to compute the transcript hash. When we are
5656
     * using DTLSv1.3 we hash the first clientHello following v1.3 but the
5657
     * server can negotiate a lower version. So we need to re-hash the
5658
     * clientHello to adhere to DTLS <= v1.2 rules. */
5659
    ret = InitHandshakeHashes(ssl);
5660
    if (ret != 0)
5661
        return ret;
5662
    ret = HashRaw(ssl, ssl->dtls13ClientHello, ssl->dtls13ClientHelloSz);
5663
    XFREE(ssl->dtls13ClientHello, ssl->heap, DYNAMIC_TYPE_DTLS_MSG);
5664
    ssl->dtls13ClientHello = NULL;
5665
    ssl->dtls13ClientHelloSz = 0;
5666
    ssl->keys.dtls_sequence_number_hi =
5667
        (word16)w64GetHigh32(ssl->dtls13EncryptEpoch->nextSeqNumber);
5668
    ssl->keys.dtls_sequence_number_lo =
5669
        w64GetLow32(ssl->dtls13EncryptEpoch->nextSeqNumber);
5670
    return ret;
5671
}
5672
#endif /* WOLFSSL_DTLS13 && !NO_WOLFSSL_CLIENT*/
5673
5674
#if defined(HAVE_ECH)
5675
/* Calculate ECH acceptance and verify the server accepted ECH.
5676
 *
5677
 * ssl          SSL/TLS object.
5678
 * label        Ascii string describing ECH acceptance type.
5679
 * labelSz      Length of label excluding NULL character.
5680
 * input        The buffer to calculate confirmation off of.
5681
 * acceptOffset Where the 8 ECH confirmation bytes start.
5682
 * helloSz      Size of hello message.
5683
 * returns 0 on success and otherwise failure.
5684
 */
5685
static int EchCheckAcceptance(WOLFSSL* ssl, byte* label, word16 labelSz,
5686
    const byte* input, int acceptOffset, int helloSz, byte msgType)
5687
{
5688
    int ret = 0;
5689
    int headerSz;
5690
    HS_Hashes* tmpHashes;
5691
    byte acceptConfirmation[ECH_ACCEPT_CONFIRMATION_SZ];
5692
5693
    XMEMSET(acceptConfirmation, 0, sizeof(acceptConfirmation));
5694
5695
#ifdef WOLFSSL_DTLS13
5696
    headerSz = ssl->options.dtls ? DTLS13_HANDSHAKE_HEADER_SZ :
5697
                                   HANDSHAKE_HEADER_SZ;
5698
#else
5699
    headerSz = HANDSHAKE_HEADER_SZ;
5700
#endif
5701
5702
    ret = EchCalcAcceptance(ssl, label, labelSz, input, acceptOffset, helloSz,
5703
            msgType == hello_retry_request, acceptConfirmation);
5704
5705
    if (ret == 0) {
5706
        tmpHashes = ssl->hsHashes;
5707
        ssl->hsHashes = ssl->hsHashesEch;
5708
5709
        /* last 8 bytes must match the expand output */
5710
        ret = ConstantCompare(acceptConfirmation, input + acceptOffset,
5711
            ECH_ACCEPT_CONFIRMATION_SZ);
5712
5713
        if (ret == 0) {
5714
            WOLFSSL_MSG("ECH accepted");
5715
            ssl->options.echAccepted = 1;
5716
5717
            /* after HRR, hsHashesEch must contain:
5718
             * message_hash(ClientHelloInner1) || HRR (actual, not zeros) */
5719
            if (msgType == hello_retry_request) {
5720
                ret = HashRaw(ssl, input, helloSz + headerSz);
5721
            }
5722
            /* normal TLS code will calculate transcript of ServerHello */
5723
            else {
5724
                ssl->hsHashes = tmpHashes;
5725
                FreeHandshakeHashes(ssl);
5726
                tmpHashes = ssl->hsHashesEch;
5727
                ssl->hsHashesEch = NULL;
5728
            }
5729
        }
5730
        else {
5731
            if (msgType != hello_retry_request && ssl->options.echAccepted) {
5732
                /* the SH has rejected ECH after the HRR has accepted it
5733
                 * RFC 9849, section 6.1.5 */
5734
                WOLFSSL_MSG("ECH rejected, but it was previously accepted...");
5735
                ret = INVALID_PARAMETER;
5736
            }
5737
            else {
5738
                WOLFSSL_MSG("ECH rejected");
5739
                ret = 0;
5740
            }
5741
            ssl->options.echAccepted = 0;
5742
5743
            /* ECH rejected, continue with outer transcript */
5744
            FreeHandshakeHashes(ssl);
5745
            ssl->hsHashesEch = NULL;
5746
        }
5747
5748
        ssl->hsHashes = tmpHashes;
5749
    }
5750
5751
    /* Skip only when the HRR signals ECH acceptance
5752
     * -> CH2 still needs ech->extensions for inner/outer extension swap
5753
     *    during write */
5754
    if (ret == 0 &&
5755
            (msgType != hello_retry_request || !ssl->options.echAccepted))
5756
        ret = TLSX_EchReplaceExtensions(ssl, ssl->options.echAccepted);
5757
5758
    return ret;
5759
}
5760
#endif /* HAVE_ECH */
5761
5762
/* handle processing of TLS 1.3 server_hello (2) and hello_retry_request (6) */
5763
/* Handle the ServerHello message from the server.
5764
 * Only a client will receive this message.
5765
 *
5766
 * ssl       The SSL/TLS object.
5767
 * input     The message buffer.
5768
 * inOutIdx  On entry, the index into the message buffer of ServerHello.
5769
 *           On exit, the index of byte after the ServerHello message.
5770
 * helloSz   The length of the current handshake message.
5771
 * returns 0 on success and otherwise failure.
5772
 */
5773
5774
typedef struct Dsh13Args {
5775
    ProtocolVersion pv;
5776
    word32          idx;
5777
    word32          begin;
5778
    const byte*     sessId;
5779
    word16          totalExtSz;
5780
    byte            sessIdSz;
5781
    byte            extMsgType;
5782
#if defined(HAVE_ECH)
5783
    TLSX* echX;
5784
    byte* acceptLabel;
5785
    word32 acceptOffset;
5786
    word16 acceptLabelSz;
5787
#endif
5788
} Dsh13Args;
5789
5790
/* sessIdSz below bounds both the copy into arrays->sessionID and the comparison
5791
 * against arrays->clientRandom, so one check only covers both while these
5792
 * match. */
5793
wc_static_assert(ID_LEN == RAN_LEN);
5794
5795
int DoTls13ServerHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
5796
                       word32 helloSz, byte* extMsgType)
5797
0
{
5798
0
    int ret;
5799
0
    byte suite[2];
5800
0
    byte tls12minor;
5801
#ifdef WOLFSSL_ASYNC_CRYPT
5802
    Dsh13Args* args = NULL;
5803
#else
5804
0
    Dsh13Args  args[1];
5805
0
#endif
5806
#ifdef WOLFSSL_ASYNC_CRYPT
5807
    WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
5808
#endif
5809
5810
0
    WOLFSSL_START(WC_FUNC_SERVER_HELLO_DO);
5811
0
    WOLFSSL_ENTER("DoTls13ServerHello");
5812
5813
0
    if (ssl == NULL || ssl->arrays == NULL)
5814
0
        return BAD_FUNC_ARG;
5815
5816
0
    tls12minor = TLSv1_2_MINOR;
5817
5818
#ifdef WOLFSSL_DTLS13
5819
    if (ssl->options.dtls)
5820
        tls12minor = DTLSv1_2_MINOR;
5821
#endif /*  WOLFSSL_DTLS13 */
5822
5823
#ifdef WOLFSSL_ASYNC_CRYPT
5824
    if (ssl->async == NULL) {
5825
        ssl->async = (struct WOLFSSL_ASYNC*)
5826
                XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
5827
                        DYNAMIC_TYPE_ASYNC);
5828
        if (ssl->async == NULL)
5829
            return MEMORY_E;
5830
        ssl->async->freeArgs = NULL;
5831
    }
5832
    args = (Dsh13Args*)ssl->async->args;
5833
5834
    ret = Tls13HelloAsyncPop(ssl, &ssl->options.asyncState);
5835
    if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) {
5836
        /* Check for error */
5837
        if (ret < 0) {
5838
            if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
5839
                /* Mark message as not received so it can process again */
5840
                ssl->msgsReceived.got_server_hello = 0;
5841
            }
5842
            return ret;
5843
        }
5844
    }
5845
    else
5846
#endif
5847
0
    {
5848
        /* Reset state */
5849
0
        ssl->options.asyncState = TLS_ASYNC_BEGIN;
5850
0
        XMEMSET(args, 0, sizeof(Dsh13Args));
5851
0
    }
5852
5853
0
    switch (ssl->options.asyncState) {
5854
0
    case TLS_ASYNC_BEGIN:
5855
0
    {
5856
0
    byte b;
5857
#if defined(WOLFSSL_DTLS13) && defined(WOLFSSL_DTLS_CID)
5858
    ssl->options.haveSupportedVersions = 0;
5859
#endif
5860
#ifdef WOLFSSL_CALLBACKS
5861
    if (ssl->hsInfoOn) AddPacketName(ssl, "ServerHello");
5862
    if (ssl->toInfoOn) AddLateName("ServerHello", &ssl->timeoutInfo);
5863
#endif
5864
5865
    /* Protocol version length check. */
5866
0
    if (helloSz < OPAQUE16_LEN)
5867
0
        return BUFFER_ERROR;
5868
5869
0
    args->idx = *inOutIdx;
5870
0
    args->begin = args->idx;
5871
5872
    /* Protocol version */
5873
0
    XMEMCPY(&args->pv, input + args->idx, OPAQUE16_LEN);
5874
0
    args->idx += OPAQUE16_LEN;
5875
5876
#ifdef WOLFSSL_DTLS
5877
    if (ssl->options.dtls &&
5878
        (args->pv.major != DTLS_MAJOR || args->pv.minor == DTLS_BOGUS_MINOR))
5879
        return VERSION_ERROR;
5880
#endif /* WOLFSSL_DTLS */
5881
5882
0
#ifndef WOLFSSL_NO_TLS12
5883
0
    {
5884
0
        byte wantDowngrade;
5885
5886
0
        wantDowngrade = args->pv.major == ssl->version.major &&
5887
0
            args->pv.minor < TLSv1_2_MINOR;
5888
5889
#ifdef WOLFSSL_DTLS13
5890
        if (ssl->options.dtls)
5891
            wantDowngrade = args->pv.major == ssl->version.major &&
5892
                args->pv.minor > DTLSv1_2_MINOR;
5893
#endif /* WOLFSSL_DTLS13 */
5894
5895
0
        if (wantDowngrade && ssl->options.downgrade) {
5896
            /* Force client hello version 1.2 to work for static RSA. */
5897
0
            ssl->chVersion.minor = TLSv1_2_MINOR;
5898
0
            ssl->version.minor = TLSv1_2_MINOR;
5899
0
            ssl->options.tls1_3 = 0;
5900
5901
#ifdef WOLFSSL_DTLS13
5902
            if (ssl->options.dtls) {
5903
                ssl->chVersion.minor = DTLSv1_2_MINOR;
5904
                ssl->version.minor = DTLSv1_2_MINOR;
5905
                ret = Dtls13ClientDoDowngrade(ssl);
5906
                if (ret != 0)
5907
                    return ret;
5908
            }
5909
#endif /* WOLFSSL_DTLS13 */
5910
5911
0
            return DoServerHello(ssl, input, inOutIdx, helloSz);
5912
0
        }
5913
0
    }
5914
0
#endif
5915
5916
0
    if (args->pv.major != ssl->version.major ||
5917
0
        args->pv.minor != tls12minor) {
5918
0
        WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
5919
0
        return VERSION_ERROR;
5920
0
    }
5921
5922
    /* Random and session id length check */
5923
0
    if ((args->idx - args->begin) + RAN_LEN + ENUM_LEN > helloSz)
5924
0
        return BUFFER_ERROR;
5925
5926
    /* Check if hello retry request */
5927
0
    if (XMEMCMP(input + args->idx, helloRetryRequestRandom, RAN_LEN) == 0) {
5928
0
        WOLFSSL_MSG("HelloRetryRequest format");
5929
0
        *extMsgType = hello_retry_request;
5930
5931
0
        if (ssl->msgsReceived.got_hello_verify_request) {
5932
0
            WOLFSSL_MSG("Received HelloRetryRequest after a "
5933
0
                        "HelloVerifyRequest");
5934
0
            WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
5935
0
            return VERSION_ERROR;
5936
0
        }
5937
5938
        /* A HelloRetryRequest comes in as an ServerHello for MiddleBox compat.
5939
         * Found message to be a HelloRetryRequest.
5940
         * Don't allow more than one HelloRetryRequest or ServerHello.
5941
         */
5942
0
        if (ssl->msgsReceived.got_hello_retry_request) {
5943
0
            WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
5944
0
            return DUPLICATE_MSG_E;
5945
0
        }
5946
0
    }
5947
0
    args->extMsgType = *extMsgType;
5948
5949
    /* Server random - keep for debugging. */
5950
0
    XMEMCPY(ssl->arrays->serverRandom, input + args->idx, RAN_LEN);
5951
#if defined(HAVE_ECH)
5952
    /* last 8 bytes of server random */
5953
    args->acceptOffset = args->idx + RAN_LEN - ECH_ACCEPT_CONFIRMATION_SZ;
5954
#endif
5955
0
    args->idx += RAN_LEN;
5956
5957
    /* Session id */
5958
0
    args->sessIdSz = input[args->idx++];
5959
0
    if (args->sessIdSz > ID_LEN ||
5960
0
        ((args->idx - args->begin) + args->sessIdSz > helloSz))
5961
0
        return BUFFER_ERROR;
5962
0
    args->sessId = input + args->idx;
5963
0
    args->idx += args->sessIdSz;
5964
5965
0
    ssl->options.haveSessionId = 1;
5966
5967
    /* Ciphersuite and compression check */
5968
0
    if ((args->idx - args->begin) + OPAQUE16_LEN + OPAQUE8_LEN > helloSz)
5969
0
        return BUFFER_ERROR;
5970
5971
    /* Set the cipher suite from the message. */
5972
0
    ssl->options.cipherSuite0 = input[args->idx++];
5973
0
    ssl->options.cipherSuite  = input[args->idx++];
5974
0
    if (*extMsgType == hello_retry_request) {
5975
0
        ssl->options.hrrCipherSuite0 = ssl->options.cipherSuite0;
5976
0
        ssl->options.hrrCipherSuite  = ssl->options.cipherSuite;
5977
0
    }
5978
0
    else if (ssl->msgsReceived.got_hello_retry_request &&
5979
0
             (ssl->options.hrrCipherSuite0 != ssl->options.cipherSuite0 ||
5980
0
                     ssl->options.hrrCipherSuite != ssl->options.cipherSuite)) {
5981
0
        WOLFSSL_MSG("Received ServerHello with different cipher suite than "
5982
0
                    "HelloRetryRequest");
5983
0
        WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
5984
0
        return INVALID_PARAMETER;
5985
0
    }
5986
#ifdef WOLFSSL_DEBUG_TLS
5987
    WOLFSSL_MSG("Chosen cipher suite:");
5988
    WOLFSSL_MSG(GetCipherNameInternal(ssl->options.cipherSuite0,
5989
                                      ssl->options.cipherSuite));
5990
#endif
5991
5992
    /* Compression */
5993
0
    b = input[args->idx++];
5994
0
    if (b != 0) {
5995
0
        WOLFSSL_MSG("Must be no compression types in list");
5996
0
        WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
5997
0
        return INVALID_PARAMETER;
5998
0
    }
5999
6000
0
    if ((args->idx - args->begin) + OPAQUE16_LEN > helloSz) {
6001
        /* Fewer than OPAQUE16_LEN bytes remain after the compression method, so
6002
         * there is no complete extensions length field. */
6003
0
        if ((args->idx - args->begin) < helloSz) {
6004
            /* A partial extensions length field is genuinely malformed: report
6005
             * it as a decode error regardless of message type. */
6006
0
            WOLFSSL_MSG("Truncated extensions length in ServerHello");
6007
0
            return BUFFER_ERROR;
6008
0
        }
6009
6010
        /* No extensions field at all. */
6011
0
        if (args->extMsgType == hello_retry_request) {
6012
            /* The sentinel Random (RFC 8446 4.1.3) identifies this as a TLS 1.3
6013
             * HelloRetryRequest, which MUST carry supported_versions
6014
             * (4.2.1/9.2). Its complete absence is a missing mandatory
6015
             * extension, so - consistently with the extensions-present case
6016
             * handled later - report it as missing_extension (via
6017
             * INCOMPLETE_DATA), regardless of whether a downgrade would
6018
             * otherwise be allowed. Reject here before DoServerHello would
6019
             * reinterpret the sentinel as a plain TLS 1.2 ServerHello.Random. */
6020
0
            WOLFSSL_MSG("HelloRetryRequest with no supported_versions");
6021
0
            WOLFSSL_ERROR_VERBOSE(INCOMPLETE_DATA);
6022
0
            return INCOMPLETE_DATA;
6023
0
        }
6024
6025
0
        if (!ssl->options.downgrade) {
6026
            /* A plain ServerHello with no extensions is not offering TLS 1.3
6027
             * (no supported_versions extension - see RFC 8446 4.2.1) but TLS
6028
             * 1.2 or below. This is a well-formed message, so a TLS 1.3-only
6029
             * client (downgrade disabled) must reject it as a version mismatch,
6030
             * not as a malformed message. Returning VERSION_ERROR makes the
6031
             * caller send a protocol_version alert (RFC 8446 6.2) rather than
6032
             * decode_error. */
6033
0
            WOLFSSL_MSG("Server offered TLS 1.2 (no supported_versions ext) "
6034
0
                        "but downgrade not allowed");
6035
0
            WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
6036
0
            return VERSION_ERROR;
6037
0
        }
6038
0
#ifndef WOLFSSL_NO_TLS12
6039
        /* Force client hello version 1.2 to work for static RSA. */
6040
0
        ssl->chVersion.minor = TLSv1_2_MINOR;
6041
0
        ssl->version.minor = TLSv1_2_MINOR;
6042
6043
#ifdef WOLFSSL_DTLS13
6044
        if (ssl->options.dtls) {
6045
            ssl->chVersion.minor = DTLSv1_2_MINOR;
6046
            ssl->version.minor = DTLSv1_2_MINOR;
6047
            ssl->options.tls1_3 = 0;
6048
            ret = Dtls13ClientDoDowngrade(ssl);
6049
            if (ret != 0)
6050
                return ret;
6051
        }
6052
#endif /* WOLFSSL_DTLS13 */
6053
6054
0
#endif
6055
0
        ssl->options.haveEMS = 0;
6056
0
        if (args->pv.minor < ssl->options.minDowngrade) {
6057
0
            WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
6058
0
            return VERSION_ERROR;
6059
0
        }
6060
0
#ifndef WOLFSSL_NO_TLS12
6061
0
        ssl->options.tls1_3 = 0;
6062
0
        return DoServerHello(ssl, input, inOutIdx, helloSz);
6063
#else
6064
        WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
6065
        return VERSION_ERROR;
6066
#endif
6067
0
    }
6068
6069
0
    if ((args->idx - args->begin) < helloSz) {
6070
0
        int foundVersion;
6071
6072
        /* Get extension length and length check. */
6073
0
        if ((args->idx - args->begin) + OPAQUE16_LEN > helloSz)
6074
0
            return BUFFER_ERROR;
6075
0
        ato16(&input[args->idx], &args->totalExtSz);
6076
0
        args->idx += OPAQUE16_LEN;
6077
0
        if ((args->idx - args->begin) + args->totalExtSz > helloSz)
6078
0
            return BUFFER_ERROR;
6079
6080
        /* Need to negotiate version first. */
6081
0
        if ((ret = TLSX_ParseVersion(ssl, input + args->idx,
6082
0
            args->totalExtSz, *extMsgType, &foundVersion))) {
6083
0
            return ret;
6084
0
        }
6085
0
        if (!foundVersion) {
6086
            /* RFC 8446 4.1.4: "The server's extensions MUST contain
6087
             * 'supported_versions'." (also 9.2: "supported_versions" is
6088
             * REQUIRED for all ... HelloRetryRequest messages). The HRR random
6089
             * unambiguously identifies a TLS 1.3 server, so its absence is not
6090
             * a downgrade attempt but a missing mandatory extension, which per
6091
             * the "missing_extension" alert definition must be reported as
6092
             * such. Return INCOMPLETE_DATA (which maps to a missing_extension
6093
             * alert) and let the caller emit the alert via
6094
             * TranslateErrorToAlert(). */
6095
0
            if (*extMsgType == hello_retry_request) {
6096
0
                WOLFSSL_MSG("HelloRetryRequest missing supported_versions "
6097
0
                            "extension");
6098
0
                WOLFSSL_ERROR_VERBOSE(INCOMPLETE_DATA);
6099
0
                return INCOMPLETE_DATA;
6100
0
            }
6101
0
            if (!ssl->options.downgrade) {
6102
0
                WOLFSSL_MSG("Server trying to downgrade to version less than "
6103
0
                            "TLS v1.3");
6104
0
                WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
6105
0
                return VERSION_ERROR;
6106
0
            }
6107
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
6108
    defined(WOLFSSL_WPAS_SMALL)
6109
            /* Check if client has disabled TLS 1.2 */
6110
            if (args->pv.minor == TLSv1_2_MINOR &&
6111
                (ssl->options.mask & WOLFSSL_OP_NO_TLSv1_2)
6112
                == WOLFSSL_OP_NO_TLSv1_2)
6113
            {
6114
                WOLFSSL_MSG("\tOption set to not allow TLSv1.2");
6115
                WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
6116
                return VERSION_ERROR;
6117
            }
6118
#endif
6119
6120
0
            if (!ssl->options.dtls &&
6121
0
                args->pv.minor < ssl->options.minDowngrade) {
6122
0
                WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
6123
0
                return VERSION_ERROR;
6124
0
            }
6125
6126
0
            if (ssl->options.dtls &&
6127
0
                args->pv.minor > ssl->options.minDowngrade) {
6128
0
                WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
6129
0
                return VERSION_ERROR;
6130
0
            }
6131
6132
0
            ssl->version.minor = args->pv.minor;
6133
0
            ssl->options.tls1_3 = 0;
6134
6135
#ifdef WOLFSSL_DTLS13
6136
            if (ssl->options.dtls) {
6137
                ret = Dtls13ClientDoDowngrade(ssl);
6138
                if (ret != 0)
6139
                    return ret;
6140
            }
6141
#endif /* WOLFSSL_DTLS13 */
6142
0
        }
6143
0
    }
6144
6145
#ifdef WOLFSSL_DTLS13
6146
    /* we are sure that version is >= v1.3 now, we can get rid of buffered
6147
     * ClientHello that was buffered to re-compute the hash in case of
6148
     * downgrade */
6149
    if (ssl->options.dtls && ssl->dtls13ClientHello != NULL) {
6150
        XFREE(ssl->dtls13ClientHello, ssl->heap, DYNAMIC_TYPE_DTLS_MSG);
6151
        ssl->dtls13ClientHello = NULL;
6152
        ssl->dtls13ClientHelloSz = 0;
6153
    }
6154
#endif /* WOLFSSL_DTLS13 */
6155
6156
    /* Advance state and proceed */
6157
0
    ssl->options.asyncState = TLS_ASYNC_BUILD;
6158
0
    } /* case TLS_ASYNC_BEGIN */
6159
0
    FALL_THROUGH;
6160
6161
0
    case TLS_ASYNC_BUILD:
6162
0
    case TLS_ASYNC_DO:
6163
0
    {
6164
    /* restore message type */
6165
0
    *extMsgType = args->extMsgType;
6166
6167
    /* Parse and handle extensions, unless lower than TLS1.3. In that case,
6168
     * extensions will be parsed in DoServerHello. */
6169
0
    if (args->totalExtSz > 0 && IsAtLeastTLSv1_3(ssl->version)) {
6170
0
        ret = TLSX_Parse(ssl, input + args->idx, args->totalExtSz,
6171
0
            *extMsgType, NULL);
6172
0
        if (ret != 0) {
6173
        #ifdef WOLFSSL_ASYNC_CRYPT
6174
            /* Handle async operation */
6175
            if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
6176
                /* Mark message as not received so it can process again */
6177
                ssl->msgsReceived.got_server_hello = 0;
6178
            }
6179
        #endif
6180
0
            return ret;
6181
0
        }
6182
6183
0
        if (*extMsgType == hello_retry_request) {
6184
            /* Update counts to reflect change of message type. */
6185
0
            ssl->msgsReceived.got_hello_retry_request = 1;
6186
0
            ssl->msgsReceived.got_server_hello = 0;
6187
0
        }
6188
0
    }
6189
6190
0
    if (args->totalExtSz > 0) {
6191
0
        args->idx += args->totalExtSz;
6192
0
    }
6193
6194
#ifdef WOLFSSL_DTLS_CID
6195
    if (ssl->options.useDtlsCID && *extMsgType == server_hello)
6196
        DtlsCIDOnExtensionsParsed(ssl);
6197
#endif /* WOLFSSL_DTLS_CID */
6198
6199
0
    if (IsAtLeastTLSv1_3(ssl->version)) {
6200
0
        *inOutIdx = args->idx;
6201
0
    }
6202
6203
0
    ssl->options.serverState = SERVER_HELLO_COMPLETE;
6204
6205
#ifdef HAVE_SECRET_CALLBACK
6206
    if (ssl->sessionSecretCb != NULL
6207
#ifdef HAVE_SESSION_TICKET
6208
            && ssl->session->ticketLen > 0
6209
#endif
6210
            ) {
6211
        int secretSz = SECRET_LEN;
6212
        ret = ssl->sessionSecretCb(ssl, ssl->session->masterSecret,
6213
                                   &secretSz, ssl->sessionSecretCtx);
6214
        if (ret != 0 || secretSz != SECRET_LEN) {
6215
            WOLFSSL_ERROR_VERBOSE(SESSION_SECRET_CB_E);
6216
            return SESSION_SECRET_CB_E;
6217
        }
6218
    }
6219
#endif /* HAVE_SECRET_CALLBACK */
6220
6221
    /* Version only negotiated in extensions for TLS v1.3.
6222
     * Only now do we know how to deal with session id.
6223
     */
6224
0
    if (!IsAtLeastTLSv1_3(ssl->version)) {
6225
0
#ifndef WOLFSSL_NO_TLS12
6226
0
        ssl->arrays->sessionIDSz = args->sessIdSz;
6227
6228
0
        if (ssl->arrays->sessionIDSz > ID_LEN) {
6229
0
            WOLFSSL_MSG("Invalid session ID size");
6230
0
            ssl->arrays->sessionIDSz = 0;
6231
0
            return BUFFER_ERROR;
6232
0
        }
6233
0
        else if (ssl->arrays->sessionIDSz) {
6234
0
            XMEMCPY(ssl->arrays->sessionID, args->sessId,
6235
0
                ssl->arrays->sessionIDSz);
6236
0
            ssl->options.haveSessionId = 1;
6237
0
        }
6238
6239
        /* Force client hello version 1.2 to work for static RSA. */
6240
0
        if (ssl->options.dtls)
6241
0
            ssl->chVersion.minor = DTLSv1_2_MINOR;
6242
0
        else
6243
0
            ssl->chVersion.minor = TLSv1_2_MINOR;
6244
        /* Complete TLS v1.2 processing of ServerHello. */
6245
0
        ret = DoServerHello(ssl, input, inOutIdx, helloSz);
6246
#else
6247
        WOLFSSL_MSG("Client using higher version, fatal error");
6248
        WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
6249
        ret = VERSION_ERROR;
6250
#endif
6251
6252
0
        WOLFSSL_LEAVE("DoTls13ServerHello", ret);
6253
6254
0
        return ret;
6255
0
    }
6256
6257
    /* Advance state and proceed */
6258
0
    ssl->options.asyncState = TLS_ASYNC_FINALIZE;
6259
0
    } /* case TLS_ASYNC_BUILD || TLS_ASYNC_DO */
6260
0
    FALL_THROUGH;
6261
6262
0
    case TLS_ASYNC_FINALIZE:
6263
0
    {
6264
    /* The echo must match the ID GetTls13SessionId() sent. */
6265
0
    byte sentIdSz = Tls13ClientSessionIdSz(ssl);
6266
#ifdef WOLFSSL_TLS13_MIDDLEBOX_COMPAT
6267
    if (ssl->options.tls13MiddleBoxCompat) {
6268
        if (args->sessIdSz == 0) {
6269
            WOLFSSL_MSG("args->sessIdSz == 0");
6270
            WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
6271
            return INVALID_PARAMETER;
6272
        }
6273
        if (sentIdSz != 0) {
6274
            if (sentIdSz != args->sessIdSz ||
6275
                XMEMCMP(ssl->session->sessionID, args->sessId,
6276
                    args->sessIdSz) != 0) {
6277
                WOLFSSL_MSG("session id doesn't match");
6278
                WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
6279
                return INVALID_PARAMETER;
6280
            }
6281
        }
6282
        else if (XMEMCMP(ssl->arrays->clientRandom, args->sessId,
6283
                args->sessIdSz) != 0) {
6284
            WOLFSSL_MSG("session id doesn't match client random");
6285
            WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
6286
            return INVALID_PARAMETER;
6287
        }
6288
    }
6289
    else
6290
#endif /* WOLFSSL_TLS13_MIDDLEBOX_COMPAT */
6291
#if defined(WOLFSSL_QUIC) || defined(WOLFSSL_DTLS13)
6292
    if (0
6293
#ifdef WOLFSSL_QUIC
6294
        || WOLFSSL_IS_QUIC(ssl)
6295
#endif
6296
#ifdef WOLFSSL_DTLS13
6297
        || ssl->options.dtls
6298
#endif
6299
    ) {
6300
        /* RFC 9147 Section 5 / RFC 9001 Section 8.4: DTLS 1.3 and QUIC
6301
         * ServerHello must have empty legacy_session_id_echo. */
6302
        int requireEmptyEcho = 1;
6303
#ifdef WOLFSSL_DTLS13_ECHO_LEGACY_SESSION_ID
6304
        /* Compat: a wolfSSL <= 5.9.0 DTLS 1.3 server echoes the client's
6305
         * legacy_session_id back instead of omitting it. */
6306
        if (ssl->options.dtls)
6307
            requireEmptyEcho = 0;
6308
#endif
6309
        if (requireEmptyEcho && args->sessIdSz != 0) {
6310
            WOLFSSL_MSG("args->sessIdSz != 0");
6311
            WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
6312
            return INVALID_PARAMETER;
6313
        }
6314
#ifdef WOLFSSL_DTLS13_ECHO_LEGACY_SESSION_ID
6315
        /* An echoing wolfSSL <= 5.9.0 server must still send back what was
6316
         * sent (RFC 8446 Section 4.1.3), so don't accept an arbitrary value.
6317
         * An empty echo is the compliant server case and stays acceptable. */
6318
        if (!requireEmptyEcho && args->sessIdSz != 0 &&
6319
                (args->sessIdSz != sentIdSz ||
6320
                 XMEMCMP(ssl->session->sessionID, args->sessId,
6321
                         args->sessIdSz) != 0)) {
6322
            WOLFSSL_MSG("Server sent different session id");
6323
            WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
6324
            return INVALID_PARAMETER;
6325
        }
6326
#endif
6327
    }
6328
    else
6329
#endif /* WOLFSSL_QUIC || WOLFSSL_DTLS13 */
6330
0
    if (args->sessIdSz != sentIdSz || (args->sessIdSz > 0 &&
6331
0
        XMEMCMP(ssl->session->sessionID, args->sessId, args->sessIdSz) != 0))
6332
0
    {
6333
0
        WOLFSSL_MSG("Server sent different session id");
6334
0
        WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
6335
0
        return INVALID_PARAMETER;
6336
0
    }
6337
6338
0
    ret = SetCipherSpecs(ssl);
6339
0
    if (ret != 0)
6340
0
        return ret;
6341
6342
#ifdef HAVE_NULL_CIPHER
6343
    if (ssl->options.cipherSuite0 == ECC_BYTE &&
6344
                              (ssl->options.cipherSuite == TLS_SHA256_SHA256 ||
6345
                               ssl->options.cipherSuite == TLS_SHA384_SHA384)) {
6346
        ;
6347
    }
6348
    else
6349
#endif
6350
#if defined(WOLFSSL_SM4_GCM) && defined(WOLFSSL_SM3)
6351
    if (ssl->options.cipherSuite0 == CIPHER_BYTE &&
6352
            ssl->options.cipherSuite == TLS_SM4_GCM_SM3) {
6353
        ; /* Do nothing. */
6354
    }
6355
    else
6356
#endif
6357
#if defined(WOLFSSL_SM4_CCM) && defined(WOLFSSL_SM3)
6358
    if (ssl->options.cipherSuite0 == CIPHER_BYTE &&
6359
            ssl->options.cipherSuite == TLS_SM4_CCM_SM3) {
6360
        ; /* Do nothing. */
6361
    }
6362
    else
6363
#endif
6364
    /* Check that the negotiated ciphersuite matches protocol version. */
6365
0
    if (ssl->options.cipherSuite0 != TLS13_BYTE) {
6366
0
        WOLFSSL_MSG("Server sent non-TLS13 cipher suite in TLS 1.3 packet");
6367
0
        WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
6368
0
        return INVALID_PARAMETER;
6369
0
    }
6370
6371
0
    suite[0] = ssl->options.cipherSuite0;
6372
0
    suite[1] = ssl->options.cipherSuite;
6373
0
    if (!FindSuiteSSL(ssl, suite)) {
6374
0
        WOLFSSL_MSG("Cipher suite not supported on client");
6375
0
        WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
6376
0
        return INVALID_PARAMETER;
6377
0
    }
6378
6379
#if defined(HAVE_ECH)
6380
    /* check for acceptConfirmation */
6381
    if (ssl->echConfigs != NULL && !ssl->options.disableECH &&
6382
            ssl->hsHashesEch != NULL) {
6383
        args->echX = TLSX_Find(ssl->extensions, TLSX_ECH);
6384
        if (args->echX == NULL || args->echX->data == NULL)
6385
            return WOLFSSL_FATAL_ERROR;
6386
6387
        if (args->extMsgType == hello_retry_request &&
6388
                ((WOLFSSL_ECH*)args->echX->data)->confBuf == NULL) {
6389
            /* server rejected ECH, fall back to outer */
6390
            Free_HS_Hashes(ssl->hsHashesEch, ssl->heap);
6391
            ssl->hsHashesEch = NULL;
6392
            /* EchCheckAcceptance is bypassed, so replace extensions now */
6393
            ret = TLSX_EchReplaceExtensions(ssl, 0);
6394
            if (ret != 0)
6395
                return ret;
6396
        }
6397
        else {
6398
            const byte* hsMsg;
6399
            int acceptOffset;
6400
            word32 headerSz = HANDSHAKE_HEADER_SZ;
6401
        #ifdef WOLFSSL_DTLS13
6402
            if (ssl->options.dtls)
6403
                headerSz = DTLS13_HANDSHAKE_HEADER_SZ;
6404
        #endif
6405
            /* EchCheckAcceptance hashes from the handshake header, which
6406
             * always precedes input + args->begin (cf. HashInput) */
6407
            hsMsg = input + args->begin - headerSz;
6408
            /* account for hrr extension instead of server random */
6409
            if (args->extMsgType == hello_retry_request) {
6410
                acceptOffset =
6411
                    (int)(((WOLFSSL_ECH*)args->echX->data)->confBuf - hsMsg);
6412
                args->acceptLabel = (byte*)echHrrAcceptConfirmationLabel;
6413
                args->acceptLabelSz = ECH_HRR_ACCEPT_CONFIRMATION_LABEL_SZ;
6414
            }
6415
            else {
6416
                acceptOffset = (int)(input + args->acceptOffset - hsMsg);
6417
                args->acceptLabel = (byte*)echAcceptConfirmationLabel;
6418
                args->acceptLabelSz = ECH_ACCEPT_CONFIRMATION_LABEL_SZ;
6419
            }
6420
            /* check acceptance */
6421
            if (ret == 0) {
6422
                ret = EchCheckAcceptance(ssl, args->acceptLabel,
6423
                    args->acceptLabelSz, hsMsg, acceptOffset, helloSz,
6424
                    args->extMsgType);
6425
            }
6426
            if (ret != 0)
6427
                return ret;
6428
            /* use the inner random for client random */
6429
            if (args->extMsgType != hello_retry_request &&
6430
                    ssl->options.echAccepted) {
6431
                XMEMCPY(ssl->arrays->clientRandom,
6432
                    ssl->arrays->clientRandomInner, RAN_LEN);
6433
            }
6434
        }
6435
    }
6436
#endif /* HAVE_ECH */
6437
6438
0
    if (*extMsgType == server_hello) {
6439
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
6440
        PreSharedKey* psk = NULL;
6441
        TLSX* ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
6442
        if (ext != NULL)
6443
            psk = (PreSharedKey*)ext->data;
6444
        while (psk != NULL && !psk->chosen)
6445
            psk = psk->next;
6446
        if (psk == NULL) {
6447
            /* A mandatory PSK is satisfied by any PSK the server chose,
6448
             * including a resumption PSK - this matches the server-side
6449
             * failNoPSK semantics, where a negotiated PSK (external or
6450
             * resumption) is accepted. The error only fires when no PSK was
6451
             * chosen at all. havePSK is only set by an external-PSK callback,
6452
             * so a peer relying solely on session-ticket resumption is
6453
             * unaffected. */
6454
            if (ssl->options.havePSK && ssl->options.failNoPSK) {
6455
                WOLFSSL_MSG("Server did not negotiate a mandatory PSK");
6456
                WOLFSSL_ERROR_VERBOSE(PSK_MISSING_ERROR);
6457
                return PSK_MISSING_ERROR;
6458
            }
6459
            ssl->options.resuming = 0;
6460
            ssl->arrays->psk_keySz = 0;
6461
            XMEMSET(ssl->arrays->psk_key, 0, MAX_PSK_KEY_LEN);
6462
        }
6463
        else {
6464
#if defined(HAVE_ECH)
6465
            /* do not resume when outerHandshake will be negotiated */
6466
            if (EchRejected(ssl)) {
6467
                WOLFSSL_MSG("ECH rejected but server negotiated PSK");
6468
                return INVALID_PARAMETER;
6469
            }
6470
#endif
6471
#ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
6472
            if (ssl->options.certWithExternPsk && psk->resumption) {
6473
                /* RFC 9973 mode requires external PSK, not ticket resumption. */
6474
                WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
6475
                return PSK_KEY_ERROR;
6476
            }
6477
            if (ssl->options.certWithExternPsk && ssl->options.shSentKeyShare == 0) {
6478
                /* RFC 9973 Sect. 3: cert_with_extern_psk requires psk_dhe_ke;
6479
                 * a ServerHello without a key_share confirms only psk_ke. */
6480
                WOLFSSL_MSG("cert_with_extern_psk: ServerHello missing key_share");
6481
                WOLFSSL_ERROR_VERBOSE(EXT_MISSING);
6482
                return EXT_MISSING;
6483
            }
6484
#endif
6485
            if ((ret = SetupPskKey(ssl, psk, 0)) != 0)
6486
                return ret;
6487
            ssl->options.pskNegotiated = 1;
6488
        }
6489
#else
6490
        /* no resumption possible */
6491
0
        ssl->options.resuming = 0;
6492
0
#endif
6493
6494
        /* sanity check on PSK / KSE */
6495
0
        if (
6496
    #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
6497
            ssl->options.pskNegotiated == 0 &&
6498
    #endif
6499
0
            (ssl->session->namedGroup == 0 ||
6500
0
             ssl->options.shSentKeyShare == 0)) {
6501
0
            return EXT_MISSING;
6502
0
        }
6503
6504
0
        ssl->keys.encryptionOn = 1;
6505
0
        ssl->options.serverState = SERVER_HELLO_COMPLETE;
6506
6507
0
    }
6508
0
    else {
6509
        /* https://datatracker.ietf.org/doc/html/rfc8446#section-4.1.4
6510
         * Clients MUST abort the handshake with an
6511
         * "illegal_parameter" alert if the HelloRetryRequest would not result
6512
         * in any change in the ClientHello.
6513
         */
6514
        /* Check if the HRR contained a cookie or a keyshare */
6515
0
        if (!ssl->options.hrrSentKeyShare
6516
0
#ifdef WOLFSSL_TLS13_COOKIE
6517
0
                && !ssl->options.hrrSentCookie
6518
0
#endif
6519
0
                ) {
6520
0
            SendAlert(ssl, alert_fatal, illegal_parameter);
6521
0
            return EXT_MISSING;
6522
0
        }
6523
6524
0
        ssl->options.tls1_3 = 1;
6525
0
        ssl->options.serverState = SERVER_HELLO_RETRY_REQUEST_COMPLETE;
6526
6527
0
        ret = RestartHandshakeHash(ssl);
6528
0
    }
6529
6530
0
    break;
6531
0
    } /* case TLS_ASYNC_FINALIZE */
6532
0
    default:
6533
0
        ret = INPUT_CASE_ERROR;
6534
0
    } /* switch (ssl->options.asyncState) */
6535
6536
#ifdef WOLFSSL_ASYNC_CRYPT
6537
    if (ret == 0) {
6538
        FreeAsyncCtx(ssl, 0);
6539
        /* Replays skip the sanity check that re-sets got_server_hello;
6540
         * restore on completion (not for HRR, which re-counts it). */
6541
        if (*extMsgType == server_hello &&
6542
                ssl->msgsReceived.got_server_hello == 0) {
6543
            ssl->msgsReceived.got_server_hello = 1;
6544
        }
6545
    }
6546
#endif
6547
6548
0
    WOLFSSL_LEAVE("DoTls13ServerHello", ret);
6549
0
    WOLFSSL_END(WC_FUNC_SERVER_HELLO_DO);
6550
6551
0
    return ret;
6552
0
}
6553
6554
/* handle processing TLS 1.3 encrypted_extensions (8) */
6555
/* Parse and handle an EncryptedExtensions message.
6556
 * Only a client will receive this message.
6557
 *
6558
 * ssl       The SSL/TLS object.
6559
 * input     The message buffer.
6560
 * inOutIdx  On entry, the index into the message buffer of
6561
 *           EncryptedExtensions.
6562
 *           On exit, the index of byte after the EncryptedExtensions
6563
 *           message.
6564
 * totalSz   The length of the current handshake message.
6565
 * returns 0 on success and otherwise failure.
6566
 */
6567
static int DoTls13EncryptedExtensions(WOLFSSL* ssl, const byte* input,
6568
                                      word32* inOutIdx, word32 totalSz)
6569
0
{
6570
0
    int    ret;
6571
0
    word32 begin = *inOutIdx;
6572
0
    word32 i = begin;
6573
0
    word16 totalExtSz;
6574
6575
0
    WOLFSSL_START(WC_FUNC_ENCRYPTED_EXTENSIONS_DO);
6576
0
    WOLFSSL_ENTER("DoTls13EncryptedExtensions");
6577
6578
#ifdef WOLFSSL_CALLBACKS
6579
    if (ssl->hsInfoOn) AddPacketName(ssl, "EncryptedExtensions");
6580
    if (ssl->toInfoOn) AddLateName("EncryptedExtensions", &ssl->timeoutInfo);
6581
#endif
6582
6583
    /* Length field of extension data. */
6584
0
    if (totalSz < OPAQUE16_LEN)
6585
0
        return BUFFER_ERROR;
6586
0
    ato16(&input[i], &totalExtSz);
6587
0
    i += OPAQUE16_LEN;
6588
6589
    /* Extension data. */
6590
0
    if (i - begin + totalExtSz != totalSz)
6591
0
        return BUFFER_ERROR;
6592
0
    if ((ret = TLSX_Parse(ssl, input + i, totalExtSz, encrypted_extensions,
6593
0
                                                                       NULL))) {
6594
0
        return ret;
6595
0
    }
6596
6597
    /* Move index to byte after message. */
6598
0
    *inOutIdx = i + totalExtSz;
6599
6600
#ifdef WOLFSSL_EARLY_DATA
6601
    if (ssl->earlyData != no_early_data) {
6602
        TLSX* ext = TLSX_Find(ssl->extensions, TLSX_EARLY_DATA);
6603
        if (ext == NULL || !ext->val) {
6604
            WOLFSSL_MSG("Early data rejected by server (no early_data "
6605
                        "EncryptedExtensions response)");
6606
            ssl->earlyData = no_early_data;
6607
        }
6608
    }
6609
6610
    if (ssl->earlyData == no_early_data) {
6611
        ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY);
6612
        if (ret != 0)
6613
            return ret;
6614
    }
6615
#endif /* WOLFSSL_EARLY_DATA */
6616
6617
0
    ssl->options.serverState = SERVER_ENCRYPTED_EXTENSIONS_COMPLETE;
6618
6619
0
    WOLFSSL_LEAVE("DoTls13EncryptedExtensions", ret);
6620
0
    WOLFSSL_END(WC_FUNC_ENCRYPTED_EXTENSIONS_DO);
6621
6622
0
    return ret;
6623
0
}
6624
6625
#ifndef NO_CERTS
6626
/* handle processing TLS v1.3 certificate_request (13) */
6627
/* Handle a TLS v1.3 CertificateRequest message.
6628
 * This message is always encrypted.
6629
 * Only a client will receive this message.
6630
 *
6631
 * ssl       The SSL/TLS object.
6632
 * input     The message buffer.
6633
 * inOutIdx  On entry, the index into the message buffer of CertificateRequest.
6634
 *           On exit, the index of byte after the CertificateRequest message.
6635
 * size      The length of the current handshake message.
6636
 * returns 0 on success and otherwise failure.
6637
 */
6638
static int DoTls13CertificateRequest(WOLFSSL* ssl, const byte* input,
6639
                                     word32* inOutIdx, word32 size)
6640
0
{
6641
0
    word16      len;
6642
0
    word32      begin = *inOutIdx;
6643
0
    int         ret = 0;
6644
0
    Suites      peerSuites;
6645
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
6646
    word16      reqCtxLen;
6647
    const byte* reqCtxData;
6648
#endif
6649
6650
0
    WOLFSSL_START(WC_FUNC_CERTIFICATE_REQUEST_DO);
6651
0
    WOLFSSL_ENTER("DoTls13CertificateRequest");
6652
6653
0
    XMEMSET(&peerSuites, 0, sizeof(Suites));
6654
0
#if !defined(WOLFSSL_NO_SIGALG)
6655
    /* Post-handshake auth can deliver several requests; each one's cert
6656
     * signature algorithms replace the last rather than adding to them. */
6657
0
    XFREE(ssl->certHashSigAlgo, ssl->heap, DYNAMIC_TYPE_TLSX);
6658
0
    ssl->certHashSigAlgo = NULL;
6659
0
    ssl->certHashSigAlgoSz = 0;
6660
0
#endif
6661
6662
#ifdef WOLFSSL_CALLBACKS
6663
    if (ssl->hsInfoOn) AddPacketName(ssl, "CertificateRequest");
6664
    if (ssl->toInfoOn) AddLateName("CertificateRequest", &ssl->timeoutInfo);
6665
#endif
6666
6667
0
    if (OPAQUE8_LEN > size)
6668
0
        return BUFFER_ERROR;
6669
6670
    /* Length of the request context. */
6671
0
    len = input[(*inOutIdx)++];
6672
0
    if ((*inOutIdx - begin) + len > size)
6673
0
        return BUFFER_ERROR;
6674
    /* INVALID_PARAMETER does not map to illegal_parameter in the central
6675
     * alert path, so emit the alert explicitly before returning. */
6676
0
    if (ssl->options.connectState < FINISHED_DONE) {
6677
        /* RFC 8446 Section 4.3.2: in the handshake the context is zero
6678
         * length. */
6679
0
        if (len > 0) {
6680
0
            SendAlert(ssl, alert_fatal, illegal_parameter);
6681
0
            WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
6682
0
            return INVALID_PARAMETER;
6683
0
        }
6684
0
    }
6685
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
6686
#ifdef WOLFSSL_QUIC
6687
    else if (WOLFSSL_IS_QUIC(ssl)) {
6688
        WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
6689
        return OUT_OF_ORDER_E;
6690
    }
6691
#endif
6692
    else if (len == 0) {
6693
        /* RFC 8446 Section 4.3.2: a post-handshake CertificateRequest context
6694
         * MUST be non-empty and unique for the connection. */
6695
        SendAlert(ssl, alert_fatal, illegal_parameter);
6696
        WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
6697
        return INVALID_PARAMETER;
6698
    }
6699
#endif
6700
6701
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
6702
    /* Remember the request context bytes; the CertReqCtx allocation and
6703
     * linking into ssl->certReqCtx is deferred until after the rest of the
6704
     * message has been validated.
6705
     */
6706
    reqCtxLen = len;
6707
    reqCtxData = input + *inOutIdx;
6708
    /* Reject a context that duplicates one still pending on the connection. */
6709
    if (ssl->options.connectState >= FINISHED_DONE) {
6710
        CertReqCtx* dup;
6711
        for (dup = ssl->certReqCtx; dup != NULL; dup = dup->next) {
6712
            if (dup->len == reqCtxLen &&
6713
                    XMEMCMP(&dup->ctx, reqCtxData, reqCtxLen) == 0) {
6714
                SendAlert(ssl, alert_fatal, illegal_parameter);
6715
                WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
6716
                return INVALID_PARAMETER;
6717
            }
6718
        }
6719
    }
6720
#endif
6721
0
    *inOutIdx += len;
6722
6723
    /* TODO: Add support for more extensions:
6724
     *   signed_certificate_timestamp, certificate_authorities, oid_filters.
6725
     */
6726
    /* Certificate extensions */
6727
0
    if ((*inOutIdx - begin) + OPAQUE16_LEN > size)
6728
0
        return BUFFER_ERROR;
6729
0
    ato16(input + *inOutIdx, &len);
6730
0
    *inOutIdx += OPAQUE16_LEN;
6731
0
    if ((*inOutIdx - begin) + len > size)
6732
0
        return BUFFER_ERROR;
6733
    /* RFC 9846 Section 4.4.2: CertificateRequest.extensions has a lower bound of
6734
     * 0, so an empty extensions block is parsed rather than rejected here. A
6735
     * request missing the mandatory signature_algorithms extension is caught by
6736
     * the check below. */
6737
0
    if ((ret = TLSX_Parse(ssl, input + *inOutIdx, len, certificate_request,
6738
0
                                                                &peerSuites))) {
6739
0
        return ret;
6740
0
    }
6741
0
    *inOutIdx += len;
6742
6743
    /* No trailing bytes allowed (RFC 8446 4.3.2). */
6744
0
    if ((*inOutIdx - begin) != size)
6745
0
        return BUFFER_ERROR;
6746
6747
    /* RFC 8446 Section 4.3.2: the signature_algorithms extension MUST be
6748
     * present in a CertificateRequest. */
6749
0
    if (peerSuites.hashSigAlgoSz == 0) {
6750
0
        SendAlert(ssl, alert_fatal, missing_extension);
6751
0
        WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
6752
0
        return INVALID_PARAMETER;
6753
0
    }
6754
6755
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
6756
    if (ssl->options.handShakeState == HANDSHAKE_DONE && IsWriteClosed(ssl)) {
6757
        WOLFSSL_LEAVE("DoTls13CertificateRequest", 0);
6758
        WOLFSSL_END(WC_FUNC_CERTIFICATE_REQUEST_DO);
6759
        return 0;
6760
    }
6761
#endif
6762
6763
0
#if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
6764
0
    SetPeerSha1CertOk(ssl, &peerSuites);
6765
0
#endif
6766
6767
#ifdef WOLFSSL_CERT_SETUP_CB
6768
    if (
6769
        /* no client cert is sent when ECH is rejected */
6770
        !EchRejected(ssl) &&
6771
        (ret = CertSetupCbWrapper(ssl)) != 0)
6772
        return ret;
6773
#endif
6774
6775
#if defined(HAVE_ECH)
6776
    /* RFC 9849 s6.1.7: ECH was offered but rejected by the server...
6777
     * the client MUST respond with an empty Certificate message. */
6778
    if (EchRejected(ssl)) {
6779
        ssl->options.sendVerify = SEND_BLANK_CERT;
6780
    }
6781
    else
6782
#endif
6783
0
    if ((ssl->buffers.certificate && ssl->buffers.certificate->buffer &&
6784
0
        ((ssl->buffers.key && ssl->buffers.key->buffer)
6785
        #ifdef HAVE_PK_CALLBACKS
6786
            || wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)
6787
        #endif
6788
0
    ))
6789
        #ifdef OPENSSL_EXTRA
6790
            || ssl->ctx->certSetupCb != NULL
6791
        #endif
6792
0
            ) {
6793
0
        if (PickHashSigAlgo(ssl, peerSuites.hashSigAlgo,
6794
0
                            peerSuites.hashSigAlgoSz, 0) != 0) {
6795
0
            WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
6796
0
            return INVALID_PARAMETER;
6797
0
        }
6798
0
        ssl->options.sendVerify = SEND_CERT;
6799
0
    }
6800
0
    else {
6801
0
#ifndef WOLFSSL_NO_CLIENT_CERT_ERROR
6802
0
        ssl->options.sendVerify = SEND_BLANK_CERT;
6803
#else
6804
        WOLFSSL_MSG("Certificate required but none set on client");
6805
        /* RFC 8446 Section 4.4.2.4: send certificate_required when a
6806
         * peer (here, the client) cannot provide a certificate that the
6807
         * other peer required. */
6808
        SendAlert(ssl, alert_fatal, certificate_required);
6809
        WOLFSSL_ERROR_VERBOSE(NO_CERT_ERROR);
6810
        return NO_CERT_ERROR;
6811
#endif
6812
0
    }
6813
6814
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
6815
    {
6816
        /* CertReqCtx has one byte at end for context value.
6817
        * Increase size to handle other implementations sending more than one byte.
6818
        * That is, allocate extra space, over one byte, to hold the context value.
6819
        */
6820
        CertReqCtx* certReqCtx = (CertReqCtx*)XMALLOC(
6821
            sizeof(CertReqCtx) + (reqCtxLen == 0 ? 0 : reqCtxLen - 1),
6822
            ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
6823
        if (certReqCtx == NULL)
6824
            return MEMORY_E;
6825
        certReqCtx->next = ssl->certReqCtx;
6826
        certReqCtx->len = reqCtxLen;
6827
        XMEMCPY(&certReqCtx->ctx, reqCtxData, reqCtxLen);
6828
        ssl->certReqCtx = certReqCtx;
6829
    }
6830
#endif
6831
6832
0
    WOLFSSL_LEAVE("DoTls13CertificateRequest", ret);
6833
0
    WOLFSSL_END(WC_FUNC_CERTIFICATE_REQUEST_DO);
6834
6835
0
    return ret;
6836
0
}
6837
#endif /* !NO_CERTS */
6838
#endif /* !NO_WOLFSSL_CLIENT */
6839
6840
#ifndef NO_WOLFSSL_SERVER
6841
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
6842
#ifndef NO_PSK
6843
int FindPskSuite(const WOLFSSL* ssl, PreSharedKey* psk, byte* psk_key,
6844
        word32* psk_keySz, const byte* suite, int* found, byte* foundSuite)
6845
{
6846
    const char* cipherName = NULL;
6847
    byte        cipherSuite0 = TLS13_BYTE;
6848
    byte        cipherSuite  = WOLFSSL_DEF_PSK_CIPHER;
6849
    int         ret = 0;
6850
6851
    *found = 0;
6852
    (void)suite;
6853
6854
    /* A longer identity can only be a session ticket */
6855
    if (psk->identityLen > MAX_PSK_ID_LEN) {
6856
        WOLFSSL_MSG("PSK identity longer than MAX_PSK_ID_LEN, not offered to "
6857
                    "the PSK callback");
6858
        return 0;
6859
    }
6860
6861
    if (ssl->options.server_psk_tls13_cb != NULL) {
6862
         *psk_keySz = ssl->options.server_psk_tls13_cb((WOLFSSL*)ssl,
6863
             (char*)psk->identity, psk_key, MAX_PSK_KEY_LEN, &cipherName);
6864
         if (*psk_keySz != 0) {
6865
             int cipherSuiteFlags = WOLFSSL_CIPHER_SUITE_FLAG_NONE;
6866
             *found = (GetCipherSuiteFromName(cipherName, &cipherSuite0,
6867
                 &cipherSuite, NULL, NULL, &cipherSuiteFlags) == 0);
6868
             (void)cipherSuiteFlags;
6869
         }
6870
    }
6871
    if (*found == 0 && (ssl->options.server_psk_cb != NULL)) {
6872
         *psk_keySz = ssl->options.server_psk_cb((WOLFSSL*)ssl,
6873
                             (char*)psk->identity, psk_key,
6874
                             MAX_PSK_KEY_LEN);
6875
         *found = (*psk_keySz != 0);
6876
    }
6877
    if (*found) {
6878
        if (*psk_keySz > MAX_PSK_KEY_LEN &&
6879
            (int)*psk_keySz != WC_NO_ERR_TRACE(USE_HW_PSK)) {
6880
            WOLFSSL_MSG("Key len too long in FindPsk()");
6881
            ret = PSK_KEY_ERROR;
6882
            WOLFSSL_ERROR_VERBOSE(ret);
6883
            *found = 0;
6884
        }
6885
        if (ret == 0) {
6886
        #if !defined(WOLFSSL_PSK_ONE_ID) && !defined(WOLFSSL_PRIORITIZE_PSK)
6887
            /* Check whether PSK ciphersuite is in SSL. */
6888
            *found = (suite[0] == cipherSuite0) && (suite[1] == cipherSuite);
6889
        #else
6890
            (void)suite;
6891
            /* Check whether PSK ciphersuite is in SSL. */
6892
            {
6893
                byte s[2] = {
6894
                    cipherSuite0,
6895
                    cipherSuite,
6896
                };
6897
                *found = FindSuiteSSL(ssl, s);
6898
            }
6899
        #endif
6900
        }
6901
    }
6902
    if (*found && foundSuite != NULL) {
6903
        foundSuite[0] = cipherSuite0;
6904
        foundSuite[1] = cipherSuite;
6905
    }
6906
6907
    return ret;
6908
}
6909
6910
/* Attempt to find the PSK (not session ticket) that matches.
6911
 *
6912
 * @param [in, out] ssl    The SSL/TLS object.
6913
 * @param [in]      psk    A pre-shared key from the extension.
6914
 * @param [out]     suite  Cipher suite to use with PSK.
6915
 * @param [out]     err    Error code.
6916
 *                         PSK_KEY_ERROR when key is too big,
6917
 *                         UNSUPPORTED_SUITE on invalid suite.
6918
 *                         Other error when attempting to derive early secret.
6919
 * @return  1 when a match found - but check error code.
6920
 * @return  0 when no match found.
6921
 */
6922
static int FindPsk(WOLFSSL* ssl, PreSharedKey* psk, const byte* suite, int* err)
6923
{
6924
    int         ret = 0;
6925
    int         found = 0;
6926
    byte        foundSuite[SUITE_LEN];
6927
6928
    WOLFSSL_ENTER("FindPsk");
6929
6930
    XMEMSET(foundSuite, 0, sizeof(foundSuite));
6931
6932
    ret = FindPskSuite(ssl, psk, ssl->arrays->psk_key, &ssl->arrays->psk_keySz,
6933
                       suite, &found, foundSuite);
6934
    if (ret == 0 && found) {
6935
        /* This identity matched via external PSK callback, not ticket resume. */
6936
        psk->resumption = 0;
6937
        /* Default to ciphersuite if cb doesn't specify. */
6938
        ssl->options.resuming = 0;
6939
6940
        /* obfuscated_ticket_age is not checked: RFC 8446 Section 4.2.11
6941
         * requires servers to ignore it for an external identity. */
6942
        /* Set PSK ciphersuite into SSL. */
6943
        ssl->options.cipherSuite0 = foundSuite[0];
6944
        ssl->options.cipherSuite  = foundSuite[1];
6945
        ret = SetCipherSpecs(ssl);
6946
        if (ret == 0) {
6947
            /* Derive the early secret using the PSK. */
6948
            ret = DeriveEarlySecret(ssl);
6949
        }
6950
        if (ret == 0) {
6951
            /* PSK negotiation has succeeded */
6952
#ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
6953
            /* RFC 9973 applies only if the client sent the extension; the
6954
             * server opting in is not enough. */
6955
            if (TLSX_Find(ssl->extensions, TLSX_CERT_WITH_EXTERN_PSK) == NULL)
6956
#endif
6957
            {
6958
                /* SERVER: using PSK for peer authentication, so no
6959
                 * certificate is requested below. */
6960
                ssl->options.peerAuthGood = 1;
6961
                ssl->options.usingPSK_cipher = 1;
6962
            }
6963
        }
6964
    }
6965
6966
    *err = ret;
6967
    WOLFSSL_LEAVE("FindPsk", found);
6968
    WOLFSSL_LEAVE("FindPsk", ret);
6969
    return found;
6970
}
6971
#endif /* !NO_PSK */
6972
6973
/* Handle any Pre-Shared Key (PSK) extension.
6974
 * Find a PSK that supports the cipher suite passed in.
6975
 *
6976
 * ssl         SSL/TLS object.
6977
 * suite       Cipher suite to find PSK for.
6978
 * usingPSK    1=Indicates handshake is using Pre-Shared Keys (2=Ephemeral)
6979
 * first       Set to 1 if first in extension
6980
 * returns 0 on success and otherwise failure.
6981
 */
6982
static int DoPreSharedKeys(WOLFSSL* ssl, const byte* input, word32 inputSz,
6983
    const byte* suite, int* usingPSK, int* first)
6984
{
6985
    int           ret = 0;
6986
    TLSX*         ext;
6987
    PreSharedKey* current;
6988
    byte          binderKey[WC_MAX_DIGEST_SIZE];
6989
    byte          binder[WC_MAX_DIGEST_SIZE];
6990
    word32        binderLen;
6991
#if defined(WOLFSSL_CERT_WITH_EXTERN_PSK) && defined(HAVE_SESSION_TICKET)
6992
    int           certWithExternOffered = 0;
6993
#endif
6994
6995
    #ifdef NO_PSK
6996
        (void) suite; /* to avoid unused var warning when not used */
6997
    #endif
6998
6999
    WOLFSSL_ENTER("DoPreSharedKeys");
7000
7001
    (void)suite;
7002
7003
#ifdef WOLFSSL_CHECK_MEM_ZERO
7004
    /* Poison and register binderKey up front; every exit below (including the
7005
     * error paths) funnels through the cleanup label which zeroes it. */
7006
    XMEMSET(binderKey, 0xff, sizeof(binderKey));
7007
    wc_MemZero_Add("DoPreSharedKeys binderKey", binderKey, sizeof(binderKey));
7008
#endif
7009
7010
#if defined(HAVE_SESSION_TICKET) && defined(WOLFSSL_EARLY_DATA)
7011
    ssl->options.ticketPredatesCtx = 0;
7012
#ifndef NO_SESSION_CACHE
7013
    /* Re-derived from this ClientHello's ticket. A stale value from the first
7014
     * hello of an HRR exchange must not gate 0-RTT for the second. */
7015
    ssl->options.ticketCacheHit = 0;
7016
#endif
7017
#endif
7018
7019
    ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
7020
    if (ext == NULL) {
7021
        WOLFSSL_MSG("No pre shared extension keys found");
7022
        ret = BAD_FUNC_ARG;
7023
        goto cleanup;
7024
    }
7025
#if defined(WOLFSSL_CERT_WITH_EXTERN_PSK) && defined(HAVE_SESSION_TICKET)
7026
    certWithExternOffered =
7027
        TLSX_Find(ssl->extensions, TLSX_CERT_WITH_EXTERN_PSK) != NULL;
7028
#endif
7029
7030
    /* Look through all client's pre-shared keys for a match. */
7031
    for (current = (PreSharedKey*)ext->data; current != NULL;
7032
            current = current->next) {
7033
    #ifndef NO_PSK
7034
        /* A session ticket can be longer than an external PSK identity. */
7035
        if (current->identityLen <= MAX_PSK_ID_LEN) {
7036
            XMEMCPY(ssl->arrays->client_identity, current->identity,
7037
                    current->identityLen);
7038
            ssl->arrays->client_identity[current->identityLen] = '\0';
7039
        }
7040
        else {
7041
            ssl->arrays->client_identity[0] = '\0';
7042
        }
7043
    #endif
7044
7045
    #ifdef HAVE_SESSION_TICKET
7046
        /* Decode the identity. */
7047
        switch (current->decryptRet) {
7048
            case PSK_DECRYPT_NONE:
7049
                ret = DoClientTicket_ex(ssl, current, 1);
7050
                /* psk->sess may be set. Need to clean up later. */
7051
                break;
7052
            case PSK_DECRYPT_OK:
7053
                ret = WOLFSSL_TICKET_RET_OK;
7054
                break;
7055
            case PSK_DECRYPT_CREATE:
7056
                ret = WOLFSSL_TICKET_RET_CREATE;
7057
                break;
7058
            case PSK_DECRYPT_FAIL:
7059
                ret = WOLFSSL_TICKET_RET_REJECT;
7060
                break;
7061
        }
7062
7063
        #ifdef WOLFSSL_ASYNC_CRYPT
7064
        if (ret == WC_NO_ERR_TRACE(WC_PENDING_E))
7065
            goto cleanup;
7066
        #endif
7067
7068
        if (ret != WOLFSSL_TICKET_RET_OK && current->sess_free_cb != NULL) {
7069
            current->sess_free_cb(ssl, current->sess,
7070
                    &current->sess_free_cb_ctx);
7071
            current->sess = NULL;
7072
            current->sess_free_cb = NULL;
7073
            XMEMSET(&current->sess_free_cb_ctx, 0,
7074
                    sizeof(psk_sess_free_cb_ctx));
7075
        }
7076
        if (ret == WOLFSSL_TICKET_RET_OK) {
7077
#if defined(WOLFSSL_CERT_WITH_EXTERN_PSK) && defined(HAVE_SESSION_TICKET)
7078
            /* RFC 9973 Sect. 5.1: all PSKs listed alongside
7079
             * tls_cert_with_extern_psk MUST be external PSKs.  A successfully
7080
             * decrypted session ticket identity is a resumption PSK, so the
7081
             * server MUST abort with illegal_parameter regardless of whether
7082
             * the ticket would otherwise be acceptable.  Check here, before
7083
             * DoClientTicketFinalize, to avoid polluting ssl->session with
7084
             * ticket state that will not be used. */
7085
            if (certWithExternOffered) {
7086
                if (current->sess_free_cb != NULL) {
7087
                    current->sess_free_cb(ssl, current->sess,
7088
                            &current->sess_free_cb_ctx);
7089
                    current->sess = NULL;
7090
                    current->sess_free_cb = NULL;
7091
                    XMEMSET(&current->sess_free_cb_ctx, 0,
7092
                            sizeof(psk_sess_free_cb_ctx));
7093
                }
7094
                ret = PSK_KEY_ERROR;
7095
                WOLFSSL_ERROR_VERBOSE(ret);
7096
                goto cleanup;
7097
            }
7098
#endif
7099
            ret = DoClientTicketCheck(ssl, current, ssl->timeout, suite);
7100
        #if defined(HAVE_SNI) || defined(HAVE_ALPN)
7101
            if (ret == 0) {
7102
                /* Decline this PSK if the SNI/ALPN bound to the ticket
7103
                 * does not match the current connection. RFC 6066 Sect.
7104
                 * 3 mandates this for SNI; wolfSSL applies the same
7105
                 * policy to ALPN as defense in depth. Skipping the PSK
7106
                 * (rather than aborting) lets the server try the next
7107
                 * candidate or fall back to a full handshake naturally
7108
                 * without unwinding committed PSK state. ALPN_Select
7109
                 * has already run earlier in DoTls13ClientHello so the
7110
                 * negotiated ALPN is available to TicketAlpnHash. */
7111
                byte curHash[TICKET_BINDING_HASH_SZ];
7112
            #ifdef HAVE_SNI
7113
                if (TicketSniHash(ssl, curHash) != 0 ||
7114
                        XMEMCMP(curHash, current->it->sniHash,
7115
                                TICKET_BINDING_HASH_SZ) != 0) {
7116
                    WOLFSSL_MSG("Ticket SNI mismatch, skipping PSK");
7117
                    ret = WOLFSSL_FATAL_ERROR;
7118
                }
7119
            #endif
7120
            #ifdef HAVE_ALPN
7121
                if (ret == 0 &&
7122
                        (TicketAlpnHash(ssl, curHash) != 0 ||
7123
                         XMEMCMP(curHash, current->it->alpnHash,
7124
                                 TICKET_BINDING_HASH_SZ) != 0)) {
7125
                    WOLFSSL_MSG("Ticket ALPN mismatch, skipping PSK");
7126
                    ret = WOLFSSL_FATAL_ERROR;
7127
                }
7128
            #endif
7129
            }
7130
        #endif
7131
            /* failNoCertxPSK excuses only a ticket from a PSK session. Before
7132
             * Finalize, so a declined ticket leaves nothing on the session. */
7133
            if (ret == 0 && ClientAuthRequired(ssl, current->it->isPSK) &&
7134
            #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
7135
                    /* Deferred, so this handshake asks for nothing. */
7136
                    !ssl->options.verifyPostHandshake &&
7137
            #endif
7138
                    !current->it->peerAuthOk) {
7139
                WOLFSSL_MSG("Ticket session lacks client auth, skipping PSK");
7140
                ret = WOLFSSL_FATAL_ERROR;
7141
            }
7142
            if (ret == 0)
7143
                DoClientTicketFinalize(ssl, current->it, current->sess);
7144
            if (current->sess_free_cb != NULL) {
7145
                current->sess_free_cb(ssl, current->sess,
7146
                        &current->sess_free_cb_ctx);
7147
                current->sess = NULL;
7148
                current->sess_free_cb = NULL;
7149
                XMEMSET(&current->sess_free_cb_ctx, 0,
7150
                        sizeof(psk_sess_free_cb_ctx));
7151
            }
7152
            if (ret != 0)
7153
                continue;
7154
7155
            /* SERVER: using secret in session ticket for peer auth. */
7156
            ssl->options.peerAuthGood = 1;
7157
7158
        #ifdef WOLFSSL_EARLY_DATA
7159
            ssl->options.maxEarlyDataSz = ssl->session->maxEarlyDataSz;
7160
            /* RFC 8446 Section 8.2: fresh servers should reject 0-RTT.
7161
             * Flag tickets minted before this ctx was created. */
7162
            if (!ssl->ctx->noFreshStartCheck) {
7163
        #ifdef WOLFSSL_32BIT_MILLI_TIME
7164
                /* A 32 bit ms clock wraps every ~49.7 days, so the ctx age is
7165
                 * only exact while it stays below the max ticket age. Past
7166
                 * that point DoClientTicketCheck has already rejected
7167
                 * anything old enough to predate the ctx, so the check can be
7168
                 * skipped.
7169
                 *
7170
                 * ctxAge is unsigned, so a clock reading before the ctx start
7171
                 * time (a backward step) wraps to just under 2^32. Letting
7172
                 * that count as an old ctx would silently disable the check
7173
                 * and admit 0-RTT for tickets minted before a restart, so the
7174
                 * near-wrap band stays in the checked range.
7175
                 *
7176
                 * The two cases are indistinguishable on a wrapping 32 bit
7177
                 * clock, so a ctx aged between (2^32 - max ticket age) and
7178
                 * 2^32 ms also lands in the band and refuses 0-RTT until it
7179
                 * wraps out. Refusing 0-RTT only costs the early data round
7180
                 * trip, so the ambiguity is resolved that way. */
7181
                word32 maxAge = (word32)TLS13_MAX_TICKET_AGE * 1000;
7182
                word32 now = TimeNowInMilliseconds();
7183
                word32 ctxAge = now - ssl->ctx->ticketStartTime;
7184
                word32 delta = ssl->ctx->ticketStartTime -
7185
                               ssl->session->ticketSeen;
7186
                ssl->options.ticketPredatesCtx =
7187
                    (now != 0 &&
7188
                     (ctxAge <= maxAge || ctxAge >= (word32)0u - maxAge) &&
7189
                     delta != 0 &&
7190
                     delta <= maxAge);
7191
        #else
7192
                ssl->options.ticketPredatesCtx =
7193
                    (ssl->session->ticketSeen < ssl->ctx->ticketStartTime);
7194
        #endif
7195
            }
7196
        #endif
7197
            /* Use the same cipher suite as before and set up for use. */
7198
            ssl->options.cipherSuite0   = ssl->session->cipherSuite0;
7199
            ssl->options.cipherSuite    = ssl->session->cipherSuite;
7200
            ret = SetCipherSpecs(ssl);
7201
            if (ret != 0)
7202
                goto cleanup;
7203
            /* TLS 1.3 suites do not record it, so restore it from the ticket. */
7204
            ssl->options.usingPSK_cipher = ssl->session->isPSK;
7205
7206
            /* Resumption PSK is resumption master secret. */
7207
            ssl->arrays->psk_keySz = ssl->specs.hash_size;
7208
            if ((ret = DeriveResumptionPSK(ssl, ssl->session->ticketNonce.data,
7209
                ssl->session->ticketNonce.len, ssl->arrays->psk_key)) != 0) {
7210
                goto cleanup;
7211
            }
7212
            /* The resumed ticket's nonce has derived its PSK. The tickets of
7213
             * this connection get PSKs from a new resumption master secret,
7214
             * so their nonces count from 0 again (RFC 8446 Section 4.6.1). */
7215
            ssl->session->ticketNonce.len = 0;
7216
7217
            /* Derive the early secret using the PSK. */
7218
            ret = DeriveEarlySecret(ssl);
7219
            if (ret != 0)
7220
                goto cleanup;
7221
7222
            /* Hash data up to binders for deriving binders in PSK extension.
7223
             * A pended binder derive below re-enters DoTls13ClientHello at
7224
             * TLS_ASYNC_BEGIN, so the hash is guarded to run only once. */
7225
        #ifdef WOLFSSL_ASYNC_CRYPT
7226
            if (!ssl->options.chHashInput)
7227
        #endif
7228
            {
7229
                ret = HashInput(ssl, input, (int)inputSz);
7230
                if (ret < 0)
7231
                    goto cleanup;
7232
            }
7233
        #ifdef WOLFSSL_ASYNC_CRYPT
7234
            ssl->options.chHashInput = 1;
7235
        #endif
7236
7237
            /* Derive the binder key to use with HMAC. */
7238
            ret = DeriveBinderKeyResume(ssl, binderKey);
7239
            if (ret != 0)
7240
                goto cleanup;
7241
        }
7242
        else
7243
    #endif /* HAVE_SESSION_TICKET */
7244
    #ifndef NO_PSK
7245
        if (FindPsk(ssl, current, suite, &ret)) {
7246
            if (ret != 0)
7247
                goto cleanup;
7248
7249
        #ifdef WOLFSSL_ASYNC_CRYPT
7250
            if (!ssl->options.chHashInput)
7251
        #endif
7252
            {
7253
                ret = HashInput(ssl, input, (int)inputSz);
7254
                if (ret < 0)
7255
                    goto cleanup;
7256
            }
7257
        #ifdef WOLFSSL_ASYNC_CRYPT
7258
            ssl->options.chHashInput = 1;
7259
        #endif
7260
7261
            /* Derive the binder key to use with HMAC. */
7262
            ret = DeriveBinderKey(ssl, binderKey);
7263
            if (ret != 0)
7264
                goto cleanup;
7265
        }
7266
        else
7267
    #endif
7268
        {
7269
            continue;
7270
        }
7271
7272
        ssl->options.sendVerify = 0;
7273
7274
        /* Derive the Finished message secret. */
7275
        ret = DeriveFinishedSecret(ssl, binderKey,
7276
                                   ssl->keys.client_write_MAC_secret,
7277
                                   0 /* neither end */);
7278
        if (ret != 0)
7279
            goto cleanup;
7280
7281
        /* Derive the binder and compare with the one in the extension. */
7282
        ret = BuildTls13HandshakeHmac(ssl,
7283
                         ssl->keys.client_write_MAC_secret, binder, &binderLen);
7284
        if (ret != 0)
7285
            goto cleanup;
7286
        if (binderLen != current->binderLen ||
7287
                             ConstantCompare(binder, current->binder,
7288
                                binderLen) != 0) {
7289
            WOLFSSL_ERROR_VERBOSE(BAD_BINDER);
7290
            ret = BAD_BINDER;
7291
            goto cleanup;
7292
        }
7293
7294
        /* This PSK works, no need to try any more. */
7295
        current->chosen = 1;
7296
        ext->resp = 1;
7297
        break;
7298
    }
7299
7300
    if (current == NULL) {
7301
        ret = 0;
7302
        goto cleanup;
7303
    }
7304
7305
    *first = (current == ext->data);
7306
    *usingPSK = 1;
7307
7308
cleanup:
7309
    ForceZero(binderKey, sizeof(binderKey));
7310
    ForceZero(binder, sizeof(binder));
7311
#ifdef WOLFSSL_CHECK_MEM_ZERO
7312
    wc_MemZero_Check(binderKey, sizeof(binderKey));
7313
#endif
7314
    WOLFSSL_LEAVE("DoPreSharedKeys", ret);
7315
7316
    return ret;
7317
}
7318
7319
/* Check whether a PSK may be used given the key exchange modes the client
7320
 * advertised and the modes this server is configured to allow.
7321
 *
7322
 * RFC 9846 Section 4.3.9 forbids selecting a mode the client did not list.
7323
 * Section 4.3.11 says a server that finds no acceptable PSK should perform a
7324
 * non-PSK handshake instead of aborting. Deciding before a PSK is selected
7325
 * leaves nothing to unwind: no ticket is decrypted, no binder is verified, no
7326
 * secret is derived and no early data is accepted.
7327
 *
7328
 * The configured policy is read, not ssl->options.noPskDheKe, which also
7329
 * carries negotiated state and is cleared by every certificate handshake.
7330
 *
7331
 * ssl         SSL/TLS object.
7332
 * clSuites    Client's cipher suite list.
7333
 * returns 1 when PSK selection may proceed and 0 when the PSK must be ignored.
7334
 */
7335
static int PskModesUsable(const WOLFSSL* ssl, const Suites* clSuites)
7336
{
7337
#ifdef HAVE_SUPPORTED_CURVES
7338
    TLSX*  ext;
7339
    word32 modes;
7340
7341
    /* Offering pre_shared_key without psk_key_exchange_modes is a MUST-level
7342
     * abort (Section 4.3.9). Leave it to CheckPreSharedKeys. */
7343
    ext = TLSX_Find(ssl->extensions, TLSX_PSK_KEY_EXCHANGE_MODES);
7344
    if (ext == NULL)
7345
        return 1;
7346
    modes = ext->val;
7347
7348
#ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
7349
    /* RFC 9973 requires psk_dhe_ke and overrides the no-(EC)DHE policy, so a
7350
     * mismatch must abort rather than fall back. */
7351
    if (TLSX_Find(ssl->extensions, TLSX_CERT_WITH_EXTERN_PSK) != NULL)
7352
        return 1;
7353
#endif
7354
7355
    /* Only decline when a certificate handshake can actually run instead.
7356
     * These are the same two things DoTls13ClientHello() requires of a
7357
     * ClientHello that negotiates no PSK. */
7358
    if (TLSX_Find(ssl->extensions, TLSX_KEY_SHARE) == NULL)
7359
        return 1;
7360
    if (clSuites == NULL || clSuites->hashSigAlgoSz == 0)
7361
        return 1;
7362
7363
    if ((modes & (1 << PSK_DHE_KE)) != 0 && !ssl->options.noPskDheKePolicy)
7364
        return 1;
7365
    if (ssl->options.onlyPskDheKe)
7366
        return 0;
7367
    return (modes & (1 << PSK_KE)) != 0;
7368
#else
7369
    /* Without (EC)DHE there is no certificate handshake to fall back to. */
7370
    (void)ssl;
7371
    (void)clSuites;
7372
    return 1;
7373
#endif
7374
}
7375
7376
/* Handle any Pre-Shared Key (PSK) extension.
7377
 * Must do this in ClientHello as it requires a hash of the truncated message.
7378
 * Don't know size of binders until Pre-Shared Key extension has been parsed.
7379
 *
7380
 * ssl         SSL/TLS object.
7381
 * input       ClientHello message.
7382
 * helloSz     Size of the ClientHello message (including binders if present).
7383
 * clSuites    Client's cipher suite list.
7384
 * usingPSK    Indicates handshake is using Pre-Shared Keys.
7385
 */
7386
static int CheckPreSharedKeys(WOLFSSL* ssl, const byte* input, word32 helloSz,
7387
                              Suites* clSuites, int* usingPSK)
7388
{
7389
    int    ret;
7390
    TLSX*  ext;
7391
    word16 bindersLen;
7392
    int    first = 0;
7393
    int    usePsk;
7394
#ifndef WOLFSSL_PSK_ONE_ID
7395
    int    i;
7396
    const Suites* suites;
7397
#else
7398
    byte   suite[2];
7399
#endif
7400
7401
    WOLFSSL_ENTER("CheckPreSharedKeys");
7402
7403
    ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
7404
    if (ext == NULL) {
7405
#ifdef WOLFSSL_EARLY_DATA
7406
        ssl->earlyData = no_early_data;
7407
#endif
7408
        if (usingPSK)
7409
            *usingPSK = 0;
7410
7411
        /* No PSK extension at all: if a mandatory external PSK is configured,
7412
         * refuse the connection rather than continue without one. havePSK is
7413
         * only set by an external-PSK callback, so a peer relying solely on
7414
         * session-ticket resumption is unaffected. */
7415
        if (ssl->options.havePSK && ssl->options.failNoPSK) {
7416
            WOLFSSL_ERROR_VERBOSE(PSK_MISSING_ERROR);
7417
            return PSK_MISSING_ERROR;
7418
        }
7419
7420
        /* Hash data up to binders for deriving binders in PSK extension. */
7421
        ret = HashInput(ssl, input,  (int)helloSz);
7422
        return ret;
7423
    }
7424
7425
    /* Wire-order check that PSK was the last extension in ClientHello is
7426
     * performed in DoTls13ClientHello immediately after TLSX_Parse, since
7427
     * post-parse code (e.g. ALPN_Select via TLSX_SetALPN) may legitimately
7428
     * prepend new entries to ssl->extensions before this point and would
7429
     * otherwise trip a head-of-list check here. */
7430
7431
    /* Assume we are going to resume with a pre-shared key. */
7432
    ssl->options.resuming = 1;
7433
7434
    /* Find the pre-shared key extension and calculate hash of truncated
7435
     * ClientHello for binders.
7436
     */
7437
    ret = TLSX_PreSharedKey_GetSizeBinders((PreSharedKey*)ext->data,
7438
                                                     client_hello, &bindersLen);
7439
    if (ret < 0)
7440
        return ret;
7441
    if (bindersLen > helloSz)
7442
        return BUFFER_ERROR;
7443
7444
    /* Refine list for PSK processing. */
7445
    sslRefineSuites(ssl, clSuites);
7446
7447
    usePsk = PskModesUsable(ssl, clSuites);
7448
    if (!usePsk) {
7449
        WOLFSSL_MSG("No usable psk_key_exchange_modes, ignoring PSK");
7450
    }
7451
7452
#ifndef WOLFSSL_PSK_ONE_ID
7453
    if (usingPSK == NULL)
7454
        return BAD_FUNC_ARG;
7455
7456
    /* set after refineSuites, to avoid taking a stale ptr to ctx->Suites */
7457
    suites = WOLFSSL_SUITES(ssl);
7458
    /* Server list has only common suites from refining in server or client
7459
     * order. */
7460
    for (i = 0; usePsk && !(*usingPSK) && i < suites->suiteSz; i += 2) {
7461
        ret = DoPreSharedKeys(ssl, input, helloSz - bindersLen,
7462
                suites->suites + i, usingPSK, &first);
7463
        if (ret != 0) {
7464
#ifdef HAVE_SESSION_TICKET
7465
#ifdef WOLFSSL_ASYNC_CRYPT
7466
            if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
7467
#endif
7468
                CleanupClientTickets((PreSharedKey*)ext->data);
7469
#endif
7470
            WOLFSSL_MSG_EX("DoPreSharedKeys: %d", ret);
7471
            return ret;
7472
        }
7473
    }
7474
#ifdef HAVE_SESSION_TICKET
7475
    CleanupClientTickets((PreSharedKey*)ext->data);
7476
#endif
7477
#else
7478
    if (usePsk) {
7479
        ret = DoPreSharedKeys(ssl, input, helloSz - bindersLen, suite, usingPSK,
7480
            &first);
7481
        if (ret != 0) {
7482
            WOLFSSL_MSG_EX("DoPreSharedKeys: %d", ret);
7483
            return ret;
7484
        }
7485
    }
7486
#endif
7487
7488
    if (!*usingPSK) {
7489
        /* No suitable PSK was negotiated. When a mandatory external PSK is
7490
         * configured, fail with a dedicated error instead of falling back to a
7491
         * certificate handshake. This must run before the no-certificate
7492
         * BAD_BINDER check below so a PSK-only server (no cert) still reports
7493
         * PSK_MISSING_ERROR. havePSK is only set by an external-PSK callback, so
7494
         * a peer relying solely on session-ticket resumption is unaffected. */
7495
        if (ssl->options.havePSK && ssl->options.failNoPSK) {
7496
            WOLFSSL_ERROR_VERBOSE(PSK_MISSING_ERROR);
7497
            return PSK_MISSING_ERROR;
7498
        }
7499
    #ifndef NO_CERTS
7500
        if (ssl->buffers.certificate == NULL
7501
        #ifdef WOLFSSL_CERT_SETUP_CB
7502
                && ssl->ctx->certSetupCb == NULL
7503
        #endif
7504
                )
7505
    #endif
7506
        {
7507
            /* Reused for identity protection: an unknown identity must look
7508
             * like a bad binder, so keep the error code shared. */
7509
            WOLFSSL_ERROR_VERBOSE(BAD_BINDER);
7510
            return BAD_BINDER;
7511
        }
7512
    }
7513
7514
    if (*usingPSK) {
7515
        /* While verifying the selected PSK, we updated the
7516
         * handshake hash up to the binder bytes in the PSK extensions.
7517
         * Continuing, we need the rest of the ClientHello hashed as well.
7518
         */
7519
        ret = HashRaw(ssl, input + helloSz - bindersLen, bindersLen);
7520
    }
7521
    else {
7522
        /* No suitable PSK found, Hash the complete ClientHello,
7523
         * as caller expect it after we return */
7524
        ret = HashInput(ssl, input,  (int)helloSz);
7525
    }
7526
    if (ret != 0)
7527
        return ret;
7528
7529
    if (*usingPSK != 0) {
7530
        word32 modes;
7531
#ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
7532
        int usingCertWithExternPsk = 0;
7533
        TLSX* certExt = NULL;
7534
        TLSX* pskExt = NULL;
7535
        PreSharedKey* chosenPsk = NULL;
7536
#endif
7537
    #ifdef WOLFSSL_EARLY_DATA
7538
        TLSX*  extEarlyData;
7539
    #ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
7540
        int hasCertWithExternPsk = (TLSX_Find(ssl->extensions,
7541
                                    TLSX_CERT_WITH_EXTERN_PSK) != NULL);
7542
    #endif
7543
7544
        extEarlyData = TLSX_Find(ssl->extensions, TLSX_EARLY_DATA);
7545
        if (extEarlyData != NULL) {
7546
            /* Check if accepting early data and first PSK.
7547
             * RFC 9973: early_data is not compatible with
7548
             * cert_with_extern_psk, so skip key derivation in that case. */
7549
            if (ssl->earlyData != no_early_data && first
7550
                && ssl->options.maxEarlyDataSz > 0
7551
    #ifdef HAVE_SESSION_TICKET
7552
                /* RFC 8446 section 8.2: freshly started servers should
7553
                 * reject 0-RTT. Tickets minted before this ctx was created
7554
                 * belong to a previous instance. */
7555
                && !ssl->options.ticketPredatesCtx
7556
    #endif
7557
    #ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
7558
                && !hasCertWithExternPsk
7559
    #endif
7560
    #if defined(HAVE_SESSION_TICKET) && !defined(NO_SESSION_CACHE)
7561
                /* RFC 8446 section 8: accept 0-RTT once per ticket. Consuming
7562
                 * the cache entry is what bounds the replay, so only accept
7563
                 * when the entry was really evicted. Best effort. */
7564
                && ssl->options.ticketCacheHit
7565
                && wolfSSL_SSL_CTX_remove_session(ssl->ctx, ssl->session) == 1
7566
    #endif
7567
            ) {
7568
                extEarlyData->resp = 1;
7569
    #if defined(HAVE_SESSION_TICKET) && !defined(NO_SESSION_CACHE)
7570
                WOLFSSL_MSG("Accepting early data for a cached ticket session");
7571
    #endif
7572
7573
                /* Derive early data decryption key. */
7574
                ret = DeriveTls13Keys(ssl, early_data_key, DECRYPT_SIDE_ONLY,
7575
                                                                             1);
7576
                if (ret != 0)
7577
                    return ret;
7578
                if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0)
7579
                    return ret;
7580
7581
                ssl->keys.encryptionOn = 1;
7582
                ssl->earlyData = process_early_data;
7583
            }
7584
            else
7585
                extEarlyData->resp = 0;
7586
        }
7587
    #endif
7588
7589
        /* Get the PSK key exchange modes the client wants to negotiate. */
7590
        ext = TLSX_Find(ssl->extensions, TLSX_PSK_KEY_EXCHANGE_MODES);
7591
        if (ext == NULL) {
7592
            WOLFSSL_ERROR_VERBOSE(MISSING_HANDSHAKE_DATA);
7593
            return MISSING_HANDSHAKE_DATA;
7594
        }
7595
        modes = ext->val;
7596
7597
    #ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
7598
        certExt = TLSX_Find(ssl->extensions, TLSX_CERT_WITH_EXTERN_PSK);
7599
        if (certExt != NULL) {
7600
            pskExt = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
7601
            if (pskExt != NULL)
7602
                chosenPsk = (PreSharedKey*)pskExt->data;
7603
            while (chosenPsk != NULL && !chosenPsk->chosen)
7604
                chosenPsk = chosenPsk->next;
7605
            if (chosenPsk == NULL || chosenPsk->resumption) {
7606
                WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
7607
                return PSK_KEY_ERROR;
7608
            }
7609
            if ((modes & (1 << PSK_DHE_KE)) == 0) {
7610
                WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
7611
                return PSK_KEY_ERROR;
7612
            }
7613
            usingCertWithExternPsk = 1;
7614
            ssl->options.certWithExternPsk = 1;
7615
            if (clSuites->hashSigAlgoSz == 0) {
7616
                WOLFSSL_ERROR_VERBOSE(MISSING_HANDSHAKE_DATA);
7617
                return MISSING_HANDSHAKE_DATA;
7618
            }
7619
            ret = PickHashSigAlgo(ssl, clSuites->hashSigAlgo,
7620
                                  clSuites->hashSigAlgoSz, 1);
7621
            if (ret != 0)
7622
                return ret;
7623
            ssl->options.sendVerify = SEND_CERT;
7624
            certExt->resp = 1;
7625
        #ifdef WOLFSSL_EARLY_DATA
7626
            /* RFC 9973: early_data is not compatible with
7627
             * cert_with_extern_psk.  TLSX_Parse already rejects the
7628
             * combination in the ClientHello, but clear the response flag
7629
             * here as a defense-in-depth measure. */
7630
            if (extEarlyData != NULL) {
7631
                WOLFSSL_MSG("Rejecting early data: "
7632
                            "cert_with_extern_psk is not 0-RTT compatible");
7633
                extEarlyData->resp = 0;
7634
                ssl->earlyData = no_early_data;
7635
            }
7636
        #endif
7637
        }
7638
        else {
7639
            ssl->options.certWithExternPsk = 0;
7640
        }
7641
    #endif
7642
7643
#ifndef HAVE_SUPPORTED_CURVES
7644
    #ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
7645
        if (usingCertWithExternPsk) {
7646
            WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
7647
            return PSK_KEY_ERROR;
7648
        }
7649
    #endif
7650
#endif
7651
    #ifdef HAVE_SUPPORTED_CURVES
7652
        ext = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
7653
        /* Use (EC)DHE for forward-security if possible. */
7654
        if (((modes & (1 << PSK_DHE_KE)) != 0 &&
7655
             !ssl->options.noPskDheKePolicy && ext != NULL)
7656
#ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
7657
             || usingCertWithExternPsk
7658
#endif
7659
        ) {
7660
            if (ext == NULL) {
7661
                WOLFSSL_ERROR_VERBOSE(EXT_MISSING);
7662
                return EXT_MISSING;
7663
            }
7664
            /* Resumption path uses previous session group. */
7665
#ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
7666
            if (!usingCertWithExternPsk)
7667
#endif
7668
                ssl->namedGroup = ssl->session->namedGroup;
7669
            *usingPSK = 2; /* generate new ephemeral key */
7670
        }
7671
        else if (ssl->options.onlyPskDheKe ||
7672
                 (ssl->options.failNoPSK && !ssl->options.resuming)) {
7673
            /* A mandatory external PSK (failNoPSK) must be combined with
7674
             * (EC)DHE for forward secrecy, so reject a pure psk_ke
7675
             * negotiation. Session-ticket resumption is exempt.
7676
             * onlyPskDheKe only reaches here when PskModesUsable() could not
7677
             * decline, i.e. there is no certificate handshake to fall back
7678
             * to. */
7679
            WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
7680
            return PSK_KEY_ERROR;
7681
        }
7682
        else
7683
    #endif
7684
        {
7685
            if ((modes & (1 << PSK_KE)) == 0) {
7686
                WOLFSSL_MSG("psk_ke mode does not allow key share");
7687
                WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
7688
                return PSK_KEY_ERROR;
7689
            }
7690
            ssl->options.noPskDheKe = 1;
7691
            ssl->arrays->preMasterSz = 0;
7692
7693
            *usingPSK = 1;
7694
        }
7695
    }
7696
    else {
7697
#ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
7698
        /* If no PSK is found, we remove the extension to make sure it
7699
         * is not sent back to the client */
7700
        TLSX_Remove(&ssl->extensions, TLSX_CERT_WITH_EXTERN_PSK, ssl->heap);
7701
        ssl->options.certWithExternPsk = 0;
7702
#endif
7703
        /* No PSK negotiated; the check above already aborted when there is no
7704
         * certificate. Fall through so the trace is emitted here too. */
7705
    }
7706
7707
    WOLFSSL_LEAVE("CheckPreSharedKeys", ret);
7708
7709
    return 0;
7710
}
7711
#endif /* HAVE_SESSION_TICKET || !NO_PSK */
7712
7713
#if defined(WOLFSSL_SEND_HRR_COOKIE)
7714
/* Compute the cookie integrity HMAC over the cookie data (and, for DTLS, the
7715
 * peer address) using the given secret and compare it in constant time against
7716
 * the MAC trailing the cookie.
7717
 *
7718
 * ssl        SSL/TLS object.
7719
 * cookie     The cookie data - hash and MAC.
7720
 * dataSz     Length of the cookie data preceding the trailing MAC.
7721
 * secret     Secret to key the HMAC with.
7722
 * secretSz   Length of the secret in bytes.
7723
 * cookieType Digest type to use for the HMAC.
7724
 * macSz      Length of the MAC in bytes.
7725
 * returns 0 on match, HRR_COOKIE_ERROR on mismatch, otherwise a negative error.
7726
 */
7727
static int TlsCheckCookieMac(const WOLFSSL* ssl, const byte* cookie,
7728
    word16 dataSz, const byte* secret, word32 secretSz, byte cookieType,
7729
    byte macSz)
7730
{
7731
    int  ret;
7732
    byte mac[WC_MAX_DIGEST_SIZE] = {0};
7733
    WC_DECLARE_VAR(cookieHmac, Hmac, 1, ssl->heap);
7734
7735
    WC_ALLOC_VAR_EX(cookieHmac, Hmac, 1, ssl->heap, DYNAMIC_TYPE_HMAC,
7736
                    return MEMORY_E);
7737
7738
    ret = wc_HmacInit(cookieHmac, ssl->heap, ssl->devId);
7739
    if (ret == 0)
7740
        ret = wc_HmacSetKey(cookieHmac, cookieType, secret, secretSz);
7741
    if (ret == 0)
7742
        ret = wc_HmacUpdate(cookieHmac, cookie, dataSz);
7743
#ifdef WOLFSSL_DTLS13
7744
    /* Tie cookie to peer address */
7745
    if (ret == 0) {
7746
        /* peerLock not necessary. Still in handshake phase. */
7747
        if (ssl->options.dtls && ssl->buffers.dtlsCtx.peer.sz > 0) {
7748
            ret = wc_HmacUpdate(cookieHmac,
7749
                (byte*)ssl->buffers.dtlsCtx.peer.sa,
7750
                ssl->buffers.dtlsCtx.peer.sz);
7751
        }
7752
    }
7753
#endif
7754
    if (ret == 0)
7755
        ret = wc_HmacFinal(cookieHmac, mac);
7756
7757
    wc_HmacFree(cookieHmac);
7758
    WC_FREE_VAR_EX(cookieHmac, ssl->heap, DYNAMIC_TYPE_HMAC);
7759
    if (ret != 0)
7760
        return ret;
7761
7762
    if (ConstantCompare(cookie + dataSz, mac, macSz) != 0)
7763
        return HRR_COOKIE_ERROR;
7764
7765
    return 0;
7766
}
7767
7768
/* Check that the Cookie data's integrity.
7769
 *
7770
 * ssl       SSL/TLS object.
7771
 * cookie    The cookie data - hash and MAC.
7772
 * cookieSz  The length of the cookie data in bytes.
7773
 * returns Length of the hash on success, otherwise failure.
7774
 */
7775
int TlsCheckCookie(const WOLFSSL* ssl, const byte* cookie, word16 cookieSz)
7776
{
7777
    int  ret;
7778
    byte cookieType = 0;
7779
    byte macSz = 0;
7780
7781
#ifndef NO_SHA256
7782
    cookieType = WC_SHA256;
7783
    macSz = WC_SHA256_DIGEST_SIZE;
7784
#elif defined(WOLFSSL_SHA384)
7785
    cookieType = WC_SHA384;
7786
    macSz = WC_SHA384_DIGEST_SIZE;
7787
#elif defined(WOLFSSL_TLS13_SHA512)
7788
    cookieType = WC_SHA512;
7789
    macSz = WC_SHA512_DIGEST_SIZE;
7790
#elif defined(WOLFSSL_SM3)
7791
    cookieType = WC_SM3;
7792
    macSz = WC_SM3_DIGEST_SIZE;
7793
#else
7794
    #error "No digest to available to use with HMAC for cookies."
7795
#endif /* NO_SHA */
7796
7797
    if ((ssl->buffers.tls13CookieSecret.buffer == NULL ||
7798
            ssl->buffers.tls13CookieSecret.length == 0)
7799
#ifdef WOLFSSL_DTLS13
7800
        && (ssl->buffers.tls13CookieSecretSecondary.buffer == NULL ||
7801
            ssl->buffers.tls13CookieSecretSecondary.length == 0)
7802
#endif
7803
        ) {
7804
        WOLFSSL_MSG("Missing DTLS 1.3 cookie secret");
7805
        return COOKIE_ERROR;
7806
    }
7807
7808
    if (cookieSz < ssl->specs.hash_size + macSz)
7809
        return HRR_COOKIE_ERROR;
7810
    cookieSz -= macSz;
7811
7812
    /* Verify against the primary secret first.  If that fails and a secondary
7813
     * (verify-only) secret is configured, try that too.  This lets a stateless
7814
     * DTLS 1.3 server keep accepting cookies issued under the secret it held
7815
     * before an application-driven secret rotation.  The secondary secret is
7816
     * DTLS 1.3 only, so its verify path is compiled in only for WOLFSSL_DTLS13. */
7817
    ret = WC_NO_ERR_TRACE(HRR_COOKIE_ERROR);
7818
    if (ssl->buffers.tls13CookieSecret.buffer != NULL &&
7819
            ssl->buffers.tls13CookieSecret.length > 0) {
7820
        ret = TlsCheckCookieMac(ssl, cookie, cookieSz,
7821
            ssl->buffers.tls13CookieSecret.buffer,
7822
            ssl->buffers.tls13CookieSecret.length, cookieType, macSz);
7823
        if (ret != 0 && ret != WC_NO_ERR_TRACE(HRR_COOKIE_ERROR))
7824
            return ret;
7825
    }
7826
#ifdef WOLFSSL_DTLS13
7827
    if (ret == WC_NO_ERR_TRACE(HRR_COOKIE_ERROR) &&
7828
            ssl->buffers.tls13CookieSecretSecondary.buffer != NULL &&
7829
            ssl->buffers.tls13CookieSecretSecondary.length > 0) {
7830
        ret = TlsCheckCookieMac(ssl, cookie, cookieSz,
7831
            ssl->buffers.tls13CookieSecretSecondary.buffer,
7832
            ssl->buffers.tls13CookieSecretSecondary.length, cookieType, macSz);
7833
        if (ret != 0 && ret != WC_NO_ERR_TRACE(HRR_COOKIE_ERROR))
7834
            return ret;
7835
    }
7836
#endif
7837
7838
    if (ret != 0) {
7839
        WOLFSSL_ERROR_VERBOSE(HRR_COOKIE_ERROR);
7840
        return HRR_COOKIE_ERROR;
7841
    }
7842
7843
    return cookieSz;
7844
}
7845
7846
/* Length of the KeyShare Extension */
7847
#define HRR_KEY_SHARE_SZ   (OPAQUE16_LEN + OPAQUE16_LEN + OPAQUE16_LEN)
7848
/* Length of the Supported Versions Extension */
7849
#define HRR_VERSIONS_SZ    (OPAQUE16_LEN + OPAQUE16_LEN + OPAQUE16_LEN)
7850
/* Length of the Cookie Extension excluding cookie data */
7851
#define HRR_COOKIE_HDR_SZ  (OPAQUE16_LEN + OPAQUE16_LEN + OPAQUE16_LEN)
7852
/* PV | Random | Session Id | CipherSuite | Compression | Ext Len */
7853
#define HRR_BODY_SZ        (VERSION_SZ + RAN_LEN + ENUM_LEN + ID_LEN + \
7854
                            SUITE_LEN + COMP_LEN + OPAQUE16_LEN)
7855
/* HH | PV | CipherSuite | Ext Len | Key Share | Supported Version | Cookie */
7856
#define MAX_HRR_SZ   (HRR_MAX_HS_HEADER_SZ   + \
7857
                        HRR_BODY_SZ         + \
7858
                          HRR_KEY_SHARE_SZ  + \
7859
                          HRR_VERSIONS_SZ   + \
7860
                          HRR_COOKIE_HDR_SZ)
7861
7862
7863
/* Restart the handshake hash from the cookie value.
7864
 *
7865
 * ssl     SSL/TLS object.
7866
 * cookie  Cookie data from client.
7867
 * returns 0 on success, otherwise failure.
7868
 */
7869
static int RestartHandshakeHashWithCookie(WOLFSSL* ssl, Cookie* cookie)
7870
{
7871
    byte   header[HANDSHAKE_HEADER_SZ] = {0};
7872
    byte   hrr[MAX_HRR_SZ] = {0};
7873
    int    hrrIdx;
7874
    word32 idx;
7875
    byte   hashSz;
7876
    byte*  cookieData;
7877
    word16 cookieDataSz;
7878
    word16 length;
7879
    int    keyShareExt = 0;
7880
    int    ret;
7881
    byte   sessIdSz;
7882
7883
    ret = TlsCheckCookie(ssl, cookie->data, cookie->len);
7884
    if (ret < 0)
7885
        return ret;
7886
    cookieDataSz = (word16)ret;
7887
    hashSz = cookie->data[0];
7888
    cookieData = cookie->data;
7889
    idx = OPAQUE8_LEN;
7890
7891
    /* Restart handshake hash with synthetic message hash. */
7892
    AddTls13HandShakeHeader(header, hashSz, 0, 0, message_hash, ssl);
7893
7894
    if ((ret = InitHandshakeHashes(ssl)) != 0)
7895
        return ret;
7896
    if ((ret = HashRaw(ssl, header, sizeof(header))) != 0)
7897
        return ret;
7898
#ifdef WOLFSSL_DEBUG_TLS
7899
    WOLFSSL_MSG("Restart Hash from Cookie");
7900
    WOLFSSL_BUFFER(cookieData + idx, hashSz);
7901
#endif
7902
    if ((ret = HashRaw(ssl, cookieData + idx, hashSz)) != 0)
7903
        return ret;
7904
7905
    /* Reconstruct the HelloRetryMessage for handshake hash. */
7906
    sessIdSz = ssl->session->sessionIDSz;
7907
#if defined(WOLFSSL_DTLS13) && !defined(WOLFSSL_DTLS13_ECHO_LEGACY_SESSION_ID)
7908
    /* RFC 9147 Section 5: a DTLS 1.3 server does not echo the session ID, so
7909
     * the reconstructed transcript must not carry one either. */
7910
    if (ssl->options.dtls)
7911
        sessIdSz = 0;
7912
#endif
7913
    length = HRR_BODY_SZ - ID_LEN + sessIdSz +
7914
             HRR_COOKIE_HDR_SZ + cookie->len;
7915
    length += HRR_VERSIONS_SZ;
7916
    /* HashSz (1 byte) + Hash (HashSz bytes) + CipherSuite (2 bytes) */
7917
    if (cookieDataSz > OPAQUE8_LEN + hashSz + OPAQUE16_LEN) {
7918
        keyShareExt = 1;
7919
        length += HRR_KEY_SHARE_SZ;
7920
    }
7921
7922
    AddTls13HandShakeHeader(hrr, length, 0, 0, server_hello, ssl);
7923
7924
    idx += hashSz;
7925
    hrrIdx = HANDSHAKE_HEADER_SZ;
7926
7927
#ifdef WOLFSSL_DTLS13
7928
    if (ssl->options.dtls)
7929
        hrrIdx += DTLS_HANDSHAKE_EXTRA;
7930
#endif /* WOLFSSL_DTLS13 */
7931
7932
    /* The negotiated protocol version. */
7933
    hrr[hrrIdx++] = ssl->version.major;
7934
    hrr[hrrIdx++] = ssl->options.dtls ? DTLSv1_2_MINOR : TLSv1_2_MINOR;
7935
7936
    /* HelloRetryRequest message has fixed value for random. */
7937
    XMEMCPY(hrr + hrrIdx, helloRetryRequestRandom, RAN_LEN);
7938
    hrrIdx += RAN_LEN;
7939
7940
    hrr[hrrIdx++] = sessIdSz;
7941
    if (sessIdSz > 0) {
7942
        XMEMCPY(hrr + hrrIdx, ssl->session->sessionID, sessIdSz);
7943
        hrrIdx += sessIdSz;
7944
    }
7945
7946
    /* Restore the cipher suite from the cookie. */
7947
    ssl->options.hrrCipherSuite0 = cookieData[idx];
7948
    hrr[hrrIdx++] = cookieData[idx++];
7949
    ssl->options.hrrCipherSuite  = cookieData[idx];
7950
    hrr[hrrIdx++] = cookieData[idx++];
7951
7952
    /* Compression not supported in TLS v1.3. */
7953
    hrr[hrrIdx++] = 0;
7954
7955
    /* Extensions' length */
7956
    length -= HRR_BODY_SZ - ID_LEN + sessIdSz;
7957
    c16toa(length, hrr + hrrIdx);
7958
    hrrIdx += 2;
7959
7960
    /* Optional KeyShare Extension */
7961
    if (keyShareExt) {
7962
        c16toa(TLSX_KEY_SHARE, hrr + hrrIdx);
7963
        hrrIdx += 2;
7964
        c16toa(OPAQUE16_LEN, hrr + hrrIdx);
7965
        hrrIdx += 2;
7966
        /* Restore the HRR key share group from the cookie. */
7967
        ato16(cookieData + idx, &ssl->hrr_keyshare_group);
7968
        hrr[hrrIdx++] = cookieData[idx++];
7969
        hrr[hrrIdx++] = cookieData[idx++];
7970
    }
7971
    c16toa(TLSX_SUPPORTED_VERSIONS, hrr + hrrIdx);
7972
    hrrIdx += 2;
7973
    c16toa(OPAQUE16_LEN, hrr + hrrIdx);
7974
    hrrIdx += 2;
7975
    #ifdef WOLFSSL_TLS13_DRAFT
7976
        hrr[hrrIdx++] = TLS_DRAFT_MAJOR;
7977
        hrr[hrrIdx++] = TLS_DRAFT_MINOR;
7978
    #else
7979
        hrr[hrrIdx++] = ssl->version.major;
7980
        hrr[hrrIdx++] = ssl->version.minor;
7981
    #endif
7982
7983
    /* Mandatory Cookie Extension */
7984
    c16toa(TLSX_COOKIE, hrr + hrrIdx);
7985
    hrrIdx += 2;
7986
    c16toa(cookie->len + OPAQUE16_LEN, hrr + hrrIdx);
7987
    hrrIdx += 2;
7988
    c16toa(cookie->len, hrr + hrrIdx);
7989
    hrrIdx += 2;
7990
7991
#ifdef WOLFSSL_DEBUG_TLS
7992
    WOLFSSL_MSG("Reconstructed HelloRetryRequest");
7993
    WOLFSSL_BUFFER(hrr, hrrIdx);
7994
    WOLFSSL_MSG("Cookie");
7995
    WOLFSSL_BUFFER(cookieData, cookie->len);
7996
#endif
7997
7998
#ifdef WOLFSSL_DTLS13
7999
    if (ssl->options.dtls) {
8000
        ret = Dtls13HashHandshake(ssl, hrr, (word16)hrrIdx);
8001
    }
8002
    else
8003
#endif /* WOLFSSL_DTLS13 */
8004
        {
8005
            ret = HashRaw(ssl, hrr, hrrIdx);
8006
        }
8007
8008
    if (ret != 0)
8009
        return ret;
8010
8011
    return HashRaw(ssl, cookieData, cookie->len);
8012
}
8013
#endif
8014
8015
/* Do SupportedVersion extension for TLS v1.3+ otherwise it is not.
8016
 *
8017
 * ssl       The SSL/TLS object.
8018
 * input     The message buffer.
8019
 * i         The index into the message buffer of ClientHello.
8020
 * helloSz   The length of the current handshake message.
8021
 * returns 0 on success and otherwise failure.
8022
 */
8023
static int DoTls13SupportedVersions(WOLFSSL* ssl, const byte* input, word32 i,
8024
                                    word32 helloSz, int* wantDowngrade)
8025
0
{
8026
0
    int    ret;
8027
0
    byte   b;
8028
0
    word16 suiteSz;
8029
0
    word16 totalExtSz;
8030
0
    int    foundVersion = 0;
8031
8032
    /* Client random */
8033
0
    i += RAN_LEN;
8034
8035
0
    if (i > helloSz)
8036
0
        return BUFFER_ERROR;
8037
    /* Session id - not used in TLS v1.3 */
8038
0
    if (helloSz - i < OPAQUE8_LEN) {
8039
0
        return BUFFER_ERROR;
8040
0
    }
8041
0
    b = input[i++];
8042
0
    if (b > helloSz - i) {
8043
0
        return BUFFER_ERROR;
8044
0
    }
8045
0
    i += b;
8046
#ifdef WOLFSSL_DTLS13
8047
    if (ssl->options.dtls) {
8048
        /* legacy_cookie - not used in DTLS v1.3 */
8049
        if (helloSz - i < OPAQUE8_LEN) {
8050
            return BUFFER_ERROR;
8051
        }
8052
        b = input[i++];
8053
        if (b > helloSz - i) {
8054
            return BUFFER_ERROR;
8055
        }
8056
        i += b;
8057
    }
8058
#endif /* WOLFSSL_DTLS13 */
8059
    /* Cipher suites */
8060
0
    if (helloSz - i < OPAQUE16_LEN)
8061
0
        return BUFFER_ERROR;
8062
0
    ato16(input + i, &suiteSz);
8063
0
    i += OPAQUE16_LEN;
8064
0
    if ((word32)suiteSz + OPAQUE8_LEN > helloSz - i)
8065
0
        return BUFFER_ERROR;
8066
0
    i += suiteSz;
8067
    /* Compression */
8068
0
    b = input[i++];
8069
0
    if (b > helloSz - i)
8070
0
        return BUFFER_ERROR;
8071
0
    i += b;
8072
8073
    /* TLS 1.3 must have extensions */
8074
0
    if (i < helloSz) {
8075
0
        if (helloSz - i < OPAQUE16_LEN)
8076
0
            return BUFFER_ERROR;
8077
0
        ato16(&input[i], &totalExtSz);
8078
0
        i += OPAQUE16_LEN;
8079
0
        if (totalExtSz != helloSz - i)
8080
0
            return BUFFER_ERROR;
8081
8082
        /* Need to negotiate version first. */
8083
0
        if ((ret = TLSX_ParseVersion(ssl, input + i, totalExtSz, client_hello,
8084
0
                                                              &foundVersion))) {
8085
0
            return ret;
8086
0
        }
8087
0
    }
8088
0
    *wantDowngrade = !foundVersion || !IsAtLeastTLSv1_3(ssl->version);
8089
8090
0
    return 0;
8091
0
}
8092
8093
#ifdef HAVE_ECH
8094
/* Calculate and write the 8 ECH confirmation bytes.
8095
 * Output into confirmation field on HRR and into ServerRandom on ServerHello.
8096
 *
8097
 * ssl          SSL/TLS object.
8098
 * label        Ascii string describing ECH acceptance or rejection.
8099
 * labelSz      Length of label excluding NULL character.
8100
 * output       The buffer to calculate/write confirmation from/to.
8101
 * acceptOffset Where the 8 ECH confirmation bytes should be placed.
8102
 * helloSz      Size of hello message.
8103
 * msgType      Type of message being written.
8104
 * returns 0 on success and otherwise failure.
8105
 */
8106
static int EchWriteAcceptance(WOLFSSL* ssl, byte* label, word16 labelSz,
8107
    byte* output, int acceptOffset, int helloSz, byte msgType)
8108
{
8109
    int ret = 0;
8110
    int headerSz;
8111
    HS_Hashes* tmpHashes;
8112
8113
#ifdef WOLFSSL_DTLS13
8114
    headerSz = ssl->options.dtls ? DTLS13_HANDSHAKE_HEADER_SZ :
8115
                                   HANDSHAKE_HEADER_SZ;
8116
#else
8117
    headerSz = HANDSHAKE_HEADER_SZ;
8118
#endif
8119
8120
    ret = EchCalcAcceptance(ssl, label, labelSz, output, acceptOffset,
8121
            helloSz - headerSz, msgType == hello_retry_request,
8122
            output + acceptOffset);
8123
8124
    if (ret == 0) {
8125
        tmpHashes = ssl->hsHashes;
8126
        ssl->hsHashes = ssl->hsHashesEch;
8127
8128
        /* after HRR, hsHashesEch must contain:
8129
         * message_hash(ClientHelloInner1) || HRR (actual, not zeros) */
8130
        if (msgType == hello_retry_request) {
8131
            ret = HashRaw(ssl, output, helloSz);
8132
        }
8133
        /* normal TLS code will calculate transcript of ServerHello */
8134
        else {
8135
            ssl->hsHashes = tmpHashes;
8136
            FreeHandshakeHashes(ssl);
8137
            tmpHashes = ssl->hsHashesEch;
8138
            ssl->hsHashesEch = NULL;
8139
        }
8140
8141
        ssl->hsHashes = tmpHashes;
8142
    }
8143
8144
    return ret;
8145
}
8146
#endif
8147
8148
/* Handle a ClientHello handshake message.
8149
 * If the protocol version in the message is not TLS v1.3 or higher, use
8150
 * DoClientHello()
8151
 * Only a server will receive this message.
8152
 *
8153
 * ssl       The SSL/TLS object.
8154
 * input     The message buffer.
8155
 * inOutIdx  On entry, the index into the message buffer of ClientHello.
8156
 *           On exit, the index of byte after the ClientHello message and
8157
 *           padding.
8158
 * helloSz   The length of the current handshake message.
8159
 * returns 0 on success and otherwise failure.
8160
 */
8161
8162
typedef struct Dch13Args {
8163
    ProtocolVersion pv;
8164
    word32          idx;
8165
    word32          begin;
8166
    int             usingPSK;
8167
} Dch13Args;
8168
8169
static void FreeDch13Args(WOLFSSL* ssl, void* pArgs)
8170
0
{
8171
    /* openssl compat builds hang on to the client suites until WOLFSSL object
8172
     * is destroyed */
8173
0
#ifndef OPENSSL_EXTRA
8174
0
    if (ssl->clSuites) {
8175
0
        XFREE(ssl->clSuites, ssl->heap, DYNAMIC_TYPE_SUITES);
8176
0
        ssl->clSuites = NULL;
8177
0
    }
8178
0
#endif
8179
0
    (void)ssl;
8180
0
    (void)pArgs;
8181
8182
0
}
8183
8184
int DoTls13ClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
8185
                       word32 helloSz)
8186
0
{
8187
0
    int ret;
8188
#ifdef WOLFSSL_ASYNC_CRYPT
8189
    Dch13Args* args = NULL;
8190
    WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
8191
#else
8192
0
    Dch13Args  args[1];
8193
0
#endif
8194
#if defined(HAVE_ECH)
8195
    TLSX* echX = NULL;
8196
#endif
8197
8198
0
    WOLFSSL_START(WC_FUNC_CLIENT_HELLO_DO);
8199
0
    WOLFSSL_ENTER("DoTls13ClientHello");
8200
8201
#ifdef WOLFSSL_ASYNC_CRYPT
8202
    if (ssl->async == NULL) {
8203
        ssl->async = (struct WOLFSSL_ASYNC*)
8204
                XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
8205
                        DYNAMIC_TYPE_ASYNC);
8206
        if (ssl->async == NULL)
8207
            ERROR_OUT(MEMORY_E, exit_dch);
8208
        /* Zeroed so the mid-flight resume test below can never route into
8209
         * uninitialised args. */
8210
        XMEMSET(ssl->async, 0, sizeof(struct WOLFSSL_ASYNC));
8211
    }
8212
    args = (Dch13Args*)ssl->async->args;
8213
8214
    ret = Tls13HelloAsyncPop(ssl, &ssl->options.asyncState);
8215
    if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) {
8216
        /* Check for error */
8217
        if (ret < 0) {
8218
            goto exit_dch;
8219
        }
8220
    }
8221
    else if (ssl->options.asyncState > TLS_ASYNC_BEGIN &&
8222
             ssl->options.asyncState < TLS_ASYNC_END) {
8223
        /* Mid-flight replay: the event may already be retired but
8224
         * asyncState/args are intact, so resume; resetting would hash the
8225
         * message twice. Fresh ClientHellos arrive at TLS_ASYNC_BEGIN. */
8226
        ret = 0;
8227
    }
8228
    else
8229
#endif
8230
0
    {
8231
        /* Reset state */
8232
0
        ret = WC_NO_ERR_TRACE(VERSION_ERROR);
8233
0
        ssl->options.asyncState = TLS_ASYNC_BEGIN;
8234
0
        XMEMSET(args, 0, sizeof(Dch13Args));
8235
    #ifdef WOLFSSL_ASYNC_CRYPT
8236
        ssl->async->freeArgs = FreeDch13Args;
8237
    #endif
8238
0
    }
8239
8240
0
    switch (ssl->options.asyncState) {
8241
0
    case TLS_ASYNC_BEGIN:
8242
0
    {
8243
0
    byte b;
8244
0
    byte sessIdSz;
8245
0
    int wantDowngrade = 0;
8246
0
    word16 totalExtSz = 0;
8247
8248
#if defined(WOLFSSL_DTLS13) && defined(WOLFSSL_DTLS_CID)
8249
    /* Reset for each ClientHello, including retries and legacy fallbacks. */
8250
    ssl->options.haveSupportedVersions = 0;
8251
#endif
8252
#ifdef WOLFSSL_CALLBACKS
8253
    if (ssl->hsInfoOn) AddPacketName(ssl, "ClientHello");
8254
    if (ssl->toInfoOn) AddLateName("ClientHello", &ssl->timeoutInfo);
8255
#endif
8256
8257
    /* do not change state in the SSL object before the next region of code
8258
     * to be able to statelessly compute a DTLS cookie */
8259
#if defined(WOLFSSL_DTLS13) && defined(WOLFSSL_SEND_HRR_COOKIE)
8260
    /* No-cookie accepts are already stateful before the first read. */
8261
    if (IsDtlsNotSctpMode(ssl) && ssl->options.sendCookie &&
8262
            !ssl->options.dtlsStateful) {
8263
        DtlsSetSeqNumForReply(ssl);
8264
        ret = DoClientHelloStateless(ssl, input + *inOutIdx, helloSz, 0, NULL);
8265
        if (ret != 0 || !ssl->options.dtlsStateful) {
8266
            *inOutIdx += helloSz;
8267
            goto exit_dch;
8268
        }
8269
        if (ssl->chGoodCb != NULL) {
8270
            int cbret = ssl->chGoodCb(ssl, ssl->chGoodCtx);
8271
            if (cbret < 0) {
8272
                ssl->error = cbret;
8273
                WOLFSSL_MSG("ClientHello Good Cb don't continue error");
8274
                return WOLFSSL_FATAL_ERROR;
8275
            }
8276
        }
8277
    }
8278
    ssl->options.dtlsStateful = 1;
8279
#endif /* WOLFSSL_DTLS */
8280
8281
0
    args->idx = *inOutIdx;
8282
0
    args->begin = args->idx;
8283
8284
    /* protocol version, random and session id length check */
8285
0
    if (OPAQUE16_LEN + RAN_LEN + OPAQUE8_LEN > helloSz) {
8286
0
        ERROR_OUT(BUFFER_ERROR, exit_dch);
8287
0
    }
8288
8289
    /* Protocol version */
8290
0
    XMEMCPY(&args->pv, input + args->idx, OPAQUE16_LEN);
8291
0
    ssl->chVersion = args->pv;   /* store */
8292
0
    args->idx += OPAQUE16_LEN;
8293
8294
8295
    /* this check pass for DTLS Major (0xff) */
8296
0
    if (args->pv.major < SSLv3_MAJOR) {
8297
0
        WOLFSSL_MSG("Legacy version field contains unsupported value");
8298
0
        ERROR_OUT(VERSION_ERROR, exit_dch);
8299
0
    }
8300
8301
#ifdef WOLFSSL_DTLS13
8302
    if (ssl->options.dtls &&
8303
        args->pv.major == DTLS_MAJOR && args->pv.minor > DTLSv1_2_MINOR) {
8304
        wantDowngrade = 1;
8305
        ssl->version.minor = args->pv.minor;
8306
    }
8307
#endif /* WOLFSSL_DTLS13 */
8308
8309
0
    if (!ssl->options.dtls) {
8310
0
#ifndef WOLFSSL_ALLOW_BAD_TLS_LEGACY_VERSION
8311
        /* Check for TLS 1.3 version (0x0304) in legacy version field. RFC 8446
8312
         * Section 4.2.1 allows this action:
8313
         *
8314
         * "Servers MAY abort the handshake upon receiving a ClientHello with
8315
         * legacy_version 0x0304 or later."
8316
         *
8317
         * Note that if WOLFSSL_ALLOW_BAD_TLS_LEGACY_VERSION is defined then the
8318
         * semantics of RFC 5246 Appendix E will be followed. A ServerHello with
8319
         * version 1.2 will be sent. The same is true if TLS 1.3 is not enabled.
8320
         */
8321
0
        if (args->pv.major == SSLv3_MAJOR && args->pv.minor >= TLSv1_3_MINOR) {
8322
0
            WOLFSSL_MSG("Legacy version field is TLS 1.3 or later. Aborting.");
8323
0
            ERROR_OUT(VERSION_ERROR, exit_dch);
8324
0
        }
8325
0
#endif /* WOLFSSL_ALLOW_BAD_TLS_LEGACY_VERSION */
8326
8327
        /* Legacy protocol version cannot negotiate TLS 1.3 or higher. */
8328
0
        if (args->pv.major > SSLv3_MAJOR || (args->pv.major == SSLv3_MAJOR &&
8329
0
                                             args->pv.minor >= TLSv1_3_MINOR)) {
8330
0
            args->pv.major = SSLv3_MAJOR;
8331
0
            args->pv.minor = TLSv1_2_MINOR;
8332
0
            wantDowngrade = 1;
8333
0
            ssl->version.minor = args->pv.minor;
8334
0
        }
8335
        /* Legacy version must be [ SSLv3_MAJOR, TLSv1_2_MINOR ] for TLS v1.3 */
8336
0
        else if (args->pv.major == SSLv3_MAJOR &&
8337
0
                 args->pv.minor < TLSv1_2_MINOR) {
8338
0
            wantDowngrade = 1;
8339
0
            ssl->version.minor = args->pv.minor;
8340
0
        }
8341
0
    }
8342
8343
0
    if (!wantDowngrade) {
8344
0
        ret = DoTls13SupportedVersions(ssl, input + args->begin,
8345
0
            args->idx - args->begin, helloSz, &wantDowngrade);
8346
0
        if (ret < 0)
8347
0
            goto exit_dch;
8348
0
    }
8349
8350
0
    if (wantDowngrade) {
8351
0
#ifndef WOLFSSL_NO_TLS12
8352
0
        byte realMinor;
8353
0
#endif
8354
#if defined(HAVE_ECH)
8355
        if (ssl->options.echProcessingInner) {
8356
            WOLFSSL_MSG("ECH: inner client hello does not support version "
8357
                        "less than TLS v1.3");
8358
            ERROR_OUT(INVALID_PARAMETER, exit_dch);
8359
        }
8360
#endif
8361
0
#ifndef WOLFSSL_NO_TLS12
8362
0
        if (!ssl->options.downgrade) {
8363
0
            WOLFSSL_MSG("Client trying to connect with lesser version than "
8364
0
                        "TLS v1.3");
8365
0
            ERROR_OUT(VERSION_ERROR, exit_dch);
8366
0
        }
8367
8368
0
        if ((!ssl->options.dtls
8369
0
                 && args->pv.minor < ssl->options.minDowngrade) ||
8370
0
            (ssl->options.dtls && args->pv.minor > ssl->options.minDowngrade)) {
8371
0
            WOLFSSL_MSG("\tversion below minimum allowed, fatal error");
8372
0
            ERROR_OUT(VERSION_ERROR, exit_dch);
8373
0
        }
8374
8375
0
        realMinor = ssl->version.minor;
8376
0
        ssl->version.minor = args->pv.minor;
8377
0
        ret = HashInput(ssl, input + args->begin, (int)helloSz);
8378
0
        ssl->version.minor = realMinor;
8379
0
        if (ret == 0) {
8380
0
            ret = DoClientHello(ssl, input, inOutIdx, helloSz);
8381
0
        }
8382
0
        goto exit_dch;
8383
#else
8384
        WOLFSSL_MSG("Client trying to connect with lesser version than "
8385
                    "TLS v1.3");
8386
        ERROR_OUT(VERSION_ERROR, exit_dch);
8387
#endif
8388
0
    }
8389
8390
    /* From here on we are a TLS 1.3 ClientHello. */
8391
8392
    /* Client random
8393
     * ECH Accepted -> This will fill with the innerClientRandom */
8394
0
    XMEMCPY(ssl->arrays->clientRandom, input + args->idx, RAN_LEN);
8395
0
    args->idx += RAN_LEN;
8396
8397
#ifdef WOLFSSL_DEBUG_TLS
8398
    WOLFSSL_MSG("client random");
8399
    WOLFSSL_BUFFER(ssl->arrays->clientRandom, RAN_LEN);
8400
#endif
8401
8402
0
    sessIdSz = input[args->idx++];
8403
0
    if (sessIdSz > ID_LEN)
8404
0
    {
8405
0
        ERROR_OUT(INVALID_PARAMETER, exit_dch);
8406
0
    }
8407
8408
0
    if (sessIdSz + args->idx > helloSz)
8409
0
        ERROR_OUT(BUFFER_ERROR, exit_dch);
8410
8411
#if defined(WOLFSSL_DTLS13) && !defined(WOLFSSL_DTLS13_ECHO_LEGACY_SESSION_ID)
8412
    /* RFC 9147 Section 5: "DTLS servers MUST NOT echo the legacy_session_id
8413
     * value from the client." Don't store it so SendTls13ServerHello can't
8414
     * echo it. */
8415
    if (ssl->options.dtls) {
8416
        ssl->session->sessionIDSz = 0;
8417
    }
8418
    else
8419
#endif
8420
0
    {
8421
0
        ssl->session->sessionIDSz = sessIdSz;
8422
0
        if (sessIdSz > 0)
8423
0
            XMEMCPY(ssl->session->sessionID, input + args->idx, sessIdSz);
8424
0
    }
8425
0
    args->idx += sessIdSz;
8426
8427
    /* RFC 8446 Appendix D.4: server MUST only send CCS if the client's
8428
     * ClientHello contains a non-empty legacy_session_id. An ECH inner hello
8429
     * is rebuilt with the outer session id, so it decides either way. */
8430
0
    if (sessIdSz == 0) {
8431
0
        ssl->options.tls13MiddleBoxCompat = 0;
8432
0
    }
8433
#ifdef WOLFSSL_QUIC
8434
    /* RFC 9001 Section 8.4: QUIC has no compatibility mode to be had. */
8435
    if (WOLFSSL_IS_QUIC(ssl)) {
8436
        ssl->options.tls13MiddleBoxCompat = 0;
8437
    }
8438
#endif
8439
8440
#ifdef WOLFSSL_DTLS13
8441
    /* legacy_cookie */
8442
    if (ssl->options.dtls) {
8443
        word32 rel = args->idx - args->begin;
8444
        byte cookieLen;
8445
        if (rel > helloSz || helloSz - rel < OPAQUE8_LEN)
8446
            ERROR_OUT(BUFFER_ERROR, exit_dch);
8447
        /* https://www.rfc-editor.org/rfc/rfc9147.html#section-5.3 */
8448
        cookieLen = input[args->idx++];
8449
        if (cookieLen != 0) {
8450
            ERROR_OUT(INVALID_PARAMETER, exit_dch);
8451
        }
8452
    }
8453
#endif /* WOLFSSL_DTLS13 */
8454
8455
0
    XFREE(ssl->clSuites, ssl->heap, DYNAMIC_TYPE_SUITES);
8456
0
    ssl->clSuites = (Suites*)XMALLOC(sizeof(Suites), ssl->heap,
8457
0
        DYNAMIC_TYPE_SUITES);
8458
0
    if (ssl->clSuites == NULL) {
8459
0
        ERROR_OUT(MEMORY_E, exit_dch);
8460
0
    }
8461
8462
    /* Cipher suites */
8463
0
    if ((args->idx - args->begin) + OPAQUE16_LEN > helloSz)
8464
0
        ERROR_OUT(BUFFER_ERROR, exit_dch);
8465
0
    ato16(&input[args->idx], &ssl->clSuites->suiteSz);
8466
0
    args->idx += OPAQUE16_LEN;
8467
0
    if ((ssl->clSuites->suiteSz % 2) != 0) {
8468
0
        ERROR_OUT(INVALID_PARAMETER, exit_dch);
8469
0
    }
8470
    /* suites and compression length check */
8471
0
    if ((args->idx - args->begin) + ssl->clSuites->suiteSz + OPAQUE8_LEN >
8472
0
            helloSz) {
8473
0
        ERROR_OUT(BUFFER_ERROR, exit_dch);
8474
0
    }
8475
0
    if (ssl->clSuites->suiteSz > WOLFSSL_MAX_SUITE_SZ)
8476
0
        ERROR_OUT(BUFFER_ERROR, exit_dch);
8477
0
    XMEMCPY(ssl->clSuites->suites, input + args->idx, ssl->clSuites->suiteSz);
8478
0
    args->idx += ssl->clSuites->suiteSz;
8479
0
    ssl->clSuites->hashSigAlgoSz = 0;
8480
0
#if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
8481
    /* Discard any list kept from a previous ClientHello on this object; a
8482
     * second hello that drops signature_algorithms_cert must not inherit it. */
8483
0
    XFREE(ssl->certHashSigAlgo, ssl->heap, DYNAMIC_TYPE_TLSX);
8484
0
    ssl->certHashSigAlgo = NULL;
8485
0
    ssl->certHashSigAlgoSz = 0;
8486
0
#endif
8487
8488
    /* Compression */
8489
0
    b = input[args->idx++];
8490
0
    if ((args->idx - args->begin) + b > helloSz)
8491
0
        ERROR_OUT(BUFFER_ERROR, exit_dch);
8492
0
    if (b != COMP_LEN) {
8493
0
        WOLFSSL_MSG("Must be one compression type in list");
8494
0
        ERROR_OUT(INVALID_PARAMETER, exit_dch);
8495
0
    }
8496
0
    b = input[args->idx++];
8497
0
    if (b != NO_COMPRESSION) {
8498
0
        WOLFSSL_MSG("Must be no compression type in list");
8499
0
        ERROR_OUT(INVALID_PARAMETER, exit_dch);
8500
0
    }
8501
8502
    /* Extensions */
8503
0
    if ((args->idx - args->begin) == helloSz)
8504
0
        ERROR_OUT(BUFFER_ERROR, exit_dch);
8505
0
    if ((args->idx - args->begin) + OPAQUE16_LEN > helloSz)
8506
0
        ERROR_OUT(BUFFER_ERROR, exit_dch);
8507
8508
0
    ato16(&input[args->idx], &totalExtSz);
8509
0
    args->idx += OPAQUE16_LEN;
8510
0
    if ((args->idx - args->begin) + totalExtSz > helloSz)
8511
0
        ERROR_OUT(BUFFER_ERROR, exit_dch);
8512
8513
    /* Auto populate extensions supported unless user defined. */
8514
0
    if ((ret = TLSX_PopulateExtensions(ssl, 1)) != 0)
8515
0
        goto exit_dch;
8516
8517
#if defined(HAVE_ECH)
8518
    if (ssl->ctx->echConfigs != NULL && !ssl->options.disableECH) {
8519
        /* save the start of the buffer so we can use it when parsing ech */
8520
        echX = TLSX_Find(ssl->extensions, TLSX_ECH);
8521
8522
        if (echX == NULL)
8523
            ERROR_OUT(WOLFSSL_FATAL_ERROR, exit_dch);
8524
8525
        ((WOLFSSL_ECH*)echX->data)->aad = input + args->begin;
8526
        ((WOLFSSL_ECH*)echX->data)->aadLen = helloSz;
8527
    }
8528
#endif
8529
8530
    /* Parse extensions */
8531
0
    if ((ret = TLSX_Parse(ssl, input + args->idx, totalExtSz, client_hello,
8532
0
                                                            ssl->clSuites))) {
8533
0
        goto exit_dch;
8534
0
    }
8535
8536
0
#if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
8537
0
    SetPeerSha1CertOk(ssl, ssl->clSuites);
8538
0
#endif
8539
8540
#if (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)) && \
8541
    defined(HAVE_TLS_EXTENSIONS)
8542
    /* RFC 8446 Section 4.2.11: the pre_shared_key extension MUST be the
8543
     * last extension in the ClientHello. wolfSSL stores extensions in
8544
     * reverse wire order (TLSX_Push prepends), so a well-formed
8545
     * ClientHello with PSK leaves PSK at the head of ssl->extensions
8546
     * here, before any post-parse code (e.g. ALPN_Select) modifies the
8547
     * list. */
8548
    {
8549
        TLSX* pskExt = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
8550
        if (pskExt != NULL && ssl->extensions != pskExt) {
8551
            WOLFSSL_MSG("pre_shared_key extension was not last in "
8552
                        "ClientHello");
8553
            WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
8554
            ERROR_OUT(PSK_KEY_ERROR, exit_dch);
8555
        }
8556
    }
8557
#endif
8558
8559
#if defined(HAVE_ECH)
8560
    /* ECH accept/reject reconciliation is done at the end of TLSX_Parse. On
8561
     * acceptance the inner hello was decrypted, so jump to exit and let the
8562
     * caller re-invoke with the inner hello. */
8563
    if (!ssl->options.echProcessingInner && echX != NULL &&
8564
            ((WOLFSSL_ECH*)echX->data)->state == ECH_WRITE_NONE &&
8565
            ((WOLFSSL_ECH*)echX->data)->innerClientHello != NULL) {
8566
        goto exit_dch;
8567
    }
8568
#endif
8569
8570
0
#ifdef HAVE_SNI
8571
0
        if ((ret = SNI_Callback(ssl)) != 0)
8572
0
            goto exit_dch;
8573
0
        ssl->options.side = WOLFSSL_SERVER_END;
8574
0
#endif
8575
8576
0
    args->idx += totalExtSz;
8577
0
    ssl->options.haveSessionId = 1;
8578
0
    ssl->options.sendVerify = SEND_CERT;
8579
8580
#if defined(WOLFSSL_SEND_HRR_COOKIE)
8581
    ssl->options.cookieGood = 0;
8582
    if (ssl->options.sendCookie &&
8583
            (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST_COMPLETE
8584
#ifdef WOLFSSL_DTLS13
8585
                    /* Always check for a valid cookie since we may have already
8586
                     * sent a HRR but we reset the state. */
8587
                    || ssl->options.dtls
8588
#endif
8589
                    )) {
8590
        TLSX* ext = TLSX_Find(ssl->extensions, TLSX_COOKIE);
8591
8592
        if (ext != NULL) {
8593
            /* Ensure the cookie came from client and isn't the one in the
8594
            * response - HelloRetryRequest.
8595
            */
8596
            if (ext->resp == 0) {
8597
                ret = RestartHandshakeHashWithCookie(ssl, (Cookie*)ext->data);
8598
                if (ret != 0)
8599
                    goto exit_dch;
8600
                /* Don't change state here as we may want to enter
8601
                 * DoTls13ClientHello again. */
8602
                ssl->options.cookieGood = 1;
8603
            }
8604
            else {
8605
                ERROR_OUT(HRR_COOKIE_ERROR, exit_dch);
8606
            }
8607
        }
8608
        else {
8609
#if defined(WOLFSSL_DTLS13) && defined(WOLFSSL_DTLS13_NO_HRR_ON_RESUME)
8610
            /* Don't error out as we may be resuming. We confirm this later. */
8611
            if (!ssl->options.dtls)
8612
#endif
8613
                ERROR_OUT(HRR_COOKIE_ERROR, exit_dch);
8614
        }
8615
    }
8616
#endif
8617
8618
0
#ifdef HAVE_SUPPORTED_CURVES
8619
0
    if (ssl->hrr_keyshare_group != 0) {
8620
        /*
8621
         * https://datatracker.ietf.org/doc/html/rfc8446#section-4.2.8
8622
         *   when sending the new ClientHello, the client MUST
8623
         *   replace the original "key_share" extension with one containing only
8624
         *   a new KeyShareEntry for the group indicated in the selected_group
8625
         *   field of the triggering HelloRetryRequest.
8626
         */
8627
0
        TLSX* extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
8628
0
        if (extension != NULL) {
8629
0
            KeyShareEntry* kse = (KeyShareEntry*)extension->data;
8630
            /* Exactly one KeyShareEntry with the HRR group must be present. */
8631
0
            if (kse == NULL || kse->next != NULL ||
8632
0
                                        kse->group != ssl->hrr_keyshare_group) {
8633
0
                ERROR_OUT(BAD_KEY_SHARE_DATA, exit_dch);
8634
0
            }
8635
0
        }
8636
0
        else
8637
0
            ERROR_OUT(BAD_KEY_SHARE_DATA, exit_dch);
8638
0
    }
8639
0
#endif
8640
8641
#if defined(HAVE_ECH)
8642
    /* hash clientHelloInner to hsHashesEch */
8643
    if (echX != NULL && ssl->ctx->echConfigs != NULL &&
8644
            !ssl->options.disableECH &&
8645
            ((WOLFSSL_ECH*)echX->data)->innerClientHello != NULL) {
8646
        ret = EchHashHelloInner(ssl, (WOLFSSL_ECH*)echX->data);
8647
        if (ret != 0)
8648
            goto exit_dch;
8649
        ((WOLFSSL_ECH*)echX->data)->innerCount = 1;
8650
    }
8651
#endif
8652
8653
#ifdef HAVE_ALPN
8654
    /* Select the ALPN protocol before PSK selection so that the
8655
     * selected value is available to the per-PSK SNI/ALPN binding check
8656
     * inside CheckPreSharedKeys/DoPreSharedKeys. ALPN_Select itself
8657
     * only inspects ssl->extensions and the app callback; it does not
8658
     * depend on any state set during PSK validation. */
8659
    if ((ret = ALPN_Select(ssl)) != 0)
8660
        goto exit_dch;
8661
#endif
8662
#if (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)) && \
8663
                                                    defined(HAVE_TLS_EXTENSIONS)
8664
    ret = CheckPreSharedKeys(ssl, input + args->begin, helloSz, ssl->clSuites,
8665
        &args->usingPSK);
8666
    if (ret != 0)
8667
        goto exit_dch;
8668
#else
8669
0
    if ((ret = HashInput(ssl, input + args->begin, (int)helloSz)) != 0)
8670
0
        goto exit_dch;
8671
0
#endif
8672
8673
#if (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)) && \
8674
                                                    defined(HAVE_TLS_EXTENSIONS)
8675
    if (!args->usingPSK
8676
#ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
8677
        || ssl->options.certWithExternPsk
8678
#endif
8679
    )
8680
#endif
8681
0
    {
8682
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
8683
        /* Not using PSK so don't require no KE. */
8684
        ssl->options.noPskDheKe = 0;
8685
#endif
8686
8687
0
#ifndef NO_CERTS
8688
0
        if (TLSX_Find(ssl->extensions, TLSX_KEY_SHARE) == NULL) {
8689
0
            WOLFSSL_MSG("Client did not send a KeyShare extension");
8690
0
            ERROR_OUT(INCOMPLETE_DATA, exit_dch);
8691
0
        }
8692
        /* Can't check ssl->extensions here as SigAlgs are unconditionally
8693
           set by TLSX_PopulateExtensions */
8694
0
        if (ssl->clSuites->hashSigAlgoSz == 0) {
8695
0
            WOLFSSL_MSG("Client did not send a SignatureAlgorithms extension");
8696
0
            ERROR_OUT(INCOMPLETE_DATA, exit_dch);
8697
0
        }
8698
#else
8699
        ERROR_OUT(INVALID_PARAMETER, exit_dch);
8700
#endif
8701
0
    }
8702
8703
0
    } /* case TLS_ASYNC_BEGIN */
8704
0
    FALL_THROUGH;
8705
8706
0
    case TLS_ASYNC_BUILD:
8707
    /* Advance state and proceed */
8708
0
    ssl->options.asyncState = TLS_ASYNC_DO;
8709
0
    FALL_THROUGH;
8710
8711
0
    case TLS_ASYNC_DO:
8712
0
    {
8713
#ifdef WOLFSSL_CERT_SETUP_CB
8714
    if ((ret = CertSetupCbWrapper(ssl)) != 0)
8715
        goto exit_dch;
8716
#endif
8717
0
#ifndef NO_CERTS
8718
0
    if (!args->usingPSK) {
8719
0
        if ((ret = MatchSuite(ssl, ssl->clSuites)) < 0) {
8720
        #ifdef WOLFSSL_ASYNC_CRYPT
8721
            if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
8722
        #endif
8723
0
                WOLFSSL_MSG("Unsupported cipher suite, ClientHello 1.3");
8724
0
            goto exit_dch;
8725
0
        }
8726
0
    }
8727
0
#endif
8728
0
#ifdef HAVE_SUPPORTED_CURVES
8729
0
    if (args->usingPSK == 2) {
8730
        /* Pick key share and Generate a new key if not present. */
8731
0
        int doHelloRetry = 0;
8732
0
        ret = TLSX_KeyShare_Establish(ssl, &doHelloRetry);
8733
0
        if (doHelloRetry) {
8734
            /* Make sure we don't send HRR twice */
8735
0
            if (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST_COMPLETE)
8736
0
                ERROR_OUT(INVALID_PARAMETER, exit_dch);
8737
0
            ssl->options.serverState = SERVER_HELLO_RETRY_REQUEST_COMPLETE;
8738
0
            if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
8739
0
                ret = 0; /* for hello_retry return 0 */
8740
0
        }
8741
0
        if (ret != 0)
8742
0
            goto exit_dch;
8743
0
    }
8744
0
#endif
8745
8746
    /* Verify the cipher suite is the same as what was chosen in HRR.
8747
     * got_client_hello == 2 covers the stateful path.
8748
     * cookieGood covers the stateless DTLS path. */
8749
0
    if ((ssl->msgsReceived.got_client_hello == 2
8750
#ifdef WOLFSSL_SEND_HRR_COOKIE
8751
            || ssl->options.cookieGood
8752
#endif
8753
0
        ) &&
8754
0
            (ssl->options.cipherSuite0 != ssl->options.hrrCipherSuite0 ||
8755
0
             ssl->options.cipherSuite  != ssl->options.hrrCipherSuite)) {
8756
0
        WOLFSSL_MSG("Cipher suite in second ClientHello does not match "
8757
0
                    "HelloRetryRequest");
8758
0
        ERROR_OUT(INVALID_PARAMETER, exit_dch);
8759
0
    }
8760
8761
    /* Advance state and proceed */
8762
0
    ssl->options.asyncState = TLS_ASYNC_VERIFY;
8763
0
    } /* case TLS_ASYNC_BUILD || TLS_ASYNC_DO */
8764
0
    FALL_THROUGH;
8765
8766
0
    case TLS_ASYNC_VERIFY:
8767
0
    {
8768
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(HAVE_SUPPORTED_CURVES)
8769
    /* Check if the KeyShare calculations from the previous state are complete.
8770
     * wolfSSL_AsyncPop advances ssl->options.asyncState so we may end up here
8771
     * with a pending calculation. */
8772
    TLSX* extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
8773
    if (extension != NULL && extension->resp == 1) {
8774
        KeyShareEntry* serverKSE = (KeyShareEntry*)extension->data;
8775
        if (serverKSE != NULL &&
8776
            serverKSE->lastRet == WC_NO_ERR_TRACE(WC_PENDING_E)) {
8777
    #if defined(WOLFSSL_HAVE_MLKEM)
8778
            if (WOLFSSL_NAMED_GROUP_IS_PQC_HYBRID(serverKSE->group)) {
8779
                ret = TLSX_KeyShare_HandlePqcHybridKeyServer(ssl, serverKSE,
8780
                        serverKSE->ke, serverKSE->keLen);
8781
            }
8782
            else
8783
    #endif
8784
            {
8785
                ret = TLSX_KeyShare_GenKey(ssl, serverKSE);
8786
            }
8787
            if (ret != 0)
8788
                goto exit_dch;
8789
        }
8790
    }
8791
#endif
8792
    /* Advance state and proceed */
8793
0
    ssl->options.asyncState = TLS_ASYNC_FINALIZE;
8794
0
    }
8795
0
    FALL_THROUGH;
8796
8797
0
    case TLS_ASYNC_FINALIZE:
8798
0
    {
8799
0
    *inOutIdx = args->idx;
8800
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
8801
    ssl->options.pskNegotiated = (args->usingPSK != 0);
8802
#endif
8803
8804
0
    if (!args->usingPSK) {
8805
0
#ifndef NO_CERTS
8806
        /* Check that the negotiated ciphersuite matches protocol version. */
8807
    #ifdef HAVE_NULL_CIPHER
8808
        if (ssl->options.cipherSuite0 == ECC_BYTE &&
8809
                              (ssl->options.cipherSuite == TLS_SHA256_SHA256 ||
8810
                               ssl->options.cipherSuite == TLS_SHA384_SHA384)) {
8811
            ;
8812
        }
8813
        else
8814
    #endif
8815
    #if defined(WOLFSSL_SM4_GCM) && defined(WOLFSSL_SM3)
8816
        if (ssl->options.cipherSuite0 == CIPHER_BYTE &&
8817
                ssl->options.cipherSuite == TLS_SM4_GCM_SM3) {
8818
            ; /* Do nothing. */
8819
        }
8820
        else
8821
    #endif
8822
    #if defined(WOLFSSL_SM4_CCM) && defined(WOLFSSL_SM3)
8823
        if (ssl->options.cipherSuite0 == CIPHER_BYTE &&
8824
                ssl->options.cipherSuite == TLS_SM4_CCM_SM3) {
8825
            ; /* Do nothing. */
8826
        }
8827
        else
8828
    #endif
8829
0
        if (ssl->options.cipherSuite0 != TLS13_BYTE) {
8830
0
            WOLFSSL_MSG("Negotiated ciphersuite from lesser version than "
8831
0
                        "TLS v1.3");
8832
0
            ERROR_OUT(MATCH_SUITE_ERROR, exit_dch);
8833
0
        }
8834
8835
    #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
8836
        if (ssl->options.resuming) {
8837
            ssl->options.resuming = 0;
8838
            ssl->arrays->psk_keySz = 0;
8839
            XMEMSET(ssl->arrays->psk_key, 0, ssl->specs.hash_size);
8840
        }
8841
    #endif
8842
8843
        /* Derive early secret for handshake secret. */
8844
0
        if ((ret = DeriveEarlySecret(ssl)) != 0)
8845
0
            goto exit_dch;
8846
0
#endif /* !NO_CERTS */
8847
0
    }
8848
8849
    /* Advanced only after the derive: earlier would let the accept loop
8850
     * proceed on an unfinished early secret. */
8851
0
    ssl->options.clientState = CLIENT_HELLO_COMPLETE;
8852
0
    break;
8853
0
    } /* case TLS_ASYNC_FINALIZE */
8854
0
    default:
8855
0
        ret = INPUT_CASE_ERROR;
8856
0
    } /* switch (ssl->options.asyncState) */
8857
8858
#ifdef WOLFSSL_SEND_HRR_COOKIE
8859
    if (ret == 0 && ssl->options.sendCookie) {
8860
        if (ssl->options.cookieGood &&
8861
                ssl->options.acceptState == TLS13_ACCEPT_FIRST_REPLY_DONE) {
8862
            /* Processing second ClientHello. Clear HRR state. */
8863
            ssl->options.serverState = NULL_STATE;
8864
        }
8865
8866
        if (ssl->options.cookieGood &&
8867
            ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
8868
            /* If we already verified the peer with a cookie then we can't
8869
             * do another HRR for cipher negotiation. Send alert and restart
8870
             * the entire handshake. */
8871
            ERROR_OUT(INVALID_PARAMETER, exit_dch);
8872
        }
8873
#ifdef WOLFSSL_DTLS13
8874
        if (ssl->options.dtls &&
8875
            ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
8876
            /* Cookie and key share negotiation should be handled in
8877
             * DoClientHelloStateless. If we enter here then something went
8878
             * wrong in our logic. */
8879
            ERROR_OUT(BAD_HELLO, exit_dch);
8880
        }
8881
#endif
8882
        /* Send a cookie */
8883
        if (!ssl->options.cookieGood &&
8884
            ssl->options.serverState != SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
8885
#ifdef WOLFSSL_DTLS13
8886
            if (ssl->options.dtls) {
8887
#ifdef WOLFSSL_DTLS13_NO_HRR_ON_RESUME
8888
                /* We can skip cookie on resumption */
8889
                if (!ssl->options.dtls || !ssl->options.dtls13NoHrrOnResume ||
8890
                        !args->usingPSK)
8891
#endif
8892
                    ERROR_OUT(BAD_HELLO, exit_dch);
8893
            }
8894
            else
8895
#endif
8896
            {
8897
                /* Need to remove the keyshare ext if we found a common group
8898
                 * and are not doing curve negotiation. */
8899
                TLSX_Remove(&ssl->extensions, TLSX_KEY_SHARE, ssl->heap);
8900
                ssl->options.serverState = SERVER_HELLO_RETRY_REQUEST_COMPLETE;
8901
            }
8902
8903
        }
8904
    }
8905
#endif /* WOLFSSL_DTLS13 */
8906
8907
#ifdef WOLFSSL_DTLS_CID
8908
    /* do not modify CID state if we are sending an HRR  */
8909
    if (ret == 0 && ssl->options.dtls && ssl->options.useDtlsCID &&
8910
            ssl->options.serverState != SERVER_HELLO_RETRY_REQUEST_COMPLETE)
8911
        DtlsCIDOnExtensionsParsed(ssl);
8912
#endif /* WOLFSSL_DTLS_CID */
8913
8914
8915
8916
0
exit_dch:
8917
8918
0
    WOLFSSL_LEAVE("DoTls13ClientHello", ret);
8919
8920
#ifdef WOLFSSL_ASYNC_CRYPT
8921
    if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
8922
        ssl->msgsReceived.got_client_hello = 0;
8923
        return ret;
8924
    }
8925
#endif
8926
8927
0
    FreeDch13Args(ssl, args);
8928
#ifdef WOLFSSL_ASYNC_CRYPT
8929
    FreeAsyncCtx(ssl, 0);
8930
    /* Back to BEGIN so a later ClientHello (HRR, duplicate) can never be
8931
     * mistaken for a replay and resume into freed args. */
8932
    ssl->options.asyncState = TLS_ASYNC_BEGIN;
8933
    /* This ClientHello is done; a later one (HRR CH2, duplicate) must hash
8934
     * itself afresh. */
8935
    ssl->options.chHashInput = 0;
8936
    /* Replays skip the sanity check that re-sets got_client_hello; restore
8937
     * on completion (only from 0: an HRR second ClientHello counts to 2). */
8938
    if (ret == 0 && ssl->msgsReceived.got_client_hello == 0) {
8939
        ssl->msgsReceived.got_client_hello = 1;
8940
    }
8941
#endif
8942
0
    WOLFSSL_END(WC_FUNC_CLIENT_HELLO_DO);
8943
8944
0
    if (ret != 0) {
8945
0
        WOLFSSL_ERROR_VERBOSE(ret);
8946
0
    }
8947
8948
#if defined(HAVE_ECH)
8949
    if (ret == 0 && echX != NULL &&
8950
        ((WOLFSSL_ECH*)echX->data)->state == ECH_WRITE_NONE &&
8951
        ((WOLFSSL_ECH*)echX->data)->innerClientHello != NULL) {
8952
8953
        /* add the header to the inner hello */
8954
        AddTls13HandShakeHeader(((WOLFSSL_ECH*)echX->data)->innerClientHello,
8955
            ((WOLFSSL_ECH*)echX->data)->innerClientHelloLen, 0, 0,
8956
            client_hello, ssl);
8957
    }
8958
#endif
8959
8960
0
    return ret;
8961
0
}
8962
8963
/* Send TLS v1.3 ServerHello message to client.
8964
 * Only a server will send this message.
8965
 *
8966
 * ssl  The SSL/TLS object.
8967
 * returns 0 on success, otherwise failure.
8968
 */
8969
/* handle generation of TLS 1.3 server_hello (2) */
8970
int SendTls13ServerHello(WOLFSSL* ssl, byte extMsgType)
8971
0
{
8972
0
    int    ret;
8973
0
    byte*  output;
8974
0
    word16 length;
8975
0
    word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
8976
0
    int    sendSz;
8977
#if defined(HAVE_ECH)
8978
    TLSX* echX = NULL;
8979
    byte* acceptLabel = (byte*)echAcceptConfirmationLabel;
8980
    word32 acceptOffset;
8981
    word16 acceptLabelSz = ECH_ACCEPT_CONFIRMATION_LABEL_SZ;
8982
#endif
8983
8984
0
    WOLFSSL_START(WC_FUNC_SERVER_HELLO_SEND);
8985
0
    WOLFSSL_ENTER("SendTls13ServerHello");
8986
8987
    /* When ssl->options.dtlsStateful is not set then cookie is calculated in
8988
     * dtls.c */
8989
0
    if (extMsgType == hello_retry_request
8990
#ifdef WOLFSSL_DTLS13
8991
            && (!ssl->options.dtls || ssl->options.dtlsStateful)
8992
#endif
8993
0
            ) {
8994
0
        WOLFSSL_MSG("wolfSSL Sending HelloRetryRequest");
8995
0
        if ((ret = RestartHandshakeHash(ssl)) < 0)
8996
0
            return ret;
8997
0
    }
8998
8999
0
    ssl->options.buildingMsg = 1;
9000
#ifdef WOLFSSL_DTLS13
9001
    if (ssl->options.dtls)
9002
        idx = DTLS_RECORD_HEADER_SZ + DTLS_HANDSHAKE_HEADER_SZ;
9003
#endif /* WOLFSSL_DTLS13 */
9004
9005
    /* Protocol version, server random, session id, cipher suite, compression
9006
     * and extensions.
9007
     */
9008
0
    length = VERSION_SZ + RAN_LEN + ENUM_LEN + ssl->session->sessionIDSz +
9009
0
             SUITE_LEN + COMP_LEN;
9010
0
    ret = TLSX_GetResponseSize(ssl, extMsgType, &length);
9011
0
    if (ret != 0)
9012
0
        return ret;
9013
0
    sendSz = (int)(idx + length);
9014
9015
    /* Check buffers are big enough and grow if needed. */
9016
0
    if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
9017
0
        return ret;
9018
9019
    /* Get position in output buffer to write new message to. */
9020
0
    output = GetOutputBuffer(ssl);
9021
9022
    /* Put the record and handshake headers on. */
9023
0
    AddTls13Headers(output, length, server_hello, ssl);
9024
9025
    /* The protocol version must be TLS v1.2 for middleboxes. */
9026
0
    output[idx++] = ssl->version.major;
9027
0
    output[idx++] = ssl->options.dtls ? DTLSv1_2_MINOR : TLSv1_2_MINOR;
9028
9029
0
    if (extMsgType == server_hello) {
9030
        /* Generate server random. */
9031
0
        if ((ret = wc_RNG_GenerateBlock(ssl->rng, output + idx, RAN_LEN)) != 0)
9032
0
            return ret;
9033
0
    }
9034
0
    else {
9035
        /* HelloRetryRequest message has fixed value for random. */
9036
0
        XMEMCPY(output + idx, helloRetryRequestRandom, RAN_LEN);
9037
0
    }
9038
9039
#if defined(HAVE_ECH)
9040
    /* last 8 bytes of server random */
9041
    acceptOffset = idx + RAN_LEN - ECH_ACCEPT_CONFIRMATION_SZ;
9042
#endif
9043
9044
    /* Store in SSL for debugging. */
9045
0
    XMEMCPY(ssl->arrays->serverRandom, output + idx, RAN_LEN);
9046
0
    idx += RAN_LEN;
9047
9048
#ifdef WOLFSSL_DEBUG_TLS
9049
    WOLFSSL_MSG("Server random");
9050
    WOLFSSL_BUFFER(ssl->arrays->serverRandom, RAN_LEN);
9051
#endif
9052
9053
#if defined(WOLFSSL_DTLS13) && !defined(WOLFSSL_DTLS13_ECHO_LEGACY_SESSION_ID)
9054
    if (ssl->options.dtls) {
9055
        /* RFC 9147 Section 5: "DTLS servers MUST NOT echo the
9056
         * legacy_session_id value from the client." */
9057
        output[idx++] = 0;
9058
    }
9059
    else
9060
#endif
9061
0
    {
9062
0
        output[idx++] = ssl->session->sessionIDSz;
9063
0
        if (ssl->session->sessionIDSz > 0) {
9064
0
            XMEMCPY(output + idx, ssl->session->sessionID,
9065
0
                ssl->session->sessionIDSz);
9066
0
            idx += ssl->session->sessionIDSz;
9067
0
        }
9068
0
    }
9069
9070
    /* Chosen cipher suite */
9071
0
    output[idx++] = ssl->options.cipherSuite0;
9072
0
    output[idx++] = ssl->options.cipherSuite;
9073
#ifdef WOLFSSL_DEBUG_TLS
9074
    WOLFSSL_MSG("Chosen cipher suite:");
9075
    WOLFSSL_MSG(GetCipherNameInternal(ssl->options.cipherSuite0,
9076
                                      ssl->options.cipherSuite));
9077
#endif
9078
9079
    /* Compression not supported in TLS v1.3. */
9080
0
    output[idx++] = 0;
9081
9082
    /* Extensions */
9083
0
    ret = TLSX_WriteResponse(ssl, output + idx, extMsgType, NULL);
9084
0
    if (ret != 0)
9085
0
        return ret;
9086
9087
    /* When we send a HRR, we store the selected key share group to later check
9088
     * that the client uses the same group in the second ClientHello.
9089
     *
9090
     * In case of stateless DTLS, we do not store the group, however, as it is
9091
     * already stored in the cookie that is sent to the client. We later recover
9092
     * the group from the cookie to prevent storing a state in a stateless
9093
     * server.
9094
     *
9095
     * Similar logic holds for the hrrCipherSuite. */
9096
0
    if (extMsgType == hello_retry_request
9097
#if defined(WOLFSSL_DTLS13) && defined(WOLFSSL_SEND_HRR_COOKIE)
9098
        && (!ssl->options.dtls || ssl->options.dtlsStateful)
9099
#endif
9100
0
    ) {
9101
0
        TLSX* ksExt = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
9102
0
        if (ksExt != NULL) {
9103
0
            KeyShareEntry* kse = (KeyShareEntry*)ksExt->data;
9104
0
            if (kse != NULL)
9105
0
                ssl->hrr_keyshare_group = kse->group;
9106
0
        }
9107
9108
0
        ssl->options.hrrCipherSuite0 = ssl->options.cipherSuite0;
9109
0
        ssl->options.hrrCipherSuite  = ssl->options.cipherSuite;
9110
0
    }
9111
9112
#ifdef WOLFSSL_SEND_HRR_COOKIE
9113
    if (ssl->options.sendCookie && extMsgType == hello_retry_request) {
9114
        /* Reset the hashes from here. We will be able to restart the hashes
9115
         * from the cookie in RestartHandshakeHashWithCookie */
9116
#ifdef WOLFSSL_DTLS13
9117
        /* When ssl->options.dtlsStateful is not set then cookie is calculated
9118
         * in dtls.c */
9119
        if (ssl->options.dtls && !ssl->options.dtlsStateful)
9120
            ret = 0;
9121
        else
9122
#endif
9123
            ret = InitHandshakeHashes(ssl);
9124
    }
9125
    else
9126
#endif
9127
0
    {
9128
#ifdef WOLFSSL_DTLS13
9129
        if (ssl->options.dtls) {
9130
            ret = Dtls13HashHandshake(
9131
                ssl,
9132
                output + Dtls13GetRlHeaderLength(ssl, 0) ,
9133
                (word16)sendSz - Dtls13GetRlHeaderLength(ssl, 0));
9134
        }
9135
        else
9136
#endif /* WOLFSSL_DTLS13 */
9137
0
        {
9138
#if defined(HAVE_ECH)
9139
            if (ssl->ctx->echConfigs != NULL && !ssl->options.disableECH) {
9140
                echX = TLSX_Find(ssl->extensions, TLSX_ECH);
9141
                if (echX == NULL)
9142
                    return WOLFSSL_FATAL_ERROR;
9143
                /* use hrr offset */
9144
                if (extMsgType == hello_retry_request) {
9145
                    acceptOffset =
9146
                        (word32)(((WOLFSSL_ECH*)echX->data)->confBuf - output);
9147
                    acceptLabel = (byte*)echHrrAcceptConfirmationLabel;
9148
                    acceptLabelSz = ECH_HRR_ACCEPT_CONFIRMATION_LABEL_SZ;
9149
                }
9150
                /* replace the last 8 bytes of server random with the accept */
9151
                if (((WOLFSSL_ECH*)echX->data)->state == ECH_PARSED_INTERNAL) {
9152
                    if (ret == 0) {
9153
                        ret = EchWriteAcceptance(ssl, acceptLabel,
9154
                            acceptLabelSz, output + RECORD_HEADER_SZ,
9155
                            acceptOffset - RECORD_HEADER_SZ,
9156
                            sendSz - RECORD_HEADER_SZ, extMsgType);
9157
                    }
9158
                    if (extMsgType == hello_retry_request) {
9159
                        /* reset the ech state for round 2 */
9160
                        ((WOLFSSL_ECH*)echX->data)->state = ECH_WRITE_NONE;
9161
                        /* inner hello no longer needed, free it */
9162
                        XFREE(((WOLFSSL_ECH*)echX->data)->innerClientHello,
9163
                              ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
9164
                        ((WOLFSSL_ECH*)echX->data)->innerClientHello = NULL;
9165
                    }
9166
                    else {
9167
                        if (ret == 0) {
9168
                            /* update serverRandom on success */
9169
                            XMEMCPY(ssl->arrays->serverRandom,
9170
                                output + acceptOffset -
9171
                                (RAN_LEN -ECH_ACCEPT_CONFIRMATION_SZ), RAN_LEN);
9172
                        }
9173
                        /* remove ech so we don't keep sending it in write */
9174
                        TLSX_Remove(&ssl->extensions, TLSX_ECH, ssl->heap);
9175
                    }
9176
                }
9177
            }
9178
#endif
9179
0
            if (ret == 0)
9180
0
                ret = HashOutput(ssl, output, sendSz, 0);
9181
0
        }
9182
0
    }
9183
9184
0
    if (ret != 0)
9185
0
        return ret;
9186
9187
#if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
9188
    if (ssl->hsInfoOn)
9189
        AddPacketName(ssl, "ServerHello");
9190
    if (ssl->toInfoOn) {
9191
        ret = AddPacketInfo(ssl, "ServerHello", handshake, output, sendSz,
9192
                      WRITE_PROTO, 0, ssl->heap);
9193
        if (ret != 0)
9194
            return ret;
9195
    }
9196
    #endif
9197
9198
0
    if (extMsgType == server_hello)
9199
0
        ssl->options.serverState = SERVER_HELLO_COMPLETE;
9200
9201
0
    ssl->options.buildingMsg = 0;
9202
#ifdef WOLFSSL_DTLS13
9203
    if (ssl->options.dtls) {
9204
        ret = Dtls13HandshakeSend(ssl, output, (word16)sendSz, (word16)sendSz,
9205
            (enum HandShakeType)extMsgType, 0);
9206
9207
        WOLFSSL_LEAVE("SendTls13ServerHello", ret);
9208
        WOLFSSL_END(WC_FUNC_SERVER_HELLO_SEND);
9209
        return ret;
9210
    }
9211
#endif /* WOLFSSL_DTLS13 */
9212
9213
0
    ssl->buffers.outputBuffer.length += (word32)sendSz;
9214
9215
0
    if (!ssl->options.groupMessages || extMsgType != server_hello)
9216
0
        ret = SendBuffered(ssl);
9217
9218
0
    WOLFSSL_LEAVE("SendTls13ServerHello", ret);
9219
0
    WOLFSSL_END(WC_FUNC_SERVER_HELLO_SEND);
9220
9221
0
    return ret;
9222
0
}
9223
9224
/* handle generation of TLS 1.3 encrypted_extensions (8) */
9225
/* Send the rest of the extensions encrypted under the handshake key.
9226
 * This message is always encrypted in TLS v1.3.
9227
 * Only a server will send this message.
9228
 *
9229
 * ssl  The SSL/TLS object.
9230
 * returns 0 on success, otherwise failure.
9231
 */
9232
static int SendTls13EncryptedExtensions(WOLFSSL* ssl)
9233
0
{
9234
0
    int    ret;
9235
0
    byte*  output;
9236
0
    word16 length = 0;
9237
0
    word32 idx;
9238
0
    int    sendSz;
9239
9240
0
    WOLFSSL_START(WC_FUNC_ENCRYPTED_EXTENSIONS_SEND);
9241
0
    WOLFSSL_ENTER("SendTls13EncryptedExtensions");
9242
9243
0
    ssl->options.buildingMsg = 1;
9244
0
    ssl->keys.encryptionOn = 1;
9245
9246
#ifdef WOLFSSL_DTLS13
9247
    if (ssl->options.dtls) {
9248
        idx = Dtls13GetHeadersLength(ssl, encrypted_extensions);
9249
    }
9250
    else
9251
#endif /* WOLFSSL_DTLS13 */
9252
0
    {
9253
0
        idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
9254
0
    }
9255
9256
#ifdef WOLFSSL_ASYNC_CRYPT
9257
    /* A suspended build already ran the key schedule below; re-running it
9258
     * would extract in place over preMasterSecret a second time. */
9259
    if (ssl->options.buildArgs13Set)
9260
        goto tls13_send_ee_build;
9261
#endif
9262
9263
0
#if defined(HAVE_SUPPORTED_CURVES) && !defined(WOLFSSL_NO_SERVER_GROUPS_EXT)
9264
0
    if ((ret = TLSX_SupportedCurve_CheckPriority(ssl)) != 0)
9265
0
        return ret;
9266
0
#endif
9267
9268
    /* Derive the handshake secret now that we are at first message to be
9269
     * encrypted under the keys.
9270
     */
9271
0
    if (ssl->kdfDeriveStep <= TLS13_SEND_KDF_NONE) {
9272
0
        ret = DeriveHandshakeSecret(ssl);
9273
0
        if (ret != 0) {
9274
0
            if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
9275
0
                ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
9276
0
            return ret;
9277
0
        }
9278
0
        ssl->kdfDeriveStep = TLS13_SEND_KDF_EE_HS_SECRET;
9279
0
    }
9280
0
    if (ssl->kdfDeriveStep <= TLS13_SEND_KDF_EE_HS_SECRET) {
9281
0
        ret = DeriveTls13Keys(ssl, handshake_key, ENCRYPT_AND_DECRYPT_SIDE, 1);
9282
0
        if (ret != 0) {
9283
0
            if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
9284
0
                ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
9285
0
            return ret;
9286
0
        }
9287
0
        ssl->kdfDeriveStep = TLS13_SEND_KDF_EE_HS_KEYS;
9288
0
    }
9289
9290
    /* Setup encrypt/decrypt keys for following messages. */
9291
#ifdef WOLFSSL_EARLY_DATA
9292
    if (ssl->kdfDeriveStep <= TLS13_SEND_KDF_EE_HS_KEYS) {
9293
        ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY);
9294
        if (ret != 0) {
9295
            if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
9296
                ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
9297
            return ret;
9298
        }
9299
        ssl->kdfDeriveStep = TLS13_SEND_KDF_EE_ENC_KEYS_SET;
9300
    }
9301
    if (ssl->earlyData != process_early_data) {
9302
        if (ssl->kdfDeriveStep <= TLS13_SEND_KDF_EE_ENC_KEYS_SET) {
9303
            ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY);
9304
            if (ret != 0) {
9305
                if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
9306
                    ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
9307
                return ret;
9308
            }
9309
            ssl->kdfDeriveStep = TLS13_SEND_KDF_EE_KEYS_SET;
9310
        }
9311
    }
9312
#else
9313
0
    if (ssl->kdfDeriveStep <= TLS13_SEND_KDF_EE_ENC_KEYS_SET) {
9314
0
        ret = SetKeysSide(ssl, ENCRYPT_AND_DECRYPT_SIDE);
9315
0
        if (ret != 0) {
9316
0
            if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
9317
0
                ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
9318
0
            return ret;
9319
0
        }
9320
0
        ssl->kdfDeriveStep = TLS13_SEND_KDF_EE_KEYS_SET;
9321
0
    }
9322
0
#endif
9323
#ifdef WOLFSSL_QUIC
9324
    if (IsAtLeastTLSv1_3(ssl->version) && WOLFSSL_IS_QUIC(ssl)) {
9325
        ret = wolfSSL_quic_add_transport_extensions(ssl, encrypted_extensions);
9326
        if (ret != 0)
9327
            return ret;
9328
    }
9329
#endif
9330
9331
#ifdef WOLFSSL_DTLS13
9332
    if (ssl->options.dtls) {
9333
        w64wrapper epochHandshake = w64From32(0, DTLS13_EPOCH_HANDSHAKE);
9334
        ssl->dtls13Epoch = epochHandshake;
9335
9336
        if (ssl->kdfDeriveStep <= TLS13_SEND_KDF_EE_KEYS_SET) {
9337
            ret = Dtls13SetEpochKeys(ssl, epochHandshake,
9338
                                     ENCRYPT_AND_DECRYPT_SIDE);
9339
            if (ret != 0) {
9340
                if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
9341
                    ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
9342
                return ret;
9343
            }
9344
            ssl->kdfDeriveStep = TLS13_SEND_KDF_EE_DTLS_EPOCH;
9345
        }
9346
    }
9347
#endif /* WOLFSSL_DTLS13 */
9348
0
    ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
9349
9350
#ifdef WOLFSSL_ASYNC_CRYPT
9351
tls13_send_ee_build:
9352
#endif
9353
9354
0
    ret = TLSX_GetResponseSize(ssl, encrypted_extensions, &length);
9355
0
    if (ret != 0)
9356
0
        return ret;
9357
9358
0
    sendSz = (int)(idx + length);
9359
    /* Encryption always on. */
9360
0
    sendSz += MAX_MSG_EXTRA;
9361
9362
    /* Check buffers are big enough and grow if needed. */
9363
0
    ret = CheckAvailableSize(ssl, sendSz);
9364
0
    if (ret != 0)
9365
0
        return ret;
9366
9367
    /* Get position in output buffer to write new message to. */
9368
0
    output = GetOutputBuffer(ssl);
9369
9370
#ifdef WOLFSSL_ASYNC_CRYPT
9371
    /* Skip on a resume: BuildTls13Message already replaced the record
9372
     * header; rewriting the plaintext headers would corrupt it. */
9373
    if (!ssl->options.buildArgs13Set)
9374
#endif
9375
0
    {
9376
        /* Put the record and handshake headers on. */
9377
0
        AddTls13Headers(output, length, encrypted_extensions, ssl);
9378
9379
0
        ret = TLSX_WriteResponse(ssl, output + idx, encrypted_extensions, NULL);
9380
0
        if (ret != 0)
9381
0
            return ret;
9382
0
    }
9383
0
    idx += length;
9384
9385
#if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
9386
    if (ssl->hsInfoOn)
9387
        AddPacketName(ssl, "EncryptedExtensions");
9388
    if (ssl->toInfoOn) {
9389
        ret = AddPacketInfo(ssl, "EncryptedExtensions", handshake, output,
9390
                      sendSz, WRITE_PROTO, 0, ssl->heap);
9391
        if (ret != 0)
9392
            return ret;
9393
    }
9394
#endif
9395
9396
#ifdef WOLFSSL_DTLS13
9397
    if (ssl->options.dtls) {
9398
        ssl->options.buildingMsg = 0;
9399
        ret = Dtls13HandshakeSend(ssl, output, (word16)sendSz, (word16)idx,
9400
                                  encrypted_extensions, 1);
9401
9402
        if (ret == 0)
9403
            ssl->options.serverState = SERVER_ENCRYPTED_EXTENSIONS_COMPLETE;
9404
9405
        WOLFSSL_LEAVE("SendTls13EncryptedExtensions", ret);
9406
        WOLFSSL_END(WC_FUNC_ENCRYPTED_EXTENSIONS_SEND);
9407
9408
        return ret;
9409
    }
9410
#endif /* WOLFSSL_DTLS13 */
9411
9412
    /* This handshake message is always encrypted. */
9413
0
    sendSz = BuildTls13Message(ssl, output, sendSz, output + RECORD_HEADER_SZ,
9414
0
                               (int)(idx - RECORD_HEADER_SZ),
9415
0
                               handshake, 1, 0, TLS13_HS_ASYNC_OKAY);
9416
0
    if (sendSz < 0)
9417
0
        return sendSz;
9418
9419
0
    ssl->buffers.outputBuffer.length += (word32)sendSz;
9420
0
    ssl->options.buildingMsg = 0;
9421
0
    ssl->options.serverState = SERVER_ENCRYPTED_EXTENSIONS_COMPLETE;
9422
9423
0
    if (!ssl->options.groupMessages)
9424
0
        ret = SendBuffered(ssl);
9425
9426
9427
0
    WOLFSSL_LEAVE("SendTls13EncryptedExtensions", ret);
9428
0
    WOLFSSL_END(WC_FUNC_ENCRYPTED_EXTENSIONS_SEND);
9429
9430
0
    return ret;
9431
0
}
9432
9433
#ifndef NO_CERTS
9434
/* handle generation TLS v1.3 certificate_request (13) */
9435
/* Send the TLS v1.3 CertificateRequest message.
9436
 * This message is always encrypted in TLS v1.3.
9437
 * Only a server will send this message.
9438
 *
9439
 * ssl        SSL/TLS object.
9440
 * reqCtx     Request context.
9441
 * reqCtxLen  Length of context. 0 when sending as part of handshake.
9442
 * returns 0 on success, otherwise failure.
9443
 */
9444
static int SendTls13CertificateRequest(WOLFSSL* ssl, byte* reqCtx,
9445
                                       word32 reqCtxLen)
9446
0
{
9447
0
    byte*   output;
9448
0
    int    ret;
9449
0
    int    sendSz;
9450
0
    word32 i;
9451
0
    word32 reqSz;
9452
9453
0
    WOLFSSL_START(WC_FUNC_CERTIFICATE_REQUEST_SEND);
9454
0
    WOLFSSL_ENTER("SendTls13CertificateRequest");
9455
9456
0
    ssl->options.buildingMsg = 1;
9457
9458
0
    if (ssl->options.side != WOLFSSL_SERVER_END)
9459
0
        return SIDE_ERROR;
9460
9461
    /* The extension writes WOLFSSL_SUITES(ssl), honoring set1_sigalgs_list. */
9462
0
    ret = TLSX_Push(&ssl->extensions, TLSX_SIGNATURE_ALGORITHMS, ssl,
9463
0
                    ssl->heap);
9464
0
    if (ret != 0)
9465
0
        return ret;
9466
9467
0
    i = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
9468
#ifdef WOLFSSL_DTLS13
9469
    if (ssl->options.dtls)
9470
        i = Dtls13GetRlHeaderLength(ssl, 1) + DTLS_HANDSHAKE_HEADER_SZ;
9471
#endif /* WOLFSSL_DTLS13 */
9472
9473
0
    reqSz = (word16)(OPAQUE8_LEN + reqCtxLen);
9474
0
    ret = TLSX_GetRequestSize(ssl, certificate_request, &reqSz);
9475
0
    if (ret != 0)
9476
0
        return ret;
9477
9478
0
    sendSz = (int)(i + reqSz);
9479
    /* Always encrypted and make room for padding. */
9480
0
    sendSz += MAX_MSG_EXTRA;
9481
9482
    /* Check buffers are big enough and grow if needed. */
9483
0
    if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
9484
0
        return ret;
9485
9486
    /* Get position in output buffer to write new message to. */
9487
0
    output = GetOutputBuffer(ssl);
9488
9489
    /* Put the record and handshake headers on. */
9490
0
    AddTls13Headers(output, reqSz, certificate_request, ssl);
9491
9492
    /* Certificate request context. */
9493
0
    output[i++] = (byte)reqCtxLen;
9494
0
    if (reqCtxLen != 0) {
9495
0
        XMEMCPY(output + i, reqCtx, reqCtxLen);
9496
0
        i += reqCtxLen;
9497
0
    }
9498
9499
    /* Certificate extensions. */
9500
0
    reqSz = 0;
9501
0
    ret = TLSX_WriteRequest(ssl, output + i, certificate_request, &reqSz);
9502
0
    if (ret != 0)
9503
0
        return ret;
9504
0
    i += reqSz;
9505
9506
#ifdef WOLFSSL_DTLS13
9507
    if (ssl->options.dtls) {
9508
        ssl->options.buildingMsg = 0;
9509
        ret =
9510
            Dtls13HandshakeSend(ssl, output, (word16)sendSz, (word16)i,
9511
                                certificate_request, 1);
9512
9513
        WOLFSSL_LEAVE("SendTls13CertificateRequest", ret);
9514
        WOLFSSL_END(WC_FUNC_CERTIFICATE_REQUEST_SEND);
9515
9516
        return ret;
9517
9518
    }
9519
#endif /* WOLFSSL_DTLS13 */
9520
9521
    /* Always encrypted. */
9522
0
    sendSz = BuildTls13Message(ssl, output, sendSz, output + RECORD_HEADER_SZ,
9523
0
                               (int)(i - RECORD_HEADER_SZ), handshake, 1, 0, 0);
9524
0
    if (sendSz < 0)
9525
0
        return sendSz;
9526
9527
    #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
9528
        if (ssl->hsInfoOn)
9529
            AddPacketName(ssl, "CertificateRequest");
9530
        if (ssl->toInfoOn) {
9531
            ret = AddPacketInfo(ssl, "CertificateRequest", handshake, output,
9532
                          sendSz, WRITE_PROTO, 0, ssl->heap);
9533
            if (ret != 0)
9534
                return ret;
9535
        }
9536
    #endif
9537
9538
0
    ssl->buffers.outputBuffer.length += (word32)sendSz;
9539
0
    ssl->options.buildingMsg = 0;
9540
0
    if (!ssl->options.groupMessages)
9541
0
        ret = SendBuffered(ssl);
9542
9543
0
    WOLFSSL_LEAVE("SendTls13CertificateRequest", ret);
9544
0
    WOLFSSL_END(WC_FUNC_CERTIFICATE_REQUEST_SEND);
9545
9546
0
    return ret;
9547
0
}
9548
#endif /* NO_CERTS */
9549
#endif /* NO_WOLFSSL_SERVER */
9550
9551
#ifndef NO_CERTS
9552
#if (!defined(NO_WOLFSSL_SERVER) || !defined(WOLFSSL_NO_CLIENT_AUTH)) && \
9553
    (!defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
9554
     defined(HAVE_ED448) || defined(HAVE_FALCON) || defined(WOLFSSL_HAVE_MLDSA) || \
9555
     defined(WOLFSSL_HAVE_SLHDSA))
9556
/* Encode the signature algorithm into buffer.
9557
 *
9558
 * hashalgo  The hash algorithm.
9559
 * hsType   The signature type.
9560
 * output    The buffer to encode into.
9561
 */
9562
static WC_INLINE void EncodeSigAlg(const WOLFSSL * ssl, byte hashAlgo,
9563
    byte hsType, byte* output)
9564
0
{
9565
0
    (void)ssl;
9566
0
    (void)hashAlgo;
9567
0
    switch (hsType) {
9568
0
#ifdef HAVE_ECC
9569
0
        case ecc_dsa_sa_algo:
9570
0
            if (ssl->pkCurveOID == ECC_BRAINPOOLP256R1_OID) {
9571
0
                output[0] = NEW_SA_MAJOR;
9572
0
                output[1] = ECDSA_BRAINPOOLP256R1TLS13_SHA256_MINOR;
9573
0
            }
9574
0
            else if (ssl->pkCurveOID == ECC_BRAINPOOLP384R1_OID) {
9575
0
                output[0] = NEW_SA_MAJOR;
9576
0
                output[1] = ECDSA_BRAINPOOLP384R1TLS13_SHA384_MINOR;
9577
0
            }
9578
0
            else if (ssl->pkCurveOID == ECC_BRAINPOOLP512R1_OID) {
9579
0
                output[0] = NEW_SA_MAJOR;
9580
0
                output[1] = ECDSA_BRAINPOOLP512R1TLS13_SHA512_MINOR;
9581
0
            }
9582
0
            else {
9583
0
                output[0] = hashAlgo;
9584
0
                output[1] = ecc_dsa_sa_algo;
9585
0
            }
9586
0
            break;
9587
0
#endif
9588
#if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
9589
        case sm2_sa_algo:
9590
            output[0] = SM2_SA_MAJOR;
9591
            output[1] = SM2_SA_MINOR;
9592
            break;
9593
#endif
9594
#ifdef HAVE_ED25519
9595
        /* ED25519: 0x0807 */
9596
        case ed25519_sa_algo:
9597
            output[0] = ED25519_SA_MAJOR;
9598
            output[1] = ED25519_SA_MINOR;
9599
            break;
9600
#endif
9601
#ifdef HAVE_ED448
9602
        /* ED448: 0x0808 */
9603
        case ed448_sa_algo:
9604
            output[0] = ED448_SA_MAJOR;
9605
            output[1] = ED448_SA_MINOR;
9606
            break;
9607
#endif
9608
0
#ifndef NO_RSA
9609
        /* PSS signatures: 0x080[4-6] or 0x080[9-B] */
9610
0
        case rsa_pss_sa_algo:
9611
0
            output[0] = rsa_pss_sa_algo;
9612
0
#ifdef WC_RSA_PSS
9613
            /* If the private key uses the RSA-PSS OID, and the peer supports
9614
             * the rsa_pss_pss_* signature algorithm in use, then report
9615
             * rsa_pss_pss_* rather than rsa_pss_rsae_*. */
9616
0
            if (ssl->useRsaPss &&
9617
0
                ((ssl->pssAlgo & (1U << hashAlgo)) != 0U) &&
9618
0
                (sha256_mac <= hashAlgo) && (hashAlgo <= sha512_mac))
9619
0
            {
9620
0
                output[1] = PSS_RSAE_TO_PSS_PSS(hashAlgo);
9621
0
            }
9622
0
            else
9623
0
#endif
9624
0
            {
9625
0
                output[1] = hashAlgo;
9626
0
            }
9627
0
            break;
9628
0
#endif
9629
#ifdef HAVE_FALCON
9630
        case falcon_level1_sa_algo:
9631
            output[0] = FALCON_LEVEL1_SA_MAJOR;
9632
            output[1] = FALCON_LEVEL1_SA_MINOR;
9633
            break;
9634
        case falcon_level5_sa_algo:
9635
            output[0] = FALCON_LEVEL5_SA_MAJOR;
9636
            output[1] = FALCON_LEVEL5_SA_MINOR;
9637
            break;
9638
#endif
9639
#ifdef WOLFSSL_HAVE_MLDSA
9640
        case mldsa_44_sa_algo:
9641
            output[0] = MLDSA_44_SA_MAJOR;
9642
            output[1] = MLDSA_44_SA_MINOR;
9643
            break;
9644
        case mldsa_65_sa_algo:
9645
            output[0] = MLDSA_65_SA_MAJOR;
9646
            output[1] = MLDSA_65_SA_MINOR;
9647
            break;
9648
        case mldsa_87_sa_algo:
9649
            output[0] = MLDSA_87_SA_MAJOR;
9650
            output[1] = MLDSA_87_SA_MINOR;
9651
            break;
9652
#endif
9653
#ifdef WOLFSSL_HAVE_SLHDSA
9654
    #if defined(WOLFSSL_SLHDSA_SHA2) && defined(WOLFSSL_SLHDSA_PARAM_SHA2_128S)
9655
        case slhdsa_sha2_128s_sa_algo:
9656
            output[0] = SLHDSA_SA_MAJOR;
9657
            output[1] = SLHDSA_SHA2_128S_SA_MINOR;
9658
            break;
9659
    #endif
9660
    #if defined(WOLFSSL_SLHDSA_SHA2) && defined(WOLFSSL_SLHDSA_PARAM_SHA2_128F)
9661
        case slhdsa_sha2_128f_sa_algo:
9662
            output[0] = SLHDSA_SA_MAJOR;
9663
            output[1] = SLHDSA_SHA2_128F_SA_MINOR;
9664
            break;
9665
    #endif
9666
    #if defined(WOLFSSL_SLHDSA_SHA2) && defined(WOLFSSL_SLHDSA_PARAM_SHA2_192S)
9667
        case slhdsa_sha2_192s_sa_algo:
9668
            output[0] = SLHDSA_SA_MAJOR;
9669
            output[1] = SLHDSA_SHA2_192S_SA_MINOR;
9670
            break;
9671
    #endif
9672
    #if defined(WOLFSSL_SLHDSA_SHA2) && defined(WOLFSSL_SLHDSA_PARAM_SHA2_192F)
9673
        case slhdsa_sha2_192f_sa_algo:
9674
            output[0] = SLHDSA_SA_MAJOR;
9675
            output[1] = SLHDSA_SHA2_192F_SA_MINOR;
9676
            break;
9677
    #endif
9678
    #if defined(WOLFSSL_SLHDSA_SHA2) && defined(WOLFSSL_SLHDSA_PARAM_SHA2_256S)
9679
        case slhdsa_sha2_256s_sa_algo:
9680
            output[0] = SLHDSA_SA_MAJOR;
9681
            output[1] = SLHDSA_SHA2_256S_SA_MINOR;
9682
            break;
9683
    #endif
9684
    #if defined(WOLFSSL_SLHDSA_SHA2) && defined(WOLFSSL_SLHDSA_PARAM_SHA2_256F)
9685
        case slhdsa_sha2_256f_sa_algo:
9686
            output[0] = SLHDSA_SA_MAJOR;
9687
            output[1] = SLHDSA_SHA2_256F_SA_MINOR;
9688
            break;
9689
    #endif
9690
    #ifdef WOLFSSL_SLHDSA_PARAM_128S
9691
        case slhdsa_shake_128s_sa_algo:
9692
            output[0] = SLHDSA_SA_MAJOR;
9693
            output[1] = SLHDSA_SHAKE_128S_SA_MINOR;
9694
            break;
9695
    #endif
9696
    #ifdef WOLFSSL_SLHDSA_PARAM_128F
9697
        case slhdsa_shake_128f_sa_algo:
9698
            output[0] = SLHDSA_SA_MAJOR;
9699
            output[1] = SLHDSA_SHAKE_128F_SA_MINOR;
9700
            break;
9701
    #endif
9702
    #ifdef WOLFSSL_SLHDSA_PARAM_192S
9703
        case slhdsa_shake_192s_sa_algo:
9704
            output[0] = SLHDSA_SA_MAJOR;
9705
            output[1] = SLHDSA_SHAKE_192S_SA_MINOR;
9706
            break;
9707
    #endif
9708
    #ifdef WOLFSSL_SLHDSA_PARAM_192F
9709
        case slhdsa_shake_192f_sa_algo:
9710
            output[0] = SLHDSA_SA_MAJOR;
9711
            output[1] = SLHDSA_SHAKE_192F_SA_MINOR;
9712
            break;
9713
    #endif
9714
    #ifdef WOLFSSL_SLHDSA_PARAM_256S
9715
        case slhdsa_shake_256s_sa_algo:
9716
            output[0] = SLHDSA_SA_MAJOR;
9717
            output[1] = SLHDSA_SHAKE_256S_SA_MINOR;
9718
            break;
9719
    #endif
9720
    #ifdef WOLFSSL_SLHDSA_PARAM_256F
9721
        case slhdsa_shake_256f_sa_algo:
9722
            output[0] = SLHDSA_SA_MAJOR;
9723
            output[1] = SLHDSA_SHAKE_256F_SA_MINOR;
9724
            break;
9725
    #endif
9726
#endif /* WOLFSSL_HAVE_SLHDSA */
9727
0
        default:
9728
0
            break;
9729
0
    }
9730
0
}
9731
#endif
9732
9733
#if !defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
9734
    defined(HAVE_ED448) || defined(HAVE_FALCON) || defined(WOLFSSL_HAVE_MLDSA) || \
9735
    defined(WOLFSSL_HAVE_SLHDSA)
9736
#ifdef WOLFSSL_DUAL_ALG_CERTS
9737
/* These match up with what the OQS team has defined. */
9738
#define HYBRID_SA_MAJOR 0xFE
9739
#define HYBRID_P256_MLDSA_44_SA_MINOR            0xA1
9740
#define HYBRID_RSA3072_MLDSA_44_SA_MINOR         0xA2
9741
#define HYBRID_P384_MLDSA_65_SA_MINOR            0xA4
9742
#define HYBRID_P521_MLDSA_87_SA_MINOR            0xA6
9743
/* Falcon hybrid codepoints aligned with oqs-provider. */
9744
#define HYBRID_P256_FALCON_LEVEL1_SA_MINOR       0xD8
9745
#define HYBRID_RSA3072_FALCON_LEVEL1_SA_MINOR    0xD9
9746
#define HYBRID_P521_FALCON_LEVEL5_SA_MINOR       0xDB
9747
9748
/* Custom defined ones for PQC first */
9749
#define HYBRID_MLDSA_44_P256_SA_MINOR            0xD1
9750
#define HYBRID_MLDSA_44_RSA3072_SA_MINOR         0xD2
9751
#define HYBRID_MLDSA_65_P384_SA_MINOR            0xD3
9752
#define HYBRID_MLDSA_87_P521_SA_MINOR            0xD4
9753
#define HYBRID_FALCON_LEVEL1_P256_SA_MINOR       0xD5
9754
#define HYBRID_FALCON_LEVEL1_RSA3072_SA_MINOR    0xD6
9755
#define HYBRID_FALCON_LEVEL5_P521_SA_MINOR       0xD7
9756
9757
9758
static void EncodeDualSigAlg(byte sigAlg, byte altSigAlg, byte* output)
9759
{
9760
    /* Initialize output to error indicator. */
9761
    output[0] = 0x0;
9762
    output[1] = 0x0;
9763
9764
    if (sigAlg == ecc_dsa_sa_algo && altSigAlg == mldsa_44_sa_algo) {
9765
        output[1] = HYBRID_P256_MLDSA_44_SA_MINOR;
9766
    }
9767
    else if (sigAlg == rsa_pss_sa_algo &&
9768
             altSigAlg == mldsa_44_sa_algo) {
9769
        output[1] = HYBRID_RSA3072_MLDSA_44_SA_MINOR;
9770
    }
9771
    else if (sigAlg == ecc_dsa_sa_algo &&
9772
             altSigAlg == mldsa_65_sa_algo) {
9773
        output[1] = HYBRID_P384_MLDSA_65_SA_MINOR;
9774
    }
9775
    else if (sigAlg == ecc_dsa_sa_algo &&
9776
             altSigAlg == mldsa_87_sa_algo) {
9777
        output[1] = HYBRID_P521_MLDSA_87_SA_MINOR;
9778
    }
9779
    else if (sigAlg == ecc_dsa_sa_algo &&
9780
             altSigAlg == falcon_level1_sa_algo) {
9781
        output[1] = HYBRID_P256_FALCON_LEVEL1_SA_MINOR;
9782
    }
9783
    else if (sigAlg == rsa_pss_sa_algo &&
9784
             altSigAlg == falcon_level1_sa_algo) {
9785
        output[1] = HYBRID_RSA3072_FALCON_LEVEL1_SA_MINOR;
9786
    }
9787
    else if (sigAlg == ecc_dsa_sa_algo &&
9788
             altSigAlg == falcon_level5_sa_algo) {
9789
        output[1] = HYBRID_P521_FALCON_LEVEL5_SA_MINOR;
9790
    }
9791
    else if (sigAlg == mldsa_44_sa_algo &&
9792
             altSigAlg == ecc_dsa_sa_algo) {
9793
        output[1] = HYBRID_MLDSA_44_P256_SA_MINOR;
9794
    }
9795
    else if (sigAlg == mldsa_44_sa_algo &&
9796
             altSigAlg == rsa_pss_sa_algo) {
9797
        output[1] = HYBRID_MLDSA_44_RSA3072_SA_MINOR;
9798
    }
9799
    else if (sigAlg == mldsa_65_sa_algo &&
9800
             altSigAlg == ecc_dsa_sa_algo) {
9801
        output[1] = HYBRID_MLDSA_65_P384_SA_MINOR;
9802
    }
9803
    else if (sigAlg == mldsa_87_sa_algo &&
9804
             altSigAlg == ecc_dsa_sa_algo) {
9805
        output[1] = HYBRID_MLDSA_87_P521_SA_MINOR;
9806
    }
9807
    else if (sigAlg == falcon_level1_sa_algo &&
9808
             altSigAlg == ecc_dsa_sa_algo) {
9809
        output[1] = HYBRID_FALCON_LEVEL1_P256_SA_MINOR;
9810
    }
9811
    else if (sigAlg == falcon_level1_sa_algo &&
9812
             altSigAlg == rsa_pss_sa_algo) {
9813
        output[1] = HYBRID_FALCON_LEVEL1_RSA3072_SA_MINOR;
9814
    }
9815
    else if (sigAlg == falcon_level5_sa_algo &&
9816
             altSigAlg == ecc_dsa_sa_algo) {
9817
        output[1] = HYBRID_FALCON_LEVEL5_P521_SA_MINOR;
9818
    }
9819
9820
    if (output[1] != 0x0) {
9821
        output[0] = HYBRID_SA_MAJOR;
9822
    }
9823
}
9824
#endif /* WOLFSSL_DUAL_ALG_CERTS */
9825
9826
static enum wc_MACAlgorithm GetNewSAHashAlgo(int typeIn)
9827
0
{
9828
0
    switch (typeIn) {
9829
0
        case RSA_PSS_RSAE_SHA256_MINOR:
9830
0
        case RSA_PSS_PSS_SHA256_MINOR:
9831
0
        case ECDSA_BRAINPOOLP256R1TLS13_SHA256_MINOR:
9832
0
            return sha256_mac;
9833
9834
0
        case RSA_PSS_RSAE_SHA384_MINOR:
9835
0
        case RSA_PSS_PSS_SHA384_MINOR:
9836
0
        case ECDSA_BRAINPOOLP384R1TLS13_SHA384_MINOR:
9837
0
            return sha384_mac;
9838
9839
0
        case RSA_PSS_RSAE_SHA512_MINOR:
9840
0
        case RSA_PSS_PSS_SHA512_MINOR:
9841
0
        case ED25519_SA_MINOR:
9842
0
        case ED448_SA_MINOR:
9843
0
        case ECDSA_BRAINPOOLP512R1TLS13_SHA512_MINOR:
9844
0
            return sha512_mac;
9845
0
        default:
9846
0
            return no_mac;
9847
0
    }
9848
0
}
9849
9850
/* Decode the signature algorithm.
9851
 *
9852
 * input     The encoded signature algorithm.
9853
 * hashalgo  The hash algorithm.
9854
 * hsType    The signature type.
9855
 * returns INVALID_PARAMETER if not recognized and 0 otherwise.
9856
 */
9857
static WC_INLINE int DecodeTls13SigAlg(byte* input, byte* hashAlgo,
9858
                                       byte* hsType)
9859
0
{
9860
0
    int ret = 0;
9861
#if defined(WOLFSSL_HAVE_SLHDSA)
9862
    byte slhType;
9863
#endif
9864
9865
0
    switch (input[0]) {
9866
    #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
9867
        case SM2_SA_MAJOR:
9868
            if (input[1] == SM2_SA_MINOR) {
9869
                *hsType = sm2_sa_algo;
9870
                *hashAlgo = sm3_mac;
9871
            }
9872
            else
9873
                ret = INVALID_PARAMETER;
9874
            break;
9875
    #endif
9876
0
        case NEW_SA_MAJOR:
9877
0
        {
9878
0
            enum wc_MACAlgorithm mac = GetNewSAHashAlgo(input[1]);
9879
0
            *hashAlgo = (byte)mac;
9880
0
        }
9881
9882
            /* PSS encryption: 0x080[4-6] */
9883
0
            if (input[1] >= RSA_PSS_RSAE_SHA256_MINOR &&
9884
0
                    input[1] <= RSA_PSS_RSAE_SHA512_MINOR) {
9885
0
                *hsType   = input[0];
9886
0
            }
9887
            /* PSS signature: 0x080[9-B] */
9888
0
            else if (input[1] >= RSA_PSS_PSS_SHA256_MINOR &&
9889
0
                    input[1] <= RSA_PSS_PSS_SHA512_MINOR) {
9890
0
                *hsType   = input[0];
9891
0
            }
9892
    #ifdef HAVE_ED25519
9893
            /* ED25519: 0x0807 */
9894
            else if (input[1] == ED25519_SA_MINOR) {
9895
                *hsType = ed25519_sa_algo;
9896
                /* Hash performed as part of sign/verify operation. */
9897
            }
9898
    #endif
9899
    #ifdef HAVE_ED448
9900
            /* ED448: 0x0808 */
9901
            else if (input[1] == ED448_SA_MINOR) {
9902
                *hsType = ed448_sa_algo;
9903
                /* Hash performed as part of sign/verify operation. */
9904
            }
9905
    #endif
9906
    #ifdef HAVE_ECC_BRAINPOOL
9907
            else if ((input[1] == ECDSA_BRAINPOOLP256R1TLS13_SHA256_MINOR) ||
9908
                     (input[1] == ECDSA_BRAINPOOLP384R1TLS13_SHA384_MINOR) ||
9909
                     (input[1] == ECDSA_BRAINPOOLP512R1TLS13_SHA512_MINOR)) {
9910
                *hsType = ecc_dsa_sa_algo;
9911
            }
9912
    #endif
9913
0
            else
9914
0
                ret = INVALID_PARAMETER;
9915
0
            break;
9916
#if defined(HAVE_FALCON)
9917
        case FALCON_SA_MAJOR:
9918
            if (input[1] == FALCON_LEVEL1_SA_MINOR) {
9919
                *hsType = falcon_level1_sa_algo;
9920
                /* Hash performed as part of sign/verify operation. */
9921
                *hashAlgo = sha512_mac;
9922
            } else if (input[1] == FALCON_LEVEL5_SA_MINOR) {
9923
                *hsType = falcon_level5_sa_algo;
9924
                /* Hash performed as part of sign/verify operation. */
9925
                *hashAlgo = sha512_mac;
9926
            }
9927
            else
9928
                ret = INVALID_PARAMETER;
9929
            break;
9930
#endif /* HAVE_FALCON */
9931
#if defined(WOLFSSL_HAVE_MLDSA) || defined(WOLFSSL_HAVE_SLHDSA)
9932
        /* ML-DSA and SLH-DSA share the same major byte (0x09); their minor
9933
         * bytes are disjoint (ML-DSA 0x04-0x06, SLH-DSA 0x11-0x1C). */
9934
        case MLDSA_SA_MAJOR:
9935
            ret = INVALID_PARAMETER;
9936
    #if defined(WOLFSSL_HAVE_MLDSA)
9937
            if (input[1] == MLDSA_44_SA_MINOR) {
9938
                *hsType = mldsa_44_sa_algo;
9939
                /* Hash performed as part of sign/verify operation. */
9940
                *hashAlgo = sha512_mac;
9941
                ret = 0;
9942
            } else if (input[1] == MLDSA_65_SA_MINOR) {
9943
                *hsType = mldsa_65_sa_algo;
9944
                *hashAlgo = sha512_mac;
9945
                ret = 0;
9946
            } else if (input[1] == MLDSA_87_SA_MINOR) {
9947
                *hsType = mldsa_87_sa_algo;
9948
                *hashAlgo = sha512_mac;
9949
                ret = 0;
9950
            }
9951
    #endif /* WOLFSSL_HAVE_MLDSA */
9952
    #if defined(WOLFSSL_HAVE_SLHDSA)
9953
            if (ret != 0) {
9954
                slhType = SlhDsaSigMinorToType(input[1]);
9955
                if (slhType != (byte)invalid_sa_algo) {
9956
                    *hsType = slhType;
9957
                    /* Hash performed as part of sign/verify operation. */
9958
                    *hashAlgo = sha512_mac;
9959
                    ret = 0;
9960
                }
9961
            }
9962
    #endif /* WOLFSSL_HAVE_SLHDSA */
9963
            break;
9964
#endif /* WOLFSSL_HAVE_MLDSA || WOLFSSL_HAVE_SLHDSA */
9965
0
        default:
9966
0
            *hashAlgo = input[0];
9967
0
            *hsType   = input[1];
9968
0
            break;
9969
0
    }
9970
9971
0
    return ret;
9972
0
}
9973
9974
#ifdef WOLFSSL_DUAL_ALG_CERTS
9975
/* Decode the hybrid signature algorithm.
9976
 *
9977
 * input     The encoded signature algorithm.
9978
 * hashalgo  The hash algorithm.
9979
 * hsType    The signature type.
9980
 * returns INVALID_PARAMETER if not recognized and 0 otherwise.
9981
 */
9982
static WC_INLINE int DecodeTls13HybridSigAlg(byte* input, byte* hashAlg,
9983
                                             byte *sigAlg, byte *altSigAlg)
9984
{
9985
9986
    if (input[0] != HYBRID_SA_MAJOR) {
9987
        return INVALID_PARAMETER;
9988
    }
9989
9990
    if (input[1] == HYBRID_P256_MLDSA_44_SA_MINOR) {
9991
        *sigAlg = ecc_dsa_sa_algo;
9992
        *hashAlg = sha256_mac;
9993
        *altSigAlg = mldsa_44_sa_algo;
9994
    }
9995
    else if (input[1] == HYBRID_RSA3072_MLDSA_44_SA_MINOR) {
9996
        *sigAlg = rsa_pss_sa_algo;
9997
        *hashAlg = sha256_mac;
9998
        *altSigAlg = mldsa_44_sa_algo;
9999
    }
10000
    else if (input[1] == HYBRID_P384_MLDSA_65_SA_MINOR) {
10001
        *sigAlg = ecc_dsa_sa_algo;
10002
        *hashAlg = sha384_mac;
10003
        *altSigAlg = mldsa_65_sa_algo;
10004
    }
10005
    else if (input[1] == HYBRID_P521_MLDSA_87_SA_MINOR) {
10006
        *sigAlg = ecc_dsa_sa_algo;
10007
        *hashAlg = sha512_mac;
10008
        *altSigAlg = mldsa_87_sa_algo;
10009
    }
10010
    else if (input[1] == HYBRID_P256_FALCON_LEVEL1_SA_MINOR) {
10011
        *sigAlg = ecc_dsa_sa_algo;
10012
        *hashAlg = sha256_mac;
10013
        *altSigAlg = falcon_level1_sa_algo;
10014
    }
10015
    else if (input[1] == HYBRID_RSA3072_FALCON_LEVEL1_SA_MINOR) {
10016
        *sigAlg = rsa_pss_sa_algo;
10017
        *hashAlg = sha256_mac;
10018
        *altSigAlg = falcon_level1_sa_algo;
10019
    }
10020
    else if (input[1] == HYBRID_P521_FALCON_LEVEL5_SA_MINOR) {
10021
        *sigAlg = ecc_dsa_sa_algo;
10022
        *hashAlg = sha512_mac;
10023
        *altSigAlg = falcon_level5_sa_algo;
10024
    }
10025
    else if (input[1] == HYBRID_MLDSA_44_P256_SA_MINOR) {
10026
        *sigAlg = mldsa_44_sa_algo;
10027
        *hashAlg = sha256_mac;
10028
        *altSigAlg = ecc_dsa_sa_algo;
10029
    }
10030
    else if (input[1] == HYBRID_MLDSA_44_RSA3072_SA_MINOR) {
10031
        *sigAlg = mldsa_44_sa_algo;
10032
        *hashAlg = sha256_mac;
10033
        *altSigAlg = rsa_pss_sa_algo;
10034
    }
10035
    else if (input[1] == HYBRID_MLDSA_65_P384_SA_MINOR) {
10036
        *sigAlg = mldsa_65_sa_algo;
10037
        *hashAlg = sha384_mac;
10038
        *altSigAlg = ecc_dsa_sa_algo;
10039
    }
10040
    else if (input[1] == HYBRID_MLDSA_87_P521_SA_MINOR) {
10041
        *sigAlg = mldsa_87_sa_algo;
10042
        *hashAlg = sha512_mac;
10043
        *altSigAlg = ecc_dsa_sa_algo;
10044
    }
10045
    else if (input[1] == HYBRID_FALCON_LEVEL1_P256_SA_MINOR) {
10046
        *sigAlg = falcon_level1_sa_algo;
10047
        *hashAlg = sha256_mac;
10048
        *altSigAlg = ecc_dsa_sa_algo;
10049
    }
10050
    else if (input[1] == HYBRID_FALCON_LEVEL1_RSA3072_SA_MINOR) {
10051
        *sigAlg = falcon_level1_sa_algo;
10052
        *hashAlg = sha256_mac;
10053
        *altSigAlg = rsa_pss_sa_algo;
10054
    }
10055
    else if (input[1] == HYBRID_FALCON_LEVEL5_P521_SA_MINOR) {
10056
        *sigAlg = falcon_level5_sa_algo;
10057
        *hashAlg = sha512_mac;
10058
        *altSigAlg = ecc_dsa_sa_algo;
10059
    }
10060
    else {
10061
        return INVALID_PARAMETER;
10062
    }
10063
10064
    return 0;
10065
}
10066
#endif /* WOLFSSL_DUAL_ALG_CERTS */
10067
10068
/* Get the hash of the messages so far.
10069
 *
10070
 * ssl   The SSL/TLS object.
10071
 * hash  The buffer to write the hash to.
10072
 * returns the length of the hash.
10073
 */
10074
static WC_INLINE int GetMsgHash(WOLFSSL* ssl, byte* hash)
10075
0
{
10076
0
    int ret = 0;
10077
0
    switch (ssl->specs.mac_algorithm) {
10078
0
    #ifndef NO_SHA256
10079
0
        case sha256_mac:
10080
0
            ret = wc_Sha256GetHash(&ssl->hsHashes->hashSha256, hash);
10081
0
            if (ret == 0)
10082
0
                ret = WC_SHA256_DIGEST_SIZE;
10083
0
            break;
10084
0
    #endif /* !NO_SHA256 */
10085
0
    #ifdef WOLFSSL_SHA384
10086
0
        case sha384_mac:
10087
0
            ret = wc_Sha384GetHash(&ssl->hsHashes->hashSha384, hash);
10088
0
            if (ret == 0)
10089
0
                ret = WC_SHA384_DIGEST_SIZE;
10090
0
            break;
10091
0
    #endif /* WOLFSSL_SHA384 */
10092
    #ifdef WOLFSSL_TLS13_SHA512
10093
        case sha512_mac:
10094
            ret = wc_Sha512GetHash(&ssl->hsHashes->hashSha512, hash);
10095
            if (ret == 0)
10096
                ret = WC_SHA512_DIGEST_SIZE;
10097
            break;
10098
    #endif /* WOLFSSL_TLS13_SHA512 */
10099
    #ifdef WOLFSSL_SM3
10100
        case sm3_mac:
10101
            ret = wc_Sm3GetHash(&ssl->hsHashes->hashSm3, hash);
10102
            if (ret == 0)
10103
                ret = WC_SM3_DIGEST_SIZE;
10104
            break;
10105
    #endif /* WOLFSSL_SM3 */
10106
0
        default:
10107
0
            break;
10108
0
    }
10109
0
    return ret;
10110
0
}
10111
10112
/* The server certificate verification label. */
10113
static const byte serverCertVfyLabel[CERT_VFY_LABEL_SZ] =
10114
    "TLS 1.3, server CertificateVerify";
10115
/* The client certificate verification label. */
10116
static const byte clientCertVfyLabel[CERT_VFY_LABEL_SZ] =
10117
    "TLS 1.3, client CertificateVerify";
10118
/* The prefix byte in the signature data. */
10119
#define SIGNING_DATA_PREFIX_BYTE   0x20
10120
10121
/* Create the signature data for TLS v1.3 certificate verification.
10122
 *
10123
 * ssl        The SSL/TLS object.
10124
 * sigData    The signature data.
10125
 * sigDataSz  The length of the signature data.
10126
 * check      Indicates this is a check not create.
10127
 */
10128
int CreateSigData(WOLFSSL* ssl, byte* sigData, word16* sigDataSz,
10129
                  int check)
10130
0
{
10131
0
    word16 idx;
10132
0
    int side = ssl->options.side;
10133
0
    int ret;
10134
10135
    /* Signature Data = Prefix | Label | Handshake Hash */
10136
0
    XMEMSET(sigData, SIGNING_DATA_PREFIX_BYTE, SIGNING_DATA_PREFIX_SZ);
10137
0
    idx = SIGNING_DATA_PREFIX_SZ;
10138
10139
0
    if ((side == WOLFSSL_SERVER_END && check) ||
10140
0
        (side == WOLFSSL_CLIENT_END && !check)) {
10141
0
        XMEMCPY(&sigData[idx], clientCertVfyLabel, CERT_VFY_LABEL_SZ);
10142
0
    }
10143
0
    if ((side == WOLFSSL_CLIENT_END && check) ||
10144
0
        (side == WOLFSSL_SERVER_END && !check)) {
10145
0
        XMEMCPY(&sigData[idx], serverCertVfyLabel, CERT_VFY_LABEL_SZ);
10146
0
    }
10147
0
    idx += CERT_VFY_LABEL_SZ;
10148
10149
0
    ret = GetMsgHash(ssl, &sigData[idx]);
10150
0
    if (ret < 0)
10151
0
        return ret;
10152
0
    if (ret == 0)
10153
0
        return HASH_TYPE_E;
10154
10155
0
    *sigDataSz = (word16)(idx + ret);
10156
0
    ret = 0;
10157
10158
0
    return ret;
10159
0
}
10160
10161
#ifndef NO_RSA
10162
/* Encode the PKCS #1.5 RSA signature.
10163
 *
10164
 * sig        The buffer to place the encoded signature into.
10165
 * sigData    The data to be signed.
10166
 * sigDataSz  The size of the data to be signed.
10167
 * hashAlgo   The hash algorithm to use when signing.
10168
 * returns the length of the encoded signature or negative on error.
10169
 */
10170
int CreateRSAEncodedSig(byte* sig, byte* sigData, int sigDataSz,
10171
                        int sigAlgo, int hashAlgo)
10172
0
{
10173
0
    Digest digest;
10174
0
    int    hashSz = 0;
10175
0
    int    ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG);
10176
0
    byte*  hash;
10177
10178
0
    (void)sigAlgo;
10179
10180
0
    hash = sig;
10181
10182
    /* Digest the signature data. */
10183
0
    switch (hashAlgo) {
10184
0
#ifndef NO_SHA256
10185
0
        case sha256_mac:
10186
0
            ret = wc_InitSha256(&digest.sha256);
10187
0
            if (ret == 0) {
10188
0
                ret = wc_Sha256Update(&digest.sha256, sigData, (word32)sigDataSz);
10189
0
                if (ret == 0)
10190
0
                    ret = wc_Sha256Final(&digest.sha256, hash);
10191
0
                wc_Sha256Free(&digest.sha256);
10192
0
            }
10193
0
            hashSz = WC_SHA256_DIGEST_SIZE;
10194
0
            break;
10195
0
#endif
10196
0
#ifdef WOLFSSL_SHA384
10197
0
        case sha384_mac:
10198
0
            ret = wc_InitSha384(&digest.sha384);
10199
0
            if (ret == 0) {
10200
0
                ret = wc_Sha384Update(&digest.sha384, sigData, (word32)sigDataSz);
10201
0
                if (ret == 0)
10202
0
                    ret = wc_Sha384Final(&digest.sha384, hash);
10203
0
                wc_Sha384Free(&digest.sha384);
10204
0
            }
10205
0
            hashSz = WC_SHA384_DIGEST_SIZE;
10206
0
            break;
10207
0
#endif
10208
0
#ifdef WOLFSSL_SHA512
10209
0
        case sha512_mac:
10210
0
            ret = wc_InitSha512(&digest.sha512);
10211
0
            if (ret == 0) {
10212
0
                ret = wc_Sha512Update(&digest.sha512, sigData, (word32)sigDataSz);
10213
0
                if (ret == 0)
10214
0
                    ret = wc_Sha512Final(&digest.sha512, hash);
10215
0
                wc_Sha512Free(&digest.sha512);
10216
0
            }
10217
0
            hashSz = WC_SHA512_DIGEST_SIZE;
10218
0
            break;
10219
0
#endif
10220
0
       default:
10221
0
            ret = BAD_FUNC_ARG;
10222
0
            break;
10223
10224
0
    }
10225
10226
0
    if (ret != 0)
10227
0
        return ret;
10228
10229
0
    return hashSz;
10230
0
}
10231
#endif /* !NO_RSA */
10232
10233
#ifdef HAVE_ECC
10234
/* Encode the ECC signature.
10235
 *
10236
 * sigData    The data to be signed.
10237
 * sigDataSz  The size of the data to be signed.
10238
 * hashAlgo   The hash algorithm to use when signing.
10239
 * returns the length of the encoded signature or negative on error.
10240
 */
10241
static int CreateECCEncodedSig(byte* sigData, int sigDataSz, int hashAlgo)
10242
0
{
10243
0
    Digest digest;
10244
0
    int    hashSz = 0;
10245
0
    int    ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG);
10246
10247
    /* Digest the signature data. */
10248
0
    switch (hashAlgo) {
10249
0
#ifndef NO_SHA256
10250
0
        case sha256_mac:
10251
0
            ret = wc_InitSha256(&digest.sha256);
10252
0
            if (ret == 0) {
10253
0
                ret = wc_Sha256Update(&digest.sha256, sigData, (word32)sigDataSz);
10254
0
                if (ret == 0)
10255
0
                    ret = wc_Sha256Final(&digest.sha256, sigData);
10256
0
                wc_Sha256Free(&digest.sha256);
10257
0
            }
10258
0
            hashSz = WC_SHA256_DIGEST_SIZE;
10259
0
            break;
10260
0
#endif
10261
0
#ifdef WOLFSSL_SHA384
10262
0
        case sha384_mac:
10263
0
            ret = wc_InitSha384(&digest.sha384);
10264
0
            if (ret == 0) {
10265
0
                ret = wc_Sha384Update(&digest.sha384, sigData, (word32)sigDataSz);
10266
0
                if (ret == 0)
10267
0
                    ret = wc_Sha384Final(&digest.sha384, sigData);
10268
0
                wc_Sha384Free(&digest.sha384);
10269
0
            }
10270
0
            hashSz = WC_SHA384_DIGEST_SIZE;
10271
0
            break;
10272
0
#endif
10273
0
#ifdef WOLFSSL_SHA512
10274
0
        case sha512_mac:
10275
0
            ret = wc_InitSha512(&digest.sha512);
10276
0
            if (ret == 0) {
10277
0
                ret = wc_Sha512Update(&digest.sha512, sigData, (word32)sigDataSz);
10278
0
                if (ret == 0)
10279
0
                    ret = wc_Sha512Final(&digest.sha512, sigData);
10280
0
                wc_Sha512Free(&digest.sha512);
10281
0
            }
10282
0
            hashSz = WC_SHA512_DIGEST_SIZE;
10283
0
            break;
10284
0
#endif
10285
0
        default:
10286
0
            ret = BAD_FUNC_ARG;
10287
0
            break;
10288
0
    }
10289
10290
0
    if (ret != 0)
10291
0
        return ret;
10292
10293
0
    return hashSz;
10294
0
}
10295
#endif /* HAVE_ECC */
10296
10297
#if !defined(NO_RSA) && defined(WC_RSA_PSS)
10298
/* Check that the decrypted signature matches the encoded signature
10299
 * based on the digest of the signature data.
10300
 *
10301
 * ssl       The SSL/TLS object.
10302
 * sigAlgo   The signature algorithm used to generate signature.
10303
 * hashAlgo  The hash algorithm used to generate signature.
10304
 * decSig    The decrypted signature.
10305
 * decSigSz  The size of the decrypted signature.
10306
 * returns 0 on success, otherwise failure.
10307
 */
10308
static int CheckRSASignature(WOLFSSL* ssl, int sigAlgo, int hashAlgo,
10309
                             byte* decSig, word32 decSigSz)
10310
0
{
10311
0
    int    ret = 0;
10312
0
    byte   sigData[MAX_SIG_DATA_SZ];
10313
0
    word16 sigDataSz;
10314
10315
0
    ret = CreateSigData(ssl, sigData, &sigDataSz, 1);
10316
0
    if (ret != 0)
10317
0
        return ret;
10318
10319
0
    if (sigAlgo == rsa_pss_sa_algo) {
10320
0
        enum wc_HashType hashType = WC_HASH_TYPE_NONE;
10321
0
        word32 sigSz;
10322
10323
0
        ret = ConvertHashPss(hashAlgo, &hashType, NULL);
10324
0
        if (ret < 0)
10325
0
            return ret;
10326
10327
        /* PSS signature can be done in-place */
10328
0
        ret = CreateRSAEncodedSig(sigData, sigData, sigDataSz,
10329
0
                                  sigAlgo, hashAlgo);
10330
0
        if (ret < 0)
10331
0
            return ret;
10332
0
        sigSz = (word32)ret;
10333
10334
0
        ret = wc_RsaPSS_CheckPadding(sigData, sigSz, decSig, decSigSz,
10335
0
                                     hashType);
10336
0
    }
10337
10338
0
    return ret;
10339
0
}
10340
#endif /* !NO_RSA && WC_RSA_PSS */
10341
#endif /* !NO_RSA || HAVE_ECC */
10342
10343
#if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER)
10344
/* Get the next certificate from the list for writing into the TLS v1.3
10345
 * Certificate message.
10346
 *
10347
 * data    The certificate list.
10348
 * length  The length of the certificate data in the list.
10349
 * idx     The index of the next certificate.
10350
 * returns the length of the certificate data. 0 indicates no more certificates
10351
 * in the list.
10352
 */
10353
static word32 NextCert(byte* data, word32 length, word32* idx)
10354
0
{
10355
0
    word32 len;
10356
10357
    /* Would index read past end of list? */
10358
0
    if (*idx + 3 > length)
10359
0
        return 0;
10360
10361
    /* Length of the current ASN.1 encoded certificate. */
10362
0
    c24to32(data + *idx, &len);
10363
    /* Include the length field. */
10364
0
    len += 3;
10365
10366
    /* Ensure len does not overrun certificate list */
10367
0
    if (*idx + len > length)
10368
0
        return 0;
10369
10370
    /* Move index to next certificate and return the current certificate's
10371
     * length.
10372
     */
10373
0
    *idx += len;
10374
0
    return len;
10375
0
}
10376
10377
#if defined(HAVE_CERTIFICATE_STATUS_REQUEST) && !defined(NO_WOLFSSL_SERVER)
10378
/* Write certificate status request into certificate to buffer.
10379
 *
10380
 * ssl       SSL/TLS object.
10381
 * certExts  DerBuffer array. buffers written
10382
 * extSz     word32 array.
10383
 *           Length of the certificate status request data for the certificate.
10384
 * extSz_num number of the CSR written
10385
 * extIdx    The index number of certificate status request data
10386
 *           for the certificate.
10387
 * offset    index offset
10388
 * returns   Total number of bytes written on success or negative value on error.
10389
 */
10390
static int WriteCSRToBuffer(WOLFSSL* ssl, DerBuffer** certExts,
10391
                                word16* extSz,  word16 extSz_num)
10392
{
10393
    int    ret = 0;
10394
    TLSX* ext;
10395
    CertificateStatusRequest* csr;
10396
    word32 ex_offset = HELLO_EXT_TYPE_SZ + OPAQUE16_LEN /* extension type */
10397
                    + OPAQUE16_LEN /* extension length */;
10398
    word32 totalSz = 0;
10399
    word32 tmpSz;
10400
    word32 extIdx;
10401
    DerBuffer* der;
10402
10403
    if (extSz_num > MAX_CERT_EXTENSIONS)
10404
        return MAX_CERT_EXTENSIONS_ERR;
10405
10406
    ext = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST);
10407
    csr = ext ? (CertificateStatusRequest*)ext->data : NULL;
10408
10409
    if (csr) {
10410
        for (extIdx = 0; extIdx < (word16)(extSz_num); extIdx++) {
10411
            tmpSz = TLSX_CSR_GetSize_ex(csr, 0, (int)extIdx);
10412
10413
            if (ssl->fragOffset != 0 && certExts[extIdx] != NULL) {
10414
                /* A fragmented send is being resumed and this buffer was
10415
                 * written by the earlier call. extSz starts over on every
10416
                 * call, so recover this entry's size from the length written
10417
                 * into the buffer. */
10418
                ato16(certExts[extIdx]->buffer, &extSz[extIdx]);
10419
                extSz[extIdx] += OPAQUE16_LEN;
10420
            }
10421
            else {
10422
                /* Not a resume, so anything still allocated here is left over
10423
                 * from a completed message and must not be reused. */
10424
                FreeDer(&certExts[extIdx]);
10425
10426
                if (tmpSz > (OPAQUE8_LEN + OPAQUE24_LEN)) {
10427
                    /* csr extension is not zero */
10428
                    if (tmpSz > WOLFSSL_MAX_16BIT)
10429
                        return BUFFER_E;
10430
                    extSz[extIdx] = (word16)tmpSz;
10431
10432
                    ret = AllocDer(&certExts[extIdx], extSz[extIdx] + ex_offset,
10433
                                                        CERT_TYPE, ssl->heap);
10434
                    if (ret < 0)
10435
                        return ret;
10436
                    der = certExts[extIdx];
10437
10438
                    /* write extension type */
10439
                    c16toa(ext->type, der->buffer
10440
                                    + OPAQUE16_LEN);
10441
                    /* writes extension data length. */
10442
                    c16toa(extSz[extIdx], der->buffer
10443
                                + HELLO_EXT_TYPE_SZ + OPAQUE16_LEN);
10444
                    /* write extension data */
10445
                    extSz[extIdx] = (word16)TLSX_CSR_Write_ex(csr,
10446
                            der->buffer + ex_offset, 0, extIdx);
10447
                    /* add extension offset */
10448
                    extSz[extIdx] += (word16)ex_offset;
10449
                    /* extension length */
10450
                    c16toa(extSz[extIdx] - OPAQUE16_LEN,
10451
                                der->buffer);
10452
                }
10453
            }
10454
            totalSz += extSz[extIdx];
10455
        }
10456
    }
10457
    else {
10458
        /* chain cert empty extension size */
10459
        totalSz += OPAQUE16_LEN * extSz_num;
10460
    }
10461
    return (int)totalSz;
10462
}
10463
#endif /* HAVE_CERTIFICATE_STATUS_REQUEST */
10464
/* Add certificate data and empty extension to output up to the fragment size.
10465
 *
10466
 * ssl     SSL/TLS object.
10467
 * cert    The certificate data to write out.
10468
 * len     The length of the certificate data.
10469
 * extSz   Length of the extension data with the certificate.
10470
 * idx     The start of the certificate data to write out.
10471
 * fragSz  The maximum size of this fragment.
10472
 * output  The buffer to write to.
10473
 * extIdx  The index number of the extension data with the certificate
10474
 * returns the number of bytes written.
10475
 */
10476
static word32 AddCertExt(WOLFSSL* ssl, byte* cert, word32 len, word16 extSz,
10477
                         word32 idx, word32 fragSz, byte* output, word16 extIdx)
10478
0
{
10479
0
    word32 i = 0;
10480
0
    word32 copySz = min(len - idx, fragSz);
10481
10482
0
    if (idx < len) {
10483
0
        XMEMCPY(output, cert + idx, copySz);
10484
0
        i = copySz;
10485
0
        if (copySz == fragSz)
10486
0
            return i;
10487
0
    }
10488
0
    copySz = len + extSz - idx - i;
10489
10490
0
    if (extSz == OPAQUE16_LEN) {
10491
0
        if (copySz <= fragSz) {
10492
            /* Empty extension */
10493
0
            output[i++] = 0;
10494
0
            output[i++] = 0;
10495
0
        }
10496
0
    }
10497
0
    else {
10498
0
        byte* certExts = ssl->buffers.certExts[extIdx]->buffer + idx + i - len;
10499
        /* Put out as much of the extensions' data as will fit in fragment. */
10500
0
        if (copySz > fragSz - i)
10501
0
            copySz = fragSz - i;
10502
0
        XMEMCPY(output + i, certExts, copySz);
10503
0
        i += copySz;
10504
0
    }
10505
10506
0
    return i;
10507
0
}
10508
10509
#if defined(HAVE_CERTIFICATE_STATUS_REQUEST) && !defined(NO_WOLFSSL_SERVER)
10510
static int SetupOcspResp(WOLFSSL* ssl)
10511
{
10512
    DecodedCert* cert = NULL;
10513
    CertificateStatusRequest* csr = NULL;
10514
    TLSX* extension = NULL;
10515
    int ret = 0;
10516
    OcspRequest* request = NULL;
10517
10518
    extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST);
10519
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
10520
    /* During post-handshake client authentication the client must staple
10521
     * its own OCSP response, but the status_request extension it offered in
10522
     * the initial ClientHello is no longer present on ssl->extensions.
10523
     * Recreate it here (the request extension still lives on
10524
     * ctx->extensions). Pass ssl so csr->ssl is set, which the response
10525
     * size/write path requires. */
10526
    if (extension == NULL &&
10527
            ssl->options.side == WOLFSSL_CLIENT_END &&
10528
            ssl->options.handShakeDone &&
10529
            TLSX_Find(ssl->ctx->extensions, TLSX_STATUS_REQUEST) != NULL) {
10530
        ret = TLSX_UseCertificateStatusRequest(&ssl->extensions,
10531
                WOLFSSL_CSR_OCSP, 0, ssl, ssl->heap, ssl->devId);
10532
        if (ret != WOLFSSL_SUCCESS)
10533
            return ret;
10534
        extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST);
10535
    }
10536
#endif
10537
    if (extension == NULL)
10538
        return 0; /* peer didn't signal ocsp support */
10539
    csr = (CertificateStatusRequest*)extension->data;
10540
    if (csr == NULL)
10541
        return MEMORY_ERROR;
10542
10543
    if (SSL_CM(ssl) != NULL &&
10544
            SSL_CM(ssl)->ocsp_stapling != NULL &&
10545
            SSL_CM(ssl)->ocsp_stapling->statusCb != NULL) {
10546
        return TLSX_CSR_SetResponseWithStatusCB(ssl);
10547
    }
10548
10549
    if (ssl->buffers.certificate == NULL) {
10550
        WOLFSSL_MSG("Certificate buffer not set!");
10551
        return BUFFER_ERROR;
10552
    }
10553
    cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), ssl->heap,
10554
                                 DYNAMIC_TYPE_DCERT);
10555
    if (cert == NULL) {
10556
        return MEMORY_E;
10557
    }
10558
    InitDecodedCert(cert, ssl->buffers.certificate->buffer,
10559
                    ssl->buffers.certificate->length, ssl->heap);
10560
    ret = ParseCert(cert, CERT_TYPE, NO_VERIFY, SSL_CM(ssl));
10561
    if (ret != 0) {
10562
        FreeDecodedCert(cert);
10563
        XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
10564
        return ret;
10565
    }
10566
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
10567
    /* On client PHA the same certificate is re-stapled every round; reuse
10568
     * request slot 0 instead of appending, else csr->requests grows until
10569
     * MAX_CERT_EXTENSIONS_ERR. */
10570
    if (ssl->options.side == WOLFSSL_CLIENT_END && ssl->options.handShakeDone) {
10571
        ret = TLSX_CSR_InitRequest_ex(ssl->extensions, cert, ssl->heap, 0);
10572
    }
10573
    else
10574
#endif
10575
    {
10576
        ret = TLSX_CSR_InitRequest(ssl->extensions, cert, ssl->heap);
10577
    }
10578
    FreeDecodedCert(cert);
10579
    XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
10580
    if (ret != 0 )
10581
        return ret;
10582
10583
    /* Free previous OCSP response buffers to avoid leak on PHA reuse */
10584
    {
10585
        int j;
10586
        for (j = 0; j < MAX_CERT_EXTENSIONS; j++) {
10587
            XFREE(csr->responses[j].buffer, ssl->heap,
10588
                DYNAMIC_TYPE_TMP_BUFFER);
10589
            csr->responses[j].buffer = NULL;
10590
            csr->responses[j].length = 0;
10591
        }
10592
    }
10593
    request = &csr->request.ocsp[0];
10594
    ret = CreateOcspResponse(ssl, &request, &csr->responses[0]);
10595
    /* Only a successful call replaces "request", with one it built for us to
10596
     * free. */
10597
    if (ret == 0 && request != &csr->request.ocsp[0]) {
10598
        /* request was allocated in CreateOcspResponse() */
10599
        FreeOcspRequest(request);
10600
        XFREE(request, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST);
10601
    }
10602
    if (ret != 0)
10603
        return ret;
10604
10605
    if (csr->responses[0].buffer)
10606
        extension->resp = 1;
10607
#if defined(WOLFSSL_TLS_OCSP_MULTI)
10608
    /* process OCSP request in certificate chain */
10609
    if ((ret = ProcessChainOCSPRequest(ssl)) != 0) {
10610
        WOLFSSL_MSG("Process Cert Chain OCSP request failed");
10611
        WOLFSSL_ERROR_VERBOSE(ret);
10612
        return ret;
10613
    }
10614
#endif
10615
    return ret;
10616
}
10617
#endif
10618
10619
#if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
10620
/* Certificate is signed with the deprecated SHA-1 hash. An unrecognized or
10621
 * unparsable algorithm is not SHA-1; the peer still verifies the chain.
10622
 *
10623
 * der    Buffer holding the DER encoded certificate.
10624
 * derSz  Length of the DER encoded certificate.
10625
 * returns 1 when SHA-1 signed, 0 otherwise.
10626
 */
10627
static int IsSha1SignedCert(const byte* der, word32 derSz)
10628
0
{
10629
0
    word32 idx = 0;
10630
0
    word32 oid = 0;
10631
0
    word32 algoIdEnd = 0;
10632
0
    int    len = 0;
10633
0
    int    isSha1 = 0;
10634
0
    int    ret;
10635
0
#if defined(WC_RSA_PSS) && !defined(NO_RSA)
10636
0
    enum wc_HashType hash = WC_HASH_TYPE_NONE;
10637
0
    int    mgf = 0;
10638
0
    int    saltLen = 0;
10639
0
#endif
10640
10641
    /* Certificate ::= SEQUENCE { tbsCertificate, signatureAlgorithm, ... }.
10642
     * GetSequence() checks each length against the maximum index passed in, so
10643
     * idx and idx + len stay inside the buffer. */
10644
0
    ret = GetSequence(der, &idx, &len, derSz);
10645
0
    if (ret >= 0)
10646
0
        ret = GetSequence(der, &idx, &len, derSz);
10647
0
    if (ret >= 0) {
10648
        /* signatureAlgorithm immediately follows the tbsCertificate. Decode
10649
         * the AlgorithmIdentifier here rather than with GetAlgoId() so the
10650
         * RSASSA-PSS parameters, which hold the digest, stay reachable. */
10651
0
        idx += (word32)len;
10652
0
        ret = GetSequence(der, &idx, &len, derSz);
10653
0
    }
10654
0
    if (ret >= 0) {
10655
0
        algoIdEnd = idx + (word32)len;
10656
0
        ret = GetObjectId(der, &idx, &oid, oidSigType, algoIdEnd);
10657
0
    }
10658
0
    if (ret >= 0) {
10659
0
        if ((oid == CTC_SHAwRSA) || (oid == CTC_SHAwECDSA) ||
10660
0
                (oid == CTC_SHAwDSA)) {
10661
0
            isSha1 = 1;
10662
0
        }
10663
0
    #if defined(WC_RSA_PSS) && !defined(NO_RSA)
10664
        /* RSASSA-PSS uses one signature OID for every digest and names the
10665
         * digest in the algorithm parameters instead. Absent parameters are
10666
         * passed through as a zero length buffer rather than skipped: RFC 4055
10667
         * makes them mean all defaults, which is SHA-1, and
10668
         * wc_DecodeRsaPssParams() reports that. */
10669
0
        else if ((oid == RSAPSSk) && (idx <= algoIdEnd) &&
10670
0
                (wc_DecodeRsaPssParams(der + idx, algoIdEnd - idx, &hash, &mgf,
10671
0
                                       &saltLen) == 0)) {
10672
0
            isSha1 = (hash == WC_HASH_TYPE_SHA);
10673
0
        }
10674
0
    #endif
10675
0
    }
10676
10677
0
    return isSha1;
10678
0
}
10679
10680
/* Certificate is self issued. RFC 8446 Section 4.4.2.2: "Certificates that are
10681
 * self-signed or certificates that are expected to be trust anchors are not
10682
 * validated as part of the chain and therefore MAY be signed with any
10683
 * algorithm."
10684
 *
10685
 * The rule is applied to self-issued certificates (issuer name equals subject
10686
 * name), which is enough here: the chain is the one this end was configured
10687
 * with, not one an attacker supplies.
10688
 *
10689
 * The certificate is parsed as CA_TYPE rather than CERT_TYPE so a trust anchor
10690
 * carrying serial number 0 still decodes. ParseCertRelative() rejects a zero
10691
 * serial for CERT_TYPE, and legacy roots, the certificates most likely to be
10692
 * SHA-1 signed, are the ones that use it. With NO_VERIFY and no certificate
10693
 * manager the serial exemption is all the type changes, and that exemption
10694
 * still requires a self-issued CA, so a leaf carrying serial 0 is reported as
10695
 * not self issued and stays subject to the SHA-1 rule.
10696
 *
10697
 * ssl           The SSL/TLS object.
10698
 * der           Buffer holding the DER encoded certificate.
10699
 * derSz         Length of the DER encoded certificate.
10700
 * isSelfIssued  On success, 1 when self issued, 0 otherwise. A certificate
10701
 *               that will not parse is reported as not self issued so the
10702
 *               SHA-1 rule still applies to it.
10703
 * returns 0 on success, MEMORY_E when the decoder cannot be allocated.
10704
 */
10705
static int IsSelfIssuedCert(WOLFSSL* ssl, const byte* der, word32 derSz,
10706
                            int* isSelfIssued)
10707
0
{
10708
0
    DecodedCert* cert;
10709
10710
0
    *isSelfIssued = 0;
10711
10712
0
    cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), ssl->heap,
10713
0
                                 DYNAMIC_TYPE_DCERT);
10714
0
    if (cert == NULL)
10715
0
        return MEMORY_E;
10716
10717
0
    InitDecodedCert(cert, der, derSz, ssl->heap);
10718
0
    if (ParseCertRelative(cert, CA_TYPE, NO_VERIFY, NULL, NULL) == 0)
10719
0
        *isSelfIssued = (cert->selfIssued != 0);
10720
0
    else
10721
0
        WOLFSSL_MSG("Cannot decode certificate, not treating as self issued");
10722
0
    FreeDecodedCert(cert);
10723
0
    XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
10724
10725
0
    return 0;
10726
0
}
10727
10728
/* Check the chain about to be sent against what the peer advertised.
10729
 *
10730
 * RFC 8446 Section 4.4.2.2 permits a fallback chain the peer did not advertise
10731
 * support for, but the chain "MUST NOT" use SHA-1 unless the peer's
10732
 * advertisement permits it. Section 4.4.2.3 requires client certificates to be
10733
 * signed with an acceptable algorithm "as described in Section 4.4.2.2", so the
10734
 * same rule covers both sides. How a failure is resolved differs by side and is
10735
 * left to the caller.
10736
 *
10737
 * ssl  The SSL/TLS object.
10738
 * returns 0 when the chain may be sent, MATCH_SUITE_ERROR when it may not and
10739
 * MEMORY_E when a certificate could not be examined.
10740
 */
10741
static int CheckCertChainSigAlgo(WOLFSSL* ssl)
10742
0
{
10743
0
    byte*  chain;
10744
0
    byte*  cur;
10745
0
    word32 chainSz;
10746
0
    word32 len;
10747
0
    word32 idx = 0;
10748
0
    int    selfIssued = 0;
10749
0
    int    ret = 0;
10750
10751
0
    if (ssl->options.peerSha1CertOk)
10752
0
        return 0;
10753
10754
0
    if (ssl->buffers.certificate == NULL ||
10755
0
            ssl->buffers.certificate->buffer == NULL) {
10756
0
        return 0;
10757
0
    }
10758
10759
0
    if (IsSha1SignedCert(ssl->buffers.certificate->buffer,
10760
0
                         ssl->buffers.certificate->length)) {
10761
0
        ret = IsSelfIssuedCert(ssl, ssl->buffers.certificate->buffer,
10762
0
                               ssl->buffers.certificate->length, &selfIssued);
10763
0
        if (ret != 0)
10764
0
            return ret;
10765
0
        if (!selfIssued)
10766
0
            ret = MATCH_SUITE_ERROR;
10767
0
    }
10768
10769
0
    if (ret == 0 && ssl->buffers.certChain != NULL &&
10770
0
            ssl->buffers.certChain->buffer != NULL &&
10771
0
            ssl->buffers.certChainCnt > 0) {
10772
0
        chain = ssl->buffers.certChain->buffer;
10773
0
        chainSz = ssl->buffers.certChain->length;
10774
10775
0
        while (ret == 0) {
10776
0
            cur = chain + idx;
10777
            /* NextCert() length includes the CERT_HEADER_SZ byte prefix and
10778
             * is 0 at the end of the list. Keep this terminator matching the
10779
             * send loop so both walk the same certificates. */
10780
0
            len = NextCert(chain, chainSz, &idx);
10781
0
            if (len == 0)
10782
0
                break;
10783
0
            if (len <= CERT_HEADER_SZ)
10784
0
                continue;
10785
0
            cur += CERT_HEADER_SZ;
10786
0
            len -= CERT_HEADER_SZ;
10787
10788
0
            if (IsSha1SignedCert(cur, len)) {
10789
0
                ret = IsSelfIssuedCert(ssl, cur, len, &selfIssued);
10790
0
                if (ret != 0)
10791
0
                    return ret;
10792
0
                if (!selfIssued)
10793
0
                    ret = MATCH_SUITE_ERROR;
10794
0
            }
10795
0
        }
10796
0
    }
10797
10798
0
    if (ret == WC_NO_ERR_TRACE(MATCH_SUITE_ERROR))
10799
0
        WOLFSSL_MSG("Chain is SHA-1 signed but peer did not advertise SHA-1");
10800
10801
0
    return ret;
10802
0
}
10803
#endif /* !NO_CERTS && !WOLFSSL_NO_SIGALG */
10804
10805
/* handle generation TLS v1.3 certificate (11) */
10806
/* Send the certificate for this end and any CAs that help with validation.
10807
 * This message is always encrypted in TLS v1.3.
10808
 *
10809
 * ssl  The SSL/TLS object.
10810
 * returns 0 on success, otherwise failure.
10811
 */
10812
static int SendTls13Certificate(WOLFSSL* ssl)
10813
0
{
10814
0
    int    ret = 0;
10815
0
    word32 certSz, certChainSz, headerSz, listSz, payloadSz;
10816
0
    word16 extSz[MAX_CERT_EXTENSIONS];
10817
0
    word16 extIdx = 0;
10818
0
    word32 maxFragment;
10819
0
    word32 totalextSz = 0;
10820
0
    word32 len = 0;
10821
0
    word32 idx = 0;
10822
0
    word32 offset = 0;
10823
0
    word32 entrySz = 0;
10824
0
    byte*  p = NULL;
10825
0
    byte   certReqCtxLen = 0;
10826
0
    sword32 length;
10827
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
10828
    byte*  certReqCtx = NULL;
10829
#endif
10830
0
#ifndef WOLFSSL_NO_SIGALG
10831
0
    int    chainRet;
10832
0
#endif
10833
10834
#ifdef OPENSSL_EXTRA
10835
    WOLFSSL_X509* x509 = NULL;
10836
    WOLFSSL_EVP_PKEY* pkey = NULL;
10837
#endif
10838
10839
0
    WOLFSSL_START(WC_FUNC_CERTIFICATE_SEND);
10840
0
    WOLFSSL_ENTER("SendTls13Certificate");
10841
10842
0
    XMEMSET(extSz, 0, sizeof(extSz));
10843
10844
0
    ssl->options.buildingMsg = 1;
10845
10846
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
10847
    if (ssl->options.side == WOLFSSL_CLIENT_END && ssl->certReqCtx != NULL) {
10848
        certReqCtxLen = ssl->certReqCtx->len;
10849
        certReqCtx = &ssl->certReqCtx->ctx;
10850
    }
10851
#endif
10852
10853
#if defined(OPENSSL_EXTRA) && defined(WOLFSSL_CERT_SETUP_CB)
10854
    /* call client cert callback if no cert has been loaded */
10855
    if ((ssl->ctx->CBClientCert != NULL) &&
10856
        /* no client cert is sent when ECH is rejected */
10857
        !EchRejected(ssl) &&
10858
        (!ssl->buffers.certificate || !ssl->buffers.certificate->buffer)) {
10859
        ret = ssl->ctx->CBClientCert(ssl, &x509, &pkey);
10860
        if (ret == 1) {
10861
            if ((wolfSSL_CTX_use_certificate(ssl->ctx, x509) == WOLFSSL_SUCCESS) &&
10862
                (wolfSSL_CTX_use_PrivateKey(ssl->ctx, pkey) == WOLFSSL_SUCCESS)) {
10863
                ssl->options.sendVerify = SEND_CERT;
10864
            }
10865
            wolfSSL_X509_free(x509);
10866
            x509 = NULL;
10867
            wolfSSL_EVP_PKEY_free(pkey);
10868
        }
10869
    }
10870
#endif
10871
10872
0
#ifndef WOLFSSL_NO_SIGALG
10873
    /* Run before the blank certificate branch below so a client with nothing
10874
     * acceptable can fall into it. Only on first entry: fragOffset is reset to
10875
     * 0 before this message is built and is non-zero only while resuming a
10876
     * fragmented send, whose chain was checked on the first pass. The result is
10877
     * kept out of ret so a pending value there is left alone. */
10878
0
    if (ssl->options.sendVerify != SEND_BLANK_CERT && ssl->fragOffset == 0) {
10879
0
        chainRet = CheckCertChainSigAlgo(ssl);
10880
0
        if ((chainRet != 0) &&
10881
0
                (chainRet != WC_NO_ERR_TRACE(MATCH_SUITE_ERROR))) {
10882
0
            return chainRet;
10883
0
        }
10884
0
        if (chainRet == WC_NO_ERR_TRACE(MATCH_SUITE_ERROR)) {
10885
0
            if (ssl->options.side == WOLFSSL_SERVER_END) {
10886
0
                SendAlert(ssl, alert_fatal, handshake_failure);
10887
0
                WOLFSSL_ERROR_VERBOSE(MATCH_SUITE_ERROR);
10888
0
                return MATCH_SUITE_ERROR;
10889
0
            }
10890
0
        #ifndef WOLFSSL_NO_CLIENT_CERT_ERROR
10891
            /* RFC 8446 Section 4.4.2: a client with no acceptable certificate
10892
             * sends an empty certificate_list rather than failing. */
10893
0
            WOLFSSL_MSG("Client chain not acceptable, sending blank cert");
10894
0
            ssl->options.sendVerify = SEND_BLANK_CERT;
10895
        #else
10896
            /* RFC 8446 Section 4.4.2.2: an endpoint that cannot produce an
10897
             * acceptable chain aborts with a certificate related alert,
10898
             * unsupported_certificate by default. */
10899
            WOLFSSL_MSG("Client chain not acceptable and blank cert not "
10900
                        "allowed");
10901
            SendAlert(ssl, alert_fatal, unsupported_certificate);
10902
            WOLFSSL_ERROR_VERBOSE(NO_CERT_ERROR);
10903
            return NO_CERT_ERROR;
10904
        #endif
10905
0
        }
10906
0
    }
10907
0
#endif
10908
10909
0
    if (ssl->options.sendVerify == SEND_BLANK_CERT) {
10910
0
        certSz = 0;
10911
0
        certChainSz = 0;
10912
0
        headerSz = OPAQUE8_LEN + certReqCtxLen + CERT_HEADER_SZ;
10913
0
        length = (sword32)headerSz;
10914
0
        listSz = 0;
10915
0
    }
10916
0
    else {
10917
0
        if (!ssl->buffers.certificate || !ssl->buffers.certificate->buffer) {
10918
0
            WOLFSSL_MSG("Send Cert missing certificate buffer");
10919
0
            return NO_CERT_ERROR;
10920
0
        }
10921
        /* Certificate Data */
10922
0
        certSz = ssl->buffers.certificate->length;
10923
0
        if (ssl->buffers.certChainCnt > MAX_CHAIN_DEPTH) {
10924
0
            WOLFSSL_MSG("Certificate chain count exceeds maximum depth");
10925
0
            return MAX_CHAIN_ERROR;
10926
0
        }
10927
        /* Cert Req Ctx Len | Cert Req Ctx | Cert List Len | Cert Data Len */
10928
0
        headerSz = OPAQUE8_LEN + certReqCtxLen + CERT_HEADER_SZ +
10929
0
                   CERT_HEADER_SZ;
10930
        /* set empty extension as default */
10931
0
        for (extIdx = 0; extIdx < (word16)XELEM_CNT(extSz); extIdx++)
10932
0
            extSz[extIdx] = OPAQUE16_LEN;
10933
10934
    #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) && !defined(NO_WOLFSSL_SERVER)
10935
        /* Staple our own OCSP response with the Certificate. Normally only the
10936
         * server staples; the client's CSR holds the server's response, so
10937
         * echoing it back is wrong. The exception is post-handshake auth (PHA),
10938
         * where the client sends its own Certificate and staples for it. */
10939
        if (ssl->options.side == WOLFSSL_SERVER_END
10940
        #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
10941
            || (ssl->options.side == WOLFSSL_CLIENT_END
10942
                && ssl->options.handShakeDone)
10943
        #endif
10944
        ) {
10945
            /* Build the responses once. A resumed send reuses them: looking
10946
             * them up again appends another set of requests to the extension
10947
             * until it overflows with MAX_CERT_EXTENSIONS_ERR. */
10948
            if (ssl->fragOffset == 0) {
10949
                ret = SetupOcspResp(ssl);
10950
                if (ret != 0)
10951
                    return ret;
10952
            }
10953
10954
            if ((1 + ssl->buffers.certChainCnt) > MAX_CERT_EXTENSIONS)
10955
                ret = MAX_CERT_EXTENSIONS_ERR;
10956
            if (ret == 0)
10957
                ret = WriteCSRToBuffer(ssl, &ssl->buffers.certExts[0], &extSz[0],
10958
                        1 /* +1 for leaf */ + (word16)ssl->buffers.certChainCnt);
10959
            if (ret < 0)
10960
                return ret;
10961
            totalextSz += ret;
10962
            ret = 0; /* Clear to signal no error */
10963
        }
10964
        else
10965
    #endif
10966
0
        {
10967
            /* Leaf cert empty extension size */
10968
0
            totalextSz += OPAQUE16_LEN;
10969
            /* chain cert empty extension size */
10970
0
            totalextSz += OPAQUE16_LEN * ssl->buffers.certChainCnt;
10971
0
        }
10972
10973
        /* Length of message data with one certificate and extensions. */
10974
0
        length = (sword32)(headerSz + certSz + totalextSz);
10975
        /* Length of list data with one certificate and extensions. */
10976
0
        listSz = CERT_HEADER_SZ + certSz + totalextSz;
10977
10978
        /* Send rest of chain if sending cert (chain has leading size/s). */
10979
0
        if (certSz > 0 && ssl->buffers.certChainCnt > 0) {
10980
0
            p = ssl->buffers.certChain->buffer;
10981
            /* Chain length including extensions. */
10982
0
            certChainSz = ssl->buffers.certChain->length;
10983
10984
0
            length += certChainSz;
10985
0
            listSz += certChainSz;
10986
0
        }
10987
0
        else
10988
0
            certChainSz = 0;
10989
0
    }
10990
10991
0
    payloadSz = (word32)length;
10992
10993
0
    if (ssl->fragOffset != 0)
10994
0
        length -= (ssl->fragOffset + headerSz);
10995
10996
0
    maxFragment = (word32)wolfssl_local_GetMaxPlaintextSize(ssl);
10997
10998
0
    extIdx = 0;
10999
11000
    /* Only ssl->fragOffset survives a WANT_WRITE, so a resume inside the chain
11001
     * has to rebuild the walk cursor from it. */
11002
0
    if (certChainSz > 0 && ssl->fragOffset >= certSz + extSz[0]) {
11003
0
        word32 chainPos = ssl->fragOffset - (certSz + extSz[0]);
11004
11005
    #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) && !defined(NO_WOLFSSL_SERVER)
11006
        /* The leaf is behind us and its buffer was rebuilt above. */
11007
        FreeDer(&ssl->buffers.certExts[0]);
11008
    #endif
11009
11010
0
        while (chainPos > 0) {
11011
0
            word32 prevIdx = idx;
11012
11013
0
            len = NextCert(ssl->buffers.certChain->buffer,
11014
0
                           ssl->buffers.certChain->length, &idx);
11015
0
            if (len == 0)
11016
0
                break;
11017
        #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) && \
11018
                !defined(NO_WOLFSSL_SERVER)
11019
            if (extIdx + 1 < MAX_CERT_EXTENSIONS)
11020
                extIdx++;
11021
        #endif
11022
0
            entrySz = len + extSz[extIdx];
11023
11024
0
            if (chainPos < entrySz) {
11025
                /* Resume part way through this entry. */
11026
0
                p = ssl->buffers.certChain->buffer + prevIdx;
11027
0
                offset = chainPos;
11028
0
                chainPos = 0;
11029
0
            }
11030
0
            else {
11031
                /* Entry already sent in full; stay primed for the next one. */
11032
            #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) && \
11033
                    !defined(NO_WOLFSSL_SERVER)
11034
                /* Its buffer was rebuilt above and nothing writes it again. */
11035
                FreeDer(&ssl->buffers.certExts[extIdx]);
11036
            #endif
11037
0
                chainPos -= entrySz;
11038
0
                offset = 0;
11039
0
                entrySz = 0;
11040
0
            }
11041
0
        }
11042
0
    }
11043
11044
0
    while (length > 0 && ret == 0) {
11045
0
        byte*  output = NULL;
11046
0
        word32 fragSz = 0;
11047
0
        word32 i = RECORD_HEADER_SZ;
11048
0
        int    sendSz = RECORD_HEADER_SZ;
11049
11050
#ifdef WOLFSSL_DTLS13
11051
        if (ssl->options.dtls) {
11052
            i = Dtls13GetRlHeaderLength(ssl, 1);
11053
            sendSz = (int)i;
11054
        }
11055
#endif /* WOLFSSL_DTLS13 */
11056
11057
0
        if (ssl->fragOffset == 0) {
11058
0
            if (headerSz + certSz + totalextSz + certChainSz <=
11059
0
                                            maxFragment - HANDSHAKE_HEADER_SZ) {
11060
0
                fragSz = headerSz + certSz + totalextSz + certChainSz;
11061
0
            }
11062
#ifdef WOLFSSL_DTLS13
11063
            else if (ssl->options.dtls){
11064
                /* short-circuit the fragmentation logic here. DTLS
11065
                   fragmentation will be done in dtls13HandshakeSend() */
11066
                fragSz = headerSz + certSz + totalextSz + certChainSz;
11067
            }
11068
#endif /* WOLFSSL_DTLS13 */
11069
0
            else {
11070
0
                fragSz = maxFragment - HANDSHAKE_HEADER_SZ;
11071
0
            }
11072
11073
0
            sendSz += fragSz + HANDSHAKE_HEADER_SZ;
11074
0
            i += HANDSHAKE_HEADER_SZ;
11075
#ifdef WOLFSSL_DTLS13
11076
            if (ssl->options.dtls) {
11077
                sendSz += DTLS_HANDSHAKE_EXTRA;
11078
                i += DTLS_HANDSHAKE_EXTRA;
11079
            }
11080
#endif /* WOLFSSL_DTLS13 */
11081
0
        }
11082
0
        else {
11083
0
            fragSz = min((word32)length, maxFragment);
11084
0
            sendSz += fragSz;
11085
0
        }
11086
11087
0
        sendSz += MAX_MSG_EXTRA;
11088
11089
        /* Check buffers are big enough and grow if needed. */
11090
0
        if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
11091
0
            return ret;
11092
11093
        /* Get position in output buffer to write new message to. */
11094
0
        output = GetOutputBuffer(ssl);
11095
11096
0
        if (ssl->fragOffset == 0) {
11097
0
            AddTls13FragHeaders(output, fragSz, 0, payloadSz, certificate, ssl);
11098
11099
            /* Request context. */
11100
0
            output[i++] = certReqCtxLen;
11101
        #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
11102
            if (certReqCtxLen > 0) {
11103
                XMEMCPY(output + i, certReqCtx, certReqCtxLen);
11104
                i += certReqCtxLen;
11105
            }
11106
        #endif
11107
0
            length -= OPAQUE8_LEN + certReqCtxLen;
11108
0
            fragSz -= OPAQUE8_LEN + certReqCtxLen;
11109
            /* Certificate list length. */
11110
0
            c32to24(listSz, output + i);
11111
0
            i += CERT_HEADER_SZ;
11112
0
            length -= CERT_HEADER_SZ;
11113
0
            fragSz -= CERT_HEADER_SZ;
11114
            /* Leaf certificate data length. */
11115
0
            if (certSz > 0) {
11116
0
                c32to24(certSz, output + i);
11117
0
                i += CERT_HEADER_SZ;
11118
0
                length -= CERT_HEADER_SZ;
11119
0
                fragSz -= CERT_HEADER_SZ;
11120
0
            }
11121
0
        }
11122
0
        else
11123
0
            AddTls13RecordHeader(output, fragSz, handshake, ssl);
11124
11125
0
        if (extIdx == 0) {
11126
0
            if (certSz > 0 && ssl->fragOffset < certSz + extSz[0]) {
11127
                /* Put in the leaf certificate with extensions. */
11128
0
                word32 copySz = AddCertExt(ssl, ssl->buffers.certificate->buffer,
11129
0
                                certSz, extSz[0], ssl->fragOffset, fragSz,
11130
0
                                output + i, 0);
11131
0
                i += copySz;
11132
0
                ssl->fragOffset += copySz;
11133
0
                length -= copySz;
11134
0
                fragSz -= copySz;
11135
0
                if (ssl->fragOffset == certSz + extSz[0])
11136
0
                    FreeDer(&ssl->buffers.certExts[0]);
11137
0
            }
11138
0
        }
11139
0
        if (certChainSz > 0 && fragSz > 0) {
11140
             /* Put in the CA certificates with extensions. */
11141
0
             while (fragSz > 0) {
11142
0
                word32 l;
11143
11144
0
                if (offset == entrySz) {
11145
                    /* Find next CA certificate to write out. */
11146
0
                    offset = 0;
11147
                    /* Point to the start of current cert in chain buffer. */
11148
0
                    p = ssl->buffers.certChain->buffer + idx;
11149
0
                    len = NextCert(ssl->buffers.certChain->buffer,
11150
0
                            ssl->buffers.certChain->length, &idx);
11151
0
                    if (len == 0)
11152
0
                        break;
11153
                #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) && \
11154
                        !defined(NO_WOLFSSL_SERVER)
11155
                    if (extIdx + 1 < MAX_CERT_EXTENSIONS)
11156
                        extIdx++;
11157
                #endif
11158
                    /* Certificate and its extensions make up the entry. */
11159
0
                    entrySz = len + extSz[extIdx];
11160
0
                }
11161
                /* Write out certificate and extension. */
11162
0
                l = AddCertExt(ssl, p, len, extSz[extIdx], offset, fragSz,
11163
0
                                                       output + i, extIdx);
11164
0
                i += l;
11165
0
                ssl->fragOffset += l;
11166
0
                length -= l;
11167
0
                fragSz -= l;
11168
0
                offset += l;
11169
11170
0
                if (extIdx != 0 && extIdx < MAX_CERT_EXTENSIONS &&
11171
0
                    ssl->buffers.certExts[extIdx] != NULL &&
11172
0
                                offset == entrySz) {
11173
0
                    FreeDer(&ssl->buffers.certExts[extIdx]);
11174
0
                }
11175
0
            }
11176
0
        }
11177
11178
0
        if ((int)i - RECORD_HEADER_SZ < 0) {
11179
0
            WOLFSSL_MSG("Send Cert bad inputSz");
11180
0
            return BUFFER_E;
11181
0
        }
11182
11183
#ifdef WOLFSSL_DTLS13
11184
        if (ssl->options.dtls) {
11185
            /* DTLS1.3 uses a separate variable and logic for fragments */
11186
            ssl->options.buildingMsg = 0;
11187
            ssl->fragOffset = 0;
11188
            if ((word32)sendSz > WOLFSSL_MAX_16BIT || i > WOLFSSL_MAX_16BIT) {
11189
                WOLFSSL_MSG("Send Cert DTLS size exceeds word16");
11190
                return BUFFER_E;
11191
            }
11192
            ret = Dtls13HandshakeSend(ssl, output, (word16)sendSz, (word16)i,
11193
                                      certificate, 1);
11194
        }
11195
        else
11196
#endif /* WOLFSSL_DTLS13 */
11197
0
        {
11198
            /* This message is always encrypted. */
11199
0
            sendSz = BuildTls13Message(ssl, output, sendSz,
11200
0
                output + RECORD_HEADER_SZ, (int)(i - RECORD_HEADER_SZ),
11201
0
                handshake, 1,
11202
0
                0, 0);
11203
0
            if (sendSz < 0)
11204
0
                return sendSz;
11205
11206
#if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
11207
            if (ssl->hsInfoOn)
11208
                AddPacketName(ssl, "Certificate");
11209
            if (ssl->toInfoOn) {
11210
                ret = AddPacketInfo(ssl, "Certificate", handshake, output,
11211
                              sendSz, WRITE_PROTO, 0, ssl->heap);
11212
                if (ret != 0)
11213
                    return ret;
11214
            }
11215
#endif
11216
11217
0
            ssl->buffers.outputBuffer.length += (word32)sendSz;
11218
0
            ssl->options.buildingMsg = 0;
11219
0
            if (!ssl->options.groupMessages)
11220
0
                ret = SendBuffered(ssl);
11221
0
        }
11222
0
    }
11223
11224
0
    if (ret != WC_NO_ERR_TRACE(WANT_WRITE)) {
11225
        /* Clean up the fragment offset. */
11226
0
        ssl->options.buildingMsg = 0;
11227
0
        ssl->fragOffset = 0;
11228
0
        if (ssl->options.side == WOLFSSL_SERVER_END)
11229
0
            ssl->options.serverState = SERVER_CERT_COMPLETE;
11230
0
    }
11231
11232
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
11233
    if (ssl->options.side == WOLFSSL_CLIENT_END && ssl->certReqCtx != NULL) {
11234
        CertReqCtx* ctx = ssl->certReqCtx;
11235
        ssl->certReqCtx = ssl->certReqCtx->next;
11236
        XFREE(ctx, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
11237
    }
11238
#endif
11239
11240
0
    WOLFSSL_LEAVE("SendTls13Certificate", ret);
11241
0
    WOLFSSL_END(WC_FUNC_CERTIFICATE_SEND);
11242
11243
0
    return ret;
11244
0
}
11245
11246
#if (!defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
11247
     defined(HAVE_ED448) || defined(HAVE_FALCON) || \
11248
     defined(WOLFSSL_HAVE_MLDSA) || defined(WOLFSSL_HAVE_SLHDSA)) && \
11249
    (!defined(NO_WOLFSSL_SERVER) || !defined(WOLFSSL_NO_CLIENT_AUTH))
11250
/* Members are grouped widest first so the struct carries no interior padding.
11251
 * Under WOLFSSL_ASYNC_CRYPT this must fit ssl->async->args (MAX_ASYNC_ARGS
11252
 * word32s), which the static assert in SendTls13CertificateVerify enforces. */
11253
typedef struct Scv13Args {
11254
    byte*  output; /* not allocated */
11255
    byte*  verify; /* not allocated */
11256
    byte*  sigData;
11257
#ifndef NO_RSA
11258
    byte*  toSign; /* not allocated */
11259
#endif
11260
#ifdef WOLFSSL_DUAL_ALG_CERTS
11261
    byte*  altSigData;
11262
#endif
11263
    /* Fragmented CertificateVerify send cursor, used when the signature does
11264
     * not fit in a single TLS record (SLH-DSA and other oversized signatures).
11265
     * Kept in the async args so a WC_PENDING_E from the record AEAD under
11266
     * WOLFSSL_ASYNC_CRYPT resumes on the same fragment instead of re-emitting
11267
     * the records already committed to the output buffer. */
11268
    byte*  frag;         /* body copy, freed by FreeScv13Args; NULL when idle */
11269
11270
    word32 idx;
11271
    word32 sigLen;
11272
    int    sendSz;
11273
    word32 length;
11274
#ifndef NO_RSA
11275
    word32 toSignSz;
11276
#endif
11277
#ifdef WOLFSSL_DUAL_ALG_CERTS
11278
    word32 altSigLen;    /* Only used in the case of both native and alt. */
11279
#endif
11280
    word32 outputSz;     /* reserved capacity of the output record buffer */
11281
    word32 fragOffset;   /* body bytes already committed to records */
11282
11283
    word16 sigDataSz;
11284
#ifdef WOLFSSL_DUAL_ALG_CERTS
11285
    word16 altSigDataSz;
11286
#endif
11287
11288
    byte   sigAlgo;
11289
#ifdef WOLFSSL_DUAL_ALG_CERTS
11290
    byte   altSigAlgo;
11291
#endif
11292
    byte   fragActive;   /* current fragment laid out, record build may pend */
11293
} Scv13Args;
11294
11295
static void FreeScv13Args(WOLFSSL* ssl, void* pArgs)
11296
0
{
11297
0
    Scv13Args* args = (Scv13Args*)pArgs;
11298
11299
0
    (void)ssl;
11300
11301
0
    if (args && args->sigData) {
11302
0
        XFREE(args->sigData, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
11303
0
        args->sigData = NULL;
11304
0
    }
11305
#ifdef WOLFSSL_DUAL_ALG_CERTS
11306
    if (args && args->altSigData != NULL) {
11307
        XFREE(args->altSigData, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
11308
        args->altSigData = NULL;
11309
    }
11310
#endif
11311
0
    if (args != NULL && args->frag != NULL) {
11312
0
        XFREE(args->frag, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
11313
0
        args->frag = NULL;
11314
0
    }
11315
0
}
11316
11317
/* handle generation TLS v1.3 certificate_verify (15) */
11318
/* Send the TLS v1.3 CertificateVerify message.
11319
 * A hash of all the message so far is used.
11320
 * The signed data is:
11321
 *     0x20 * 64 | context string | 0x00 | hash of messages
11322
 * This message is always encrypted in TLS v1.3.
11323
 *
11324
 * ssl  The SSL/TLS object.
11325
 * returns 0 on success, otherwise failure.
11326
 */
11327
static int SendTls13CertificateVerify(WOLFSSL* ssl)
11328
0
{
11329
0
    int ret = 0;
11330
0
#ifndef NO_RSA
11331
    /* Use this as a temporary buffer for RSA signature verification. */
11332
0
    buffer* rsaSigBuf = &ssl->buffers.sig;
11333
0
#endif
11334
#ifdef WOLFSSL_ASYNC_CRYPT
11335
    Scv13Args* args = NULL;
11336
    WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
11337
#else
11338
0
    Scv13Args  args[1];
11339
0
#endif
11340
11341
#ifdef WOLFSSL_DTLS13
11342
    int recordLayerHdrExtra;
11343
#endif /* WOLFSSL_DTLS13 */
11344
11345
0
    WOLFSSL_START(WC_FUNC_CERTIFICATE_VERIFY_SEND);
11346
0
    WOLFSSL_ENTER("SendTls13CertificateVerify");
11347
11348
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
11349
    wolfssl_priv_der_blind_toggle(ssl->buffers.key, ssl->buffers.keyMask);
11350
#endif
11351
11352
0
    ssl->options.buildingMsg = 1;
11353
11354
#if defined(WOLFSSL_RENESAS_TSIP_TLS)
11355
    ret = tsip_Tls13SendCertVerify(ssl);
11356
    if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
11357
        goto exit_scv;
11358
    }
11359
    ret = 0;
11360
#endif /* WOLFSSL_RENESAS_TSIP_TLS */
11361
11362
#ifdef WOLFSSL_DTLS13
11363
    /* can be negative */
11364
    if (ssl->options.dtls)
11365
        recordLayerHdrExtra = Dtls13GetRlHeaderLength(ssl, 1) - RECORD_HEADER_SZ;
11366
    else
11367
        recordLayerHdrExtra = 0;
11368
11369
#endif /* WOLFSSL_DTLS13 */
11370
11371
#ifdef WOLFSSL_ASYNC_CRYPT
11372
    if (ssl->async == NULL) {
11373
        ssl->async = (struct WOLFSSL_ASYNC*)
11374
                XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
11375
                        DYNAMIC_TYPE_ASYNC);
11376
        if (ssl->async == NULL)
11377
            ERROR_OUT(MEMORY_E, exit_scv);
11378
    }
11379
    args = (Scv13Args*)ssl->async->args;
11380
11381
    ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
11382
    if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) {
11383
        /* Check for error */
11384
        if (ret < 0)
11385
            goto exit_scv;
11386
    }
11387
    else
11388
#endif
11389
0
    {
11390
        /* Reset state */
11391
0
        ret = 0;
11392
0
        ssl->options.asyncState = TLS_ASYNC_BEGIN;
11393
0
        XMEMSET(args, 0, sizeof(Scv13Args));
11394
    #ifdef WOLFSSL_ASYNC_CRYPT
11395
        ssl->async->freeArgs = FreeScv13Args;
11396
    #endif
11397
0
    }
11398
11399
#ifdef WOLFSSL_TLS13_STREAM_CERT_VERIFY
11400
    /* Resuming a partially-sent streamed CertificateVerify (e.g. after a
11401
     * non-blocking WANT_WRITE): the signature is already assembled in
11402
     * ssl->buffers.certVerifyMsg and ssl->fragOffset marks how much has been
11403
     * committed to records, so skip re-signing and continue sending. */
11404
    if (ssl->buffers.certVerifyMsg.buffer != NULL && ssl->fragOffset != 0) {
11405
        ssl->options.asyncState = TLS_ASYNC_END;
11406
    }
11407
#endif
11408
11409
0
    switch(ssl->options.asyncState)
11410
0
    {
11411
0
        case TLS_ASYNC_BEGIN:
11412
0
        {
11413
0
            if (ssl->options.sendVerify == SEND_BLANK_CERT) {
11414
            #ifdef WOLFSSL_BLIND_PRIVATE_KEY
11415
                wolfssl_priv_der_blind_toggle(ssl->buffers.key,
11416
                    ssl->buffers.keyMask);
11417
            #endif
11418
0
                return 0;  /* sent blank cert, can't verify */
11419
0
            }
11420
11421
            /* The output buffer is reserved in TLS_ASYNC_BUILD, once the
11422
             * private key has been decoded and the actual signature size is
11423
             * known. This avoids reserving the worst-case WC_MAX_CERT_VERIFY_SZ
11424
             * (very large when SLH-DSA is enabled) for every algorithm. */
11425
11426
            /* Advance state and proceed */
11427
0
            ssl->options.asyncState = TLS_ASYNC_BUILD;
11428
0
        } /* case TLS_ASYNC_BEGIN */
11429
0
        FALL_THROUGH;
11430
11431
0
        case TLS_ASYNC_BUILD:
11432
0
        {
11433
0
            int rem;
11434
#ifdef WOLFSSL_TLS13_STREAM_CERT_VERIFY
11435
            word32 bodySz;
11436
            word32 maxFrag;
11437
#endif
11438
0
            int doStream = 0;
11439
11440
            /* Decode the private key first so the output buffer can be sized
11441
             * to the actual signature length rather than the worst-case
11442
             * WC_MAX_CERT_VERIFY_SZ (very large when SLH-DSA is enabled). */
11443
0
            if (ssl->buffers.key == NULL) {
11444
            #ifdef HAVE_PK_CALLBACKS
11445
                if (wolfSSL_CTX_IsPrivatePkSet(ssl->ctx))
11446
                    args->sigLen = (word32)GetPrivateKeySigSize(ssl);
11447
                else
11448
            #endif
11449
0
                    ERROR_OUT(NO_PRIVATE_KEY, exit_scv);
11450
0
            }
11451
0
            else {
11452
#ifdef WOLFSSL_DUAL_ALG_CERTS
11453
                if (ssl->sigSpec != NULL &&
11454
                    *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_ALTERNATIVE) {
11455
                    /* In the case of alternative, we swap in the alt. */
11456
                    if (ssl->buffers.altKey == NULL) {
11457
                        ERROR_OUT(NO_PRIVATE_KEY, exit_scv);
11458
                    }
11459
                    ssl->buffers.keyType = ssl->buffers.altKeyType;
11460
                    ssl->buffers.keySz = ssl->buffers.altKeySz;
11461
                    /* If we own it, free key before overriding it. */
11462
                    if (ssl->buffers.weOwnKey) {
11463
                        FreeKeyDer(&ssl->buffers.key);
11464
                    #ifdef WOLFSSL_BLIND_PRIVATE_KEY
11465
                        FreeDer(&ssl->buffers.keyMask);
11466
                    #endif
11467
                    }
11468
11469
                    /* Swap keys */
11470
                    ssl->buffers.key     = ssl->buffers.altKey;
11471
                    ssl->buffers.weOwnKey = ssl->buffers.weOwnAltKey;
11472
                    /* buffers.key is the only owner of the alt key now. */
11473
                    ssl->buffers.weOwnAltKey = 0;
11474
11475
                #ifdef WOLFSSL_BLIND_PRIVATE_KEY
11476
                    ssl->buffers.keyMask = ssl->buffers.altKeyMask;
11477
                    /* Unblind the alternative key before decoding */
11478
                    wolfssl_priv_der_blind_toggle(ssl->buffers.key, ssl->buffers.keyMask);
11479
                #endif
11480
                }
11481
#endif /* WOLFSSL_DUAL_ALG_CERTS */
11482
0
                ret = DecodePrivateKey(ssl, &args->sigLen);
11483
0
                if (ret != 0)
11484
0
                    goto exit_scv;
11485
0
            }
11486
11487
0
            if (args->sigLen == 0) {
11488
0
                ERROR_OUT(NO_PRIVATE_KEY, exit_scv);
11489
0
            }
11490
11491
#ifdef WOLFSSL_DUAL_ALG_CERTS
11492
            if (ssl->peerSigSpec == NULL) {
11493
                /* The peer did not respond. We didn't send CKS or they don't
11494
                 * support it. Either way, we do not need to handle dual
11495
                 * key/sig case. */
11496
                ssl->sigSpec = NULL;
11497
                ssl->sigSpecSz = 0;
11498
            }
11499
11500
            if (ssl->sigSpec != NULL &&
11501
                *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) {
11502
                /* The native was already decoded. Decode the alternative now
11503
                 * too so its signature length is included when the output
11504
                 * buffer is sized below. */
11505
                if (ssl->buffers.altKey == NULL) {
11506
                    ERROR_OUT(NO_PRIVATE_KEY, exit_scv);
11507
                }
11508
11509
                /* After this call, args->altSigLen has the length we need for
11510
                 * the alternative signature. */
11511
                ret = DecodeAltPrivateKey(ssl, &args->altSigLen);
11512
                if (ret != 0)
11513
                    goto exit_scv;
11514
11515
                if (ssl->buffers.altKeyType == ecc_dsa_sa_algo ||
11516
                    ssl->buffers.altKeyType == falcon_level1_sa_algo ||
11517
                    ssl->buffers.altKeyType == falcon_level5_sa_algo ||
11518
                    ssl->buffers.altKeyType == mldsa_44_sa_algo ||
11519
                    ssl->buffers.altKeyType == mldsa_65_sa_algo ||
11520
                    ssl->buffers.altKeyType == mldsa_87_sa_algo) {
11521
                    args->altSigAlgo = ssl->buffers.altKeyType;
11522
                }
11523
                else if (ssl->buffers.altKeyType == rsa_sa_algo &&
11524
                         ssl->hsAltType == DYNAMIC_TYPE_RSA) {
11525
                    args->altSigAlgo = rsa_pss_sa_algo;
11526
                }
11527
                else {
11528
                    ERROR_OUT(ALGO_ID_E, exit_scv);
11529
                }
11530
            }
11531
#endif /* WOLFSSL_DUAL_ALG_CERTS */
11532
11533
            /* Decide how the CertificateVerify body will be emitted. When it
11534
             * exceeds a single record (e.g. a large SLH-DSA/ML-DSA signature,
11535
             * or any signature under a small max_fragment_length) on TLS 1.3,
11536
             * use the streaming path: generate the signature into a
11537
             * connection-level body buffer and send it one record at a time in
11538
             * TLS_ASYNC_END, so the shared output buffer never has to hold the
11539
             * whole signature. Otherwise reserve the output buffer for the
11540
             * whole message and build it in place. */
11541
#ifdef WOLFSSL_TLS13_STREAM_CERT_VERIFY
11542
            bodySz = HASH_SIG_SIZE + VERIFY_HEADER + (word32)args->sigLen;
11543
        #ifdef WOLFSSL_DUAL_ALG_CERTS
11544
            /* A dual (BOTH) body carries a second length-prefixed signature.
11545
             * args->sigLen/altSigLen are upper bounds here for variable-length
11546
             * schemes (ECDSA, Falcon), so this may over-size the body buffer by
11547
             * a few bytes; the body is assembled contiguously with the actual
11548
             * lengths, the exact length is recorded in TLS_ASYNC_FINALIZE, and
11549
             * the trailing slack is never sent. */
11550
            if (ssl->sigSpec != NULL &&
11551
                    *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) {
11552
                bodySz += (word32)args->altSigLen + OPAQUE16_LEN + OPAQUE16_LEN;
11553
            }
11554
        #endif
11555
            maxFrag = (word32)wolfssl_local_GetMaxPlaintextSize(ssl);
11556
            if (!ssl->options.dtls &&
11557
                    (word32)HANDSHAKE_HEADER_SZ + bodySz > maxFrag) {
11558
                doStream = 1;
11559
            }
11560
#endif /* WOLFSSL_TLS13_STREAM_CERT_VERIFY */
11561
11562
0
            if (doStream) {
11563
#ifdef WOLFSSL_TLS13_STREAM_CERT_VERIFY
11564
                /* Generate the body directly into the connection-level buffer.
11565
                 * bodySz is exact here (a single fixed-or-max-length
11566
                 * signature); the final length is recorded in
11567
                 * TLS_ASYNC_FINALIZE. args->output stays NULL to mark the
11568
                 * streaming path; the send loop reserves one record at a
11569
                 * time. */
11570
                XFREE(ssl->buffers.certVerifyMsg.buffer, ssl->heap,
11571
                      DYNAMIC_TYPE_TMP_BUFFER);
11572
                ssl->buffers.certVerifyMsg.buffer =
11573
                    (byte*)XMALLOC(bodySz, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
11574
                if (ssl->buffers.certVerifyMsg.buffer == NULL) {
11575
                    ssl->buffers.certVerifyMsg.length = 0;
11576
                    ERROR_OUT(MEMORY_E, exit_scv);
11577
                }
11578
                ssl->buffers.certVerifyMsg.length = bodySz;
11579
                ssl->fragOffset = 0;
11580
                args->verify = ssl->buffers.certVerifyMsg.buffer;
11581
                args->idx = 0;
11582
                args->sendSz = (int)bodySz;
11583
                args->output = NULL;
11584
                args->outputSz = 0;
11585
#endif /* WOLFSSL_TLS13_STREAM_CERT_VERIFY */
11586
0
            }
11587
0
            else {
11588
                /* Reserve the output buffer, sized from the actual signature
11589
                 * length(s) plus record/handshake framing and encryption
11590
                 * slack. */
11591
0
                args->sendSz = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ +
11592
0
                               HASH_SIG_SIZE + VERIFY_HEADER + (int)args->sigLen;
11593
            #ifdef WOLFSSL_DUAL_ALG_CERTS
11594
                /* A dual (BOTH) body carries a second signature behind its own
11595
                 * length prefix, plus the combined length prefix. Matches the
11596
                 * streaming bodySz above. */
11597
                if (ssl->sigSpec != NULL &&
11598
                        *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) {
11599
                    args->sendSz += (int)args->altSigLen + OPAQUE16_LEN +
11600
                                    OPAQUE16_LEN;
11601
                }
11602
                else {
11603
                    args->sendSz += (int)args->altSigLen;
11604
                }
11605
            #endif
11606
            #ifdef WOLFSSL_DTLS13
11607
                if (ssl->options.dtls)
11608
                    args->sendSz += recordLayerHdrExtra + DTLS_HANDSHAKE_EXTRA;
11609
            #endif /* WOLFSSL_DTLS13 */
11610
                /* Framing and always-on encryption expansion. */
11611
0
                args->sendSz += MAX_MSG_EXTRA;
11612
11613
                /* check for available size */
11614
0
                if ((ret = CheckAvailableSize(ssl, args->sendSz)) != 0) {
11615
0
                    goto exit_scv;
11616
0
                }
11617
11618
                /* get output buffer */
11619
0
                args->output = GetOutputBuffer(ssl);
11620
                /* Remember the reserved capacity for BuildTls13Message /
11621
                 * Dtls13HandshakeSend in TLS_ASYNC_END. */
11622
0
                args->outputSz = (word32)args->sendSz;
11623
11624
0
                rem = (int)(ssl->buffers.outputBuffer.bufferSize
11625
0
                                - ssl->buffers.outputBuffer.length
11626
0
                                - RECORD_HEADER_SZ - HANDSHAKE_HEADER_SZ);
11627
11628
                /* idx is used to track verify pointer offset to output */
11629
0
                args->idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
11630
0
                args->verify =
11631
0
                          &args->output[RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ];
11632
11633
            #ifdef WOLFSSL_DTLS13
11634
                if (ssl->options.dtls) {
11635
                    rem -= recordLayerHdrExtra + DTLS_HANDSHAKE_EXTRA;
11636
                    args->idx += recordLayerHdrExtra + DTLS_HANDSHAKE_EXTRA;
11637
                    args->verify += recordLayerHdrExtra + DTLS_HANDSHAKE_EXTRA;
11638
                }
11639
            #endif /* WOLFSSL_DTLS13 */
11640
11641
0
                if (rem < 0 || (int)args->sigLen > rem) {
11642
0
                    ERROR_OUT(BUFFER_E, exit_scv);
11643
0
                }
11644
0
            }
11645
11646
            /* Add signature algorithm. */
11647
0
            if (ssl->hsType == DYNAMIC_TYPE_RSA)
11648
0
                args->sigAlgo = rsa_pss_sa_algo;
11649
0
        #ifdef HAVE_ECC
11650
0
            else if (ssl->hsType == DYNAMIC_TYPE_ECC) {
11651
        #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
11652
                if (ssl->buffers.keyType == sm2_sa_algo) {
11653
                    args->sigAlgo = sm2_sa_algo;
11654
                }
11655
                else
11656
        #endif
11657
0
                {
11658
0
                    args->sigAlgo = ecc_dsa_sa_algo;
11659
0
                }
11660
0
            }
11661
0
        #endif
11662
        #ifdef HAVE_ED25519
11663
            else if (ssl->hsType == DYNAMIC_TYPE_ED25519)
11664
                args->sigAlgo = ed25519_sa_algo;
11665
        #endif
11666
        #ifdef HAVE_ED448
11667
            else if (ssl->hsType == DYNAMIC_TYPE_ED448)
11668
                args->sigAlgo = ed448_sa_algo;
11669
        #endif
11670
        #if defined(HAVE_FALCON)
11671
            else if (ssl->hsType == DYNAMIC_TYPE_FALCON) {
11672
                args->sigAlgo = ssl->buffers.keyType;
11673
            }
11674
        #endif /* HAVE_FALCON */
11675
        #if defined(WOLFSSL_HAVE_MLDSA)
11676
            else if (ssl->hsType == DYNAMIC_TYPE_MLDSA) {
11677
                args->sigAlgo = ssl->buffers.keyType;
11678
            }
11679
        #endif /* WOLFSSL_HAVE_MLDSA */
11680
        #if defined(WOLFSSL_HAVE_SLHDSA)
11681
            else if (ssl->hsType == DYNAMIC_TYPE_SLHDSA) {
11682
                args->sigAlgo = ssl->buffers.keyType;
11683
            }
11684
        #endif /* WOLFSSL_HAVE_SLHDSA */
11685
0
            else {
11686
0
                ERROR_OUT(ALGO_ID_E, exit_scv);
11687
0
            }
11688
11689
        #ifdef WOLFSSL_DUAL_ALG_CERTS
11690
            if (ssl->sigSpec != NULL &&
11691
                *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) {
11692
                /* The alternative key was already decoded and its sig-alg
11693
                 * determined above (when sizing the output buffer). Encode the
11694
                 * dual (native + alternative) signature algorithm pair. */
11695
                EncodeDualSigAlg(args->sigAlgo, args->altSigAlgo, args->verify);
11696
                if (args->verify[0] == 0) {
11697
                    ERROR_OUT(ALGO_ID_E, exit_scv);
11698
                }
11699
            }
11700
            else
11701
        #endif /* WOLFSSL_DUAL_ALG_CERTS */
11702
0
                EncodeSigAlg(ssl, ssl->options.hashAlgo, args->sigAlgo,
11703
0
                             args->verify);
11704
11705
0
            if (args->sigData == NULL) {
11706
0
                word32 sigLen = MAX_SIG_DATA_SZ;
11707
0
                if ((ssl->hsType == DYNAMIC_TYPE_RSA) &&
11708
0
                    (args->sigLen > MAX_SIG_DATA_SZ)) {
11709
                    /* We store the RSA signature in the sigData buffer
11710
                     * temporarily, hence its size must be fitting. */
11711
0
                    sigLen = args->sigLen;
11712
0
                }
11713
0
                args->sigData = (byte*)XMALLOC(sigLen, ssl->heap,
11714
0
                                                    DYNAMIC_TYPE_SIGNATURE);
11715
0
                if (args->sigData == NULL) {
11716
0
                    ERROR_OUT(MEMORY_E, exit_scv);
11717
0
                }
11718
0
            }
11719
11720
        #ifdef WOLFSSL_DUAL_ALG_CERTS
11721
            if ((ssl->sigSpec != NULL) &&
11722
                (*ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) &&
11723
                (args->altSigData == NULL)) {
11724
                word32 sigLen = MAX_SIG_DATA_SZ;
11725
                if (ssl->hsAltType == DYNAMIC_TYPE_RSA &&
11726
                    args->altSigLen > MAX_SIG_DATA_SZ) {
11727
                    /* We store the RSA signature in the sigData buffer
11728
                     * temporarily, hence its size must be fitting. */
11729
                    sigLen = args->altSigLen;
11730
                }
11731
                args->altSigData = (byte*)XMALLOC(sigLen, ssl->heap,
11732
                                                    DYNAMIC_TYPE_SIGNATURE);
11733
                if (args->altSigData == NULL) {
11734
                    ERROR_OUT(MEMORY_E, exit_scv);
11735
                }
11736
            }
11737
        #endif /* WOLFSSL_DUAL_ALG_CERTS */
11738
11739
            /* Create the data to be signed. */
11740
0
            ret = CreateSigData(ssl, args->sigData, &args->sigDataSz, 0);
11741
0
            if (ret != 0)
11742
0
                goto exit_scv;
11743
11744
        #ifdef WOLFSSL_DUAL_ALG_CERTS
11745
            if ((ssl->sigSpec != NULL) &&
11746
                (*ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH)) {
11747
                XMEMCPY(args->altSigData, args->sigData, args->sigDataSz);
11748
                args->altSigDataSz = args->sigDataSz;
11749
            }
11750
        #endif /* WOLFSSL_DUAL_ALG_CERTS */
11751
11752
0
        #ifndef NO_RSA
11753
0
            if (ssl->hsType == DYNAMIC_TYPE_RSA) {
11754
                /* build encoded signature buffer */
11755
0
                rsaSigBuf->length = WC_MAX_DIGEST_SIZE;
11756
0
                rsaSigBuf->buffer = (byte*)XMALLOC(rsaSigBuf->length, ssl->heap,
11757
0
                                                   DYNAMIC_TYPE_SIGNATURE);
11758
0
                if (rsaSigBuf->buffer == NULL) {
11759
0
                    ERROR_OUT(MEMORY_E, exit_scv);
11760
0
                }
11761
11762
0
                ret = CreateRSAEncodedSig(rsaSigBuf->buffer, args->sigData,
11763
0
                    args->sigDataSz, args->sigAlgo, ssl->options.hashAlgo);
11764
0
                if (ret < 0)
11765
0
                    goto exit_scv;
11766
0
                rsaSigBuf->length = (unsigned int)ret;
11767
0
                ret = 0;
11768
0
            }
11769
0
        #endif /* !NO_RSA */
11770
0
        #ifdef HAVE_ECC
11771
0
            if (ssl->hsType == DYNAMIC_TYPE_ECC) {
11772
0
                args->sigLen = (word32)args->sendSz - args->idx -
11773
0
                               HASH_SIG_SIZE -
11774
0
                               VERIFY_HEADER;
11775
            #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
11776
                if (ssl->buffers.keyType != sm2_sa_algo)
11777
            #endif
11778
0
                {
11779
0
                    ret = CreateECCEncodedSig(args->sigData,
11780
0
                        args->sigDataSz, ssl->options.hashAlgo);
11781
0
                    if (ret < 0)
11782
0
                        goto exit_scv;
11783
0
                    args->sigDataSz = (word16)ret;
11784
0
                    ret = 0;
11785
0
                }
11786
0
            }
11787
0
        #endif /* HAVE_ECC */
11788
        #ifdef HAVE_ED25519
11789
            if (ssl->hsType == DYNAMIC_TYPE_ED25519) {
11790
                ret = Ed25519CheckPubKey(ssl);
11791
                if (ret < 0) {
11792
                    ERROR_OUT(ret, exit_scv);
11793
                }
11794
                args->sigLen = ED25519_SIG_SIZE;
11795
            }
11796
        #endif /* HAVE_ED25519 */
11797
        #ifdef HAVE_ED448
11798
            if (ssl->hsType == DYNAMIC_TYPE_ED448) {
11799
                ret = Ed448CheckPubKey(ssl);
11800
                if (ret < 0) {
11801
                    ERROR_OUT(ret, exit_scv);
11802
                }
11803
                args->sigLen = ED448_SIG_SIZE;
11804
            }
11805
11806
        #endif /* HAVE_ED448 */
11807
        #if defined(HAVE_FALCON)
11808
            if (ssl->hsType == DYNAMIC_TYPE_FALCON) {
11809
                /* Per-key, not the family maximum: this is handed to the
11810
                 * signer as the output capacity and the buffer above was
11811
                 * reserved from this key's signature length. */
11812
                int fSigSz = wc_falcon_sig_size((falcon_key*)ssl->hsKey);
11813
                if (fSigSz <= 0) {
11814
                    ERROR_OUT(ALGO_ID_E, exit_scv);
11815
                }
11816
                args->sigLen = (word32)fSigSz;
11817
            }
11818
        #endif /* HAVE_FALCON */
11819
        #if defined(WOLFSSL_HAVE_MLDSA) && !defined(WOLFSSL_MLDSA_NO_SIGN)
11820
            if (ssl->hsType == DYNAMIC_TYPE_MLDSA) {
11821
                int mSigSz = wc_MlDsaKey_SigSize((wc_MlDsaKey*)ssl->hsKey);
11822
                if (mSigSz <= 0) {
11823
                    ERROR_OUT(ALGO_ID_E, exit_scv);
11824
                }
11825
                args->sigLen = (word32)mSigSz;
11826
            }
11827
        #endif /* WOLFSSL_HAVE_MLDSA && !WOLFSSL_MLDSA_NO_SIGN */
11828
        #if defined(WOLFSSL_HAVE_SLHDSA)
11829
            if (ssl->hsType == DYNAMIC_TYPE_SLHDSA) {
11830
                int slhSigSz = wc_SlhDsaKey_SigSize((SlhDsaKey*)ssl->hsKey);
11831
                if (slhSigSz <= 0) {
11832
                    ERROR_OUT(ALGO_ID_E, exit_scv);
11833
                }
11834
                args->sigLen = (word32)slhSigSz;
11835
            }
11836
        #endif /* WOLFSSL_HAVE_SLHDSA */
11837
11838
        #ifdef WOLFSSL_DUAL_ALG_CERTS
11839
            if (ssl->sigSpec != NULL &&
11840
                *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) {
11841
11842
            #ifndef NO_RSA
11843
                if (ssl->hsAltType == DYNAMIC_TYPE_RSA) {
11844
                    /* build encoded signature buffer */
11845
                    XFREE(rsaSigBuf->buffer, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
11846
                    rsaSigBuf->length = WC_MAX_DIGEST_SIZE;
11847
                    rsaSigBuf->buffer = (byte*)XMALLOC(rsaSigBuf->length,
11848
                                                       ssl->heap,
11849
                                                       DYNAMIC_TYPE_SIGNATURE);
11850
                    if (rsaSigBuf->buffer == NULL) {
11851
                        ERROR_OUT(MEMORY_E, exit_scv);
11852
                    }
11853
11854
                    ret = CreateRSAEncodedSig(rsaSigBuf->buffer,
11855
                                    args->altSigData, args->altSigDataSz,
11856
                                    args->altSigAlgo, ssl->options.hashAlgo);
11857
                    if (ret < 0)
11858
                        goto exit_scv;
11859
                    rsaSigBuf->length = ret;
11860
                    ret = 0;
11861
                }
11862
            #endif /* !NO_RSA */
11863
            #ifdef HAVE_ECC
11864
                if (ssl->hsAltType == DYNAMIC_TYPE_ECC) {
11865
                    ret = CreateECCEncodedSig(args->altSigData,
11866
                            args->altSigDataSz, ssl->options.hashAlgo);
11867
                    if (ret < 0)
11868
                        goto exit_scv;
11869
                    args->altSigDataSz = (word16)ret;
11870
                    ret = 0;
11871
                }
11872
            #endif /* HAVE_ECC */
11873
            }
11874
        #endif /* WOLFSSL_DUAL_ALG_CERTS */
11875
11876
            /* Advance state and proceed */
11877
0
            ssl->options.asyncState = TLS_ASYNC_DO;
11878
0
        } /* case TLS_ASYNC_BUILD */
11879
0
        FALL_THROUGH;
11880
11881
0
        case TLS_ASYNC_DO:
11882
0
        {
11883
0
            byte* sigOut = args->verify + HASH_SIG_SIZE + VERIFY_HEADER;
11884
        #ifdef WOLFSSL_DUAL_ALG_CERTS
11885
            if (ssl->sigSpec != NULL &&
11886
                *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) {
11887
                /* As we have two signatures in the message, we store
11888
                 * the length of each before the actual signature. This
11889
                 * is necessary, as we could have two algorithms with
11890
                 * variable length signatures. */
11891
                sigOut += OPAQUE16_LEN;
11892
            }
11893
        #endif
11894
            /* Only the per-algorithm signing branches below consume this. */
11895
0
            (void)sigOut;
11896
0
        #ifdef HAVE_ECC
11897
0
            if (ssl->hsType == DYNAMIC_TYPE_ECC) {
11898
            #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
11899
                if (ssl->buffers.keyType == sm2_sa_algo) {
11900
                    ret = Sm2wSm3Sign(ssl, TLS13_SM2_SIG_ID,
11901
                        TLS13_SM2_SIG_ID_SZ, args->sigData, args->sigDataSz,
11902
                        sigOut, &args->sigLen, (ecc_key*)ssl->hsKey, NULL);
11903
                }
11904
                else
11905
            #endif
11906
0
                {
11907
0
                    ret = EccSign(ssl, args->sigData, args->sigDataSz,
11908
0
                        sigOut, &args->sigLen, (ecc_key*)ssl->hsKey,
11909
                #ifdef HAVE_PK_CALLBACKS
11910
                        ssl->buffers.key
11911
                #else
11912
0
                        NULL
11913
0
                #endif
11914
0
                    );
11915
0
                }
11916
0
                args->length = args->sigLen;
11917
0
            }
11918
0
        #endif /* HAVE_ECC */
11919
        #ifdef HAVE_ED25519
11920
            if (ssl->hsType == DYNAMIC_TYPE_ED25519) {
11921
                ret = Ed25519Sign(ssl, args->sigData, args->sigDataSz,
11922
                    sigOut, &args->sigLen, (ed25519_key*)ssl->hsKey,
11923
            #ifdef HAVE_PK_CALLBACKS
11924
                    ssl->buffers.key
11925
            #else
11926
                    NULL
11927
            #endif
11928
                );
11929
                args->length = args->sigLen;
11930
            }
11931
        #endif
11932
        #ifdef HAVE_ED448
11933
            if (ssl->hsType == DYNAMIC_TYPE_ED448) {
11934
                ret = Ed448Sign(ssl, args->sigData, args->sigDataSz,
11935
                    sigOut, &args->sigLen, (ed448_key*)ssl->hsKey,
11936
            #ifdef HAVE_PK_CALLBACKS
11937
                    ssl->buffers.key
11938
            #else
11939
                    NULL
11940
            #endif
11941
                );
11942
                args->length = args->sigLen;
11943
            }
11944
        #endif
11945
        #if defined(HAVE_FALCON)
11946
            if (ssl->hsType == DYNAMIC_TYPE_FALCON) {
11947
                ret = wc_falcon_sign_msg(args->sigData, args->sigDataSz,
11948
                                         sigOut, &args->sigLen,
11949
                                         (falcon_key*)ssl->hsKey, ssl->rng);
11950
                args->length = args->sigLen;
11951
            }
11952
        #endif /* HAVE_FALCON */
11953
        #if defined(WOLFSSL_HAVE_MLDSA) && !defined(WOLFSSL_MLDSA_NO_SIGN)
11954
            if (ssl->hsType == DYNAMIC_TYPE_MLDSA) {
11955
                ret = wc_MlDsaKey_SignCtx((wc_MlDsaKey*)ssl->hsKey, NULL, 0,
11956
                                          sigOut, &args->sigLen,
11957
                                          args->sigData, args->sigDataSz,
11958
                                          ssl->rng);
11959
                args->length = args->sigLen;
11960
            }
11961
        #endif /* WOLFSSL_HAVE_MLDSA */
11962
        #if defined(WOLFSSL_HAVE_SLHDSA) && !defined(WOLFSSL_SLHDSA_VERIFY_ONLY)
11963
            if (ssl->hsType == DYNAMIC_TYPE_SLHDSA) {
11964
                /* The FIPS wrapper for wc_SlhDsaKey_Sign gates on the per-thread
11965
                 * privateKeyReadEnable flag (unlike ML-DSA sign), returning
11966
                 * FIPS_PRIVATE_KEY_LOCKED_E when the key is locked. Bracket the
11967
                 * sign so it can read the SLH-DSA private key. */
11968
                PRIVATE_KEY_UNLOCK();
11969
                ret = wc_SlhDsaKey_Sign((SlhDsaKey*)ssl->hsKey, NULL, 0,
11970
                                        args->sigData, args->sigDataSz,
11971
                                        sigOut, &args->sigLen, ssl->rng);
11972
                PRIVATE_KEY_LOCK();
11973
                args->length = args->sigLen;
11974
            }
11975
        #endif /* WOLFSSL_HAVE_SLHDSA */
11976
0
        #if !defined(NO_RSA) && !defined(WOLFSSL_RSA_PUBLIC_ONLY) && \
11977
0
            !defined(WOLFSSL_RSA_VERIFY_ONLY)
11978
0
            if (ssl->hsType == DYNAMIC_TYPE_RSA) {
11979
0
                args->toSign = rsaSigBuf->buffer;
11980
0
                args->toSignSz = (word32)rsaSigBuf->length;
11981
            #if defined(HAVE_PK_CALLBACKS) && \
11982
                defined(TLS13_RSA_PSS_SIGN_CB_NO_PREHASH)
11983
                /* Pass full data to sign (args->sigData), not hash of */
11984
                if (ssl->ctx->RsaPssSignCb) {
11985
                    args->toSign = args->sigData;
11986
                    args->toSignSz = args->sigDataSz;
11987
                }
11988
            #endif
11989
0
                ret = RsaSign(ssl, (const byte*)args->toSign, args->toSignSz,
11990
0
                              sigOut, &args->sigLen, args->sigAlgo,
11991
0
                              ssl->options.hashAlgo, (RsaKey*)ssl->hsKey,
11992
0
                              ssl->buffers.key);
11993
0
                if (ret == 0) {
11994
0
                    args->length = args->sigLen;
11995
0
                    XMEMCPY(args->sigData, sigOut, args->sigLen);
11996
0
                }
11997
0
            }
11998
0
        #endif /* !NO_RSA && !WOLFSSL_RSA_PUBLIC_ONLY && !WOLFSSL_RSA_VERIFY_ONLY */
11999
12000
            /* Check for error */
12001
0
            if (ret != 0) {
12002
0
                goto exit_scv;
12003
0
            }
12004
12005
        #ifdef WOLFSSL_DUAL_ALG_CERTS
12006
            if (ssl->sigSpec != NULL &&
12007
                *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) {
12008
                /* Add signature length for the first signature. */
12009
                c16toa((word16)args->sigLen, sigOut - OPAQUE16_LEN);
12010
                args->length += OPAQUE16_LEN;
12011
12012
                /* Advance our pointer to where we store the alt signature.
12013
                 * We also add additional space for the length field of the
12014
                 * second signature. */
12015
                sigOut += args->sigLen + OPAQUE16_LEN;
12016
12017
                /* Generate the alternative signature */
12018
            #ifdef HAVE_ECC
12019
                if (ssl->hsAltType == DYNAMIC_TYPE_ECC) {
12020
                    ret = EccSign(ssl, args->altSigData, args->altSigDataSz,
12021
                                  sigOut, &args->altSigLen,
12022
                                  (ecc_key*)ssl->hsAltKey,
12023
                    #ifdef HAVE_PK_CALLBACKS
12024
                                  ssl->buffers.altKey
12025
                    #else
12026
                                  NULL
12027
                    #endif
12028
                                  );
12029
                }
12030
            #endif /* HAVE_ECC */
12031
            #if !defined(NO_RSA) && !defined(WOLFSSL_RSA_PUBLIC_ONLY) && \
12032
                !defined(WOLFSSL_RSA_VERIFY_ONLY)
12033
                if (ssl->hsAltType == DYNAMIC_TYPE_RSA) {
12034
                    args->toSign = rsaSigBuf->buffer;
12035
                    args->toSignSz = (word32)rsaSigBuf->length;
12036
                #if defined(HAVE_PK_CALLBACKS) && \
12037
                    defined(TLS13_RSA_PSS_SIGN_CB_NO_PREHASH)
12038
                    /* Pass full data to sign (args->altSigData), not hash of */
12039
                    if (ssl->ctx->RsaPssSignCb) {
12040
                        args->toSign = args->altSigData;
12041
                        args->toSignSz = (word32)args->altSigDataSz;
12042
                    }
12043
                #endif
12044
                    ret = RsaSign(ssl, (const byte*)args->toSign,
12045
                                  args->toSignSz, sigOut, &args->altSigLen,
12046
                                  args->altSigAlgo, ssl->options.hashAlgo,
12047
                                  (RsaKey*)ssl->hsAltKey,
12048
                                  ssl->buffers.altKey);
12049
12050
                    if (ret == 0) {
12051
                        XMEMCPY(args->altSigData, sigOut, args->altSigLen);
12052
                    }
12053
                }
12054
            #endif /* !NO_RSA && !WOLFSSL_RSA_PUBLIC_ONLY && !WOLFSSL_RSA_VERIFY_ONLY */
12055
            #if defined(HAVE_FALCON)
12056
                if (ssl->hsAltType == DYNAMIC_TYPE_FALCON) {
12057
                    ret = wc_falcon_sign_msg(args->altSigData,
12058
                                             args->altSigDataSz, sigOut,
12059
                                             &args->altSigLen,
12060
                                             (falcon_key*)ssl->hsAltKey,
12061
                                             ssl->rng);
12062
                }
12063
            #endif /* HAVE_FALCON */
12064
            #if defined(WOLFSSL_HAVE_MLDSA) && !defined(WOLFSSL_MLDSA_NO_SIGN)
12065
                if (ssl->hsAltType == DYNAMIC_TYPE_MLDSA) {
12066
                    ret = wc_MlDsaKey_SignCtx((wc_MlDsaKey*)ssl->hsAltKey,
12067
                                NULL, 0, sigOut, &args->altSigLen,
12068
                                args->altSigData, args->altSigDataSz, ssl->rng);
12069
                }
12070
            #endif /* WOLFSSL_HAVE_MLDSA */
12071
12072
                /* Check for error */
12073
                if (ret != 0) {
12074
                    goto exit_scv;
12075
                }
12076
12077
                /* Add signature length for the alternative signature. */
12078
                c16toa((word16)args->altSigLen, sigOut - OPAQUE16_LEN);
12079
12080
                /* Add length of the alt sig to the total length */
12081
                args->length += args->altSigLen + OPAQUE16_LEN;
12082
            }
12083
        #endif /* WOLFSSL_DUAL_ALG_CERTS */
12084
12085
            /* The TLS 1.3 CertificateVerify signature is length-prefixed with a
12086
             * 2-byte field (opaque signature<0..2^16-1>), so the body - a single
12087
             * signature, or the combined native + alternative signature with
12088
             * WOLFSSL_DUAL_ALG_CERTS - cannot exceed 65535 bytes. Reject rather
12089
             * than let c16toa truncate it into a malformed message. args->length
12090
             * is word32 so the dual-alg accumulation above cannot wrap before
12091
             * this check. */
12092
0
            if (args->length > WOLFSSL_MAX_16BIT) {
12093
0
                ERROR_OUT(BUFFER_E, exit_scv);
12094
0
            }
12095
12096
            /* Add signature length. */
12097
0
            c16toa((word16)args->length, args->verify + HASH_SIG_SIZE);
12098
12099
            /* Advance state and proceed */
12100
0
            ssl->options.asyncState = TLS_ASYNC_VERIFY;
12101
0
        } /* case TLS_ASYNC_DO */
12102
0
        FALL_THROUGH;
12103
12104
0
        case TLS_ASYNC_VERIFY:
12105
0
        {
12106
0
        #ifndef NO_RSA
12107
0
            if (ssl->hsType == DYNAMIC_TYPE_RSA) {
12108
                /* check for signature faults */
12109
0
                ret = VerifyRsaSign(ssl, args->sigData, args->sigLen,
12110
0
                    rsaSigBuf->buffer, (word32)rsaSigBuf->length, args->sigAlgo,
12111
0
                    ssl->options.hashAlgo, (RsaKey*)ssl->hsKey,
12112
0
                    ssl->buffers.key);
12113
0
            }
12114
        #ifdef WOLFSSL_DUAL_ALG_CERTS
12115
            if (ssl->sigSpec != NULL &&
12116
                *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH &&
12117
                ssl->hsAltType == DYNAMIC_TYPE_RSA) {
12118
                /* check for signature faults */
12119
                ret = VerifyRsaSign(ssl, args->altSigData, args->altSigLen,
12120
                        rsaSigBuf->buffer, (word32)rsaSigBuf->length,
12121
                        args->altSigAlgo, ssl->options.hashAlgo,
12122
                        (RsaKey*)ssl->hsAltKey, ssl->buffers.altKey);
12123
            }
12124
        #endif /* WOLFSSL_DUAL_ALG_CERTS */
12125
0
        #endif /* !NO_RSA */
12126
        #if defined(HAVE_ECC) && defined(WOLFSSL_CHECK_SIG_FAULTS)
12127
            if (ssl->hsType == DYNAMIC_TYPE_ECC) {
12128
                byte* sigOut = args->verify + HASH_SIG_SIZE + VERIFY_HEADER;
12129
            #ifdef WOLFSSL_DUAL_ALG_CERTS
12130
                if (ssl->sigSpec != NULL &&
12131
                    *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) {
12132
                    /* Add our length offset. */
12133
                    sigOut += OPAQUE16_LEN;
12134
                }
12135
            #endif
12136
            #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
12137
                if (ssl->buffers.keyType == sm2_sa_algo) {
12138
                    ret = Sm2wSm3Verify(ssl, TLS13_SM2_SIG_ID,
12139
                        TLS13_SM2_SIG_ID_SZ,
12140
                        sigOut, args->sigLen, args->sigData, args->sigDataSz,
12141
                        (ecc_key*)ssl->hsKey, NULL);
12142
                }
12143
                else
12144
            #endif
12145
                {
12146
                #ifdef HAVE_PK_CALLBACKS
12147
                    buffer tmp;
12148
12149
                    /* Private key may be held by the PK callback. */
12150
                    tmp.length = ssl->buffers.key ?
12151
                        ssl->buffers.key->length : 0;
12152
                    tmp.buffer = ssl->buffers.key ?
12153
                        ssl->buffers.key->buffer : NULL;
12154
                #endif
12155
                    ret = EccVerify(ssl, sigOut, args->sigLen,
12156
                            args->sigData, args->sigDataSz,
12157
                            (ecc_key*)ssl->hsKey,
12158
                #ifdef HAVE_PK_CALLBACKS
12159
                            &tmp
12160
                #else
12161
                            NULL
12162
                #endif
12163
                            );
12164
                }
12165
            }
12166
        #ifdef WOLFSSL_DUAL_ALG_CERTS
12167
            if (ssl->sigSpec != NULL &&
12168
                *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH &&
12169
                ssl->hsAltType == DYNAMIC_TYPE_ECC) {
12170
                /* check for signature faults */
12171
                byte* sigOut = args->verify + HASH_SIG_SIZE + VERIFY_HEADER +
12172
                                args->sigLen + OPAQUE16_LEN + OPAQUE16_LEN;
12173
            #ifdef HAVE_PK_CALLBACKS
12174
                buffer tmp;
12175
12176
                /* Private key may be held by the PK callback. */
12177
                tmp.length = ssl->buffers.altKey ?
12178
                    ssl->buffers.altKey->length : 0;
12179
                tmp.buffer = ssl->buffers.altKey ?
12180
                    ssl->buffers.altKey->buffer : NULL;
12181
            #endif
12182
                ret = EccVerify(ssl, sigOut, args->altSigLen,
12183
                        args->altSigData, args->altSigDataSz,
12184
                        (ecc_key*)ssl->hsAltKey,
12185
            #ifdef HAVE_PK_CALLBACKS
12186
                        &tmp
12187
            #else
12188
                        NULL
12189
            #endif
12190
                        );
12191
            }
12192
        #endif /* WOLFSSL_DUAL_ALG_CERTS */
12193
        #endif /* HAVE_ECC && WOLFSSL_CHECK_SIG_FAULTS */
12194
12195
            /* Check for error */
12196
0
            if (ret != 0) {
12197
0
                goto exit_scv;
12198
0
            }
12199
12200
            /* Advance state and proceed */
12201
0
            ssl->options.asyncState = TLS_ASYNC_FINALIZE;
12202
0
        } /* case TLS_ASYNC_VERIFY */
12203
0
        FALL_THROUGH;
12204
12205
0
        case TLS_ASYNC_FINALIZE:
12206
0
        {
12207
#ifdef WOLFSSL_TLS13_STREAM_CERT_VERIFY
12208
            if (ssl->buffers.certVerifyMsg.buffer != NULL) {
12209
                /* Streaming path: the assembled body sits in certVerifyMsg;
12210
                 * record its final length (exact even for variable-length
12211
                 * signatures). Per-fragment record/handshake headers are added
12212
                 * in TLS_ASYNC_END. */
12213
                ssl->buffers.certVerifyMsg.length =
12214
                    (word32)args->length + HASH_SIG_SIZE + VERIFY_HEADER;
12215
            }
12216
#endif /* WOLFSSL_TLS13_STREAM_CERT_VERIFY */
12217
            /* In-place path: put the record and handshake headers on now.
12218
             * args->output is NULL only on the streaming path. */
12219
0
            if (args->output != NULL) {
12220
0
                AddTls13Headers(args->output, args->length + HASH_SIG_SIZE +
12221
0
                                VERIFY_HEADER, certificate_verify, ssl);
12222
12223
0
                args->sendSz = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ +
12224
0
                                args->length + HASH_SIG_SIZE + VERIFY_HEADER;
12225
            #ifdef WOLFSSL_DTLS13
12226
                if (ssl->options.dtls)
12227
                    args->sendSz += recordLayerHdrExtra + DTLS_HANDSHAKE_EXTRA;
12228
            #endif /* WOLFSSL_DTLS13 */
12229
0
            }
12230
            /* Advance state and proceed */
12231
0
            ssl->options.asyncState = TLS_ASYNC_END;
12232
0
        } /* case TLS_ASYNC_FINALIZE */
12233
0
        FALL_THROUGH;
12234
12235
0
        case TLS_ASYNC_END:
12236
0
        {
12237
            /* Body of the handshake message: [sigAlg(2) | sigLen(2) | sig]. In
12238
             * the in-place path it sits at args->verify in the output buffer;
12239
             * in the streaming path it sits in ssl->buffers.certVerifyMsg. */
12240
0
            word32 msgSz;
12241
0
            word32 maxFrag = (word32)wolfssl_local_GetMaxPlaintextSize(ssl);
12242
0
            byte*  output;
12243
0
            word32 fragSz;
12244
0
            word32 i;
12245
0
            int    recSz;
12246
0
            int    thisSendSz;
12247
12248
#ifdef WOLFSSL_TLS13_STREAM_CERT_VERIFY
12249
            if (ssl->buffers.certVerifyMsg.buffer != NULL) {
12250
                /* Streamed send: the assembled body lives in
12251
                 * ssl->buffers.certVerifyMsg and the send cursor in
12252
                 * ssl->fragOffset - both connection-level - so a non-blocking
12253
                 * WANT_WRITE resumes here (via TLS_ASYNC_END) without
12254
                 * recomputing the signature. Emit one encrypted record per
12255
                 * iteration and flush it, so the output buffer never holds more
12256
                 * than a single fragment. Only the first record carries the
12257
                 * handshake header; BuildTls13Message hashes each fragment's
12258
                 * plaintext in order, keeping the transcript hash correct. The
12259
                 * cursor is advanced before the flush because the record is
12260
                 * already committed to the output buffer; the cursor tracks
12261
                 * message-body -> record progress, not bytes on the wire, so a
12262
                 * WANT_WRITE resumes on the next fragment. Advancing after the
12263
                 * flush would rebuild and double-send the fragment on resume.
12264
                 * This is not merely a convention: the accept/connect loop
12265
                 * flushes pending output and returns WANT_WRITE without
12266
                 * re-entering this function until the output buffer drains, so
12267
                 * the committed record is never skipped or overwritten.
12268
                 * certVerifyMsg is released on completion or error at exit_scv;
12269
                 * it is kept across WANT_WRITE for resume. */
12270
                msgSz = ssl->buffers.certVerifyMsg.length;
12271
                if (maxFrag <= HANDSHAKE_HEADER_SZ) {
12272
                    ERROR_OUT(BUFFER_E, exit_scv);
12273
                }
12274
                while (ssl->fragOffset < msgSz && ret == 0) {
12275
                    if (ssl->fragOffset == 0) {
12276
                        fragSz = maxFrag - HANDSHAKE_HEADER_SZ;
12277
                        if (fragSz > msgSz)
12278
                            fragSz = msgSz;
12279
                        i = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
12280
                        thisSendSz = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ +
12281
                                     (int)fragSz + MAX_MSG_EXTRA;
12282
                    }
12283
                    else {
12284
                        fragSz = msgSz - ssl->fragOffset;
12285
                        if (fragSz > maxFrag)
12286
                            fragSz = maxFrag;
12287
                        i = RECORD_HEADER_SZ;
12288
                        thisSendSz = RECORD_HEADER_SZ + (int)fragSz +
12289
                                     MAX_MSG_EXTRA;
12290
                    }
12291
12292
                    if ((ret = CheckAvailableSize(ssl, thisSendSz)) != 0) {
12293
                        goto exit_scv;
12294
                    }
12295
                    output = GetOutputBuffer(ssl);
12296
12297
                    if (ssl->fragOffset == 0) {
12298
                        AddTls13FragHeaders(output, fragSz, 0, msgSz,
12299
                                            certificate_verify, ssl);
12300
                    }
12301
                    else {
12302
                        AddTls13RecordHeader(output, fragSz, handshake, ssl);
12303
                    }
12304
                    XMEMCPY(output + i,
12305
                            ssl->buffers.certVerifyMsg.buffer + ssl->fragOffset,
12306
                            fragSz);
12307
12308
                    /* This message is always encrypted. */
12309
                    recSz = BuildTls13Message(ssl, output, thisSendSz,
12310
                                output + RECORD_HEADER_SZ,
12311
                                (int)(i - RECORD_HEADER_SZ + fragSz), handshake,
12312
                                1, 0, 0);
12313
                    if (recSz < 0) {
12314
                        ret = recSz;
12315
                        goto exit_scv;
12316
                    }
12317
12318
                #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
12319
                    /* Trace the logical CertificateVerify once (first fragment),
12320
                     * matching the single-record path. */
12321
                    if (ssl->fragOffset == 0) {
12322
                        if (ssl->hsInfoOn)
12323
                            AddPacketName(ssl, "CertificateVerify");
12324
                        if (ssl->toInfoOn) {
12325
                            ret = AddPacketInfo(ssl, "CertificateVerify",
12326
                                        handshake, output, recSz, WRITE_PROTO, 0,
12327
                                        ssl->heap);
12328
                            if (ret != 0)
12329
                                goto exit_scv;
12330
                        }
12331
                    }
12332
                #endif
12333
12334
                    ssl->buffers.outputBuffer.length += (word32)recSz;
12335
                    ssl->fragOffset += fragSz;
12336
                    /* Flush every fragment unconditionally - unlike the
12337
                     * in-place path this cannot honor ssl->options.groupMessages
12338
                     * (batch with later handshake messages), because streaming
12339
                     * exists precisely to keep the output buffer bounded to a
12340
                     * single fragment. */
12341
                    ret = SendBuffered(ssl);
12342
                }
12343
12344
                ssl->options.buildingMsg = 0;
12345
                break;
12346
            }
12347
#endif /* WOLFSSL_TLS13_STREAM_CERT_VERIFY */
12348
12349
            /* In-place path: the whole message is in args->output. */
12350
0
            msgSz = (word32)args->length + HASH_SIG_SIZE + VERIFY_HEADER;
12351
12352
#ifdef WOLFSSL_DTLS13
12353
            if (ssl->options.dtls) {
12354
                ssl->options.buildingMsg = 0;
12355
12356
                /* Dtls13HandshakeSend takes word16 output/send sizes, so the
12357
                 * whole assembled CertificateVerify (signature plus framing)
12358
                 * must fit in 16 bits. Every current SLH-DSA parameter set
12359
                 * stays well under this (256f, the largest, is ~50KB), but
12360
                 * guard the casts explicitly - mirroring the args->length check
12361
                 * on the TLS path - so a future larger signature fails loudly
12362
                 * instead of being silently truncated into a malformed record.
12363
                 * outputSz is the reserved capacity and is >= sendSz, so it
12364
                 * bounds both casts. */
12365
                if (args->outputSz > WOLFSSL_MAX_16BIT) {
12366
                    ERROR_OUT(BUFFER_E, exit_scv);
12367
                }
12368
12369
                ret = Dtls13HandshakeSend(ssl, args->output,
12370
                    (word16)args->outputSz,
12371
                    (word16)args->sendSz, certificate_verify, 1);
12372
                if (ret != 0)
12373
                    goto exit_scv;
12374
12375
                break;
12376
            }
12377
#endif /* WOLFSSL_DTLS13 */
12378
12379
0
            if (HANDSHAKE_HEADER_SZ + msgSz <= maxFrag) {
12380
                /* Fits in a single record: the common path used by RSA, ECC,
12381
                 * EdDSA and ML-DSA is left byte-for-byte unchanged. */
12382
12383
                /* Always encrypted. A record AEAD pend propagates through
12384
                 * exit_scv (args kept) and the retry resumes the build. */
12385
0
                ret = BuildTls13Message(ssl, args->output,
12386
0
                                        (int)args->outputSz,
12387
0
                                        args->output + RECORD_HEADER_SZ,
12388
0
                                        args->sendSz - RECORD_HEADER_SZ,
12389
0
                                        handshake, 1, 0,
12390
0
                                        TLS13_HS_ASYNC_OKAY);
12391
12392
0
                if (ret < 0) {
12393
0
                    goto exit_scv;
12394
0
                }
12395
0
                else {
12396
0
                    args->sendSz = ret;
12397
0
                    ret = 0;
12398
0
                }
12399
12400
            #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
12401
                if (ssl->hsInfoOn)
12402
                    AddPacketName(ssl, "CertificateVerify");
12403
                if (ssl->toInfoOn) {
12404
                    ret = AddPacketInfo(ssl, "CertificateVerify", handshake,
12405
                                args->output, args->sendSz, WRITE_PROTO, 0,
12406
                                ssl->heap);
12407
                    if (ret != 0)
12408
                        goto exit_scv;
12409
                }
12410
            #endif
12411
12412
0
                ssl->buffers.outputBuffer.length += (word32)args->sendSz;
12413
0
            }
12414
0
            else {
12415
                /* Signature does not fit in a single TLS record (e.g. SLH-DSA,
12416
                 * whose signatures range up to ~50KB). Fragment the handshake
12417
                 * message across multiple encrypted records. Only the first
12418
                 * fragment carries the 4-byte handshake header; the transcript
12419
                 * hash is maintained correctly because BuildTls13Message hashes
12420
                 * each fragment's plaintext in order.
12421
                 *
12422
                 * The fragmentation cursor lives in args (frag/fragOffset/
12423
                 * fragActive) so that a WC_PENDING_E from the record AEAD under
12424
                 * WOLFSSL_ASYNC_CRYPT resumes on the same fragment rather than
12425
                 * restarting at offset 0 and re-emitting committed records. */
12426
0
                if (maxFrag <= HANDSHAKE_HEADER_SZ) {
12427
0
                    ERROR_OUT(BUFFER_E, exit_scv);
12428
0
                }
12429
12430
                /* Copy the assembled body out of the output buffer once, before
12431
                 * we begin overwriting it with per-record data. args->frag is
12432
                 * preserved across async resumes and freed by FreeScv13Args. */
12433
0
                if (args->frag == NULL) {
12434
0
                    args->frag = (byte*)XMALLOC(msgSz, ssl->heap,
12435
0
                                                DYNAMIC_TYPE_TMP_BUFFER);
12436
0
                    if (args->frag == NULL) {
12437
0
                        ERROR_OUT(MEMORY_E, exit_scv);
12438
0
                    }
12439
0
                    XMEMCPY(args->frag, args->verify, msgSz);
12440
0
                    args->fragOffset = 0;
12441
0
                    args->fragActive = 0;
12442
0
                }
12443
12444
0
                while (args->fragOffset < msgSz && ret == 0) {
12445
0
                    if (args->fragOffset == 0) {
12446
0
                        fragSz = maxFrag - HANDSHAKE_HEADER_SZ;
12447
0
                        if (fragSz > msgSz)
12448
0
                            fragSz = msgSz;
12449
0
                        thisSendSz = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ +
12450
0
                                     (int)fragSz + MAX_MSG_EXTRA;
12451
0
                    }
12452
0
                    else {
12453
0
                        fragSz = msgSz - args->fragOffset;
12454
0
                        if (fragSz > maxFrag)
12455
0
                            fragSz = maxFrag;
12456
0
                        thisSendSz = RECORD_HEADER_SZ + (int)fragSz +
12457
0
                                     MAX_MSG_EXTRA;
12458
0
                    }
12459
12460
0
                    if ((ret = CheckAvailableSize(ssl, thisSendSz)) != 0) {
12461
0
                        goto exit_scv;
12462
0
                    }
12463
0
                    output = GetOutputBuffer(ssl);
12464
12465
0
                    i = RECORD_HEADER_SZ;
12466
0
                    if (args->fragOffset == 0)
12467
0
                        i += HANDSHAKE_HEADER_SZ;
12468
12469
                    /* Lay out this fragment's record header and plaintext once.
12470
                     * On an async resume of a pending fragment they are already
12471
                     * in place (outputBuffer.length was not advanced), so skip
12472
                     * straight to re-driving BuildTls13Message. */
12473
0
                    if (!args->fragActive) {
12474
0
                        if (args->fragOffset == 0) {
12475
0
                            AddTls13FragHeaders(output, fragSz, 0, msgSz,
12476
0
                                                certificate_verify, ssl);
12477
0
                        }
12478
0
                        else {
12479
0
                            AddTls13RecordHeader(output, fragSz, handshake, ssl);
12480
0
                        }
12481
0
                        XMEMCPY(output + i, args->frag + args->fragOffset,
12482
0
                                fragSz);
12483
0
                        args->fragActive = 1;
12484
0
                    }
12485
0
                    i += fragSz;
12486
12487
                    /* This message is always encrypted. */
12488
0
                    recSz = BuildTls13Message(ssl, output, thisSendSz,
12489
0
                                output + RECORD_HEADER_SZ,
12490
0
                                (int)(i - RECORD_HEADER_SZ), handshake, 1, 0, 0);
12491
0
                    if (recSz < 0) {
12492
                        /* WC_PENDING_E leaves frag/fragOffset/fragActive intact
12493
                         * for resume; real errors are cleaned up by
12494
                         * FreeScv13Args at exit_scv. */
12495
0
                        ret = recSz;
12496
0
                        goto exit_scv;
12497
0
                    }
12498
12499
                #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
12500
                    /* Trace the logical CertificateVerify once (on the first
12501
                     * fragment), matching the single-record path rather than
12502
                     * emitting one entry per record. */
12503
                    if (args->fragOffset == 0) {
12504
                        if (ssl->hsInfoOn)
12505
                            AddPacketName(ssl, "CertificateVerify");
12506
                        if (ssl->toInfoOn) {
12507
                            ret = AddPacketInfo(ssl, "CertificateVerify",
12508
                                        handshake, output, recSz, WRITE_PROTO, 0,
12509
                                        ssl->heap);
12510
                            if (ret != 0)
12511
                                goto exit_scv;
12512
                        }
12513
                    }
12514
                #endif
12515
12516
0
                    ssl->buffers.outputBuffer.length += (word32)recSz;
12517
0
                    args->fragOffset += fragSz;
12518
0
                    args->fragActive = 0;
12519
0
                }
12520
0
            }
12521
12522
0
            ssl->options.buildingMsg = 0;
12523
0
            if (!ssl->options.groupMessages)
12524
0
                ret = SendBuffered(ssl);
12525
0
            break;
12526
0
        }
12527
0
        default:
12528
0
            ret = INPUT_CASE_ERROR;
12529
0
    } /* switch(ssl->options.asyncState) */
12530
12531
0
exit_scv:
12532
#ifdef WOLFSSL_TLS13_STREAM_CERT_VERIFY
12533
    /* A streamed CertificateVerify keeps its assembled body across a
12534
     * non-blocking WANT_WRITE so the send resumes without recomputing the
12535
     * signature; release it on completion or on any real error. This path is
12536
     * mutually exclusive with WOLFSSL_ASYNC_CRYPT (see the feature guard in
12537
     * internal.h), so ret is never WC_PENDING_E here and the buffer needs no
12538
     * retention across an async resume. */
12539
    if (ret != WC_NO_ERR_TRACE(WANT_WRITE) &&
12540
            ssl->buffers.certVerifyMsg.buffer != NULL) {
12541
        XFREE(ssl->buffers.certVerifyMsg.buffer, ssl->heap,
12542
              DYNAMIC_TYPE_TMP_BUFFER);
12543
        ssl->buffers.certVerifyMsg.buffer = NULL;
12544
        ssl->buffers.certVerifyMsg.length = 0;
12545
        ssl->fragOffset = 0;
12546
    }
12547
#endif /* WOLFSSL_TLS13_STREAM_CERT_VERIFY */
12548
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
12549
    if (ret == 0) {
12550
        ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.key,
12551
            &ssl->buffers.keyMask);
12552
    }
12553
    else {
12554
        wolfssl_priv_der_blind_toggle(ssl->buffers.key, ssl->buffers.keyMask);
12555
    }
12556
#endif
12557
12558
0
    WOLFSSL_LEAVE("SendTls13CertificateVerify", ret);
12559
0
    WOLFSSL_END(WC_FUNC_CERTIFICATE_VERIFY_SEND);
12560
12561
#ifdef WOLFSSL_ASYNC_CRYPT
12562
    /* Handle async operation */
12563
    if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
12564
        return ret;
12565
    }
12566
#endif /* WOLFSSL_ASYNC_CRYPT */
12567
12568
    /* Final cleanup */
12569
0
    FreeScv13Args(ssl, args);
12570
0
    FreeKeyExchange(ssl);
12571
0
#ifdef WOLFSSL_ASYNC_IO
12572
    /* Cleanup async */
12573
0
    FreeAsyncCtx(ssl, 0);
12574
0
#endif
12575
12576
0
    if (ret != 0) {
12577
0
        WOLFSSL_ERROR_VERBOSE(ret);
12578
0
    }
12579
12580
0
    return ret;
12581
0
}
12582
#endif
12583
#endif /* !NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER */
12584
12585
#if !defined(NO_WOLFSSL_CLIENT) || !defined(WOLFSSL_NO_CLIENT_AUTH)
12586
/* handle processing TLS v1.3 certificate (11) */
12587
/* Parse and handle a TLS v1.3 Certificate message.
12588
 *
12589
 * ssl       The SSL/TLS object.
12590
 * input     The message buffer.
12591
 * inOutIdx  On entry, the index into the message buffer of Certificate.
12592
 *           On exit, the index of byte after the Certificate message.
12593
 * totalSz   The length of the current handshake message.
12594
 * returns 0 on success and otherwise failure.
12595
 */
12596
static int DoTls13Certificate(WOLFSSL* ssl, byte* input, word32* inOutIdx,
12597
                              word32 totalSz)
12598
0
{
12599
0
    int ret = 0;
12600
12601
0
    WOLFSSL_START(WC_FUNC_CERTIFICATE_DO);
12602
0
    WOLFSSL_ENTER("DoTls13Certificate");
12603
12604
#ifdef WOLFSSL_DTLS13
12605
    if (ssl->options.dtls && ssl->options.handShakeDone) {
12606
        /* certificate needs some special care after the handshake */
12607
        ret = Dtls13RtxProcessingCertificate(
12608
            ssl, input + *inOutIdx, totalSz);
12609
    }
12610
#endif /* WOLFSSL_DTLS13 */
12611
12612
0
    if (ret == 0)
12613
0
        ret = ProcessPeerCerts(ssl, input, inOutIdx, totalSz);
12614
0
    if (ret == 0) {
12615
0
#if !defined(NO_WOLFSSL_CLIENT)
12616
0
        if (ssl->options.side == WOLFSSL_CLIENT_END)
12617
0
            ssl->options.serverState = SERVER_CERT_COMPLETE;
12618
0
#endif
12619
#if !defined(NO_WOLFSSL_SERVER) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
12620
        if (ssl->options.side == WOLFSSL_SERVER_END &&
12621
                                ssl->options.handShakeState == HANDSHAKE_DONE) {
12622
            /* reset handshake states */
12623
            ssl->options.serverState = SERVER_FINISHED_COMPLETE;
12624
            ssl->options.acceptState  = TICKET_SENT;
12625
            ssl->options.handShakeState = SERVER_FINISHED_COMPLETE;
12626
        }
12627
#endif
12628
0
    }
12629
12630
0
    WOLFSSL_LEAVE("DoTls13Certificate", ret);
12631
0
    WOLFSSL_END(WC_FUNC_CERTIFICATE_DO);
12632
12633
0
    return ret;
12634
0
}
12635
#endif
12636
12637
#if (!defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
12638
     defined(HAVE_ED448) || defined(HAVE_FALCON) || \
12639
     defined(WOLFSSL_HAVE_MLDSA) || defined(WOLFSSL_HAVE_SLHDSA)) && \
12640
    !defined(NO_CERTS)
12641
12642
typedef struct Dcv13Args {
12643
    byte*  output; /* not allocated */
12644
    word32 sendSz;
12645
    word16 sz;
12646
    word32 sigSz;
12647
    word32 idx;
12648
    word32 begin;
12649
12650
    byte*  sigData;
12651
    word16 sigDataSz;
12652
#ifdef WOLFSSL_DUAL_ALG_CERTS
12653
    byte   altSigAlgo;
12654
    byte*  altSigData;
12655
    word32 altSigDataSz;
12656
    word32 altSignatureSz;
12657
    byte   altPeerAuthGood;
12658
#endif
12659
} Dcv13Args;
12660
12661
static void FreeDcv13Args(WOLFSSL* ssl, void* pArgs)
12662
0
{
12663
0
    Dcv13Args* args = (Dcv13Args*)pArgs;
12664
12665
0
    if (args && args->sigData != NULL) {
12666
0
        XFREE(args->sigData, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
12667
0
        args->sigData = NULL;
12668
0
    }
12669
#ifdef WOLFSSL_DUAL_ALG_CERTS
12670
    if (args && args->altSigData != NULL) {
12671
        XFREE(args->altSigData, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
12672
        args->altSigData = NULL;
12673
    }
12674
#endif
12675
0
    (void)ssl;
12676
0
}
12677
12678
#ifdef WOLFSSL_DUAL_ALG_CERTS
12679
#ifndef NO_RSA
12680
/* ssl->peerCert->sapkiDer is the alternative public key. Hopefully it is a
12681
 * RSA public key. Convert it into a usable public key. */
12682
static int decodeRsaKey(WOLFSSL* ssl)
12683
{
12684
    int keyRet;
12685
    word32 tmpIdx = 0;
12686
12687
    if (ssl->peerRsaKeyPresent)
12688
        return INVALID_PARAMETER;
12689
12690
    keyRet = AllocKey(ssl, DYNAMIC_TYPE_RSA, (void**)&ssl->peerRsaKey);
12691
    if (keyRet != 0)
12692
        return PEER_KEY_ERROR;
12693
12694
    ssl->peerRsaKeyPresent = 1;
12695
    keyRet = wc_RsaPublicKeyDecode(GetPeerCert(ssl)->sapkiDer, &tmpIdx,
12696
                                   ssl->peerRsaKey,
12697
                                   GetPeerCert(ssl)->sapkiLen);
12698
    if (keyRet != 0)
12699
        return PEER_KEY_ERROR;
12700
12701
    return 0;
12702
}
12703
#endif /* !NO_RSA */
12704
12705
#ifdef HAVE_ECC
12706
/* ssl->peerCert->sapkiDer is the alternative public key. Hopefully it is a
12707
 * ECC public key. Convert it into a usable public key. */
12708
static int decodeEccKey(WOLFSSL* ssl)
12709
{
12710
    int keyRet;
12711
    word32 tmpIdx = 0;
12712
12713
    if (ssl->peerEccDsaKeyPresent)
12714
        return INVALID_PARAMETER;
12715
12716
    keyRet = AllocKey(ssl, DYNAMIC_TYPE_ECC, (void**)&ssl->peerEccDsaKey);
12717
    if (keyRet != 0)
12718
        return PEER_KEY_ERROR;
12719
12720
    ssl->peerEccDsaKeyPresent = 1;
12721
    keyRet = wc_EccPublicKeyDecode(GetPeerCert(ssl)->sapkiDer, &tmpIdx,
12722
                                   ssl->peerEccDsaKey,
12723
                                   GetPeerCert(ssl)->sapkiLen);
12724
    if (keyRet != 0)
12725
        return PEER_KEY_ERROR;
12726
12727
    return 0;
12728
}
12729
#endif /* HAVE_ECC */
12730
12731
#ifdef WOLFSSL_HAVE_MLDSA
12732
/* ssl->peerCert->sapkiDer is the alternative public key. Hopefully it is a
12733
 * ML-DSA public key. Convert it into a usable public key. */
12734
static int decodeMlDsaKey(WOLFSSL* ssl, int level)
12735
{
12736
    int keyRet;
12737
    word32 tmpIdx = 0;
12738
12739
    if (ssl->peerMlDsaKeyPresent)
12740
        return INVALID_PARAMETER;
12741
12742
    keyRet = AllocKey(ssl, DYNAMIC_TYPE_MLDSA,
12743
                      (void**)&ssl->peerMlDsaKey);
12744
    if (keyRet != 0)
12745
        return PEER_KEY_ERROR;
12746
12747
    ssl->peerMlDsaKeyPresent = 1;
12748
    keyRet = wc_MlDsaKey_SetParams(ssl->peerMlDsaKey, level);
12749
    if (keyRet != 0)
12750
        return PEER_KEY_ERROR;
12751
12752
    keyRet = wc_MlDsaKey_PublicKeyDecode(ssl->peerMlDsaKey,
12753
                                         GetPeerCert(ssl)->sapkiDer,
12754
                                         GetPeerCert(ssl)->sapkiLen, &tmpIdx);
12755
    if (keyRet != 0)
12756
        return PEER_KEY_ERROR;
12757
12758
    return 0;
12759
}
12760
#endif /* WOLFSSL_HAVE_MLDSA */
12761
12762
#ifdef HAVE_FALCON
12763
/* ssl->peerCert->sapkiDer is the alternative public key. Hopefully it is a
12764
 * falcon public key. Convert it into a usable public key. */
12765
static int decodeFalconKey(WOLFSSL* ssl, int level)
12766
{
12767
    int keyRet;
12768
    word32 tmpIdx = 0;
12769
12770
    if (ssl->peerFalconKeyPresent)
12771
        return INVALID_PARAMETER;
12772
12773
    keyRet = AllocKey(ssl, DYNAMIC_TYPE_FALCON, (void**)&ssl->peerFalconKey);
12774
    if (keyRet != 0)
12775
        return PEER_KEY_ERROR;
12776
12777
    ssl->peerFalconKeyPresent = 1;
12778
    keyRet = wc_falcon_set_level(ssl->peerFalconKey, level);
12779
    if (keyRet != 0)
12780
        return PEER_KEY_ERROR;
12781
12782
    keyRet = wc_Falcon_PublicKeyDecode(GetPeerCert(ssl)->sapkiDer, &tmpIdx,
12783
                                       ssl->peerFalconKey,
12784
                                       GetPeerCert(ssl)->sapkiLen);
12785
    if (keyRet != 0)
12786
        return PEER_KEY_ERROR;
12787
12788
    return 0;
12789
}
12790
#endif /* HAVE_FALCON */
12791
#endif /* WOLFSSL_DUAL_ALG_CERTS */
12792
12793
/* handle processing TLS v1.3 certificate_verify (15) */
12794
/* Parse and handle a TLS v1.3 CertificateVerify message.
12795
 *
12796
 * ssl       The SSL/TLS object.
12797
 * input     The message buffer.
12798
 * inOutIdx  On entry, the index into the message buffer of
12799
 *           CertificateVerify.
12800
 *           On exit, the index of byte after the CertificateVerify message.
12801
 * totalSz   The length of the current handshake message.
12802
 * returns 0 on success and otherwise failure.
12803
 */
12804
static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input,
12805
                                    word32* inOutIdx, word32 totalSz)
12806
0
{
12807
0
    int         ret = 0;
12808
0
    byte*       sig = NULL;
12809
0
#ifndef NO_RSA
12810
    /* Use this as a temporary buffer for RSA signature verification. */
12811
0
    buffer*     rsaSigBuf = &ssl->buffers.sig;
12812
0
#endif
12813
#ifdef WOLFSSL_ASYNC_CRYPT
12814
    Dcv13Args* args = NULL;
12815
    WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
12816
#else
12817
0
    Dcv13Args  args[1];
12818
0
#endif
12819
12820
0
    WOLFSSL_START(WC_FUNC_CERTIFICATE_VERIFY_DO);
12821
0
    WOLFSSL_ENTER("DoTls13CertificateVerify");
12822
12823
#if defined(WOLFSSL_RENESAS_TSIP_TLS)
12824
    ret = tsip_Tls13CertificateVerify(ssl, input, inOutIdx, totalSz);
12825
    if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
12826
        goto exit_dcv;
12827
    }
12828
    ret = 0;
12829
#endif
12830
12831
#ifdef WOLFSSL_ASYNC_CRYPT
12832
    if (ssl->async == NULL) {
12833
        ssl->async = (struct WOLFSSL_ASYNC*)
12834
                XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
12835
                        DYNAMIC_TYPE_ASYNC);
12836
        if (ssl->async == NULL)
12837
            ERROR_OUT(MEMORY_E, exit_dcv);
12838
    }
12839
    args = (Dcv13Args*)ssl->async->args;
12840
12841
    ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
12842
    if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) {
12843
        /* Check for error */
12844
        if (ret < 0)
12845
            goto exit_dcv;
12846
    }
12847
    else
12848
#endif
12849
0
    {
12850
        /* Reset state */
12851
0
        ret = 0;
12852
0
        ssl->options.asyncState = TLS_ASYNC_BEGIN;
12853
0
        XMEMSET(args, 0, sizeof(Dcv13Args));
12854
0
        ssl->options.peerHashAlgo = sha_mac;
12855
0
        ssl->options.peerSigAlgo = anonymous_sa_algo;
12856
0
        args->idx = *inOutIdx;
12857
0
        args->begin = *inOutIdx;
12858
    #ifdef WOLFSSL_ASYNC_CRYPT
12859
        ssl->async->freeArgs = FreeDcv13Args;
12860
    #endif
12861
0
    }
12862
12863
0
    switch(ssl->options.asyncState)
12864
0
    {
12865
0
        case TLS_ASYNC_BEGIN:
12866
0
        {
12867
        #ifdef WOLFSSL_CALLBACKS
12868
            if (ssl->hsInfoOn) AddPacketName(ssl, "CertificateVerify");
12869
            if (ssl->toInfoOn) AddLateName("CertificateVerify",
12870
                                           &ssl->timeoutInfo);
12871
        #endif
12872
12873
            /* Advance state and proceed */
12874
0
            ssl->options.asyncState = TLS_ASYNC_BUILD;
12875
0
        } /* case TLS_ASYNC_BEGIN */
12876
0
        FALL_THROUGH;
12877
12878
0
        case TLS_ASYNC_BUILD:
12879
0
        {
12880
0
            int validSigAlgo;
12881
0
            const Suites* suites = WOLFSSL_SUITES(ssl);
12882
0
            word16 i;
12883
12884
            /* Signature algorithm. */
12885
0
            if ((args->idx - args->begin) + ENUM_LEN + ENUM_LEN > totalSz) {
12886
0
                ERROR_OUT(BUFFER_ERROR, exit_dcv);
12887
0
            }
12888
12889
#ifdef WOLFSSL_DUAL_ALG_CERTS
12890
            if (ssl->peerSigSpec == NULL) {
12891
                /* The peer did not respond. We didn't send CKS or they don't
12892
                 * support it. Either way, we do not need to handle dual
12893
                 * key/sig case. */
12894
                ssl->sigSpec = NULL;
12895
                ssl->sigSpecSz = 0;
12896
            }
12897
12898
            /* If no CKS extension or either native or alternative, then just
12899
             * get a normal sigalgo.  But if BOTH, then get the native and alt
12900
             * sig algos. */
12901
            if (ssl->sigSpec == NULL ||
12902
                *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_NATIVE ||
12903
                *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_ALTERNATIVE) {
12904
#endif /* WOLFSSL_DUAL_ALG_CERTS */
12905
0
                validSigAlgo = 0;
12906
0
                for (i = 0; i < suites->hashSigAlgoSz; i += 2) {
12907
0
                     if ((suites->hashSigAlgo[i + 0] == input[args->idx + 0]) &&
12908
0
                             (suites->hashSigAlgo[i + 1] == input[args->idx + 1])) {
12909
0
                         validSigAlgo = 1;
12910
0
                         break;
12911
0
                     }
12912
0
                }
12913
0
                if (!validSigAlgo) {
12914
0
                    ERROR_OUT(INVALID_PARAMETER, exit_dcv);
12915
0
                }
12916
12917
0
                ret = DecodeTls13SigAlg(input + args->idx,
12918
0
                        &ssl->options.peerHashAlgo, &ssl->options.peerSigAlgo);
12919
#ifdef WOLFSSL_DUAL_ALG_CERTS
12920
            }
12921
            else {
12922
                ret = DecodeTls13HybridSigAlg(input + args->idx,
12923
                                              &ssl->options.peerHashAlgo,
12924
                                              &ssl->options.peerSigAlgo,
12925
                                              &args->altSigAlgo);
12926
            }
12927
#endif /* WOLFSSL_DUAL_ALG_CERTS */
12928
12929
0
            if (ret < 0)
12930
0
                goto exit_dcv;
12931
0
            args->idx += OPAQUE16_LEN;
12932
12933
            /* Signature length. */
12934
0
            if ((args->idx - args->begin) + OPAQUE16_LEN > totalSz) {
12935
0
                ERROR_OUT(BUFFER_ERROR, exit_dcv);
12936
0
            }
12937
0
            ato16(input + args->idx, &args->sz);
12938
0
            args->idx += OPAQUE16_LEN;
12939
12940
            /* Signature data. */
12941
0
            if ((args->idx - args->begin) + args->sz > totalSz) {
12942
0
                ERROR_OUT(BUFFER_ERROR, exit_dcv);
12943
0
            }
12944
12945
#ifdef WOLFSSL_DUAL_ALG_CERTS
12946
            if ((ssl->sigSpec != NULL) &&
12947
                (*ssl->sigSpec != WOLFSSL_CKS_SIGSPEC_NATIVE)) {
12948
12949
                word16 sa;
12950
                /* The alternative public key comes from the kept peer
12951
                 * certificate. */
12952
                if (GetPeerCert(ssl) == NULL) {
12953
                    ERROR_OUT(PEER_KEY_ERROR, exit_dcv);
12954
                }
12955
                if (args->altSigAlgo == 0)
12956
                    sa = ssl->options.peerSigAlgo;
12957
                else
12958
                    sa = args->altSigAlgo;
12959
12960
                switch(sa) {
12961
            #ifndef NO_RSA
12962
                case rsa_pss_sa_algo:
12963
                    ret = decodeRsaKey(ssl);
12964
                    break;
12965
            #endif
12966
            #ifdef HAVE_ECC
12967
                case ecc_dsa_sa_algo:
12968
                    ret = decodeEccKey(ssl);
12969
                    break;
12970
            #endif
12971
            #ifdef WOLFSSL_HAVE_MLDSA
12972
                case mldsa_44_sa_algo:
12973
                    ret = decodeMlDsaKey(ssl, WC_ML_DSA_44);
12974
                    break;
12975
                case mldsa_65_sa_algo:
12976
                    ret = decodeMlDsaKey(ssl, WC_ML_DSA_65);
12977
                    break;
12978
                case mldsa_87_sa_algo:
12979
                    ret = decodeMlDsaKey(ssl, WC_ML_DSA_87);
12980
                    break;
12981
            #endif
12982
            #ifdef WOLFSSL_HAVE_SLHDSA
12983
                case slhdsa_sha2_128s_sa_algo:
12984
                case slhdsa_sha2_128f_sa_algo:
12985
                case slhdsa_sha2_192s_sa_algo:
12986
                case slhdsa_sha2_192f_sa_algo:
12987
                case slhdsa_sha2_256s_sa_algo:
12988
                case slhdsa_sha2_256f_sa_algo:
12989
                case slhdsa_shake_128s_sa_algo:
12990
                case slhdsa_shake_128f_sa_algo:
12991
                case slhdsa_shake_192s_sa_algo:
12992
                case slhdsa_shake_192f_sa_algo:
12993
                case slhdsa_shake_256s_sa_algo:
12994
                case slhdsa_shake_256f_sa_algo:
12995
                    /* SLH-DSA is not supported as an alternative (dual-algorithm
12996
                     * / CKS) key. The alternative-signature verification block
12997
                     * in this function has no SLH-DSA case, so a decoded key
12998
                     * would never be verified and the handshake would always be
12999
                     * rejected at TLS_ASYNC_FINALIZE. Fail fast here instead of
13000
                     * allocating a key that can never authenticate the peer. */
13001
                    ERROR_OUT(ALGO_ID_E, exit_dcv);
13002
            #endif
13003
            #ifdef HAVE_FALCON
13004
                case falcon_level1_sa_algo:
13005
                    ret = decodeFalconKey(ssl, 1);
13006
                    break;
13007
                case falcon_level5_sa_algo:
13008
                    ret = decodeFalconKey(ssl, 5);
13009
                    break;
13010
            #endif
13011
                default:
13012
                    ERROR_OUT(PEER_KEY_ERROR, exit_dcv);
13013
                }
13014
13015
                if (ret != 0)
13016
                    ERROR_OUT(ret, exit_dcv);
13017
13018
                if (*ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_ALTERNATIVE) {
13019
                    /* Now swap in the alternative by removing the native.
13020
                     * sa contains the alternative signature type. */
13021
                #ifndef NO_RSA
13022
                    if (ssl->peerRsaKeyPresent && sa != rsa_pss_sa_algo) {
13023
                        FreeKey(ssl, DYNAMIC_TYPE_RSA,
13024
                                (void**)&ssl->peerRsaKey);
13025
                        ssl->peerRsaKeyPresent = 0;
13026
                    }
13027
                #endif
13028
                #ifdef HAVE_ECC
13029
                    else if (ssl->peerEccDsaKeyPresent &&
13030
                             sa != ecc_dsa_sa_algo) {
13031
                        FreeKey(ssl, DYNAMIC_TYPE_ECC,
13032
                                (void**)&ssl->peerEccDsaKey);
13033
                        ssl->peerEccDsaKeyPresent = 0;
13034
                    }
13035
                #endif
13036
                #ifdef WOLFSSL_HAVE_MLDSA
13037
                    else if (ssl->peerMlDsaKeyPresent &&
13038
                             sa != mldsa_44_sa_algo &&
13039
                             sa != mldsa_65_sa_algo &&
13040
                             sa != mldsa_87_sa_algo) {
13041
                        FreeKey(ssl, DYNAMIC_TYPE_MLDSA,
13042
                                (void**)&ssl->peerMlDsaKey);
13043
                        ssl->peerMlDsaKeyPresent = 0;
13044
                    }
13045
                #endif
13046
                #ifdef WOLFSSL_HAVE_SLHDSA
13047
                    else if (ssl->peerSlhDsaKeyPresent &&
13048
                             !IsSlhDsaSigAlgo(sa)) {
13049
                        FreeKey(ssl, DYNAMIC_TYPE_SLHDSA,
13050
                                (void**)&ssl->peerSlhDsaKey);
13051
                        ssl->peerSlhDsaKeyPresent = 0;
13052
                    }
13053
                #endif
13054
                #ifdef HAVE_FALCON
13055
                    else if (ssl->peerFalconKeyPresent &&
13056
                             sa != falcon_level1_sa_algo &&
13057
                             sa != falcon_level5_sa_algo) {
13058
                        FreeKey(ssl, DYNAMIC_TYPE_FALCON,
13059
                                (void**)&ssl->peerFalconKey);
13060
                        ssl->peerFalconKeyPresent = 0;
13061
                    }
13062
                #endif
13063
                    else {
13064
                        ERROR_OUT(PEER_KEY_ERROR, exit_dcv);
13065
                    }
13066
                }
13067
            }
13068
#endif /* WOLFSSL_DUAL_ALG_CERTS */
13069
13070
            /* Check for public key of required type. */
13071
            /* Assume invalid unless signature algo matches the key provided */
13072
0
            validSigAlgo = 0;
13073
        #ifdef HAVE_ED25519
13074
            if (ssl->options.peerSigAlgo == ed25519_sa_algo) {
13075
                WOLFSSL_MSG("Peer sent ED25519 sig");
13076
                validSigAlgo = (ssl->peerEd25519Key != NULL) &&
13077
                                                     ssl->peerEd25519KeyPresent;
13078
            }
13079
        #endif
13080
        #ifdef HAVE_ED448
13081
            if (ssl->options.peerSigAlgo == ed448_sa_algo) {
13082
                WOLFSSL_MSG("Peer sent ED448 sig");
13083
                validSigAlgo = (ssl->peerEd448Key != NULL) &&
13084
                                                       ssl->peerEd448KeyPresent;
13085
            }
13086
        #endif
13087
0
        #ifdef HAVE_ECC
13088
0
            if (ssl->options.peerSigAlgo == ecc_dsa_sa_algo) {
13089
0
                WOLFSSL_MSG("Peer sent ECC sig");
13090
0
                validSigAlgo = (ssl->peerEccDsaKey != NULL) &&
13091
0
                                                      ssl->peerEccDsaKeyPresent;
13092
0
            }
13093
0
        #endif
13094
        #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
13095
            if (ssl->options.peerSigAlgo == sm2_sa_algo) {
13096
                WOLFSSL_MSG("Peer sent SM2 sig");
13097
                validSigAlgo = (ssl->peerEccDsaKey != NULL) &&
13098
                                                      ssl->peerEccDsaKeyPresent;
13099
            }
13100
        #endif
13101
        #ifdef HAVE_FALCON
13102
            if (ssl->options.peerSigAlgo == falcon_level1_sa_algo) {
13103
                WOLFSSL_MSG("Peer sent Falcon Level 1 sig");
13104
                validSigAlgo = (ssl->peerFalconKey != NULL) &&
13105
                               ssl->peerFalconKeyPresent;
13106
            }
13107
            if (ssl->options.peerSigAlgo == falcon_level5_sa_algo) {
13108
                WOLFSSL_MSG("Peer sent Falcon Level 5 sig");
13109
                validSigAlgo = (ssl->peerFalconKey != NULL) &&
13110
                               ssl->peerFalconKeyPresent;
13111
            }
13112
        #endif
13113
        #ifdef WOLFSSL_HAVE_MLDSA
13114
            if (ssl->options.peerSigAlgo == mldsa_44_sa_algo) {
13115
                WOLFSSL_MSG("Peer sent ML-DSA Level 2 sig");
13116
                validSigAlgo = (ssl->peerMlDsaKey != NULL) &&
13117
                               ssl->peerMlDsaKeyPresent;
13118
            }
13119
            if (ssl->options.peerSigAlgo == mldsa_65_sa_algo) {
13120
                WOLFSSL_MSG("Peer sent ML-DSA Level 3 sig");
13121
                validSigAlgo = (ssl->peerMlDsaKey != NULL) &&
13122
                               ssl->peerMlDsaKeyPresent;
13123
            }
13124
            if (ssl->options.peerSigAlgo == mldsa_87_sa_algo) {
13125
                WOLFSSL_MSG("Peer sent ML-DSA Level 5 sig");
13126
                validSigAlgo = (ssl->peerMlDsaKey != NULL) &&
13127
                               ssl->peerMlDsaKeyPresent;
13128
            }
13129
        #endif
13130
        #ifdef WOLFSSL_HAVE_SLHDSA
13131
            if (IsSlhDsaSigAlgo(ssl->options.peerSigAlgo)) {
13132
                WOLFSSL_MSG("Peer sent SLH-DSA sig");
13133
                validSigAlgo = (ssl->peerSlhDsaKey != NULL) &&
13134
                               ssl->peerSlhDsaKeyPresent;
13135
            }
13136
        #endif
13137
0
        #ifndef NO_RSA
13138
0
            if (ssl->options.peerSigAlgo == rsa_sa_algo) {
13139
0
                WOLFSSL_MSG("Peer sent PKCS#1.5 algo - not valid TLS 1.3");
13140
0
                ERROR_OUT(INVALID_PARAMETER, exit_dcv);
13141
0
            }
13142
0
            if (ssl->options.peerSigAlgo == rsa_pss_sa_algo) {
13143
0
                WOLFSSL_MSG("Peer sent RSA sig");
13144
0
                validSigAlgo = (ssl->peerRsaKey != NULL) &&
13145
0
                                                         ssl->peerRsaKeyPresent;
13146
0
            }
13147
0
        #endif
13148
0
            if (!validSigAlgo) {
13149
0
                WOLFSSL_MSG("Sig algo doesn't correspond to certificate");
13150
0
                ERROR_OUT(SIG_VERIFY_E, exit_dcv);
13151
0
            }
13152
13153
0
            args->sigSz = args->sz;
13154
#ifdef WOLFSSL_DUAL_ALG_CERTS
13155
            if (ssl->sigSpec != NULL &&
13156
                *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) {
13157
                /* In case we received two signatures, both of them are encoded
13158
                 * with their size as 16-bit integeter prior in memory. Hence,
13159
                 * we can decode both lengths here now. */
13160
                word32 tmpIdx = args->idx;
13161
                word16 tmpSz = 0;
13162
                if (args->sz < OPAQUE16_LEN) {
13163
                    ERROR_OUT(BUFFER_ERROR, exit_dcv);
13164
                }
13165
                ato16(input + tmpIdx, &tmpSz);
13166
                args->sigSz = tmpSz;
13167
13168
                tmpIdx += OPAQUE16_LEN + args->sigSz;
13169
                if (tmpIdx - args->idx + OPAQUE16_LEN > args->sz) {
13170
                    ERROR_OUT(BUFFER_ERROR, exit_dcv);
13171
                }
13172
                ato16(input + tmpIdx, &tmpSz);
13173
                args->altSignatureSz = tmpSz;
13174
13175
                if (args->sz != (args->sigSz + args->altSignatureSz +
13176
                                    OPAQUE16_LEN + OPAQUE16_LEN)) {
13177
                    ERROR_OUT(BUFFER_ERROR, exit_dcv);
13178
                }
13179
            }
13180
#endif /* WOLFSSL_DUAL_ALG_CERTS */
13181
13182
0
        #if !defined(NO_RSA) && defined(WC_RSA_PSS)
13183
            /* In case we have to verify an RSA signature, we have to store the
13184
             * signature in the 'rsaSigBuf' structure for further processing.
13185
             */
13186
0
            if (ssl->peerRsaKey != NULL && ssl->peerRsaKeyPresent != 0) {
13187
0
                word32 sigSz = args->sigSz;
13188
0
                sig = input + args->idx;
13189
            #ifdef WOLFSSL_DUAL_ALG_CERTS
13190
                /* Check if our alternative signature was RSA */
13191
                if (ssl->sigSpec != NULL &&
13192
                    *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) {
13193
                    if (ssl->options.peerSigAlgo != rsa_pss_sa_algo) {
13194
                        /* We have to skip the first signature (length field
13195
                         * and signature itself) and the length field of the
13196
                         * alternative signature. */
13197
                        sig += OPAQUE16_LEN + OPAQUE16_LEN + args->sigSz;
13198
                        sigSz = args->altSignatureSz;
13199
                    }
13200
                    else {
13201
                        /* We have to skip the length field */
13202
                        sig += OPAQUE16_LEN;
13203
                    }
13204
                }
13205
            #endif
13206
0
                rsaSigBuf->buffer = (byte*)XMALLOC(sigSz, ssl->heap,
13207
0
                                         DYNAMIC_TYPE_SIGNATURE);
13208
0
                if (rsaSigBuf->buffer == NULL) {
13209
0
                    ERROR_OUT(MEMORY_E, exit_dcv);
13210
0
                }
13211
0
                rsaSigBuf->length = sigSz;
13212
0
                XMEMCPY(rsaSigBuf->buffer, sig, rsaSigBuf->length);
13213
0
            }
13214
0
        #endif /* !NO_RSA && WC_RSA_PSS */
13215
13216
0
            args->sigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap,
13217
0
                                                    DYNAMIC_TYPE_SIGNATURE);
13218
0
            if (args->sigData == NULL) {
13219
0
                ERROR_OUT(MEMORY_E, exit_dcv);
13220
0
            }
13221
13222
0
            ret = CreateSigData(ssl, args->sigData, &args->sigDataSz, 1);
13223
0
            if (ret < 0)
13224
0
                goto exit_dcv;
13225
13226
        #ifdef WOLFSSL_DUAL_ALG_CERTS
13227
            if ((ssl->sigSpec != NULL) &&
13228
                (*ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH)) {
13229
                args->altSigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap,
13230
                                                        DYNAMIC_TYPE_SIGNATURE);
13231
                if (args->altSigData == NULL) {
13232
                    ERROR_OUT(MEMORY_E, exit_dcv);
13233
                }
13234
                XMEMCPY(args->altSigData, args->sigData, args->sigDataSz);
13235
                args->altSigDataSz = args->sigDataSz;
13236
            }
13237
        #endif /* WOLFSSL_DUAL_ALG_CERTS */
13238
13239
0
        #ifdef HAVE_ECC
13240
0
            if ((ssl->options.peerSigAlgo == ecc_dsa_sa_algo) &&
13241
0
                (ssl->peerEccDsaKeyPresent)) {
13242
0
                ret = CreateECCEncodedSig(args->sigData,
13243
0
                    args->sigDataSz, ssl->options.peerHashAlgo);
13244
0
                if (ret < 0)
13245
0
                    goto exit_dcv;
13246
0
                args->sigDataSz = (word16)ret;
13247
0
                ret = 0;
13248
0
            }
13249
13250
        #ifdef WOLFSSL_DUAL_ALG_CERTS
13251
            if ((ssl->sigSpec != NULL) &&
13252
                (*ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) &&
13253
                (args->altSigAlgo == ecc_dsa_sa_algo) &&
13254
                (ssl->peerEccDsaKeyPresent)) {
13255
                ret = CreateECCEncodedSig(args->altSigData,
13256
                        args->altSigDataSz, ssl->options.peerHashAlgo);
13257
                    if (ret < 0)
13258
                        goto exit_dcv;
13259
                    args->altSigDataSz = (word16)ret;
13260
                    ret = 0;
13261
            }
13262
        #endif /* WOLFSSL_DUAL_ALG_CERTS */
13263
0
        #endif /* HAVE_ECC */
13264
13265
            /* Advance state and proceed */
13266
0
            ssl->options.asyncState = TLS_ASYNC_DO;
13267
0
        } /* case TLS_ASYNC_BUILD */
13268
0
        FALL_THROUGH;
13269
13270
0
        case TLS_ASYNC_DO:
13271
0
        {
13272
0
            sig = input + args->idx;
13273
0
            (void)sig;
13274
        #ifdef WOLFSSL_DUAL_ALG_CERTS
13275
            if (ssl->sigSpec != NULL &&
13276
                *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) {
13277
                /* As we have two signatures in the message, we stored
13278
                 * the length of each before the actual signature. This
13279
                 * is necessary, as we could have two algorithms with
13280
                 * variable length signatures. */
13281
                sig += OPAQUE16_LEN;
13282
            }
13283
        #endif
13284
0
        #ifndef NO_RSA
13285
0
            if ((ssl->options.peerSigAlgo == rsa_pss_sa_algo) &&
13286
0
                (ssl->peerRsaKey != NULL) && (ssl->peerRsaKeyPresent != 0)) {
13287
0
                WOLFSSL_MSG("Doing RSA peer cert verify");
13288
0
                ret = RsaVerify(ssl, rsaSigBuf->buffer,
13289
0
                                (word32)rsaSigBuf->length, &args->output,
13290
0
                                ssl->options.peerSigAlgo,
13291
0
                                ssl->options.peerHashAlgo, ssl->peerRsaKey,
13292
                #ifdef HAVE_PK_CALLBACKS
13293
                                &ssl->buffers.peerRsaKey
13294
                #else
13295
0
                                NULL
13296
0
                #endif
13297
0
                                );
13298
0
                if (ret >= 0) {
13299
0
                    args->sendSz = (word32)ret;
13300
0
                    ret = 0;
13301
0
                }
13302
0
            }
13303
0
        #endif /* !NO_RSA */
13304
0
        #ifdef HAVE_ECC
13305
0
            if ((ssl->options.peerSigAlgo == ecc_dsa_sa_algo) &&
13306
0
                    ssl->peerEccDsaKeyPresent) {
13307
0
                WOLFSSL_MSG("Doing ECC peer cert verify");
13308
0
                ret = EccVerify(ssl, sig, args->sigSz,
13309
0
                    args->sigData, args->sigDataSz,
13310
0
                    ssl->peerEccDsaKey,
13311
                #ifdef HAVE_PK_CALLBACKS
13312
                    &ssl->buffers.peerEccDsaKey
13313
                #else
13314
0
                    NULL
13315
0
                #endif
13316
0
                    );
13317
13318
0
                if (ret >= 0) {
13319
                    /* CLIENT/SERVER: data verified with public key from
13320
                     * certificate. */
13321
0
                    ssl->options.peerAuthGood = 1;
13322
13323
0
                    FreeKey(ssl, DYNAMIC_TYPE_ECC, (void**)&ssl->peerEccDsaKey);
13324
0
                    ssl->peerEccDsaKeyPresent = 0;
13325
0
                }
13326
0
            }
13327
0
        #endif /* HAVE_ECC */
13328
        #if defined(HAVE_ECC) && defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
13329
            if ((ssl->options.peerSigAlgo == sm2_sa_algo) &&
13330
                   ssl->peerEccDsaKeyPresent) {
13331
                WOLFSSL_MSG("Doing SM2/SM3 peer cert verify");
13332
                ret = Sm2wSm3Verify(ssl, TLS13_SM2_SIG_ID, TLS13_SM2_SIG_ID_SZ,
13333
                    sig, args->sigSz, args->sigData, args->sigDataSz,
13334
                    ssl->peerEccDsaKey, NULL);
13335
                if (ret >= 0) {
13336
                    /* CLIENT/SERVER: data verified with public key from
13337
                     * certificate. */
13338
                    ssl->options.peerAuthGood = 1;
13339
13340
                    FreeKey(ssl, DYNAMIC_TYPE_ECC, (void**)&ssl->peerEccDsaKey);
13341
                    ssl->peerEccDsaKeyPresent = 0;
13342
                }
13343
            }
13344
        #endif
13345
        #ifdef HAVE_ED25519
13346
            if ((ssl->options.peerSigAlgo == ed25519_sa_algo) &&
13347
                (ssl->peerEd25519KeyPresent)) {
13348
                WOLFSSL_MSG("Doing ED25519 peer cert verify");
13349
                ret = Ed25519Verify(ssl, sig, args->sigSz,
13350
                    args->sigData, args->sigDataSz,
13351
                    ssl->peerEd25519Key,
13352
                #ifdef HAVE_PK_CALLBACKS
13353
                    &ssl->buffers.peerEd25519Key
13354
                #else
13355
                    NULL
13356
                #endif
13357
                    );
13358
13359
                if (ret >= 0) {
13360
                    /* CLIENT/SERVER: data verified with public key from
13361
                     * certificate. */
13362
                    ssl->options.peerAuthGood = 1;
13363
                    FreeKey(ssl, DYNAMIC_TYPE_ED25519,
13364
                                                  (void**)&ssl->peerEd25519Key);
13365
                    ssl->peerEd25519KeyPresent = 0;
13366
                }
13367
            }
13368
        #endif
13369
        #ifdef HAVE_ED448
13370
            if ((ssl->options.peerSigAlgo == ed448_sa_algo) &&
13371
                (ssl->peerEd448KeyPresent)) {
13372
                WOLFSSL_MSG("Doing ED448 peer cert verify");
13373
                ret = Ed448Verify(ssl, sig, args->sigSz,
13374
                    args->sigData, args->sigDataSz,
13375
                    ssl->peerEd448Key,
13376
                #ifdef HAVE_PK_CALLBACKS
13377
                    &ssl->buffers.peerEd448Key
13378
                #else
13379
                    NULL
13380
                #endif
13381
                );
13382
13383
                if (ret >= 0) {
13384
                    /* CLIENT/SERVER: data verified with public key from
13385
                     * certificate. */
13386
                    ssl->options.peerAuthGood = 1;
13387
                    FreeKey(ssl, DYNAMIC_TYPE_ED448,
13388
                                                    (void**)&ssl->peerEd448Key);
13389
                    ssl->peerEd448KeyPresent = 0;
13390
                }
13391
            }
13392
        #endif
13393
        #if defined(HAVE_FALCON)
13394
            if (((ssl->options.peerSigAlgo == falcon_level1_sa_algo) ||
13395
                 (ssl->options.peerSigAlgo == falcon_level5_sa_algo)) &&
13396
                (ssl->peerFalconKeyPresent)) {
13397
                int res = 0;
13398
                WOLFSSL_MSG("Doing Falcon peer cert verify");
13399
                ret = wc_falcon_verify_msg(sig, args->sigSz,
13400
                                           args->sigData, args->sigDataSz,
13401
                                           &res, ssl->peerFalconKey);
13402
13403
                if ((ret >= 0) && (res == 1)) {
13404
                    /* CLIENT/SERVER: data verified with public key from
13405
                     * certificate. */
13406
                    ssl->options.peerAuthGood = 1;
13407
13408
                    FreeKey(ssl, DYNAMIC_TYPE_FALCON,
13409
                                                   (void**)&ssl->peerFalconKey);
13410
                    ssl->peerFalconKeyPresent = 0;
13411
                }
13412
                else if ((ret >= 0) && (res == 0)) {
13413
                    WOLFSSL_MSG("Falcon signature verification failed");
13414
                    ret = SIG_VERIFY_E;
13415
                }
13416
            }
13417
        #endif /* HAVE_FALCON */
13418
        #if defined(WOLFSSL_HAVE_MLDSA) && !defined(WOLFSSL_MLDSA_NO_VERIFY)
13419
            if (((ssl->options.peerSigAlgo == mldsa_44_sa_algo) ||
13420
                 (ssl->options.peerSigAlgo == mldsa_65_sa_algo) ||
13421
                 (ssl->options.peerSigAlgo == mldsa_87_sa_algo)) &&
13422
                (ssl->peerMlDsaKeyPresent)) {
13423
                int res = 0;
13424
                WOLFSSL_MSG("Doing ML-DSA peer cert verify");
13425
                ret = wc_MlDsaKey_VerifyCtx(ssl->peerMlDsaKey, sig, args->sigSz,
13426
                                            NULL, 0, args->sigData,
13427
                                            args->sigDataSz, &res);
13428
13429
                if ((ret >= 0) && (res == 1)) {
13430
                    /* CLIENT/SERVER: data verified with public key from
13431
                     * certificate. */
13432
                    ssl->options.peerAuthGood = 1;
13433
13434
                    FreeKey(ssl, DYNAMIC_TYPE_MLDSA,
13435
                            (void**)&ssl->peerMlDsaKey);
13436
                    ssl->peerMlDsaKeyPresent = 0;
13437
                }
13438
                else if ((ret >= 0) && (res == 0)) {
13439
                    WOLFSSL_MSG("ML-DSA signature verification failed");
13440
                    ret = SIG_VERIFY_E;
13441
                }
13442
            }
13443
        #endif /* WOLFSSL_HAVE_MLDSA */
13444
        #if defined(WOLFSSL_HAVE_SLHDSA)
13445
            if (IsSlhDsaSigAlgo(ssl->options.peerSigAlgo) &&
13446
                (ssl->peerSlhDsaKeyPresent)) {
13447
                WOLFSSL_MSG("Doing SLH-DSA peer cert verify");
13448
13449
                /* The advertised signature scheme must match the parameter set
13450
                 * of the peer's certificate key (RFC 8446 4.4.3). The key
13451
                 * params come from the certificate OID, so a mismatch means the
13452
                 * peer is over-claiming its security level; reject it. */
13453
                if ((ssl->peerSlhDsaKey->params == NULL) ||
13454
                    (SlhDsaParamToType((int)ssl->peerSlhDsaKey->params->param)
13455
                        != ssl->options.peerSigAlgo)) {
13456
                    ERROR_OUT(SIG_VERIFY_E, exit_dcv);
13457
                }
13458
13459
                /* wc_SlhDsaKey_Verify returns 0 for a valid signature. */
13460
                ret = wc_SlhDsaKey_Verify(ssl->peerSlhDsaKey, NULL, 0,
13461
                                          args->sigData, args->sigDataSz,
13462
                                          sig, args->sigSz);
13463
13464
                if (ret == 0) {
13465
                    /* CLIENT/SERVER: data verified with public key from
13466
                     * certificate. */
13467
                    ssl->options.peerAuthGood = 1;
13468
13469
                    FreeKey(ssl, DYNAMIC_TYPE_SLHDSA,
13470
                            (void**)&ssl->peerSlhDsaKey);
13471
                    ssl->peerSlhDsaKeyPresent = 0;
13472
                }
13473
                else {
13474
                    /* wc_SlhDsaKey_Verify already returns SIG_VERIFY_E on a
13475
                     * signature mismatch and propagates real errors verbatim
13476
                     * (WC_PENDING_E on the async crypto-callback path, MEMORY_E,
13477
                     * ...), so leave ret unchanged. Flattening everything to
13478
                     * SIG_VERIFY_E would break async resume and mask
13479
                     * diagnostics; the ML-DSA/Falcon blocks above likewise
13480
                     * preserve non-completion return codes. */
13481
                    WOLFSSL_MSG("SLH-DSA signature verification failed");
13482
                }
13483
            }
13484
        #endif /* WOLFSSL_HAVE_SLHDSA */
13485
13486
            /* Check for error */
13487
0
            if (ret != 0) {
13488
0
                goto exit_dcv;
13489
0
            }
13490
13491
        #ifdef WOLFSSL_DUAL_ALG_CERTS
13492
            if (ssl->sigSpec != NULL &&
13493
                *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) {
13494
                /* Move forward to the alternative signature. */
13495
                sig += args->sigSz + OPAQUE16_LEN;
13496
13497
                /* Verify the alternative signature */
13498
            #ifndef NO_RSA
13499
                if ((args->altSigAlgo == rsa_pss_sa_algo) &&
13500
                    (ssl->peerRsaKey != NULL) &&
13501
                    (ssl->peerRsaKeyPresent != 0)) {
13502
                    WOLFSSL_MSG("Doing RSA peer cert alt verify");
13503
                    ret = RsaVerify(ssl, rsaSigBuf->buffer,
13504
                                    (word32)rsaSigBuf->length,
13505
                                    &args->output, args->altSigAlgo,
13506
                                    ssl->options.peerHashAlgo, ssl->peerRsaKey,
13507
                    #ifdef HAVE_PK_CALLBACKS
13508
                                    &ssl->buffers.peerRsaKey
13509
                    #else
13510
                                    NULL
13511
                    #endif
13512
                                    );
13513
                    if (ret >= 0) {
13514
                        args->sendSz = ret;
13515
                        ret = 0;
13516
                    }
13517
                }
13518
            #endif /* !NO_RSA */
13519
            #ifdef HAVE_ECC
13520
                if ((args->altSigAlgo == ecc_dsa_sa_algo) &&
13521
                    (ssl->peerEccDsaKeyPresent)) {
13522
                    WOLFSSL_MSG("Doing ECC peer cert alt verify");
13523
                    ret = EccVerify(ssl, sig, args->altSignatureSz,
13524
                                args->altSigData, args->altSigDataSz,
13525
                                ssl->peerEccDsaKey,
13526
                    #ifdef HAVE_PK_CALLBACKS
13527
                                &ssl->buffers.peerEccDsaKey
13528
                    #else
13529
                                NULL
13530
                    #endif
13531
                                );
13532
13533
                    if (ret >= 0) {
13534
                        /* CLIENT/SERVER: data verified with public key from
13535
                        * certificate. */
13536
                        args->altPeerAuthGood = 1;
13537
13538
                        FreeKey(ssl, DYNAMIC_TYPE_ECC,
13539
                                                (void**)&ssl->peerEccDsaKey);
13540
                        ssl->peerEccDsaKeyPresent = 0;
13541
                    }
13542
                }
13543
            #endif /* HAVE_ECC */
13544
            #if defined(HAVE_FALCON)
13545
                if (((args->altSigAlgo == falcon_level1_sa_algo) ||
13546
                     (args->altSigAlgo == falcon_level5_sa_algo)) &&
13547
                    (ssl->peerFalconKeyPresent)) {
13548
                    int res = 0;
13549
                    WOLFSSL_MSG("Doing Falcon peer cert alt verify");
13550
                    ret = wc_falcon_verify_msg(sig, args->altSignatureSz,
13551
                                        args->altSigData, args->altSigDataSz,
13552
                                        &res, ssl->peerFalconKey);
13553
13554
                    if ((ret >= 0) && (res == 1)) {
13555
                        /* CLIENT/SERVER: data verified with public key from
13556
                        * certificate. */
13557
                        args->altPeerAuthGood = 1;
13558
13559
                        FreeKey(ssl, DYNAMIC_TYPE_FALCON,
13560
                                                (void**)&ssl->peerFalconKey);
13561
                        ssl->peerFalconKeyPresent = 0;
13562
                    }
13563
                    else if ((ret >= 0) && (res == 0)) {
13564
                        WOLFSSL_MSG("Falcon signature verification failed");
13565
                        ret = SIG_VERIFY_E;
13566
                    }
13567
                }
13568
            #endif /* HAVE_FALCON */
13569
            #if defined(WOLFSSL_HAVE_MLDSA) && !defined(WOLFSSL_MLDSA_NO_VERIFY)
13570
                if (((args->altSigAlgo == mldsa_44_sa_algo) ||
13571
                     (args->altSigAlgo == mldsa_65_sa_algo) ||
13572
                     (args->altSigAlgo == mldsa_87_sa_algo)) &&
13573
                    (ssl->peerMlDsaKeyPresent)) {
13574
                    int res = 0;
13575
                    WOLFSSL_MSG("Doing ML-DSA peer cert alt verify");
13576
                    ret = wc_MlDsaKey_VerifyCtx(ssl->peerMlDsaKey, sig,
13577
                                        args->altSignatureSz, NULL, 0,
13578
                                        args->altSigData,
13579
                                        args->altSigDataSz, &res);
13580
13581
                    if ((ret >= 0) && (res == 1)) {
13582
                        /* CLIENT/SERVER: data verified with public key from
13583
                        * certificate. */
13584
                        args->altPeerAuthGood = 1;
13585
13586
                        FreeKey(ssl, DYNAMIC_TYPE_MLDSA,
13587
                                            (void**)&ssl->peerMlDsaKey);
13588
                        ssl->peerMlDsaKeyPresent = 0;
13589
                    }
13590
                    else if ((ret >= 0) && (res == 0)) {
13591
                        WOLFSSL_MSG("ML-DSA signature verification failed");
13592
                        ret = SIG_VERIFY_E;
13593
                    }
13594
                }
13595
            #endif /* WOLFSSL_HAVE_MLDSA */
13596
13597
                /* Check for error */
13598
                if (ret != 0) {
13599
                    goto exit_dcv;
13600
                }
13601
            }
13602
        #endif /* WOLFSSL_DUAL_ALG_CERTS */
13603
13604
            /* Advance state and proceed */
13605
0
            ssl->options.asyncState = TLS_ASYNC_VERIFY;
13606
0
        } /* case TLS_ASYNC_DO */
13607
0
        FALL_THROUGH;
13608
13609
0
        case TLS_ASYNC_VERIFY:
13610
0
        {
13611
0
        #if !defined(NO_RSA) && defined(WC_RSA_PSS)
13612
0
            if (ssl->peerRsaKey != NULL && ssl->peerRsaKeyPresent != 0) {
13613
0
                int sigAlgo = ssl->options.peerSigAlgo;
13614
            #ifdef WOLFSSL_DUAL_ALG_CERTS
13615
                /* Check if our alternative signature was RSA */
13616
                if (ssl->sigSpec != NULL &&
13617
                    *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH &&
13618
                    ssl->options.peerSigAlgo != rsa_pss_sa_algo) {
13619
                    sigAlgo = args->altSigAlgo;
13620
                }
13621
            #endif
13622
0
                ret = CheckRSASignature(ssl, sigAlgo,
13623
0
                        ssl->options.peerHashAlgo, args->output, args->sendSz);
13624
0
                if (ret != 0)
13625
0
                    goto exit_dcv;
13626
13627
                /* CLIENT/SERVER: data verified with public key from
13628
                 * certificate. */
13629
0
                ssl->peerRsaKeyPresent = 0;
13630
0
                FreeKey(ssl, DYNAMIC_TYPE_RSA, (void**)&ssl->peerRsaKey);
13631
            #ifdef WOLFSSL_DUAL_ALG_CERTS
13632
                /* Check if our alternative signature was RSA */
13633
                if (ssl->sigSpec != NULL &&
13634
                    *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH &&
13635
                    ssl->options.peerSigAlgo != rsa_pss_sa_algo) {
13636
                    args->altPeerAuthGood = 1;
13637
                }
13638
                else
13639
            #endif
13640
0
                    ssl->options.peerAuthGood = 1;
13641
0
            }
13642
0
        #endif /* !NO_RSA && WC_RSA_PSS */
13643
13644
            /* Advance state and proceed */
13645
0
            ssl->options.asyncState = TLS_ASYNC_FINALIZE;
13646
0
        } /* case TLS_ASYNC_VERIFY */
13647
0
        FALL_THROUGH;
13648
13649
0
        case TLS_ASYNC_FINALIZE:
13650
0
        {
13651
#ifdef WOLFSSL_DUAL_ALG_CERTS
13652
            if (ssl->options.peerAuthGood &&
13653
                ssl->sigSpec != NULL &&
13654
                *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) {
13655
                ssl->options.peerAuthGood = args->altPeerAuthGood;
13656
            }
13657
#endif /* WOLFSSL_DUAL_ALG_CERTS */
13658
0
            ssl->options.havePeerVerify = 1;
13659
13660
            /* Set final index */
13661
0
            args->idx += args->sz;
13662
0
            *inOutIdx = args->idx;
13663
13664
            /* Advance state and proceed */
13665
0
            ssl->options.asyncState = TLS_ASYNC_END;
13666
13667
0
        #if !defined(NO_WOLFSSL_CLIENT)
13668
0
            if (ssl->options.side == WOLFSSL_CLIENT_END)
13669
0
                ssl->options.serverState = SERVER_CERT_VERIFY_COMPLETE;
13670
0
        #endif
13671
0
        } /* case TLS_ASYNC_FINALIZE */
13672
0
        FALL_THROUGH;
13673
13674
0
        case TLS_ASYNC_END:
13675
0
        {
13676
0
            break;
13677
0
        }
13678
13679
0
        default:
13680
0
            ret = INPUT_CASE_ERROR;
13681
0
    } /* switch(ssl->options.asyncState) */
13682
13683
0
exit_dcv:
13684
13685
0
    WOLFSSL_LEAVE("DoTls13CertificateVerify", ret);
13686
0
    WOLFSSL_END(WC_FUNC_CERTIFICATE_VERIFY_DO);
13687
13688
#ifdef WOLFSSL_ASYNC_CRYPT
13689
    /* Handle async operation */
13690
    if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
13691
        /* Mark message as not received so it can process again */
13692
        ssl->msgsReceived.got_certificate_verify = 0;
13693
13694
        return ret;
13695
    }
13696
    else
13697
#endif /* WOLFSSL_ASYNC_CRYPT */
13698
0
    if (ret != 0) {
13699
0
        WOLFSSL_ERROR_VERBOSE(ret);
13700
13701
0
        if (ret != WC_NO_ERR_TRACE(INVALID_PARAMETER)) {
13702
0
            SendAlert(ssl, alert_fatal, decrypt_error);
13703
0
        }
13704
0
    }
13705
13706
    /* Final cleanup */
13707
0
    FreeDcv13Args(ssl, args);
13708
0
    FreeKeyExchange(ssl);
13709
0
#ifdef WOLFSSL_ASYNC_IO
13710
    /* Cleanup async */
13711
0
    FreeAsyncCtx(ssl, 0);
13712
0
#endif
13713
#ifdef WOLFSSL_ASYNC_CRYPT
13714
    /* Replays skip the sanity check that re-sets got_certificate_verify;
13715
     * restore on completion or Finished reports out-of-order. */
13716
    if (ret == 0 && ssl->msgsReceived.got_certificate_verify == 0) {
13717
        ssl->msgsReceived.got_certificate_verify = 1;
13718
    }
13719
#endif
13720
13721
0
    return ret;
13722
0
}
13723
#endif /* !NO_RSA || HAVE_ECC || HAVE_ED25519 || HAVE_ED448 ||
13724
        * HAVE_FALCON || WOLFSSL_HAVE_MLDSA || WOLFSSL_HAVE_SLHDSA */
13725
#endif /* !NO_CERTS */
13726
13727
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
13728
/* Message is being processed after the enclosing handshake completed. Whatever
13729
 * resumption, PSK or deferred (post-handshake) verification excused during that
13730
 * handshake, a later post-handshake exchange has to stand on its own. */
13731
#define TLS13_AFTER_HANDSHAKE(ssl)  ((ssl)->options.handShakeDone)
13732
#else
13733
0
#define TLS13_AFTER_HANDSHAKE(ssl)  0
13734
#endif
13735
13736
/* Parse and handle a TLS v1.3 Finished message.
13737
 *
13738
 * ssl       The SSL/TLS object.
13739
 * input     The message buffer.
13740
 * inOutIdx  On entry, the index into the message buffer of Finished.
13741
 *           On exit, the index of byte after the Finished message and padding.
13742
 * size      Length of message data.
13743
 * totalSz   Length of remaining data in the message buffer.
13744
 * sniff     Indicates whether we are sniffing packets.
13745
 * returns 0 on success and otherwise failure.
13746
 */
13747
int DoTls13Finished(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
13748
                           word32 size, word32 totalSz, int sniff)
13749
0
{
13750
0
    int    ret;
13751
0
    word32 finishedSz = 0;
13752
0
    byte*  secret;
13753
0
    byte   mac[WC_MAX_DIGEST_SIZE];
13754
13755
0
    WOLFSSL_START(WC_FUNC_FINISHED_DO);
13756
0
    WOLFSSL_ENTER("DoTls13Finished");
13757
13758
0
#if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CLIENT_AUTH) && \
13759
0
    !defined(NO_WOLFSSL_SERVER)
13760
    /* verify the client sent certificate if required */
13761
0
    if ((!ssl->options.resuming || TLS13_AFTER_HANDSHAKE(ssl)) &&
13762
0
            ClientAuthRequired(ssl, ssl->options.usingPSK_cipher)) {
13763
#ifdef OPENSSL_COMPATIBLE_DEFAULTS
13764
        if (ssl->options.usingPSK_cipher && !TLS13_AFTER_HANDSHAKE(ssl)) {
13765
            WOLFSSL_MSG("TLS v1.3 client used PSK but cert required. Allowing "
13766
                        "for OpenSSL compatibility");
13767
        }
13768
        else
13769
#endif
13770
0
        if (
13771
        #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
13772
            /* Exempt only the enclosing handshake; a post-handshake exchange
13773
             * still requires a peer certificate and a valid
13774
             * CertificateVerify. */
13775
            (!ssl->options.verifyPostHandshake || TLS13_AFTER_HANDSHAKE(ssl)) &&
13776
        #endif
13777
0
            (!ssl->options.havePeerCert || !ssl->options.havePeerVerify)) {
13778
0
            ret = NO_PEER_CERT; /* NO_PEER_VERIFY */
13779
0
            WOLFSSL_MSG("TLS v1.3 client did not present peer cert");
13780
0
            DoCertFatalAlert(ssl, ret);
13781
0
            goto cleanup;
13782
0
        }
13783
0
    }
13784
0
#endif
13785
13786
#if !defined(NO_CERTS) && !defined(NO_PSK) && \
13787
    defined(WOLFSSL_CERT_WITH_EXTERN_PSK)
13788
    /* Verify the server sent a certificate if requested */
13789
    if (ssl->options.side == WOLFSSL_CLIENT_END && ssl->options.pskNegotiated &&
13790
            ssl->options.failNoCert) {
13791
        if ((TLSX_Find(ssl->extensions, TLSX_CERT_WITH_EXTERN_PSK) != NULL) &&
13792
                (!ssl->options.havePeerCert || !ssl->options.havePeerVerify)) {
13793
            ret = NO_PEER_CERT;
13794
            WOLFSSL_MSG("TLS v1.3 server did not present peer cert");
13795
            DoCertFatalAlert(ssl, ret);
13796
            goto cleanup;
13797
        }
13798
    }
13799
#endif
13800
13801
    /* check against totalSz */
13802
0
    if (*inOutIdx + size > totalSz) {
13803
0
        ret = BUFFER_E;
13804
0
        goto cleanup;
13805
0
    }
13806
13807
#if defined(WOLFSSL_RENESAS_TSIP_TLS)
13808
    ret = tsip_Tls13HandleFinished(ssl, input, inOutIdx, size, totalSz);
13809
    if (ret == 0) {
13810
        ssl->options.serverState = SERVER_FINISHED_COMPLETE;
13811
        goto cleanup;
13812
    }
13813
    if (ret == WC_NO_ERR_TRACE(VERIFY_FINISHED_ERROR)) {
13814
        SendAlert(ssl, alert_fatal, decrypt_error);
13815
        goto cleanup;
13816
    }
13817
    if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
13818
        /* other errors */
13819
        goto cleanup;
13820
    }
13821
    ret = 0;
13822
#endif /* WOLFSSL_RENESAS_TSIP_TLS */
13823
13824
0
    if (ssl->options.handShakeDone) {
13825
0
        ret = DeriveFinishedSecret(ssl, ssl->clientSecret,
13826
0
                                   ssl->keys.client_write_MAC_secret,
13827
0
                                   WOLFSSL_CLIENT_END);
13828
0
        if (ret != 0)
13829
0
            goto cleanup;
13830
13831
0
        secret = ssl->keys.client_write_MAC_secret;
13832
0
    }
13833
0
    else if (ssl->options.side == WOLFSSL_CLIENT_END) {
13834
        /* All the handshake messages have been received to calculate
13835
         * client and server finished keys.
13836
         */
13837
0
        ret = DeriveFinishedSecret(ssl, ssl->clientSecret,
13838
0
                                   ssl->keys.client_write_MAC_secret,
13839
0
                                   WOLFSSL_CLIENT_END);
13840
0
        if (ret != 0)
13841
0
            goto cleanup;
13842
13843
0
        ret = DeriveFinishedSecret(ssl, ssl->serverSecret,
13844
0
                                   ssl->keys.server_write_MAC_secret,
13845
0
                                   WOLFSSL_SERVER_END);
13846
0
        if (ret != 0)
13847
0
            goto cleanup;
13848
13849
0
        secret = ssl->keys.server_write_MAC_secret;
13850
0
    }
13851
0
    else {
13852
0
        secret = ssl->keys.client_write_MAC_secret;
13853
0
    }
13854
13855
0
    if (sniff == NO_SNIFF) {
13856
13857
0
        ret = BuildTls13HandshakeHmac(ssl, secret, mac, &finishedSz);
13858
    #ifdef WOLFSSL_HAVE_TLS_UNIQUE
13859
        if (finishedSz > TLS_FINISHED_SZ_MAX) {
13860
            ret = BUFFER_ERROR;
13861
            goto cleanup;
13862
        }
13863
        if (ssl->options.side == WOLFSSL_CLIENT_END) {
13864
            XMEMCPY(ssl->serverFinished, mac, finishedSz);
13865
            ssl->serverFinished_len = (byte)finishedSz;
13866
        }
13867
        else {
13868
            XMEMCPY(ssl->clientFinished, mac, finishedSz);
13869
            ssl->clientFinished_len = (byte)finishedSz;
13870
        }
13871
    #endif /* WOLFSSL_HAVE_TLS_UNIQUE */
13872
0
        if (ret != 0)
13873
0
            goto cleanup;
13874
0
        if (size != finishedSz) {
13875
0
            ret = BUFFER_ERROR;
13876
0
            goto cleanup;
13877
0
        }
13878
0
    }
13879
13880
#ifdef WOLFSSL_CALLBACKS
13881
    if (ssl->hsInfoOn) AddPacketName(ssl, "Finished");
13882
    if (ssl->toInfoOn) AddLateName("Finished", &ssl->timeoutInfo);
13883
#endif
13884
13885
0
    if (sniff == NO_SNIFF) {
13886
        /* Actually check verify data. */
13887
0
        if (size > WC_MAX_DIGEST_SIZE ||
13888
0
                ConstantCompare(input + *inOutIdx, mac, size) != 0){
13889
0
            WOLFSSL_MSG("Verify finished error on hashes");
13890
0
            SendAlert(ssl, alert_fatal, decrypt_error);
13891
0
            WOLFSSL_ERROR_VERBOSE(VERIFY_FINISHED_ERROR);
13892
0
            ret = VERIFY_FINISHED_ERROR;
13893
0
            goto cleanup;
13894
0
        }
13895
0
    }
13896
13897
0
    *inOutIdx += size;
13898
13899
0
#ifndef NO_WOLFSSL_SERVER
13900
0
    if (ssl->options.side == WOLFSSL_SERVER_END &&
13901
0
                                                  !ssl->options.handShakeDone) {
13902
#ifdef WOLFSSL_EARLY_DATA
13903
        if (ssl->earlyData != no_early_data) {
13904
            if ((ret = DeriveTls13Keys(ssl, no_key, DECRYPT_SIDE_ONLY, 1)) != 0)
13905
                goto cleanup;
13906
        }
13907
#endif
13908
        /* Setup keys for application data messages from client. */
13909
0
        if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0)
13910
0
            goto cleanup;
13911
0
    }
13912
0
#endif
13913
13914
0
#ifndef NO_WOLFSSL_CLIENT
13915
0
    if (ssl->options.side == WOLFSSL_CLIENT_END)
13916
0
        ssl->options.serverState = SERVER_FINISHED_COMPLETE;
13917
0
#endif
13918
0
#ifndef NO_WOLFSSL_SERVER
13919
0
    if (ssl->options.side == WOLFSSL_SERVER_END) {
13920
0
        ssl->options.clientState = CLIENT_FINISHED_COMPLETE;
13921
0
        ssl->options.handShakeState = HANDSHAKE_DONE;
13922
0
        ssl->options.handShakeDone  = 1;
13923
0
    }
13924
0
#endif
13925
13926
#if defined(WOLFSSL_DTLS13) && defined(WOLFSSL_EARLY_DATA)
13927
    if (ssl->options.dtls && ssl->earlyData > early_data_ext) {
13928
        /* DTLSv1.3 has no EndOfearlydata messages. We stop processing EarlyData
13929
           as soon we receive the client's finished message */
13930
        ssl->earlyData = done_early_data;
13931
    }
13932
#endif /* WOLFSSL_DTLS13 && WOLFSSL_EARLY_DATA */
13933
#if defined(WOLFSSL_QUIC) && defined(WOLFSSL_EARLY_DATA)
13934
    if (WOLFSSL_IS_QUIC(ssl) && ssl->earlyData > early_data_ext) {
13935
        /* QUIC has no EndOfEarlyData messages. We stop processing EarlyData
13936
           as soon we receive the client's finished message */
13937
        ssl->earlyData = done_early_data;
13938
    }
13939
#endif /* WOLFSSL_QUIC && WOLFSSL_EARLY_DATA */
13940
13941
0
    ret = 0;
13942
0
cleanup:
13943
0
    ForceZero(mac, sizeof(mac));
13944
0
    WOLFSSL_LEAVE("DoTls13Finished", ret);
13945
0
    WOLFSSL_END(WC_FUNC_FINISHED_DO);
13946
13947
0
    return ret;
13948
0
}
13949
13950
#if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER)
13951
/* Send the TLS v1.3 Finished message.
13952
 *
13953
 * ssl  The SSL/TLS object.
13954
 * returns 0 on success, otherwise failure.
13955
 */
13956
static int SendTls13Finished(WOLFSSL* ssl)
13957
0
{
13958
0
    byte  finishedSz = ssl->specs.hash_size;
13959
0
    byte* input;
13960
0
    byte* output;
13961
0
    int   ret = 0; /* the resume goto can skip every build-phase assign */
13962
0
    int   headerSz = HANDSHAKE_HEADER_SZ;
13963
0
    int   outputSz;
13964
0
    byte* secret;
13965
13966
#ifdef WOLFSSL_DTLS13
13967
    int dtlsRet = 0, isDtls = 0;
13968
#endif /* WOLFSSL_DTLS13 */
13969
13970
0
    WOLFSSL_START(WC_FUNC_FINISHED_SEND);
13971
0
    WOLFSSL_ENTER("SendTls13Finished");
13972
13973
#ifdef WOLFSSL_DTLS13
13974
    if (ssl->options.dtls) {
13975
        headerSz = DTLS_HANDSHAKE_HEADER_SZ;
13976
        /* using isDtls instead of ssl->options.dtls will abide clang static
13977
           analyzer on using an uninitialized value */
13978
        isDtls = 1;
13979
    }
13980
#endif /* WOLFSSL_DTLS13 */
13981
13982
    /* Post-send key-schedule resume: the Finished record is already
13983
     * queued, so skip the build phase (re-running would queue it twice). */
13984
0
    if (ssl->kdfDeriveStep > 0)
13985
0
        goto tls13_send_finished_derives;
13986
13987
0
    ssl->options.buildingMsg = 1;
13988
13989
0
    outputSz = WC_MAX_DIGEST_SIZE + headerSz + MAX_MSG_EXTRA;
13990
#ifdef WOLFSSL_DTLS13
13991
    /* MAX_MSG_EXTRA reserves RECORD_HEADER_SZ, which is the size of the DTLS
13992
     * 1.3 unified header without the CID, so only the CID is missing. */
13993
    if (isDtls)
13994
        outputSz += DtlsGetCidTxSize(ssl);
13995
#endif /* WOLFSSL_DTLS13 */
13996
    /* Check buffers are big enough and grow if needed. */
13997
0
    if ((ret = CheckAvailableSize(ssl, outputSz)) != 0)
13998
0
        return ret;
13999
14000
    /* get output buffer */
14001
0
    output = GetOutputBuffer(ssl);
14002
0
    input = output + RECORD_HEADER_SZ;
14003
14004
#ifdef WOLFSSL_DTLS13
14005
    if (isDtls)
14006
        input = output + Dtls13GetRlHeaderLength(ssl, 1);
14007
#endif /* WOLFSSL_DTLS13 */
14008
14009
0
    AddTls13HandShakeHeader(input, (word32)finishedSz, 0, (word32)finishedSz,
14010
0
            finished, ssl);
14011
14012
#ifdef WOLFSSL_ASYNC_CRYPT
14013
    /* A suspended build already wrote the verify data and hashed it;
14014
     * recomputing would hash the body twice. */
14015
    if (ssl->options.buildArgs13Set)
14016
        goto tls13_send_finished_encrypt;
14017
#endif
14018
14019
#if defined(WOLFSSL_RENESAS_TSIP_TLS)
14020
    if (ssl->options.side == WOLFSSL_CLIENT_END) {
14021
        ret = tsip_Tls13SendFinished(ssl, output, outputSz, input, 1);
14022
        if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
14023
            return ret;
14024
        }
14025
        ret = 0;
14026
    }
14027
#endif /* WOLFSSL_RENESAS_TSIP_TLS */
14028
14029
    /* make finished hashes */
14030
0
    if (ssl->options.handShakeDone) {
14031
0
        ret = DeriveFinishedSecret(ssl, ssl->clientSecret,
14032
0
                                   ssl->keys.client_write_MAC_secret,
14033
0
                                   WOLFSSL_CLIENT_END);
14034
0
        if (ret != 0)
14035
0
            return ret;
14036
14037
0
        secret = ssl->keys.client_write_MAC_secret;
14038
0
    }
14039
0
    else if (ssl->options.side == WOLFSSL_CLIENT_END)
14040
0
        secret = ssl->keys.client_write_MAC_secret;
14041
0
    else {
14042
        /* All the handshake messages have been done to calculate client and
14043
         * server finished keys.
14044
         */
14045
0
        ret = DeriveFinishedSecret(ssl, ssl->clientSecret,
14046
0
                                   ssl->keys.client_write_MAC_secret,
14047
0
                                   WOLFSSL_CLIENT_END);
14048
0
        if (ret != 0)
14049
0
            return ret;
14050
14051
0
        ret = DeriveFinishedSecret(ssl, ssl->serverSecret,
14052
0
                                   ssl->keys.server_write_MAC_secret,
14053
0
                                   WOLFSSL_SERVER_END);
14054
0
        if (ret != 0)
14055
0
            return ret;
14056
14057
0
        secret = ssl->keys.server_write_MAC_secret;
14058
0
    }
14059
0
    ret = BuildTls13HandshakeHmac(ssl, secret, &input[headerSz], NULL);
14060
0
    if (ret != 0)
14061
0
        return ret;
14062
    #ifdef WOLFSSL_HAVE_TLS_UNIQUE
14063
        if (ssl->options.side == WOLFSSL_CLIENT_END) {
14064
            XMEMCPY(ssl->clientFinished, &input[headerSz], finishedSz);
14065
            ssl->clientFinished_len = finishedSz;
14066
        }
14067
        else {
14068
            XMEMCPY(ssl->serverFinished, &input[headerSz], finishedSz);
14069
            ssl->serverFinished_len = finishedSz;
14070
        }
14071
    #endif /* WOLFSSL_HAVE_TLS_UNIQUE */
14072
14073
#ifdef WOLFSSL_ASYNC_CRYPT
14074
tls13_send_finished_encrypt:
14075
#endif
14076
14077
#ifdef WOLFSSL_DTLS13
14078
    if (isDtls) {
14079
        dtlsRet = Dtls13HandshakeSend(ssl, output, (word16)outputSz,
14080
            (word16)(Dtls13GetRlHeaderLength(ssl, 1) + headerSz + finishedSz), finished,
14081
            1);
14082
        if (dtlsRet != 0 && dtlsRet != WC_NO_ERR_TRACE(WANT_WRITE))
14083
            return dtlsRet;
14084
14085
    } else
14086
#endif /* WOLFSSL_DTLS13 */
14087
0
    {
14088
        /* This message is always encrypted. */
14089
0
        int sendSz = BuildTls13Message(ssl, output, outputSz, input,
14090
0
                                   headerSz + finishedSz, handshake, 1, 0,
14091
0
                                   TLS13_HS_ASYNC_OKAY);
14092
0
        if (sendSz < 0) {
14093
        #ifdef WOLFSSL_ASYNC_CRYPT
14094
            /* Propagate a pending record encryption rather than reporting it
14095
             * as a build failure: the retry resumes the record. */
14096
            if (sendSz == WC_NO_ERR_TRACE(WC_PENDING_E))
14097
                return sendSz;
14098
        #endif
14099
0
            WOLFSSL_ERROR_VERBOSE(BUILD_MSG_ERROR);
14100
0
            return BUILD_MSG_ERROR;
14101
0
        }
14102
14103
        #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
14104
            if (ssl->hsInfoOn) AddPacketName(ssl, "Finished");
14105
            if (ssl->toInfoOn) {
14106
                ret = AddPacketInfo(ssl, "Finished", handshake, output, sendSz,
14107
                              WRITE_PROTO, 0, ssl->heap);
14108
                if (ret != 0)
14109
                    return ret;
14110
            }
14111
        #endif
14112
14113
0
        ssl->buffers.outputBuffer.length += (word32)sendSz;
14114
0
        ssl->options.buildingMsg = 0;
14115
0
    }
14116
14117
    /* Build phase complete; steps below are individually resumable. */
14118
0
    ssl->kdfDeriveStep = TLS13_SEND_KDF_FIN_ENTERED;
14119
0
tls13_send_finished_derives:
14120
14121
0
    if (ssl->options.side == WOLFSSL_SERVER_END) {
14122
#ifdef WOLFSSL_EARLY_DATA
14123
        byte storeTrafficDecKeys = ssl->earlyData == no_early_data;
14124
#endif
14125
        /* Can send application data now. */
14126
0
        if (ssl->kdfDeriveStep <= TLS13_SEND_KDF_FIN_ENTERED) {
14127
0
            ret = DeriveMasterSecret(ssl);
14128
0
            if (ret != 0) {
14129
0
                if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
14130
0
                    ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
14131
0
                return ret;
14132
0
            }
14133
0
            ssl->kdfDeriveStep = TLS13_SEND_KDF_FIN_MASTER_SECRET;
14134
0
        }
14135
        /* Last use of preMasterSecret - zeroize as soon as possible. */
14136
0
        ForceZero(ssl->arrays->preMasterSecret, MAX_PREMASTER_SZ);
14137
#ifdef WOLFSSL_EARLY_DATA
14138
14139
#ifdef WOLFSSL_DTLS13
14140
        /* DTLS13 dynamically change keys and it needs all
14141
           the keys in ssl->keys to save the keying material */
14142
        if (isDtls)
14143
            storeTrafficDecKeys = 1;
14144
#endif /* WOLFSSL_DTLS13 */
14145
14146
        if (ssl->kdfDeriveStep <= TLS13_SEND_KDF_FIN_MASTER_SECRET) {
14147
            ret = DeriveTls13Keys(ssl, traffic_key, ENCRYPT_SIDE_ONLY, 1);
14148
            if (ret != 0) {
14149
                if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
14150
                    ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
14151
                return ret;
14152
            }
14153
            ssl->kdfDeriveStep = TLS13_SEND_KDF_FIN_ENC_TRAFFIC_KEYS;
14154
        }
14155
        if (ssl->kdfDeriveStep <= TLS13_SEND_KDF_FIN_ENC_TRAFFIC_KEYS) {
14156
            ret = DeriveTls13Keys(ssl, traffic_key, DECRYPT_SIDE_ONLY,
14157
                                  storeTrafficDecKeys);
14158
            if (ret != 0) {
14159
                if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
14160
                    ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
14161
                return ret;
14162
            }
14163
            ssl->kdfDeriveStep = TLS13_SEND_KDF_FIN_TRAFFIC_KEYS;
14164
        }
14165
#else
14166
0
        if (ssl->kdfDeriveStep <= TLS13_SEND_KDF_FIN_ENC_TRAFFIC_KEYS) {
14167
0
            ret = DeriveTls13Keys(ssl, traffic_key, ENCRYPT_AND_DECRYPT_SIDE,
14168
0
                                  1);
14169
0
            if (ret != 0) {
14170
0
                if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
14171
0
                    ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
14172
0
                return ret;
14173
0
            }
14174
0
            ssl->kdfDeriveStep = TLS13_SEND_KDF_FIN_TRAFFIC_KEYS;
14175
0
        }
14176
0
#endif
14177
0
        if (ssl->kdfDeriveStep <= TLS13_SEND_KDF_FIN_TRAFFIC_KEYS) {
14178
0
            ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY);
14179
0
            if (ret != 0) {
14180
0
                if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
14181
0
                    ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
14182
0
                return ret;
14183
0
            }
14184
0
            ssl->kdfDeriveStep = TLS13_SEND_KDF_FIN_ENC_KEYS_SET;
14185
0
        }
14186
14187
#ifdef WOLFSSL_DTLS13
14188
        if (isDtls) {
14189
            w64wrapper epochTraffic0;
14190
            epochTraffic0 = w64From32(0, DTLS13_EPOCH_TRAFFIC0);
14191
            ssl->dtls13Epoch = epochTraffic0;
14192
            ssl->dtls13PeerEpoch = epochTraffic0;
14193
14194
            if (ssl->kdfDeriveStep <= TLS13_SEND_KDF_FIN_ENC_KEYS_SET) {
14195
                ret = Dtls13SetEpochKeys(ssl, epochTraffic0,
14196
                                         ENCRYPT_AND_DECRYPT_SIDE);
14197
                if (ret != 0) {
14198
                    if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
14199
                        ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
14200
                    return ret;
14201
                }
14202
                ssl->kdfDeriveStep = TLS13_SEND_KDF_FIN_DTLS_TRAFFIC_EPOCH;
14203
            }
14204
        }
14205
#endif /* WOLFSSL_DTLS13 */
14206
14207
0
    }
14208
14209
0
    if (ssl->options.side == WOLFSSL_CLIENT_END &&
14210
0
                                                  !ssl->options.handShakeDone) {
14211
#ifdef WOLFSSL_EARLY_DATA
14212
        if (ssl->earlyData != no_early_data) {
14213
            if (ssl->kdfDeriveStep <= TLS13_SEND_KDF_FIN_DTLS_TRAFFIC_EPOCH) {
14214
                ret = DeriveTls13Keys(ssl, no_key, ENCRYPT_SIDE_ONLY, 1);
14215
                if (ret != 0) {
14216
                    if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
14217
                        ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
14218
                    return ret;
14219
                }
14220
                ssl->kdfDeriveStep = TLS13_SEND_KDF_FIN_EARLY_ENC_KEYS;
14221
            }
14222
        }
14223
#endif
14224
        /* Setup keys for application data messages. */
14225
0
        if (ssl->kdfDeriveStep <= TLS13_SEND_KDF_FIN_EARLY_ENC_KEYS) {
14226
0
            ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY);
14227
0
            if (ret != 0) {
14228
0
                if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
14229
0
                    ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
14230
0
                return ret;
14231
0
            }
14232
0
            ssl->kdfDeriveStep = TLS13_SEND_KDF_FIN_EARLY_KEYS_SET;
14233
0
        }
14234
14235
#if defined(HAVE_SESSION_TICKET)
14236
        if (ssl->kdfDeriveStep <= TLS13_SEND_KDF_FIN_EARLY_KEYS_SET) {
14237
            ret = DeriveResumptionSecret(ssl, ssl->session->masterSecret);
14238
            if (ret != 0) {
14239
                if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
14240
                    ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
14241
                return ret;
14242
            }
14243
            ssl->kdfDeriveStep = TLS13_SEND_KDF_FIN_RESUMPTION_SECRET;
14244
        }
14245
#endif
14246
14247
#ifdef WOLFSSL_DTLS13
14248
        if (isDtls) {
14249
            w64wrapper epochTraffic0;
14250
            epochTraffic0 = w64From32(0, DTLS13_EPOCH_TRAFFIC0);
14251
            ssl->dtls13Epoch = epochTraffic0;
14252
            ssl->dtls13PeerEpoch = epochTraffic0;
14253
14254
            /* Step-guarded like every other derive in this function, so a
14255
             * pend resumes here and a real error clears the resume state. */
14256
            if (ssl->kdfDeriveStep <= TLS13_SEND_KDF_FIN_RESUMPTION_SECRET) {
14257
                ret = Dtls13SetEpochKeys(
14258
                    ssl, epochTraffic0, ENCRYPT_AND_DECRYPT_SIDE);
14259
                if (ret != 0) {
14260
                    if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
14261
                        ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
14262
                    return ret;
14263
                }
14264
                ssl->kdfDeriveStep = TLS13_SEND_KDF_FIN_DTLS_EPOCH_SET;
14265
            }
14266
        }
14267
#endif /* WOLFSSL_DTLS13 */
14268
0
    }
14269
14270
0
    ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
14271
14272
0
#ifndef NO_WOLFSSL_CLIENT
14273
0
    if (ssl->options.side == WOLFSSL_CLIENT_END) {
14274
0
        ssl->options.clientState = CLIENT_FINISHED_COMPLETE;
14275
0
        ssl->options.handShakeState = HANDSHAKE_DONE;
14276
0
        ssl->options.handShakeDone  = 1;
14277
0
    }
14278
0
#endif
14279
0
#ifndef NO_WOLFSSL_SERVER
14280
0
    if (ssl->options.side == WOLFSSL_SERVER_END) {
14281
0
        ssl->options.serverState = SERVER_FINISHED_COMPLETE;
14282
0
    }
14283
0
#endif
14284
14285
#ifdef WOLFSSL_DTLS13
14286
    if (isDtls) {
14287
        WOLFSSL_LEAVE("SendTls13Finished", ret);
14288
        WOLFSSL_END(WC_FUNC_FINISHED_SEND);
14289
14290
        return dtlsRet;
14291
    }
14292
#endif /* WOLFSSL_DTLS13 */
14293
14294
0
    if ((ret = SendBuffered(ssl)) != 0)
14295
0
        return ret;
14296
14297
0
    WOLFSSL_LEAVE("SendTls13Finished", ret);
14298
0
    WOLFSSL_END(WC_FUNC_FINISHED_SEND);
14299
14300
0
    return ret;
14301
0
}
14302
#endif /* !NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER */
14303
14304
/* RFC 9846 Section 4.7.3: a TLS 1.3 sender MUST NOT allow its number of key
14305
 * updates to exceed 2^48-1. DTLS 1.3 bounds the epoch instead (RFC 9147
14306
 * Section 4.2.1), so this only covers TLS.
14307
 *
14308
 * ssl  The SSL/TLS object.
14309
 * returns 1 when a further KeyUpdate would exceed the limit, 0 otherwise.
14310
 */
14311
int Tls13KeyUpdateLimitReached(WOLFSSL* ssl)
14312
0
{
14313
0
    if (ssl->options.dtls)
14314
0
        return 0;
14315
14316
0
    return w64GTE(ssl->keys.keyUpdateCount,
14317
0
                  w64From32(TLS13_KEY_UPDATE_MAX_HI32,
14318
0
                            TLS13_KEY_UPDATE_MAX_LO32));
14319
0
}
14320
14321
/* handle generation TLS v1.3 key_update (24) */
14322
/* Send the TLS v1.3 KeyUpdate message.
14323
 *
14324
 * ssl  The SSL/TLS object.
14325
 * returns 0 on success, otherwise failure.
14326
 */
14327
int SendTls13KeyUpdate(WOLFSSL* ssl)
14328
0
{
14329
0
    byte*  input;
14330
0
    byte*  output;
14331
0
    int    ret;
14332
0
    int    headerSz = HANDSHAKE_HEADER_SZ;
14333
0
    int    outputSz;
14334
0
    word32 i = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
14335
14336
0
    WOLFSSL_START(WC_FUNC_KEY_UPDATE_SEND);
14337
0
    WOLFSSL_ENTER("SendTls13KeyUpdate");
14338
14339
#ifdef WOLFSSL_DTLS13
14340
    if (ssl->options.dtls) {
14341
        /* RFC 9147 Section 4.2.1: do not send a KeyUpdate that would advance
14342
         * the sending epoch beyond 2^48-1. */
14343
        if (w64GTE(ssl->dtls13Epoch,
14344
                   w64From32(DTLS13_EPOCH_MAX_HI32, DTLS13_EPOCH_MAX_LO32))) {
14345
            WOLFSSL_MSG("DTLS 1.3 sending epoch at maximum; refusing KeyUpdate");
14346
            return BAD_STATE_E;
14347
        }
14348
        i = Dtls13GetRlHeaderLength(ssl, 1) + DTLS_HANDSHAKE_HEADER_SZ;
14349
    }
14350
#endif /* WOLFSSL_DTLS13 */
14351
14352
    /* RFC 9846 Section 4.7.3: a sending implementation MUST NOT allow its
14353
     * number of key updates to exceed 2^48-1. Receivers MUST NOT enforce this
14354
     * on the peer. */
14355
0
    if (Tls13KeyUpdateLimitReached(ssl)) {
14356
0
        WOLFSSL_MSG("TLS 1.3 key update count at maximum; refusing KeyUpdate");
14357
0
        return BAD_STATE_E;
14358
0
    }
14359
14360
    /* i already carries the real record and handshake header lengths.
14361
     * MAX_MSG_EXTRA only budgets RECORD_HEADER_SZ. */
14362
0
    outputSz = (int)i + OPAQUE8_LEN + MAX_MSG_EXTRA;
14363
    /* Check buffers are big enough and grow if needed. */
14364
0
    if ((ret = CheckAvailableSize(ssl, outputSz)) != 0)
14365
0
        return ret;
14366
14367
    /* get output buffer */
14368
0
    output = GetOutputBuffer(ssl);
14369
0
    input = output + RECORD_HEADER_SZ;
14370
14371
#ifdef WOLFSSL_DTLS13
14372
    if (ssl->options.dtls)
14373
        input = output + Dtls13GetRlHeaderLength(ssl, 1);
14374
#endif /* WOLFSSL_DTLS13 */
14375
14376
0
    AddTls13Headers(output, OPAQUE8_LEN, key_update, ssl);
14377
14378
    /* A TLS response left for SendData() is owed even if a later
14379
     * update_not_requested cleared keyUpdateRespond, and this KeyUpdate,
14380
     * whoever asked for it, answers it. */
14381
0
    if (!ssl->options.dtls && ssl->options.sendKeyUpdate) {
14382
0
        ssl->keys.keyUpdateRespond = 1;
14383
0
        ssl->options.sendKeyUpdate = 0;
14384
0
    }
14385
14386
    /* If:
14387
     *   1. I haven't sent a KeyUpdate requesting a response and
14388
     *   2. This isn't responding to peer KeyUpdate requiring a response then,
14389
     * I want a response.
14390
     */
14391
0
    ssl->keys.updateResponseReq = output[i++] =
14392
0
         !ssl->keys.updateResponseReq && !ssl->keys.keyUpdateRespond;
14393
    /* Sent response, no longer need to respond. */
14394
0
    ssl->keys.keyUpdateRespond = 0;
14395
14396
#ifdef WOLFSSL_DTLS13
14397
    if (ssl->options.dtls) {
14398
        ret = Dtls13HandshakeSend(ssl, output, (word16)outputSz,
14399
            OPAQUE8_LEN + Dtls13GetRlHeaderLength(ssl, 1) +
14400
                DTLS_HANDSHAKE_HEADER_SZ,
14401
            key_update, 0);
14402
    }
14403
    else
14404
#endif /* WOLFSSL_DTLS13 */
14405
0
    {
14406
        /* This message is always encrypted. */
14407
0
        int sendSz = BuildTls13Message(ssl, output, outputSz, input,
14408
0
                                   headerSz + OPAQUE8_LEN, handshake, 0, 0, 0);
14409
0
        if (sendSz < 0)
14410
0
            return BUILD_MSG_ERROR;
14411
14412
        #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
14413
            if (ssl->hsInfoOn) AddPacketName(ssl, "KeyUpdate");
14414
            if (ssl->toInfoOn) {
14415
                ret = AddPacketInfo(ssl, "KeyUpdate", handshake, output, sendSz,
14416
                              WRITE_PROTO, 0, ssl->heap);
14417
                if (ret != 0)
14418
                    return ret;
14419
            }
14420
        #endif
14421
14422
0
        ssl->buffers.outputBuffer.length += (word32)sendSz;
14423
14424
0
        ret = SendBuffered(ssl);
14425
14426
14427
0
        if (ret != 0 && ret != WC_NO_ERR_TRACE(WANT_WRITE))
14428
0
            return ret;
14429
0
    }
14430
14431
    /* In DTLS we must wait for the ack before setting up the new keys */
14432
0
    if (!ssl->options.dtls) {
14433
0
        int keyRet; /* ret may hold WANT_WRITE */
14434
14435
        /* Future traffic uses new encryption keys. */
14436
0
        if ((keyRet = DeriveTls13Keys(
14437
0
                       ssl, update_traffic_key, ENCRYPT_SIDE_ONLY, 1))
14438
0
            != 0)
14439
0
            return keyRet;
14440
0
        if ((keyRet = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
14441
0
            return keyRet;
14442
14443
        /* Count this key update against the RFC 9846 sender limit. */
14444
0
        w64Increment(&ssl->keys.keyUpdateCount);
14445
0
    }
14446
14447
14448
0
    WOLFSSL_LEAVE("SendTls13KeyUpdate", ret);
14449
0
    WOLFSSL_END(WC_FUNC_KEY_UPDATE_SEND);
14450
14451
0
    return ret;
14452
0
}
14453
14454
/* handle processing TLS v1.3 key_update (24) */
14455
/* Parse and handle a TLS v1.3 KeyUpdate message.
14456
 *
14457
 * ssl       The SSL/TLS object.
14458
 * input     The message buffer.
14459
 * inOutIdx  On entry, the index into the message buffer of Finished.
14460
 *           On exit, the index of byte after the Finished message and padding.
14461
 * totalSz   The length of the current handshake message.
14462
 * returns 0 on success and otherwise failure.
14463
 */
14464
static int DoTls13KeyUpdate(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
14465
                            word32 totalSz)
14466
0
{
14467
0
    int    ret;
14468
0
    word32 i = *inOutIdx;
14469
14470
0
    WOLFSSL_START(WC_FUNC_KEY_UPDATE_DO);
14471
0
    WOLFSSL_ENTER("DoTls13KeyUpdate");
14472
14473
    /* check against totalSz */
14474
0
    if (OPAQUE8_LEN != totalSz)
14475
0
        return BUFFER_E;
14476
14477
0
    switch (input[i]) {
14478
0
        case update_not_requested:
14479
            /* This message in response to any outstanding request. */
14480
0
            ssl->keys.keyUpdateRespond = 0;
14481
0
            ssl->keys.updateResponseReq = 0;
14482
0
            break;
14483
0
        case update_requested:
14484
            /* New key update requiring a response. */
14485
0
            ssl->keys.keyUpdateRespond = 1;
14486
0
            break;
14487
0
        default:
14488
0
            WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
14489
0
            return INVALID_PARAMETER;
14490
0
    }
14491
14492
    /* Move index to byte after message. */
14493
0
    *inOutIdx += totalSz;
14494
14495
    /* Future traffic uses new decryption keys. */
14496
0
    if ((ret = DeriveTls13Keys(ssl, update_traffic_key, DECRYPT_SIDE_ONLY, 1))
14497
0
                                                                         != 0) {
14498
0
        return ret;
14499
0
    }
14500
0
    if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0)
14501
0
        return ret;
14502
14503
#ifdef WOLFSSL_DTLS13
14504
    if (ssl->options.dtls) {
14505
        /* Increment on a local copy so ssl->dtls13PeerEpoch is left
14506
         * untouched when the check fails. */
14507
        w64wrapper newEpoch = ssl->dtls13PeerEpoch;
14508
        w64Increment(&newEpoch);
14509
14510
        /* RFC 9147 Section 8: the 2^48-1 cap is sender-only; receivers MUST
14511
         * NOT enforce it. Guard only the wrap-to-zero (Section 4.2.1). */
14512
        if (w64IsZero(newEpoch))
14513
            return BAD_STATE_E;
14514
14515
        ssl->dtls13PeerEpoch = newEpoch;
14516
14517
        ret = Dtls13SetEpochKeys(ssl, ssl->dtls13PeerEpoch, DECRYPT_SIDE_ONLY);
14518
        if (ret != 0)
14519
            return ret;
14520
    }
14521
#endif /* WOLFSSL_DTLS13 */
14522
14523
0
    if (ssl->keys.keyUpdateRespond) {
14524
0
        if (IsWriteClosed(ssl)) {
14525
0
            WOLFSSL_MSG("Not answering KeyUpdate after close_notify");
14526
0
            ssl->keys.keyUpdateRespond = 0;
14527
0
            return 0;
14528
0
        }
14529
14530
#ifdef WOLFSSL_DTLS13
14531
        /* we already sent a keyUpdate (either in response to a previous
14532
           KeyUpdate or initiated by the application) and we are waiting for the
14533
           ack. We can't send a new KeyUpdate right away but to honor the RFC we
14534
           should send another KeyUpdate after the one in-flight is acked. We
14535
           don't do that as it looks redundant, it will make the code more
14536
           complex and I don't see a good use case for that. */
14537
        if (ssl->options.dtls && ssl->dtls13WaitKeyUpdateAck) {
14538
            ssl->keys.keyUpdateRespond = 0;
14539
            return 0;
14540
        }
14541
#endif /* WOLFSSL_DTLS13 */
14542
14543
#if defined(HAVE_WRITE_DUP) && defined(WOLFSSL_TLS13)
14544
        /* Read side cannot write; delegate the response to the write side.
14545
         * The key update cap is deliberately not checked here: the two sides
14546
         * are separate WOLFSSL objects with separate keys, and only the write
14547
         * side ever sends a KeyUpdate, so this object's keyUpdateCount is not
14548
         * the one the limit applies to. The check is applied on the write side
14549
         * in wolfssl_write_dup_do_tls13_work(). */
14550
        if (ssl->dupWrite != NULL && ssl->dupSide == READ_DUP_SIDE) {
14551
            if (wc_LockMutex(&ssl->dupWrite->dupMutex) != 0)
14552
                return BAD_MUTEX_E;
14553
            ssl->dupWrite->keyUpdateRespond = 1;
14554
            wc_UnLockMutex(&ssl->dupWrite->dupMutex);
14555
            ssl->keys.keyUpdateRespond = 0;
14556
            return 0;
14557
        }
14558
#endif /* HAVE_WRITE_DUP && WOLFSSL_TLS13 */
14559
14560
        /* RFC 9846 Section 4.7.3: a sender that would exceed the key update
14561
         * limit "MUST NOT send its own KeyUpdate ... and SHOULD instead ignore
14562
         * the 'update_requested' flag". Dropping the response rather than
14563
         * failing keeps the connection alive on the current keys until the
14564
         * Section 5.5 data limits eventually force it closed. */
14565
0
        if (Tls13KeyUpdateLimitReached(ssl)) {
14566
0
            WOLFSSL_MSG("Key update limit reached; ignoring update_requested");
14567
0
            ssl->keys.keyUpdateRespond = 0;
14568
0
            return 0;
14569
0
        }
14570
14571
0
#ifndef WOLFSSL_RW_THREADED
14572
        /* RFC 8446 Section 4.6.3: the response is due before the next
14573
         * application data record, and one KeyUpdate answers every request
14574
         * received while we are silent. While earlier output is still waiting
14575
         * for the peer to read it, don't queue a response per request behind
14576
         * it; leave one for SendData() to send. DTLS has at most one KeyUpdate
14577
         * in flight, see above. */
14578
0
        if (ssl->options.dtls || ssl->buffers.outputBuffer.length == 0) {
14579
            /* This response answers a deferred request as well. */
14580
0
            ssl->options.sendKeyUpdate = 0;
14581
0
            ret = SendTls13KeyUpdate(ssl);
14582
        #ifdef WOLFSSL_DTLS13
14583
            if (ssl->options.dtls)
14584
                return ret;
14585
        #endif
14586
            /* reply is sent by the next write */
14587
0
            if (ret == WC_NO_ERR_TRACE(WANT_WRITE))
14588
0
                ret = 0;
14589
0
            return ret;
14590
0
        }
14591
0
#endif
14592
0
        ssl->options.sendKeyUpdate = 1;
14593
0
        return 0;
14594
0
    }
14595
14596
0
    WOLFSSL_LEAVE("DoTls13KeyUpdate", ret);
14597
0
    WOLFSSL_END(WC_FUNC_KEY_UPDATE_DO);
14598
14599
0
    return 0;
14600
0
}
14601
14602
#ifdef WOLFSSL_EARLY_DATA
14603
#ifndef NO_WOLFSSL_CLIENT
14604
/* Send the TLS v1.3 EndOfEarlyData message to indicate that there will be no
14605
 * more early application data.
14606
 * The encryption key now changes to the pre-calculated handshake key.
14607
 *
14608
 * ssl  The SSL/TLS object.
14609
 * returns 0 on success and otherwise failure.
14610
 */
14611
static int SendTls13EndOfEarlyData(WOLFSSL* ssl)
14612
{
14613
    byte*  output;
14614
    int    ret;
14615
    int    sendSz;
14616
    word32 length;
14617
    word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
14618
14619
    WOLFSSL_START(WC_FUNC_END_OF_EARLY_DATA_SEND);
14620
    WOLFSSL_ENTER("SendTls13EndOfEarlyData");
14621
14622
    length = 0;
14623
    sendSz = (int)(idx + length + MAX_MSG_EXTRA);
14624
    ssl->options.buildingMsg = 1;
14625
14626
    /* Check buffers are big enough and grow if needed. */
14627
    if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
14628
        return ret;
14629
14630
    /* Get position in output buffer to write new message to. */
14631
    output = GetOutputBuffer(ssl);
14632
14633
    /* Put the record and handshake headers on. */
14634
    AddTls13Headers(output, length, end_of_early_data, ssl);
14635
14636
    /* This message is always encrypted. */
14637
    sendSz = BuildTls13Message(ssl, output, sendSz, output + RECORD_HEADER_SZ,
14638
                               idx - RECORD_HEADER_SZ, handshake, 1, 0, 0);
14639
    if (sendSz < 0)
14640
        return sendSz;
14641
14642
    ssl->buffers.outputBuffer.length += sendSz;
14643
14644
    if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
14645
        return ret;
14646
14647
    ssl->options.buildingMsg = 0;
14648
    if (!ssl->options.groupMessages)
14649
        ret = SendBuffered(ssl);
14650
14651
    ssl->earlyData = done_early_data;
14652
14653
    WOLFSSL_LEAVE("SendTls13EndOfEarlyData", ret);
14654
    WOLFSSL_END(WC_FUNC_END_OF_EARLY_DATA_SEND);
14655
14656
    return ret;
14657
}
14658
#endif /* !NO_WOLFSSL_CLIENT */
14659
14660
#ifndef NO_WOLFSSL_SERVER
14661
/* handle processing of TLS 1.3 end_of_early_data (5) */
14662
/* Parse the TLS v1.3 EndOfEarlyData message that indicates that there will be
14663
 * no more early application data.
14664
 * The decryption key now changes to the pre-calculated handshake key.
14665
 *
14666
 * ssl  The SSL/TLS object.
14667
 * returns 0 on success and otherwise failure.
14668
 */
14669
static int DoTls13EndOfEarlyData(WOLFSSL* ssl, const byte* input,
14670
                                 word32* inOutIdx, word32 size)
14671
{
14672
    int    ret;
14673
    word32 begin = *inOutIdx;
14674
14675
    (void)input;
14676
14677
    WOLFSSL_START(WC_FUNC_END_OF_EARLY_DATA_DO);
14678
    WOLFSSL_ENTER("DoTls13EndOfEarlyData");
14679
14680
    if ((*inOutIdx - begin) != size)
14681
        return BUFFER_ERROR;
14682
14683
    if (ssl->earlyData == no_early_data) {
14684
        WOLFSSL_MSG("EndOfEarlyData received unexpectedly");
14685
        SendAlert(ssl, alert_fatal, unexpected_message);
14686
        WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
14687
        return OUT_OF_ORDER_E;
14688
    }
14689
14690
    ssl->earlyData = done_early_data;
14691
14692
    ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY);
14693
14694
    WOLFSSL_LEAVE("DoTls13EndOfEarlyData", ret);
14695
    WOLFSSL_END(WC_FUNC_END_OF_EARLY_DATA_DO);
14696
14697
    return ret;
14698
}
14699
#endif /* !NO_WOLFSSL_SERVER */
14700
#endif /* WOLFSSL_EARLY_DATA */
14701
14702
#if defined(HAVE_SESSION_TICKET) && defined(WOLFSSL_TICKET_NONCE_MALLOC) &&    \
14703
    (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
14704
int SessionTicketNoncePopulate(WOLFSSL_SESSION *session, const byte *nonce,
14705
    byte len)
14706
{
14707
    if (session->ticketNonce.data
14708
            != session->ticketNonce.dataStatic) {
14709
         XFREE(session->ticketNonce.data, session->heap,
14710
             DYNAMIC_TYPE_SESSION_TICK);
14711
         session->ticketNonce.data = session->ticketNonce.dataStatic;
14712
         session->ticketNonce.len = 0;
14713
    }
14714
14715
    if (len > MAX_TICKET_NONCE_STATIC_SZ) {
14716
        WOLFSSL_MSG("Using dynamic nonce buffer");
14717
        session->ticketNonce.data = (byte*)XMALLOC(len,
14718
            session->heap, DYNAMIC_TYPE_SESSION_TICK);
14719
        if (session->ticketNonce.data == NULL)
14720
            return MEMORY_ERROR;
14721
    }
14722
    XMEMCPY(session->ticketNonce.data, nonce, len);
14723
    session->ticketNonce.len = len;
14724
    return 0;
14725
}
14726
#endif
14727
#ifndef NO_WOLFSSL_CLIENT
14728
/* Handle a New Session Ticket handshake message.
14729
 * Message contains the information required to perform resumption.
14730
 *
14731
 * ssl       The SSL/TLS object.
14732
 * input     The message buffer.
14733
 * inOutIdx  On entry, the index into the message buffer of NewSessionTicket.
14734
 *           On exit, the index of byte after the NewSessionTicket message.
14735
 *           Record padding is skipped by the caller.
14736
 * size      The length of the current handshake message.
14737
 * returns 0 on success, otherwise failure.
14738
 */
14739
static int DoTls13NewSessionTicket(WOLFSSL* ssl, const byte* input,
14740
                                   word32* inOutIdx, word32 size)
14741
0
{
14742
#ifdef HAVE_SESSION_TICKET
14743
    int    ret;
14744
    word32 begin = *inOutIdx;
14745
    word32 lifetime;
14746
    word32 ageAdd;
14747
    word16 length;
14748
#ifdef WOLFSSL_32BIT_MILLI_TIME
14749
    word32 now;
14750
#else
14751
    sword64 now;
14752
#endif
14753
    const byte* nonce;
14754
    byte        nonceLength;
14755
14756
    WOLFSSL_START(WC_FUNC_NEW_SESSION_TICKET_DO);
14757
    WOLFSSL_ENTER("DoTls13NewSessionTicket");
14758
14759
#ifdef HAVE_ECH
14760
    /* ignore session ticket when ECH is rejected */
14761
    if (EchRejected(ssl)) {
14762
        *inOutIdx += size;
14763
        return 0;
14764
    }
14765
#endif
14766
14767
    /* Lifetime hint. */
14768
    if ((*inOutIdx - begin) + SESSION_HINT_SZ > size)
14769
        return BUFFER_ERROR;
14770
    ato32(input + *inOutIdx, &lifetime);
14771
    *inOutIdx += SESSION_HINT_SZ;
14772
    if (lifetime > MAX_LIFETIME) {
14773
        WOLFSSL_ERROR_VERBOSE(SERVER_HINT_ERROR);
14774
        return SERVER_HINT_ERROR;
14775
    }
14776
14777
    /* Age add. */
14778
    if ((*inOutIdx - begin) + SESSION_ADD_SZ > size)
14779
        return BUFFER_ERROR;
14780
    ato32(input + *inOutIdx, &ageAdd);
14781
    *inOutIdx += SESSION_ADD_SZ;
14782
14783
    /* Ticket nonce. */
14784
    if ((*inOutIdx - begin) + 1 > size)
14785
        return BUFFER_ERROR;
14786
    nonceLength = input[*inOutIdx];
14787
#if !defined(WOLFSSL_TICKET_NONCE_MALLOC) &&                                   \
14788
    (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3))
14789
    if (nonceLength > MAX_TICKET_NONCE_STATIC_SZ) {
14790
        WOLFSSL_MSG("Nonce length not supported");
14791
        WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
14792
        return INVALID_PARAMETER;
14793
    }
14794
#endif /* WOLFSSL_TICKET_NONCE_MALLOC && FIPS_VERSION_GE(5,3) */
14795
    *inOutIdx += 1;
14796
    if ((*inOutIdx - begin) + nonceLength > size)
14797
        return BUFFER_ERROR;
14798
    nonce = input + *inOutIdx;
14799
    *inOutIdx += nonceLength;
14800
14801
    /* Ticket length. */
14802
    if ((*inOutIdx - begin) + LENGTH_SZ > size)
14803
        return BUFFER_ERROR;
14804
    ato16(input + *inOutIdx, &length);
14805
    *inOutIdx += LENGTH_SZ;
14806
    if ((*inOutIdx - begin) + length > size)
14807
        return BUFFER_ERROR;
14808
    /* note: we reject zero length ticket here, and not in SetTicket(),
14809
     * because zero length is valid for TLS 1.2 */
14810
    if (length == 0)
14811
        return BUFFER_ERROR;
14812
14813
    if ((ret = SetTicket(ssl, input + *inOutIdx, length)) != 0)
14814
        return ret;
14815
    *inOutIdx += length;
14816
14817
    now = TimeNowInMilliseconds();
14818
    if (now == 0)
14819
        return GETTIME_ERROR;
14820
    /* Copy in ticket data (server identity). */
14821
    ssl->timeout                  = lifetime;
14822
    ssl->session->timeout         = lifetime;
14823
    ssl->session->cipherSuite0    = ssl->options.cipherSuite0;
14824
    ssl->session->cipherSuite     = ssl->options.cipherSuite;
14825
    ssl->session->ticketSeen      = now;
14826
    ssl->session->ticketAdd       = ageAdd;
14827
    #ifdef WOLFSSL_EARLY_DATA
14828
    ssl->session->maxEarlyDataSz  = ssl->options.maxEarlyDataSz;
14829
    #endif
14830
14831
#if defined(WOLFSSL_TICKET_NONCE_MALLOC) &&                                    \
14832
    (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
14833
    ret = SessionTicketNoncePopulate(ssl->session, nonce, nonceLength);
14834
    if (ret != 0)
14835
        return ret;
14836
#else
14837
    ssl->session->ticketNonce.len = nonceLength;
14838
    if (nonceLength > MAX_TICKET_NONCE_STATIC_SZ) {
14839
        ret = BUFFER_ERROR;
14840
        return ret;
14841
    }
14842
    if (nonceLength > 0)
14843
        XMEMCPY(ssl->session->ticketNonce.data, nonce, nonceLength);
14844
#endif /* defined(WOLFSSL_TICKET_NONCE_MALLOC) && FIPS_VERSION_GE(5,3) */
14845
14846
    ssl->session->namedGroup      = ssl->namedGroup;
14847
14848
    if ((*inOutIdx - begin) + EXTS_SZ > size)
14849
        return BUFFER_ERROR;
14850
    ato16(input + *inOutIdx, &length);
14851
    *inOutIdx += EXTS_SZ;
14852
    if ((*inOutIdx - begin) + length != size)
14853
        return BUFFER_ERROR;
14854
    /* RFC 9846 Section 4.7.1: the extensions are Section 4.3 Extension TLVs.
14855
     * Malformed framing is a syntax error even when no extension in the list
14856
     * is one we act on. */
14857
    ret = TLSX_Parse(ssl, input + *inOutIdx, length, session_ticket, NULL);
14858
    if (ret != 0)
14859
        return ret;
14860
    *inOutIdx += length;
14861
14862
    SetupSession(ssl);
14863
    #ifndef NO_SESSION_CACHE
14864
        AddSession(ssl);
14865
    #endif
14866
14867
    ssl->expect_session_ticket = 0;
14868
#else
14869
0
    (void)ssl;
14870
0
    (void)input;
14871
14872
0
    WOLFSSL_ENTER("DoTls13NewSessionTicket");
14873
14874
0
    *inOutIdx += size;
14875
0
#endif /* HAVE_SESSION_TICKET */
14876
14877
0
    WOLFSSL_LEAVE("DoTls13NewSessionTicket", 0);
14878
0
    WOLFSSL_END(WC_FUNC_NEW_SESSION_TICKET_DO);
14879
14880
0
    return 0;
14881
0
}
14882
#endif /* NO_WOLFSSL_CLIENT */
14883
14884
#ifndef NO_WOLFSSL_SERVER
14885
    #ifdef HAVE_SESSION_TICKET
14886
14887
#ifdef WOLFSSL_TLS13_TICKET_BEFORE_FINISHED
14888
/* Offset of the MAC size in the finished message. */
14889
#define FINISHED_MSG_SIZE_OFFSET    3
14890
14891
/* Calculate the resumption secret which includes the unseen client finished
14892
 * message.
14893
 *
14894
 * ssl  The SSL/TLS object.
14895
 * returns 0 on success, otherwise failure.
14896
 */
14897
static int ExpectedResumptionSecret(WOLFSSL* ssl)
14898
{
14899
    int         ret;
14900
    int         saveRet = 0;
14901
    word32      finishedSz = 0;
14902
    byte        mac[WC_MAX_DIGEST_SIZE];
14903
    Digest      digest;
14904
    byte header[] = { 0x14, 0x00, 0x00, 0x00 };
14905
14906
    XMEMSET(&digest, 0, sizeof(Digest));
14907
14908
    /* Copy the running hash so we can restore it after. */
14909
    switch (ssl->specs.mac_algorithm) {
14910
    #ifndef NO_SHA256
14911
        case sha256_mac:
14912
            ret = wc_Sha256Copy(&ssl->hsHashes->hashSha256, &digest.sha256);
14913
            if (ret != 0)
14914
                return ret;
14915
            break;
14916
    #endif
14917
    #ifdef WOLFSSL_SHA384
14918
        case sha384_mac:
14919
            ret = wc_Sha384Copy(&ssl->hsHashes->hashSha384, &digest.sha384);
14920
            if (ret != 0)
14921
                return ret;
14922
            break;
14923
    #endif
14924
    #ifdef WOLFSSL_TLS13_SHA512
14925
        case sha512_mac:
14926
            ret = wc_Sha512Copy(&ssl->hsHashes->hashSha512, &digest.sha512);
14927
            if (ret != 0)
14928
                return ret;
14929
            break;
14930
    #endif
14931
    #ifdef WOLFSSL_SM3
14932
        case sm3_mac:
14933
            ret = wc_Sm3Copy(&ssl->hsHashes->hashSm3, &digest.sm3);
14934
            if (ret != 0)
14935
                return ret;
14936
            break;
14937
    #endif
14938
    }
14939
14940
#ifdef WOLFSSL_EARLY_DATA
14941
    /* The client only sends EndOfEarlyData when early data was accepted, and
14942
     * never with DTLS or QUIC. It comes before, and is covered by, the
14943
     * client's Finished message. */
14944
    if (ssl->earlyData == process_early_data && !ssl->options.dtls &&
14945
            !WOLFSSL_IS_QUIC(ssl)) {
14946
        static const byte endOfEarlyData[] = { 0x05, 0x00, 0x00, 0x00 };
14947
        ret = HashRaw(ssl, endOfEarlyData, sizeof(endOfEarlyData));
14948
        if (ret != 0)
14949
            goto restore;
14950
    }
14951
#endif
14952
    /* Generate the Client's Finished message and hash it. */
14953
    ret = BuildTls13HandshakeHmac(ssl, ssl->keys.client_write_MAC_secret, mac,
14954
                                  &finishedSz);
14955
    if (ret != 0)
14956
        goto restore;
14957
    header[FINISHED_MSG_SIZE_OFFSET] = finishedSz;
14958
    if ((ret = HashRaw(ssl, header, sizeof(header))) != 0)
14959
        goto restore;
14960
    if ((ret = HashRaw(ssl, mac, finishedSz)) != 0)
14961
        goto restore;
14962
14963
    if ((ret = DeriveResumptionSecret(ssl, ssl->session->masterSecret)) != 0)
14964
        goto restore;
14965
14966
    /* Restore the hash inline with currently seen messages. */
14967
restore:
14968
    /* The restore result must not mask the error that got here, or a
14969
     * WC_PENDING_E would be reported as success with the derive skipped. */
14970
    saveRet = ret;
14971
    switch (ssl->specs.mac_algorithm) {
14972
    #ifndef NO_SHA256
14973
        case sha256_mac:
14974
            wc_Sha256Free(&ssl->hsHashes->hashSha256);
14975
            ret = wc_Sha256Copy(&digest.sha256, &ssl->hsHashes->hashSha256);
14976
            wc_Sha256Free(&digest.sha256);
14977
            break;
14978
    #endif
14979
    #ifdef WOLFSSL_SHA384
14980
        case sha384_mac:
14981
            wc_Sha384Free(&ssl->hsHashes->hashSha384);
14982
            ret = wc_Sha384Copy(&digest.sha384, &ssl->hsHashes->hashSha384);
14983
            wc_Sha384Free(&digest.sha384);
14984
            break;
14985
    #endif
14986
    #ifdef WOLFSSL_TLS13_SHA512
14987
        case sha512_mac:
14988
            wc_Sha512Free(&ssl->hsHashes->hashSha512);
14989
            ret = wc_Sha512Copy(&digest.sha512, &ssl->hsHashes->hashSha512);
14990
            wc_Sha512Free(&digest.sha512);
14991
            break;
14992
    #endif
14993
    #ifdef WOLFSSL_SM3
14994
        case sm3_mac:
14995
            wc_Sm3Free(&ssl->hsHashes->hashSm3);
14996
            ret = wc_Sm3Copy(&digest.sm3, &ssl->hsHashes->hashSm3);
14997
            wc_Sm3Free(&digest.sm3);
14998
            break;
14999
    #endif
15000
    }
15001
    if (saveRet != 0)
15002
        ret = saveRet;
15003
15004
    ForceZero(mac, sizeof(mac));
15005
    return ret;
15006
}
15007
#endif
15008
15009
/* Check the client advertised a PSK key exchange mode a resumption ticket can
15010
 * be used with.
15011
 *
15012
 * RFC 9846 Section 4.3.9: psk_key_exchange_modes restricts both the PSKs
15013
 * offered in the ClientHello and those the server might supply through
15014
 * NewSessionTicket, and servers should not send tickets that are incompatible
15015
 * with the advertised modes. RFC 9846 Section 4.7.1 makes sending a ticket
15016
 * conditional on the client's hello carrying a suitable extension.
15017
 *
15018
 * ssl  The SSL/TLS object.
15019
 * returns 0 when a ticket may be sent, MISSING_HANDSHAKE_DATA when the
15020
 *         extension was not received and PSK_KEY_ERROR when none of the
15021
 *         advertised modes is usable.
15022
 */
15023
static int CheckTls13TicketPskModes(WOLFSSL* ssl)
15024
{
15025
#ifdef WOLFSSL_TLS13_TICKET_CHECK_PSK_MODES
15026
    if (!ssl->options.pskKeModesRecvd) {
15027
        WOLFSSL_MSG("No psk_key_exchange_modes in ClientHello");
15028
        return MISSING_HANDSHAKE_DATA;
15029
    }
15030
15031
    if ((ssl->options.pskKeModes & (1 << PSK_KE)) != 0
15032
    #ifdef HAVE_SUPPORTED_CURVES
15033
        && !ssl->options.onlyPskDheKe
15034
    #endif
15035
        ) {
15036
        return 0;
15037
    }
15038
    /* The configured policy, not noPskDheKe - a certificate handshake clears
15039
     * that one before the ticket is sent, which would make this always true. */
15040
    if ((ssl->options.pskKeModes & (1 << PSK_DHE_KE)) != 0 &&
15041
            !ssl->options.noPskDheKePolicy) {
15042
        return 0;
15043
    }
15044
15045
    WOLFSSL_MSG("No usable psk_key_exchange_modes advertised by client");
15046
    return PSK_KEY_ERROR;
15047
#else
15048
    (void)ssl;
15049
    return 0;
15050
#endif
15051
}
15052
15053
/* Send New Session Ticket handshake message.
15054
 * Message contains the information required to perform resumption.
15055
 *
15056
 * ssl  The SSL/TLS object.
15057
 * returns 0 on success, otherwise failure.
15058
 */
15059
static int SendTls13NewSessionTicket(WOLFSSL* ssl)
15060
{
15061
    byte*  output;
15062
    int    ret;
15063
    word32 length;
15064
    int    sendSz;
15065
    word16 extSz;
15066
    int    genAltSessionID;
15067
    word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
15068
15069
    WOLFSSL_START(WC_FUNC_NEW_SESSION_TICKET_SEND);
15070
    WOLFSSL_ENTER("SendTls13NewSessionTicket");
15071
15072
    if (DefTicketHintTooLarge(ssl)) {
15073
        WOLFSSL_MSG("Ticket hint exceeds half the ticket key lifetime; "
15074
                    "skipping ticket");
15075
        return 0;
15076
    }
15077
15078
    if (CheckTls13TicketPskModes(ssl) != 0) {
15079
        WOLFSSL_MSG("Client advertised no usable PSK key exchange mode; "
15080
                    "skipping ticket");
15081
        return 0;
15082
    }
15083
15084
#ifdef WOLFSSL_DTLS13
15085
    if (ssl->options.dtls)
15086
        idx = Dtls13GetRlHeaderLength(ssl, 1) + DTLS_HANDSHAKE_HEADER_SZ;
15087
#endif /* WOLFSSL_DTLS13 */
15088
15089
#ifdef WOLFSSL_TLS13_TICKET_BEFORE_FINISHED
15090
    if (!ssl->msgsReceived.got_finished) {
15091
        if ((ret = ExpectedResumptionSecret(ssl)) != 0)
15092
            return ret;
15093
    }
15094
#endif
15095
15096
    /* Start ticket nonce at 0 and go up to 255. */
15097
    if (ssl->session->ticketNonce.len == 0) {
15098
        ssl->session->ticketNonce.len = DEF_TICKET_NONCE_SZ;
15099
        ssl->session->ticketNonce.data[0] = 0;
15100
    }
15101
    else
15102
    #ifdef WOLFSSL_ASYNC_CRYPT
15103
        if (ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E))
15104
    #endif
15105
    {
15106
        if (ssl->session->ticketNonce.data[0] == 255) {
15107
            /* RFC8446 Section 4.6.1: Each ticket must have a unique nonce
15108
             * value. As the nonce is only a single byte, we have to prevent
15109
             * the overflow and abort. */
15110
            return SESSION_TICKET_NONCE_OVERFLOW;
15111
        }
15112
        else
15113
            ssl->session->ticketNonce.data[0]++;
15114
    }
15115
15116
    /* Generate a new ID for the new ticket so that we don't overwrite any old
15117
     * ones. Only an ID ticket is cached without WOLFSSL_TICKET_HAVE_ID. */
15118
    genAltSessionID = (ssl->options.mask & WOLFSSL_OP_NO_TICKET) != 0;
15119
#if defined(WOLFSSL_TICKET_HAVE_ID) && defined(WOLFSSL_EARLY_DATA) && \
15120
    !defined(NO_SESSION_CACHE)
15121
    /* A 0-RTT capable ticket needs a cache entry of its own to back the
15122
     * single-use bound of RFC 8446 Sect. 8. Sessions that cannot send early
15123
     * data keep one ID, so state bound to the cache entry (ex_data) survives
15124
     * a resumption. */
15125
    if (ssl->options.maxEarlyDataSz > 0)
15126
        genAltSessionID = 1;
15127
#endif
15128
#ifdef WOLFSSL_ASYNC_CRYPT
15129
    /* CreateTicket() already copied the ID into the ticket being encrypted,
15130
     * so keep it across an async retry. */
15131
    if (ssl->error == WC_NO_ERR_TRACE(WC_PENDING_E))
15132
        genAltSessionID = 0;
15133
#endif
15134
    if (genAltSessionID) {
15135
        ret = SessionNewAltId(ssl);
15136
        if (ret != 0)
15137
            return ret;
15138
    }
15139
15140
    if (!ssl->options.noTicketTls13) {
15141
        if ((ret = SetupTicket(ssl)) != 0)
15142
            return ret;
15143
        /* No need to create the ticket if we only send the ID */
15144
        if ((ssl->options.mask & WOLFSSL_OP_NO_TICKET) == 0) {
15145
            if ((ret = CreateTicket(ssl)) != 0)
15146
                return ret;
15147
        }
15148
    }
15149
15150
#ifdef WOLFSSL_EARLY_DATA
15151
    ssl->session->maxEarlyDataSz = ssl->options.maxEarlyDataSz;
15152
    if (ssl->session->maxEarlyDataSz > 0)
15153
        TLSX_EarlyData_Use(ssl, ssl->session->maxEarlyDataSz, 1);
15154
    extSz = 0;
15155
    ret = TLSX_GetResponseSize(ssl, session_ticket, &extSz);
15156
    if (ret != 0)
15157
        return ret;
15158
#else
15159
    extSz = EXTS_SZ;
15160
#endif
15161
    /* Lifetime | Age Add | Ticket session ID | Extensions */
15162
    length = SESSION_HINT_SZ + SESSION_ADD_SZ + LENGTH_SZ;
15163
    if ((ssl->options.mask & WOLFSSL_OP_NO_TICKET) != 0)
15164
        length += ID_LEN + extSz;
15165
    else
15166
        length += ssl->session->ticketLen + extSz;
15167
    /* Nonce */
15168
    length += TICKET_NONCE_LEN_SZ + DEF_TICKET_NONCE_SZ;
15169
15170
    sendSz = (int)(idx + length + MAX_MSG_EXTRA);
15171
15172
    /* Check buffers are big enough and grow if needed. */
15173
    if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
15174
        return ret;
15175
15176
    /* Get position in output buffer to write new message to. */
15177
    output = GetOutputBuffer(ssl);
15178
15179
    /* Put the record and handshake headers on. */
15180
    AddTls13Headers(output, length, session_ticket, ssl);
15181
15182
    /* Lifetime hint */
15183
    c32toa(ssl->ctx->ticketHint, output + idx);
15184
    idx += SESSION_HINT_SZ;
15185
    /* Age add - obfuscator */
15186
    c32toa(ssl->session->ticketAdd, output + idx);
15187
    idx += SESSION_ADD_SZ;
15188
15189
    output[idx++] = ssl->session->ticketNonce.len;
15190
    output[idx++] = ssl->session->ticketNonce.data[0];
15191
15192
    /* length */
15193
    if ((ssl->options.mask & WOLFSSL_OP_NO_TICKET) != 0) {
15194
        c16toa(ID_LEN, output + idx);
15195
    }
15196
    else {
15197
        c16toa(ssl->session->ticketLen, output + idx);
15198
    }
15199
15200
    idx += LENGTH_SZ;
15201
    /* ticket */
15202
    if ((ssl->options.mask & WOLFSSL_OP_NO_TICKET) != 0) {
15203
        if (ssl->session->haveAltSessionID)
15204
            XMEMCPY(output + idx, ssl->session->altSessionID, ID_LEN);
15205
        else
15206
            return BAD_FUNC_ARG; /* Should not happen */
15207
        idx += ID_LEN;
15208
    }
15209
    else {
15210
        XMEMCPY(output + idx, ssl->session->ticket, ssl->session->ticketLen);
15211
        idx += ssl->session->ticketLen;
15212
    }
15213
15214
#ifdef WOLFSSL_EARLY_DATA
15215
    extSz = 0;
15216
    ret = TLSX_WriteResponse(ssl, output + idx, session_ticket, &extSz);
15217
    if (ret != 0)
15218
        return ret;
15219
    idx += extSz;
15220
#else
15221
    /* No extension support - empty extensions. */
15222
    c16toa(0, output + idx);
15223
    idx += EXTS_SZ;
15224
#endif
15225
15226
    if (idx > WOLFSSL_MAX_16BIT ||
15227
        sendSz > (int)WOLFSSL_MAX_16BIT) {
15228
        return BAD_LENGTH_E;
15229
    }
15230
15231
    ssl->options.haveSessionId = 1;
15232
15233
    SetupSession(ssl);
15234
    /* Only add to cache when support built in and when the ticket contains
15235
     * an ID. Otherwise we have no way to actually retrieve the ticket from the
15236
     * cache. */
15237
#if !defined(NO_SESSION_CACHE) && defined(WOLFSSL_TICKET_HAVE_ID)
15238
    AddSession(ssl);
15239
#endif
15240
15241
#ifdef WOLFSSL_DTLS13
15242
    if (ssl->options.dtls)
15243
        return Dtls13HandshakeSend(ssl, output, (word16)sendSz,
15244
                                   (word16)idx, session_ticket, 0);
15245
#endif /* WOLFSSL_DTLS13 */
15246
15247
    /* This message is always encrypted. */
15248
    sendSz = BuildTls13Message(ssl, output, sendSz,
15249
                               output + RECORD_HEADER_SZ,
15250
                               (word16)idx - RECORD_HEADER_SZ,
15251
                               handshake, 0, 0, 0);
15252
    if (sendSz < 0)
15253
        return sendSz;
15254
15255
    ssl->buffers.outputBuffer.length += sendSz;
15256
15257
    /* Always send as this is either directly after server's Finished or only
15258
     * message after client's Finished.
15259
     */
15260
    ret = SendBuffered(ssl);
15261
15262
    WOLFSSL_LEAVE("SendTls13NewSessionTicket", 0);
15263
    WOLFSSL_END(WC_FUNC_NEW_SESSION_TICKET_SEND);
15264
15265
    return ret;
15266
}
15267
    #endif /* HAVE_SESSION_TICKET */
15268
#endif /* NO_WOLFSSL_SERVER */
15269
15270
/* Make sure no duplicates, no fast forward, or other problems
15271
 *
15272
 * ssl   The SSL/TLS object.
15273
 * type  Type of handshake message received.
15274
 * returns 0 on success, otherwise failure.
15275
 */
15276
static int SanityCheckTls13MsgReceived(WOLFSSL* ssl, byte type)
15277
0
{
15278
    /* verify not a duplicate, mark received, check state */
15279
0
    switch (type) {
15280
15281
0
#ifndef NO_WOLFSSL_SERVER
15282
0
        case client_hello:
15283
0
        #ifndef NO_WOLFSSL_CLIENT
15284
            /* Only valid when received on SERVER side. */
15285
0
            if (ssl->options.side == WOLFSSL_CLIENT_END) {
15286
0
                WOLFSSL_MSG("ClientHello received by client");
15287
0
                WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
15288
0
                return SIDE_ERROR;
15289
0
            }
15290
0
        #endif
15291
            /* A replay after a pend arrives with got_client_hello cleared
15292
             * (see exit_dch); a genuine duplicate arrives with it set. */
15293
0
            if (ssl->options.clientState >= CLIENT_HELLO_COMPLETE
15294
        #ifdef WOLFSSL_ASYNC_CRYPT
15295
                && ssl->msgsReceived.got_client_hello != 0
15296
        #endif
15297
0
                ) {
15298
0
                WOLFSSL_MSG("ClientHello received out of order");
15299
0
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15300
0
                return OUT_OF_ORDER_E;
15301
0
            }
15302
            /* Check previously seen. */
15303
            /* Initial and after HelloRetryRequest - no more than 2. */
15304
0
            if (ssl->msgsReceived.got_client_hello == 2) {
15305
0
                WOLFSSL_MSG("Too many ClientHello received");
15306
0
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
15307
0
                return DUPLICATE_MSG_E;
15308
0
            }
15309
            /* Second only after HelloRetryRequest seen. */
15310
0
            if (ssl->msgsReceived.got_client_hello == 1 &&
15311
0
                ssl->options.serverState !=
15312
0
                                          SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
15313
0
                WOLFSSL_MSG("Duplicate ClientHello received");
15314
0
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
15315
0
                return DUPLICATE_MSG_E;
15316
0
            }
15317
0
            ssl->msgsReceived.got_client_hello++;
15318
15319
0
            break;
15320
0
#endif
15321
15322
0
#ifndef NO_WOLFSSL_CLIENT
15323
0
        case server_hello:
15324
0
        #ifndef NO_WOLFSSL_SERVER
15325
            /* Only valid when received on CLIENT side. */
15326
0
            if (ssl->options.side == WOLFSSL_SERVER_END) {
15327
0
                WOLFSSL_MSG("ServerHello received by server");
15328
0
                WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
15329
0
                return SIDE_ERROR;
15330
0
            }
15331
0
        #endif
15332
            /* Check state. */
15333
0
            if (ssl->options.serverState >= SERVER_HELLO_COMPLETE) {
15334
0
                WOLFSSL_MSG("ServerHello received out of order");
15335
0
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15336
0
                return OUT_OF_ORDER_E;
15337
0
            }
15338
            /* Check previously seen. */
15339
            /* Only once after ClientHello.
15340
             * HelloRetryRequest has ServerHello type but count fixed up later
15341
             * - see DoTls13ServerHello().
15342
             */
15343
0
            if (ssl->msgsReceived.got_server_hello) {
15344
0
                WOLFSSL_MSG("Duplicate ServerHello received");
15345
0
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
15346
0
                return DUPLICATE_MSG_E;
15347
0
            }
15348
0
            ssl->msgsReceived.got_server_hello = 1;
15349
15350
0
            break;
15351
0
#endif
15352
15353
0
#ifndef NO_WOLFSSL_CLIENT
15354
0
        case session_ticket:
15355
0
        #ifndef NO_WOLFSSL_SERVER
15356
            /* Only valid when received on CLIENT side. */
15357
0
            if (ssl->options.side == WOLFSSL_SERVER_END) {
15358
0
                WOLFSSL_MSG("NewSessionTicket received by server");
15359
0
                WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
15360
0
                return SIDE_ERROR;
15361
0
            }
15362
0
        #endif
15363
            /* Check state. */
15364
        #ifdef WOLFSSL_TLS13_TICKET_BEFORE_FINISHED
15365
            /* Only allowed after server's Finished message. */
15366
            if (ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
15367
                WOLFSSL_MSG("NewSessionTicket received out of order");
15368
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15369
                return OUT_OF_ORDER_E;
15370
            }
15371
        #else
15372
            /* Only allowed after client's Finished message. */
15373
0
            if (ssl->options.clientState < CLIENT_FINISHED_COMPLETE) {
15374
0
                WOLFSSL_MSG("NewSessionTicket received out of order");
15375
0
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15376
0
                return OUT_OF_ORDER_E;
15377
0
            }
15378
0
        #endif
15379
            /* Many SessionTickets can be sent. */
15380
0
            ssl->msgsReceived.got_session_ticket = 1;
15381
15382
0
            break;
15383
0
#endif
15384
15385
0
#ifndef NO_WOLFSSL_SERVER
15386
    #ifdef WOLFSSL_EARLY_DATA
15387
        case end_of_early_data:
15388
        #ifndef NO_WOLFSSL_CLIENT
15389
            /* Only valid when received on SERVER side. */
15390
            if (ssl->options.side == WOLFSSL_CLIENT_END) {
15391
                WOLFSSL_MSG("EndOfEarlyData received by client");
15392
                WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
15393
                return SIDE_ERROR;
15394
            }
15395
        #endif
15396
            /* Check state. */
15397
            /* Only after server's Finished and before client's Finished. */
15398
            if (ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
15399
                WOLFSSL_MSG("EndOfEarlyData received out of order");
15400
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15401
                return OUT_OF_ORDER_E;
15402
            }
15403
            if (ssl->options.clientState >= CLIENT_FINISHED_COMPLETE) {
15404
                WOLFSSL_MSG("EndOfEarlyData received out of order");
15405
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15406
                return OUT_OF_ORDER_E;
15407
            }
15408
            /* Check previously seen. */
15409
            if (ssl->msgsReceived.got_end_of_early_data) {
15410
                WOLFSSL_MSG("Too many EndOfEarlyData received");
15411
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
15412
                return DUPLICATE_MSG_E;
15413
            }
15414
            ssl->msgsReceived.got_end_of_early_data = 1;
15415
15416
            break;
15417
    #endif
15418
0
#endif
15419
15420
0
#ifndef NO_WOLFSSL_CLIENT
15421
0
        case encrypted_extensions:
15422
0
        #ifndef NO_WOLFSSL_SERVER
15423
            /* Only valid when received on CLIENT side. */
15424
0
            if (ssl->options.side == WOLFSSL_SERVER_END) {
15425
0
                WOLFSSL_MSG("EncryptedExtensions received by server");
15426
0
                WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
15427
0
                return SIDE_ERROR;
15428
0
            }
15429
0
        #endif
15430
            /* Check state. */
15431
            /* Must be received directly after ServerHello.
15432
             * DoTls13EncryptedExtensions() changes state to:
15433
             *   SERVER_ENCRYPTED_EXTENSIONS_COMPLETE.
15434
             */
15435
0
            if (ssl->options.serverState != SERVER_HELLO_COMPLETE) {
15436
0
                WOLFSSL_MSG("EncryptedExtensions received out of order");
15437
0
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15438
0
                return OUT_OF_ORDER_E;
15439
0
            }
15440
            /* Check previously seen. */
15441
0
            if (ssl->msgsReceived.got_encrypted_extensions) {
15442
0
                WOLFSSL_MSG("Duplicate EncryptedExtensions received");
15443
0
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
15444
0
                return DUPLICATE_MSG_E;
15445
0
            }
15446
0
            ssl->msgsReceived.got_encrypted_extensions = 1;
15447
15448
0
            break;
15449
0
#endif
15450
15451
0
        case certificate:
15452
            /* Valid on both sides. */
15453
0
    #ifndef NO_WOLFSSL_CLIENT
15454
            /* Check state. */
15455
            /* On client, seen after EncryptedExtension and CertificateRequest
15456
             * (if sent) and before CertificateVerify and Finished.
15457
             * DoTls13Certificate() sets serverState to SERVER_CERT_COMPLETE.
15458
             */
15459
0
            if (ssl->options.side == WOLFSSL_CLIENT_END &&
15460
0
                ssl->options.serverState !=
15461
0
                                         SERVER_ENCRYPTED_EXTENSIONS_COMPLETE) {
15462
0
                WOLFSSL_MSG("Certificate received out of order - Client");
15463
0
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15464
0
                return OUT_OF_ORDER_E;
15465
0
            }
15466
        #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
15467
            /* Server's authenticating with PSK must not send this. */
15468
            if (ssl->options.side == WOLFSSL_CLIENT_END &&
15469
                             ssl->options.serverState == SERVER_CERT_COMPLETE &&
15470
                             ssl->options.pskNegotiated
15471
#ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
15472
                             && !ssl->options.certWithExternPsk
15473
#endif
15474
               ) {
15475
                WOLFSSL_MSG("Certificate received while using PSK");
15476
                WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
15477
                return SANITY_MSG_E;
15478
            }
15479
        #endif
15480
0
    #endif
15481
0
    #ifndef NO_WOLFSSL_SERVER
15482
            /* Check state. */
15483
            /* On Server, valid after ClientHello received and ServerFinished
15484
             * sent. */
15485
0
            if (ssl->options.side == WOLFSSL_SERVER_END &&
15486
0
                ssl->options.clientState != CLIENT_HELLO_COMPLETE &&
15487
0
                ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
15488
0
                WOLFSSL_MSG("Certificate received out of order - Server");
15489
0
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15490
0
                return OUT_OF_ORDER_E;
15491
0
            }
15492
        #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
15493
            /* RFC 8446 4.4.2: the client only sends this in response to a
15494
             * CertificateRequest, which a server authenticating with a PSK
15495
             * does not send in the main handshake (but may post-handshake). */
15496
            if (ssl->options.side == WOLFSSL_SERVER_END &&
15497
                ssl->options.pskNegotiated && !TLS13_AFTER_HANDSHAKE(ssl)
15498
#ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
15499
                && !ssl->options.certWithExternPsk
15500
#endif
15501
               ) {
15502
                WOLFSSL_MSG("Certificate received while using PSK - Server");
15503
                WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
15504
                return SANITY_MSG_E;
15505
            }
15506
        #endif
15507
0
    #endif
15508
            /* Check previously seen. */
15509
0
            if (ssl->msgsReceived.got_certificate) {
15510
0
                WOLFSSL_MSG("Duplicate Certificate received");
15511
0
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
15512
0
                return DUPLICATE_MSG_E;
15513
0
            }
15514
0
            ssl->msgsReceived.got_certificate = 1;
15515
15516
0
            break;
15517
15518
0
#ifndef NO_WOLFSSL_CLIENT
15519
0
        case certificate_request:
15520
0
        #ifndef NO_WOLFSSL_SERVER
15521
            /* Only valid when received on CLIENT side. */
15522
0
            if (ssl->options.side == WOLFSSL_SERVER_END) {
15523
0
                WOLFSSL_MSG("CertificateRequest received by server");
15524
0
                WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
15525
0
                return SIDE_ERROR;
15526
0
            }
15527
0
        #endif
15528
            /* Check state. */
15529
0
        #ifndef WOLFSSL_POST_HANDSHAKE_AUTH
15530
            /* Only valid when sent after EncryptedExtensions and before
15531
             * Certificate. */
15532
0
            if (ssl->options.serverState !=
15533
0
                                         SERVER_ENCRYPTED_EXTENSIONS_COMPLETE) {
15534
0
                WOLFSSL_MSG("CertificateRequest received out of order");
15535
0
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15536
0
                return OUT_OF_ORDER_E;
15537
0
            }
15538
        #else
15539
            /* Valid when sent after EncryptedExtensions and before Certificate
15540
             * and after both client and server have sent Finished (Post
15541
             * Handshake Authentication). */
15542
            if (ssl->options.serverState !=
15543
                                         SERVER_ENCRYPTED_EXTENSIONS_COMPLETE &&
15544
                       (ssl->options.serverState < SERVER_FINISHED_COMPLETE ||
15545
                        ssl->options.clientState != CLIENT_FINISHED_COMPLETE)) {
15546
                WOLFSSL_MSG("CertificateRequest received out of order");
15547
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15548
                return OUT_OF_ORDER_E;
15549
            }
15550
            /* RFC 8446 4.6.2: A client that receives a post-handshake
15551
             * CertificateRequest message without having sent the
15552
             * "post_handshake_auth" extension MUST send an
15553
             * "unexpected_message" fatal alert. wolfSSL_allow_post_handshake_auth()
15554
             * must be called before wolfSSL_connect() so postHandshakeAuth
15555
             * reflects whether the extension was offered. */
15556
            if (ssl->options.serverState >= SERVER_FINISHED_COMPLETE &&
15557
                ssl->options.clientState == CLIENT_FINISHED_COMPLETE &&
15558
                !ssl->options.postHandshakeAuth) {
15559
                WOLFSSL_MSG("Post-handshake CertificateRequest received "
15560
                            "without having sent post_handshake_auth "
15561
                            "extension");
15562
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15563
                return OUT_OF_ORDER_E;
15564
            }
15565
        #endif
15566
        #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
15567
            /* RFC 8446 4.3.2: a server authenticating with a PSK must not send
15568
             * this in the main handshake, but may send it post-handshake. */
15569
            if (ssl->options.pskNegotiated && !TLS13_AFTER_HANDSHAKE(ssl)
15570
#ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
15571
                && !ssl->options.certWithExternPsk
15572
#endif
15573
               ) {
15574
                WOLFSSL_MSG("CertificateRequest received while using PSK");
15575
                WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
15576
                return SANITY_MSG_E;
15577
            }
15578
        #endif
15579
            /* Check previously seen. */
15580
0
        #ifndef WOLFSSL_POST_HANDSHAKE_AUTH
15581
            /* Only once during handshake. */
15582
0
            if (ssl->msgsReceived.got_certificate_request) {
15583
0
                WOLFSSL_MSG("Duplicate CertificateRequest received");
15584
0
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
15585
0
                return DUPLICATE_MSG_E;
15586
0
            }
15587
        #else
15588
            /* Only once during handshake. */
15589
            if (ssl->msgsReceived.got_certificate_request &&
15590
                ssl->options.clientState != CLIENT_FINISHED_COMPLETE) {
15591
                WOLFSSL_MSG("Duplicate CertificateRequest received");
15592
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
15593
                return DUPLICATE_MSG_E;
15594
            }
15595
        #endif
15596
0
            ssl->msgsReceived.got_certificate_request = 1;
15597
15598
0
            break;
15599
0
#endif
15600
15601
0
        case certificate_verify:
15602
            /* Valid on both sides. */
15603
0
    #ifndef NO_WOLFSSL_CLIENT
15604
            /* Check state on client.
15605
             * Valid only directly after a Certificate message. */
15606
0
            if (ssl->options.side == WOLFSSL_CLIENT_END) {
15607
0
                if (ssl->options.serverState != SERVER_CERT_COMPLETE) {
15608
0
                    WOLFSSL_MSG("No Cert before CertVerify");
15609
0
                    WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15610
0
                    return OUT_OF_ORDER_E;
15611
0
                }
15612
            #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
15613
                /* Server's authenticating with PSK must not send this. */
15614
                if (ssl->options.pskNegotiated
15615
#ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
15616
                    && !ssl->options.certWithExternPsk
15617
#endif
15618
                   ) {
15619
                    WOLFSSL_MSG("CertificateVerify received while using PSK");
15620
                    WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
15621
                    return SANITY_MSG_E;
15622
                }
15623
            #endif
15624
0
            }
15625
0
    #endif
15626
0
    #ifndef NO_WOLFSSL_SERVER
15627
            /* Check state on server. */
15628
0
            if (ssl->options.side == WOLFSSL_SERVER_END) {
15629
                /* Server must have sent Finished message. */
15630
0
                if (ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
15631
0
                    WOLFSSL_MSG("CertificateVerify received out of order");
15632
0
                    WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15633
0
                    return OUT_OF_ORDER_E;
15634
0
                }
15635
                /* Valid only directly after a Certificate message. */
15636
0
                if (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
15637
0
                    WOLFSSL_MSG("CertificateVerify before ClientHello done");
15638
0
                    WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15639
0
                    return OUT_OF_ORDER_E;
15640
0
                }
15641
0
                if (!ssl->msgsReceived.got_certificate) {
15642
0
                    WOLFSSL_MSG("No Cert before CertificateVerify");
15643
0
                    WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15644
0
                    return OUT_OF_ORDER_E;
15645
0
                }
15646
0
            }
15647
0
    #endif
15648
            /* Check previously seen. */
15649
0
            if (ssl->msgsReceived.got_certificate_verify) {
15650
0
                WOLFSSL_MSG("Duplicate CertificateVerify received");
15651
0
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
15652
0
                return DUPLICATE_MSG_E;
15653
0
            }
15654
0
            ssl->msgsReceived.got_certificate_verify = 1;
15655
15656
0
            break;
15657
15658
0
        case finished:
15659
            /* Valid on both sides. */
15660
0
        #ifndef NO_WOLFSSL_CLIENT
15661
            /* Check state on client. */
15662
0
            if (ssl->options.side == WOLFSSL_CLIENT_END) {
15663
                /* After sending ClientHello */
15664
0
                if (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
15665
0
                    WOLFSSL_MSG("Finished received out of order - clientState");
15666
0
                    WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15667
0
                    return OUT_OF_ORDER_E;
15668
0
                }
15669
                /* Must have seen certificate and verify from server except when
15670
                 * using PSK. */
15671
            #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
15672
                if (ssl->options.pskNegotiated) {
15673
#ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
15674
                    if (ssl->options.certWithExternPsk) {
15675
                        if (ssl->options.serverState !=
15676
                                                SERVER_CERT_VERIFY_COMPLETE) {
15677
                            WOLFSSL_MSG("Finished received out of order - "
15678
                                        "cert_with_extern_psk");
15679
                            WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15680
                            return OUT_OF_ORDER_E;
15681
                        }
15682
                    }
15683
                    else
15684
#endif
15685
                    {
15686
                        if (ssl->options.serverState !=
15687
                                         SERVER_ENCRYPTED_EXTENSIONS_COMPLETE) {
15688
                            WOLFSSL_MSG("Finished received out of order - PSK");
15689
                            WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15690
                            return OUT_OF_ORDER_E;
15691
                        }
15692
                    }
15693
                }
15694
                else
15695
            #endif
15696
0
                if (ssl->options.serverState != SERVER_CERT_VERIFY_COMPLETE) {
15697
0
                    WOLFSSL_MSG("Finished received out of order - serverState");
15698
0
                    WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15699
0
                    return OUT_OF_ORDER_E;
15700
0
                }
15701
0
            }
15702
0
        #endif
15703
0
        #ifndef NO_WOLFSSL_SERVER
15704
            /* Check state on server. */
15705
0
            if (ssl->options.side == WOLFSSL_SERVER_END) {
15706
0
                if (ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
15707
0
                    WOLFSSL_MSG("Finished received out of order - serverState");
15708
0
                    WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15709
0
                    return OUT_OF_ORDER_E;
15710
0
                }
15711
0
                if (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
15712
0
                    WOLFSSL_MSG("Finished received out of order - clientState");
15713
0
                    WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15714
0
                    return OUT_OF_ORDER_E;
15715
0
                }
15716
            #ifdef WOLFSSL_EARLY_DATA
15717
                if (ssl->earlyData == process_early_data &&
15718
                    /* early data may be lost when using DTLS */
15719
                    !ssl->options.dtls
15720
                    /* QUIC does not use EndOfEarlyData records */
15721
                    && !WOLFSSL_IS_QUIC(ssl)) {
15722
                    WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15723
                    return OUT_OF_ORDER_E;
15724
                }
15725
            #endif
15726
0
            }
15727
0
        #endif
15728
        #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
15729
            if (!ssl->options.pskNegotiated ||
15730
                (ssl->options.side == WOLFSSL_SERVER_END &&
15731
                 TLS13_AFTER_HANDSHAKE(ssl))
15732
#ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
15733
                || ssl->options.certWithExternPsk
15734
#endif
15735
            )
15736
        #endif
15737
0
            {
15738
                /* Must have received a Certificate message from client if
15739
                 * verifying the peer. Empty certificate message indicates
15740
                 * no certificate available.
15741
                 */
15742
0
                if (ssl->options.verifyPeer &&
15743
                #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
15744
                    /* The post-handshake-auth exemption is only valid during
15745
                     * the enclosing handshake. Once the server has requested a
15746
                     * certificate post-handshake, one is required again.
15747
                     * Whether an empty Certificate is then accepted follows the
15748
                     * verify mode (FAIL_IF_NO_PEER_CERT), exactly as for
15749
                     * first-handshake client authentication. */
15750
                    (!ssl->options.verifyPostHandshake ||
15751
                     TLS13_AFTER_HANDSHAKE(ssl)) &&
15752
                #endif
15753
0
                                           !ssl->msgsReceived.got_certificate) {
15754
0
                    WOLFSSL_MSG("Finished received out of order - "
15755
0
                                "missing Certificate message");
15756
0
                    WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15757
0
                    return OUT_OF_ORDER_E;
15758
0
                }
15759
                /* Mutual authentication on server requires a certificate from
15760
                 * peer. Verify peer set on client side requires a certificate
15761
                 * from peer as not doing PSK.
15762
                 */
15763
0
                if ((ssl->options.mutualAuth ||
15764
0
                    (ssl->options.side == WOLFSSL_CLIENT_END &&
15765
0
                     ssl->options.verifyPeer)) && !ssl->options.havePeerCert) {
15766
0
                    WOLFSSL_MSG("Finished received out of order - "
15767
0
                                "no valid certificate");
15768
0
                    WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15769
0
                    return OUT_OF_ORDER_E;
15770
0
                }
15771
0
            }
15772
            /* Must have received a valid CertificateVerify if got a peer
15773
             * certificate. A certificate without proof of possession is never
15774
             * acceptable, regardless of how the handshake was authenticated.
15775
             */
15776
0
            if (ssl->options.havePeerCert && !ssl->options.havePeerVerify) {
15777
0
                WOLFSSL_MSG("Finished received out of order - "
15778
0
                            "Certificate message but no CertificateVerify");
15779
0
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15780
0
                return OUT_OF_ORDER_E;
15781
0
            }
15782
            /* Check previously seen. */
15783
0
            if (ssl->msgsReceived.got_finished) {
15784
0
                WOLFSSL_MSG("Duplicate Finished received");
15785
0
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
15786
0
                return DUPLICATE_MSG_E;
15787
0
            }
15788
0
            ssl->msgsReceived.got_finished = 1;
15789
15790
0
            break;
15791
15792
0
        case key_update:
15793
            /* Valid on both sides. */
15794
#ifdef WOLFSSL_QUIC
15795
            /* RFC 9001 Section 6: QUIC performs key updates at the QUIC
15796
             * packet-protection layer, so a TLS KeyUpdate message must be
15797
             * rejected as a fatal unexpected_message connection error. The
15798
             * caller sends that alert for any sanity failure. */
15799
            if (WOLFSSL_IS_QUIC(ssl)) {
15800
                WOLFSSL_MSG("KeyUpdate received over QUIC");
15801
                WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
15802
                return SANITY_MSG_E;
15803
            }
15804
#endif
15805
            /* Check state.
15806
             * Client and server must have received finished message from other
15807
             * side.
15808
             */
15809
0
            if (!ssl->msgsReceived.got_finished) {
15810
0
                WOLFSSL_MSG("No KeyUpdate before Finished");
15811
0
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15812
0
                return OUT_OF_ORDER_E;
15813
0
            }
15814
            /* Multiple KeyUpdates can be sent. */
15815
0
            break;
15816
#if defined(WOLFSSL_DTLS13) && !defined(WOLFSSL_NO_TLS12)
15817
        case hello_verify_request:
15818
            if (!ssl->options.dtls) {
15819
                WOLFSSL_MSG("HelloVerifyRequest when not in DTLS");
15820
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15821
                return OUT_OF_ORDER_E;
15822
            }
15823
            if (ssl->msgsReceived.got_hello_verify_request) {
15824
                WOLFSSL_MSG("Duplicate HelloVerifyRequest received");
15825
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
15826
                return DUPLICATE_MSG_E;
15827
            }
15828
            ssl->msgsReceived.got_hello_verify_request = 1;
15829
            if (ssl->msgsReceived.got_hello_retry_request) {
15830
                WOLFSSL_MSG(
15831
                    "Both HelloVerifyRequest and HelloRetryRequest received");
15832
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
15833
                return DUPLICATE_MSG_E;
15834
            }
15835
            if (ssl->options.serverState >=
15836
                    SERVER_HELLO_RETRY_REQUEST_COMPLETE ||
15837
                ssl->options.connectState != CLIENT_HELLO_SENT) {
15838
                WOLFSSL_MSG("HelloVerifyRequest received out of order");
15839
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15840
                return OUT_OF_ORDER_E;
15841
            }
15842
            if (ssl->options.side == WOLFSSL_SERVER_END) {
15843
                WOLFSSL_MSG("HelloVerifyRequest received on the server");
15844
                WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
15845
                return SIDE_ERROR;
15846
            }
15847
            if (!ssl->options.downgrade ||
15848
                ssl->options.minDowngrade < DTLSv1_2_MINOR) {
15849
                WOLFSSL_MSG(
15850
                    "HelloVerifyRequest received but not DTLSv1.2 allowed");
15851
                WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
15852
                return VERSION_ERROR;
15853
            }
15854
            break;
15855
#endif /* WOLFSSL_DTLS13 && !WOLFSSL_NO_TLS12*/
15856
15857
#if defined(WOLFSSL_DTLS13) && defined(WOLFSSL_DTLS_CID)
15858
        case request_connection_id:
15859
        case new_connection_id:
15860
        {
15861
            CIDInfo* cidInfo = ssl->dtlsCidInfo;
15862
15863
            /* DTLS 1.3 only (RFC 9147) */
15864
            if (!ssl->options.dtls) {
15865
                WOLFSSL_MSG("CID message received but not DTLS");
15866
                WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
15867
                return SANITY_MSG_E;
15868
            }
15869
            /* RFC 9147 Section 9: if CIDs were not negotiated, MUST abort
15870
             * with an unexpected_message alert */
15871
            if (cidInfo == NULL || !cidInfo->negotiated) {
15872
                WOLFSSL_MSG("CID message received but CID not negotiated");
15873
                WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
15874
                return SANITY_MSG_E;
15875
            }
15876
            if (ssl->options.handShakeState != HANDSHAKE_DONE) {
15877
                WOLFSSL_MSG("CID message received out of order");
15878
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15879
                return OUT_OF_ORDER_E;
15880
            }
15881
            if (type == request_connection_id) {
15882
                /* the peer MUST NOT request CIDs while sending an empty
15883
                 * CID itself */
15884
                if (cidInfo->rx == NULL || cidInfo->rx->length == 0) {
15885
                    WOLFSSL_MSG("RequestConnectionId from peer sending an "
15886
                                "empty CID");
15887
                    WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
15888
                    return SANITY_MSG_E;
15889
                }
15890
            }
15891
            else {
15892
                /* the peer MUST NOT issue CIDs after negotiating receiving
15893
                 * an empty CID */
15894
                if (cidInfo->tx == NULL || cidInfo->tx->length == 0) {
15895
                    WOLFSSL_MSG("NewConnectionId from peer that negotiated "
15896
                                "an empty CID");
15897
                    WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
15898
                    return SANITY_MSG_E;
15899
                }
15900
            }
15901
            break;
15902
        }
15903
#endif /* WOLFSSL_DTLS13 && WOLFSSL_DTLS_CID */
15904
15905
0
        default:
15906
0
            WOLFSSL_MSG("Unknown message type");
15907
0
            WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
15908
0
            return SANITY_MSG_E;
15909
0
    }
15910
15911
0
    return 0;
15912
0
}
15913
15914
/* Handle a type of handshake message that has been received.
15915
 *
15916
 * ssl       The SSL/TLS object.
15917
 * input     The message buffer.
15918
 * inOutIdx  On entry, the index into the buffer of the current message.
15919
 *           On exit, the index into the buffer of the next message.
15920
 * size      The length of the current handshake message.
15921
 * totalSz   Length of remaining data in the message buffer.
15922
 * returns 0 on success and otherwise failure.
15923
 */
15924
/* Run the key schedule belonging to a just-processed handshake message.
15925
 * A pend here cannot replay the message (its handler already advanced
15926
 * state); the record is consumed and this is called again from
15927
 * DoProcessReplyEx() entry, pre-dispatch, or the reply-loop exits.
15928
 * Returns 0, WC_PENDING_E while the device is busy, else an error. */
15929
int DoTls13MsgDerives(WOLFSSL* ssl, byte type)
15930
0
{
15931
0
    int ret = 0;
15932
15933
0
    (void)ssl;
15934
0
    (void)type;
15935
15936
0
#ifndef NO_WOLFSSL_CLIENT
15937
0
    if (ssl->options.side == WOLFSSL_CLIENT_END) {
15938
0
        if (type == server_hello) {
15939
            /* Entered before the first derive, or a pend there would
15940
             * route the retry back to the message handler. */
15941
0
            if (ssl->kdfMsgStep == TLS13_MSG_KDF_NONE) {
15942
0
                ssl->kdfMsgStep = TLS13_MSG_KDF_SH_ENTERED;
15943
0
                ssl->kdfMsgType = type;
15944
0
            }
15945
15946
0
            if (ssl->kdfMsgStep <= TLS13_MSG_KDF_SH_ENTERED) {
15947
0
                ret = DeriveEarlySecret(ssl);
15948
0
                if (ret != 0) {
15949
0
                    if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
15950
0
                        ssl->kdfMsgStep = TLS13_MSG_KDF_NONE;
15951
0
                    return ret;
15952
0
                }
15953
0
                ssl->kdfMsgStep = TLS13_MSG_KDF_SH_EARLY_SECRET;
15954
0
            }
15955
0
            if (ssl->kdfMsgStep <= TLS13_MSG_KDF_SH_EARLY_SECRET) {
15956
0
                ret = DeriveHandshakeSecret(ssl);
15957
0
                if (ret != 0) {
15958
0
                    if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
15959
0
                        ssl->kdfMsgStep = TLS13_MSG_KDF_NONE;
15960
0
                    return ret;
15961
0
                }
15962
0
                ssl->kdfMsgStep = TLS13_MSG_KDF_SH_HS_SECRET;
15963
0
            }
15964
0
            if (ssl->kdfMsgStep <= TLS13_MSG_KDF_SH_HS_SECRET) {
15965
0
                ret = DeriveTls13Keys(ssl, handshake_key,
15966
0
                                      ENCRYPT_AND_DECRYPT_SIDE, 1);
15967
0
                if (ret != 0) {
15968
0
                    if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
15969
0
                        ssl->kdfMsgStep = TLS13_MSG_KDF_NONE;
15970
0
                    return ret;
15971
0
                }
15972
0
                ssl->kdfMsgStep = TLS13_MSG_KDF_SH_HS_KEYS;
15973
0
            }
15974
    #ifdef WOLFSSL_EARLY_DATA
15975
            if (ssl->earlyData != no_early_data) {
15976
                if (ssl->kdfMsgStep <= TLS13_MSG_KDF_SH_HS_KEYS) {
15977
                    ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY);
15978
                    if (ret != 0) {
15979
                        if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
15980
                            ssl->kdfMsgStep = TLS13_MSG_KDF_NONE;
15981
                        return ret;
15982
                    }
15983
                    ssl->kdfMsgStep = TLS13_MSG_KDF_SH_KEYS_SET;
15984
                }
15985
            }
15986
            else
15987
    #endif
15988
0
            {
15989
0
                if (ssl->kdfMsgStep <= TLS13_MSG_KDF_SH_HS_KEYS) {
15990
0
                    ret = SetKeysSide(ssl, ENCRYPT_AND_DECRYPT_SIDE);
15991
0
                    if (ret != 0) {
15992
0
                        if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
15993
0
                            ssl->kdfMsgStep = TLS13_MSG_KDF_NONE;
15994
0
                        return ret;
15995
0
                    }
15996
0
                    ssl->kdfMsgStep = TLS13_MSG_KDF_SH_KEYS_SET;
15997
0
                }
15998
0
            }
15999
16000
#ifdef WOLFSSL_DTLS13
16001
            if (ssl->options.dtls) {
16002
                w64wrapper epochHandshake;
16003
                epochHandshake = w64From32(0, DTLS13_EPOCH_HANDSHAKE);
16004
                ssl->dtls13Epoch = epochHandshake;
16005
                ssl->dtls13PeerEpoch = epochHandshake;
16006
16007
                if (ssl->kdfMsgStep <= TLS13_MSG_KDF_SH_KEYS_SET) {
16008
                    ret = Dtls13SetEpochKeys(ssl, epochHandshake,
16009
                                             ENCRYPT_AND_DECRYPT_SIDE);
16010
                    if (ret != 0) {
16011
                        if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
16012
                            ssl->kdfMsgStep = TLS13_MSG_KDF_NONE;
16013
                        return ret;
16014
                    }
16015
                    ssl->kdfMsgStep = TLS13_MSG_KDF_SH_DTLS_EPOCH;
16016
                }
16017
            }
16018
#endif /* WOLFSSL_DTLS13 */
16019
0
            ssl->kdfMsgStep = TLS13_MSG_KDF_NONE;
16020
0
        }
16021
16022
0
        if (type == finished) {
16023
            /* Mark the phase entered before the first derive, so a pending
16024
             * there still routes the retry back here. */
16025
0
            if (ssl->kdfMsgStep == TLS13_MSG_KDF_NONE) {
16026
0
                ssl->kdfMsgStep = TLS13_MSG_KDF_FIN_ENTERED;
16027
0
                ssl->kdfMsgType = type;
16028
0
            }
16029
16030
0
            if (ssl->kdfMsgStep <= TLS13_MSG_KDF_FIN_ENTERED) {
16031
0
                if ((ret = DeriveMasterSecret(ssl)) != 0) {
16032
0
                    if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
16033
0
                        ssl->kdfMsgStep = TLS13_MSG_KDF_NONE;
16034
0
                    return ret;
16035
0
                }
16036
                /* Zeroized only after the derive completed: a pend retry
16037
                 * still reads preMasterSecret. */
16038
0
                ForceZero(ssl->arrays->preMasterSecret, MAX_PREMASTER_SZ);
16039
0
                ssl->kdfMsgStep = TLS13_MSG_KDF_FIN_MASTER_SECRET;
16040
0
            }
16041
    #ifdef WOLFSSL_EARLY_DATA
16042
    #ifdef WOLFSSL_QUIC
16043
            if (ssl->kdfMsgStep <= TLS13_MSG_KDF_FIN_MASTER_SECRET) {
16044
                if (WOLFSSL_IS_QUIC(ssl) &&
16045
                        ssl->earlyData != no_early_data) {
16046
                    /* QUIC never sends/receives EndOfEarlyData, but
16047
                     * having early data means the last encryption keys
16048
                     * had not been set yet. */
16049
                    if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0) {
16050
                        if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
16051
                            ssl->kdfMsgStep = TLS13_MSG_KDF_NONE;
16052
                        return ret;
16053
                    }
16054
                }
16055
                ssl->kdfMsgStep = TLS13_MSG_KDF_FIN_QUIC_EARLY_KEYS;
16056
            }
16057
    #endif
16058
            if (ssl->kdfMsgStep <= TLS13_MSG_KDF_FIN_QUIC_EARLY_KEYS) {
16059
                ret = DeriveTls13Keys(ssl, traffic_key,
16060
                            ENCRYPT_AND_DECRYPT_SIDE,
16061
                            ssl->earlyData == no_early_data);
16062
                if (ret != 0) {
16063
                    if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
16064
                        ssl->kdfMsgStep = TLS13_MSG_KDF_NONE;
16065
                    return ret;
16066
                }
16067
                ssl->kdfMsgStep = TLS13_MSG_KDF_FIN_TRAFFIC_KEYS;
16068
            }
16069
            if (ssl->earlyData != no_early_data) {
16070
                if (ssl->kdfMsgStep <= TLS13_MSG_KDF_FIN_TRAFFIC_KEYS) {
16071
                    if ((ret = DeriveTls13Keys(ssl, no_key,
16072
                                            DECRYPT_SIDE_ONLY, 1)) != 0) {
16073
                        if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
16074
                            ssl->kdfMsgStep = TLS13_MSG_KDF_NONE;
16075
                        return ret;
16076
                    }
16077
                    ssl->kdfMsgStep = TLS13_MSG_KDF_FIN_TRAFFIC_DONE;
16078
                }
16079
            }
16080
    #else
16081
0
            if (ssl->kdfMsgStep <= TLS13_MSG_KDF_FIN_QUIC_EARLY_KEYS) {
16082
0
                ret = DeriveTls13Keys(ssl, traffic_key,
16083
0
                            ENCRYPT_AND_DECRYPT_SIDE, 1);
16084
0
                if (ret != 0) {
16085
0
                    if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
16086
0
                        ssl->kdfMsgStep = TLS13_MSG_KDF_NONE;
16087
0
                    return ret;
16088
0
                }
16089
0
                ssl->kdfMsgStep = TLS13_MSG_KDF_FIN_TRAFFIC_DONE;
16090
0
            }
16091
0
    #endif
16092
            /* Setup keys for application data messages. */
16093
0
            if (ssl->kdfMsgStep <= TLS13_MSG_KDF_FIN_TRAFFIC_DONE) {
16094
0
                if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0) {
16095
0
                    if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
16096
0
                        ssl->kdfMsgStep = TLS13_MSG_KDF_NONE;
16097
0
                    return ret;
16098
0
                }
16099
0
                ssl->kdfMsgStep = TLS13_MSG_KDF_FIN_KEYS_SET;
16100
0
            }
16101
0
            ssl->kdfMsgStep = TLS13_MSG_KDF_NONE;
16102
0
        }
16103
0
    }
16104
0
#endif /* NO_WOLFSSL_CLIENT */
16105
16106
0
#ifndef NO_WOLFSSL_SERVER
16107
    #if defined(HAVE_SESSION_TICKET)
16108
        if (ssl->options.side == WOLFSSL_SERVER_END && type == finished) {
16109
            if (ssl->kdfMsgStep == TLS13_MSG_KDF_NONE) {
16110
                ssl->kdfMsgStep = TLS13_MSG_KDF_SFIN_ENTERED;
16111
                ssl->kdfMsgType = type;
16112
            }
16113
            if (ssl->kdfMsgStep <= TLS13_MSG_KDF_SFIN_ENTERED) {
16114
                ret = DeriveResumptionSecret(ssl, ssl->session->masterSecret);
16115
                if (ret != 0) {
16116
                    if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
16117
                        ssl->kdfMsgStep = TLS13_MSG_KDF_NONE;
16118
                    return ret;
16119
                }
16120
                ssl->kdfMsgStep = TLS13_MSG_KDF_SFIN_RESUMPTION_SECRET;
16121
            }
16122
            ssl->kdfMsgStep = TLS13_MSG_KDF_NONE;
16123
        }
16124
    #endif
16125
0
#endif /* NO_WOLFSSL_SERVER */
16126
16127
0
    return ret;
16128
0
}
16129
16130
int DoTls13HandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx,
16131
                            byte type, word32 size, word32 totalSz)
16132
0
{
16133
0
    int ret = 0, tmp;
16134
0
    word32 inIdx = *inOutIdx;
16135
0
    int alertType;
16136
0
    int skipSanity = 0;
16137
#if defined(HAVE_ECH) && !defined(NO_WOLFSSL_SERVER)
16138
    TLSX* echX = NULL;
16139
    word32 echInOutIdx;
16140
#endif
16141
16142
0
    (void)totalSz;
16143
16144
0
    WOLFSSL_ENTER("DoTls13HandShakeMsgType");
16145
16146
    /* make sure we can read the message */
16147
0
    if (*inOutIdx + size > totalSz)
16148
0
        return INCOMPLETE_DATA;
16149
16150
#ifdef WOLFSSL_ASYNC_CRYPT
16151
    /* A message being replayed after its own handler pended has already
16152
     * passed its sanity check and advanced the got_* state on the first
16153
     * pass; the handler restores its cleared marker on completion. Consume
16154
     * the one-shot marker here so only that replayed message skips the
16155
     * check - messages dispatched after it (ssl->error may still read
16156
     * WC_PENDING_E from a trailing key-schedule pend) are still checked. */
16157
    skipSanity = ssl->options.asyncReplayMsg;
16158
    ssl->options.asyncReplayMsg = 0;
16159
#endif
16160
16161
    /* Sanity check msg received. Skipped on a WC_PENDING_E resume (it
16162
     * would reject the replay against already-advanced state); handlers
16163
     * restore their cleared got_* markers on completion instead. */
16164
0
    if (!skipSanity &&
16165
0
            (ret = SanityCheckTls13MsgReceived(ssl, type)) != 0) {
16166
0
        WOLFSSL_MSG("Sanity Check on handshake message type received failed");
16167
0
        if (ret == WC_NO_ERR_TRACE(VERSION_ERROR))
16168
0
            SendAlert(ssl, alert_fatal, wolfssl_alert_protocol_version);
16169
0
        else
16170
0
            SendAlert(ssl, alert_fatal, unexpected_message);
16171
0
        return ret;
16172
0
    }
16173
16174
#if defined(WOLFSSL_CALLBACKS)
16175
    /* add name later, add on record and handshake header part back on */
16176
    if (ssl->toInfoOn) {
16177
        ret = AddPacketInfo(ssl, 0, handshake, input + *inOutIdx -
16178
            HANDSHAKE_HEADER_SZ, size + HANDSHAKE_HEADER_SZ, READ_PROTO,
16179
            RECORD_HEADER_SZ, ssl->heap);
16180
        if (ret != 0)
16181
            return ret;
16182
        AddLateRecordHeader(&ssl->curRL, &ssl->timeoutInfo);
16183
    }
16184
#endif
16185
16186
0
    if (ssl->options.handShakeState == HANDSHAKE_DONE &&
16187
0
            type != session_ticket && type != certificate_request &&
16188
0
            type != certificate && type != key_update && type != finished
16189
#if defined(WOLFSSL_DTLS13) && defined(WOLFSSL_DTLS_CID)
16190
            && type != request_connection_id && type != new_connection_id
16191
#endif
16192
0
            ) {
16193
0
        WOLFSSL_MSG("HandShake message after handshake complete");
16194
0
        SendAlert(ssl, alert_fatal, unexpected_message);
16195
0
        WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
16196
0
        return OUT_OF_ORDER_E;
16197
0
    }
16198
16199
0
    if (ssl->options.side == WOLFSSL_CLIENT_END &&
16200
0
               ssl->options.serverState == NULL_STATE &&
16201
0
               type != server_hello && type != hello_retry_request
16202
#if defined(WOLFSSL_DTLS13) && !defined(WOLFSSL_NO_TLS12)
16203
        && (!ssl->options.dtls || type != hello_verify_request)
16204
#endif /* defined(WOLFSSL_DTLS13) && !defined(WOLFSSL_NO_TLS12) */
16205
0
        ) {
16206
0
        WOLFSSL_MSG("First server message not server hello");
16207
0
        SendAlert(ssl, alert_fatal, unexpected_message);
16208
0
        WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
16209
0
        return OUT_OF_ORDER_E;
16210
0
    }
16211
16212
0
    if (ssl->options.side == WOLFSSL_SERVER_END &&
16213
0
               ssl->options.clientState == NULL_STATE && type != client_hello) {
16214
0
        WOLFSSL_MSG("First client message not client hello");
16215
0
        SendAlert(ssl, alert_fatal, unexpected_message);
16216
0
        WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
16217
0
        return OUT_OF_ORDER_E;
16218
0
    }
16219
16220
    /* above checks handshake state */
16221
    /* Finish an earlier message's key schedule before this message is
16222
     * judged: it installs state this one is checked against. */
16223
0
    if (ssl->kdfMsgStep > 0) {
16224
0
        ret = DoTls13MsgDerives(ssl, ssl->kdfMsgType);
16225
0
        if (ret != 0)
16226
0
            return ret;
16227
        /* A resolved pend must not suppress the next sanity check. */
16228
0
        if (ssl->error == WC_NO_ERR_TRACE(WC_PENDING_E)) {
16229
0
            ssl->error = 0;
16230
0
        }
16231
0
    }
16232
16233
0
    switch (type) {
16234
0
#ifndef NO_WOLFSSL_CLIENT
16235
    /* Messages only received by client. */
16236
0
    case server_hello:
16237
0
        WOLFSSL_MSG("processing server hello");
16238
0
        ret = DoTls13ServerHello(ssl, input, inOutIdx, size, &type);
16239
    #if !defined(WOLFSSL_NO_CLIENT_AUTH) && \
16240
               ((defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)) || \
16241
                (defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)))
16242
        if (ssl->options.resuming || !IsAtLeastTLSv1_2(ssl) ||
16243
                                               IsAtLeastTLSv1_3(ssl->version)) {
16244
            ssl->options.cacheMessages = 0;
16245
            if ((ssl->hsHashes != NULL) && (ssl->hsHashes->messages != NULL)) {
16246
                ForceZero(ssl->hsHashes->messages, ssl->hsHashes->length);
16247
                XFREE(ssl->hsHashes->messages, ssl->heap, DYNAMIC_TYPE_HASHES);
16248
                ssl->hsHashes->messages = NULL;
16249
            }
16250
        }
16251
    #endif
16252
0
        break;
16253
16254
0
    case encrypted_extensions:
16255
0
        WOLFSSL_MSG("processing encrypted extensions");
16256
0
        ret = DoTls13EncryptedExtensions(ssl, input, inOutIdx, size);
16257
0
        break;
16258
16259
0
    #ifndef NO_CERTS
16260
0
    case certificate_request:
16261
0
        WOLFSSL_MSG("processing certificate request");
16262
0
        ret = DoTls13CertificateRequest(ssl, input, inOutIdx, size);
16263
0
        break;
16264
0
    #endif
16265
16266
0
    case session_ticket:
16267
0
        WOLFSSL_MSG("processing new session ticket");
16268
0
        ret = DoTls13NewSessionTicket(ssl, input, inOutIdx, size);
16269
0
        break;
16270
0
#endif /* !NO_WOLFSSL_CLIENT */
16271
16272
0
#ifndef NO_WOLFSSL_SERVER
16273
    /* Messages only received by server. */
16274
0
    case client_hello:
16275
0
        WOLFSSL_MSG("processing client hello");
16276
#if defined(HAVE_ECH)
16277
        /* keep the start idx so we can restore it for the inner call */
16278
        echInOutIdx = *inOutIdx;
16279
#endif
16280
0
        ret = DoTls13ClientHello(ssl, input, inOutIdx, size);
16281
    #if !defined(WOLFSSL_NO_CLIENT_AUTH) && \
16282
               ((defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)) || \
16283
                (defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)))
16284
        if ((ssl->options.resuming || !ssl->options.verifyPeer ||
16285
               !IsAtLeastTLSv1_2(ssl) || IsAtLeastTLSv1_3(ssl->version))
16286
        #ifdef WOLFSSL_DTLS13
16287
               && (!ssl->options.dtls)
16288
        #endif
16289
               ) {
16290
        #ifdef WOLFSSL_HAVE_HS_SUSPEND
16291
            if (!IsHsSuspendErr(ret))
16292
        #endif
16293
            {
16294
                ssl->options.cacheMessages = 0;
16295
                if ((ssl->hsHashes != NULL) &&
16296
                        (ssl->hsHashes->messages != NULL)) {
16297
                    ForceZero(ssl->hsHashes->messages, ssl->hsHashes->length);
16298
                    XFREE(ssl->hsHashes->messages, ssl->heap,
16299
                        DYNAMIC_TYPE_HASHES);
16300
                    ssl->hsHashes->messages = NULL;
16301
                }
16302
            }
16303
        }
16304
    #endif
16305
#if defined(HAVE_ECH)
16306
        if (ret == 0) {
16307
            echX = TLSX_Find(ssl->extensions, TLSX_ECH);
16308
16309
            if (echX != NULL &&
16310
                    ((WOLFSSL_ECH*)echX->data)->state == ECH_WRITE_NONE &&
16311
                    ((WOLFSSL_ECH*)echX->data)->innerClientHello != NULL) {
16312
                byte copyRandom = ((WOLFSSL_ECH*)echX->data)->innerCount == 0;
16313
                /* reset the inOutIdx to the outer start */
16314
                *inOutIdx = echInOutIdx;
16315
                /* call again with the inner hello */
16316
                if (ret == 0) {
16317
                    echInOutIdx = HANDSHAKE_HEADER_SZ;
16318
#ifdef WOLFSSL_DTLS13
16319
                    if (ssl->options.dtls)
16320
                        echInOutIdx = DTLS13_HANDSHAKE_HEADER_SZ;
16321
#endif
16322
                    ssl->options.echProcessingInner = 1;
16323
                    ret = DoTls13ClientHello(ssl,
16324
                        ((WOLFSSL_ECH*)echX->data)->innerClientHello,
16325
                        &echInOutIdx,
16326
                        ((WOLFSSL_ECH*)echX->data)->innerClientHelloLen);
16327
                    ssl->options.echProcessingInner = 0;
16328
                }
16329
                if (ret == 0 && ((WOLFSSL_ECH*)echX->data)->state !=
16330
                        ECH_PARSED_INTERNAL) {
16331
                    WOLFSSL_MSG("ECH: inner ClientHello missing ECH extension");
16332
                    ret = INVALID_PARAMETER;
16333
                }
16334
                /* if the inner ech parsed successfully we have successfully
16335
                 * handled the hello and can skip the whole message */
16336
                if (ret == 0) {
16337
                    /* Copy inner client random for ECH acceptance calculation.
16338
                     * Only on first inner ClientHello (before HRR), not CH2. */
16339
                    if (copyRandom) {
16340
                        XMEMCPY(ssl->arrays->clientRandomInner,
16341
                                ssl->arrays->clientRandom, RAN_LEN);
16342
                    }
16343
                    *inOutIdx += size;
16344
                }
16345
            }
16346
        }
16347
#endif /* HAVE_ECH */
16348
0
        break;
16349
16350
    #ifdef WOLFSSL_EARLY_DATA
16351
    case end_of_early_data:
16352
        WOLFSSL_MSG("processing end of early data");
16353
        ret = DoTls13EndOfEarlyData(ssl, input, inOutIdx, size);
16354
        break;
16355
    #endif
16356
0
#endif /* !NO_WOLFSSL_SERVER */
16357
16358
    /* Messages received by both client and server. */
16359
0
#if !defined(NO_CERTS) && (!defined(NO_WOLFSSL_CLIENT) || \
16360
0
                           !defined(WOLFSSL_NO_CLIENT_AUTH))
16361
0
    case certificate:
16362
0
        WOLFSSL_MSG("processing certificate");
16363
0
        ret = DoTls13Certificate(ssl, input, inOutIdx, size);
16364
0
        break;
16365
0
#endif
16366
16367
0
#if (!defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
16368
0
     defined(HAVE_ED448) || defined(HAVE_FALCON) || \
16369
0
     defined(WOLFSSL_HAVE_MLDSA) || defined(WOLFSSL_HAVE_SLHDSA)) && \
16370
0
    !defined(NO_CERTS)
16371
0
    case certificate_verify:
16372
0
        WOLFSSL_MSG("processing certificate verify");
16373
0
        ret = DoTls13CertificateVerify(ssl, input, inOutIdx, size);
16374
0
        break;
16375
0
#endif
16376
0
    case finished:
16377
0
        WOLFSSL_MSG("processing finished");
16378
0
        ret = DoTls13Finished(ssl, input, inOutIdx, size, totalSz, NO_SNIFF);
16379
0
        break;
16380
16381
0
    case key_update:
16382
0
        WOLFSSL_MSG("processing key update");
16383
0
        ret = DoTls13KeyUpdate(ssl, input, inOutIdx, size);
16384
0
        break;
16385
16386
#if defined(WOLFSSL_DTLS13) && defined(WOLFSSL_DTLS_CID)
16387
    case request_connection_id:
16388
        WOLFSSL_MSG("processing request connection id");
16389
        ret = DoDtls13RequestConnectionId(ssl, input, inOutIdx, size);
16390
        break;
16391
16392
    case new_connection_id:
16393
        WOLFSSL_MSG("processing new connection id");
16394
        ret = DoDtls13NewConnectionId(ssl, input, inOutIdx, size);
16395
        break;
16396
#endif /* WOLFSSL_DTLS13 && WOLFSSL_DTLS_CID */
16397
16398
#if defined(WOLFSSL_DTLS13) && !defined(WOLFSSL_NO_TLS12) && \
16399
    !defined(NO_WOLFSSL_CLIENT)
16400
    case hello_verify_request:
16401
        WOLFSSL_MSG("processing hello verify request");
16402
        ret = DoHelloVerifyRequest(ssl, input, inOutIdx, size);
16403
        break;
16404
#endif
16405
0
    default:
16406
0
        WOLFSSL_MSG("Unknown handshake message type");
16407
0
        ret = UNKNOWN_HANDSHAKE_TYPE;
16408
0
        break;
16409
0
    }
16410
16411
#ifdef WOLFSSL_ASYNC_CRYPT
16412
    /* Handler pended: this exact message will be replayed. Mark it so the
16413
     * replay skips its sanity check (it already passed and advanced state).
16414
     * Set from the handler's own ret, before the trailing key-schedule
16415
     * derive below can re-raise WC_PENDING_E for an already-done message. */
16416
    if (ret == WC_NO_ERR_TRACE(WC_PENDING_E))
16417
        ssl->options.asyncReplayMsg = 1;
16418
#endif
16419
16420
#ifdef WOLFSSL_HAVE_HS_SUSPEND
16421
    /* if suspended, offset index so this msg will be processed again */
16422
    /* NOTE: check this now before other calls can overwrite ret */
16423
    if (IsHsSuspendErr(ret) && *inOutIdx > 0) {
16424
        /* DTLS always stores a message in a buffer when async is enable, so we
16425
         * don't need to adjust for the extra bytes here (*inOutIdx is always
16426
         * == 0) */
16427
        *inOutIdx -= HANDSHAKE_HEADER_SZ;
16428
    }
16429
16430
    /* make sure suspend error is cleared */
16431
    if (ret == 0 && IsHsSuspendErr(ssl->error)) {
16432
        ssl->error = 0;
16433
    }
16434
#endif
16435
#if defined(HAVE_WRITE_DUP) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
16436
    /* Read side: a fresh PHA CertificateRequest. Resume from the transcript
16437
     * the write side published after the previous PHA response, so this CR is
16438
     * hashed onto the same base the server has. */
16439
    if (ret == 0 && type == certificate_request &&
16440
            ssl->options.side == WOLFSSL_CLIENT_END &&
16441
            ssl->dupSide == READ_DUP_SIDE &&
16442
            ssl->options.handShakeState == HANDSHAKE_DONE &&
16443
            ssl->dupWrite != NULL) {
16444
        if (wc_LockMutex(&ssl->dupWrite->dupMutex) != 0)
16445
            return BAD_MUTEX_E;
16446
        if (ssl->dupWrite->postHandshakeSyncedHashState != NULL) {
16447
            FreeHandshakeHashes(ssl);
16448
            ssl->hsHashes = ssl->dupWrite->postHandshakeSyncedHashState;
16449
            ssl->dupWrite->postHandshakeSyncedHashState = NULL;
16450
        }
16451
        wc_UnLockMutex(&ssl->dupWrite->dupMutex);
16452
    }
16453
#endif /* HAVE_WRITE_DUP && WOLFSSL_POST_HANDSHAKE_AUTH */
16454
0
    if (ret == 0 && type != client_hello && type != session_ticket &&
16455
0
                                                           type != key_update
16456
#if defined(WOLFSSL_DTLS13) && defined(WOLFSSL_DTLS_CID)
16457
            && type != request_connection_id && type != new_connection_id
16458
#endif
16459
0
            ) {
16460
0
        ret = HashInput(ssl, input + inIdx, (int)size);
16461
0
    }
16462
16463
0
    alertType = TranslateErrorToAlert(ret);
16464
16465
    /* Skip when a fatal alert already went out for this error. The message
16466
     * handlers reached above send their own, more specific alert before
16467
     * returning (a protocol_version from the version checks in DoClientHello,
16468
     * decode_error, illegal_parameter, inappropriate_fallback), and a second
16469
     * fatal alert on a connection that is already being torn down is not a
16470
     * message the peer can act on. Matches the guard in
16471
     * SendFatalAlertOnly(). */
16472
0
    if (alertType != invalid_alert &&
16473
0
            ssl->alert_history.last_tx.level != alert_fatal) {
16474
#ifdef WOLFSSL_DTLS13
16475
        if (type == client_hello && ssl->options.dtls)
16476
            DtlsSetSeqNumForReply(ssl);
16477
#endif
16478
0
        tmp = SendAlert(ssl, alert_fatal, alertType);
16479
        /* propagate socket error instead of tls error to be sure the error is
16480
         * not ignored by DTLS code */
16481
0
        if (tmp == WC_NO_ERR_TRACE(SOCKET_ERROR_E))
16482
0
            ret = SOCKET_ERROR_E;
16483
0
    }
16484
16485
0
    if (ret == 0 && ssl->options.tls1_3) {
16486
        /* The message is hashed by now; run the key schedule that belongs to
16487
         * it. */
16488
0
        ret = DoTls13MsgDerives(ssl, type);
16489
0
        if (ret != 0)
16490
0
            return ret;
16491
16492
    #if !defined(NO_WOLFSSL_CLIENT) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
16493
        if (ssl->options.side == WOLFSSL_CLIENT_END) {
16494
            if (type == certificate_request &&
16495
                                ssl->options.handShakeState == HANDSHAKE_DONE) {
16496
                if (IsWriteClosed(ssl)) {
16497
                    WOLFSSL_MSG("Ignoring CertificateRequest after "
16498
                                "close_notify");
16499
                }
16500
                else
16501
#if defined(HAVE_WRITE_DUP)
16502
                /* Read side cannot write; delegate the cert response to the
16503
                 * write side by saving auth state in the shared WriteDup. */
16504
                if (ssl->dupSide == READ_DUP_SIDE) {
16505
                    if (ssl->dupWrite == NULL)
16506
                        return BAD_STATE_E;
16507
                    if (wc_LockMutex(&ssl->dupWrite->dupMutex) != 0)
16508
                        return BAD_MUTEX_E;
16509
                    /* Copy the current transcript so the write side can
16510
                     * compute the correct Finished MAC. */
16511
                    ret = InitHandshakeHashesAndCopy(ssl, ssl->hsHashes,
16512
                                      &ssl->dupWrite->postHandshakeHashState);
16513
                    if (ret == 0) {
16514
                        /* Copy the cert request context. */
16515
                        CertReqCtx** tail = &ssl->certReqCtx;
16516
                        while (*tail != NULL)
16517
                            tail = &(*tail)->next;
16518
                        *tail = ssl->dupWrite->postHandshakeCertReqCtx;
16519
                        ssl->dupWrite->postHandshakeCertReqCtx = ssl->certReqCtx;
16520
                        ssl->certReqCtx = NULL;
16521
                        ssl->dupWrite->postHandshakeSendVerify =
16522
                            ssl->options.sendVerify;
16523
                        ssl->dupWrite->postHandshakeSigAlgo =
16524
                            ssl->options.sigAlgo;
16525
                        ssl->dupWrite->postHandshakeHashAlgo =
16526
                            ssl->options.hashAlgo;
16527
                    #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
16528
                        /* The request just parsed decides whether the chain
16529
                         * about to be sent may be SHA-1 signed. */
16530
                        ssl->dupWrite->postHandshakeSha1CertOk =
16531
                            (byte)ssl->options.peerSha1CertOk;
16532
                    #endif
16533
                        ssl->dupWrite->postHandshakeAuthPending = 1;
16534
                    }
16535
                    wc_UnLockMutex(&ssl->dupWrite->dupMutex);
16536
                    /* Leave ssl->options unchanged: read side must not reset
16537
                     * its states or call wolfSSL_connect_TLSv13. */
16538
                }
16539
                else
16540
#endif /* HAVE_WRITE_DUP */
16541
                {
16542
                    /* reset handshake states */
16543
                    ssl->options.clientState = CLIENT_HELLO_COMPLETE;
16544
                    ssl->options.connectState  = FIRST_REPLY_DONE;
16545
                    ssl->options.handShakeState = CLIENT_HELLO_COMPLETE;
16546
                    ssl->options.processReply = 0; /* doProcessInit */
16547
16548
                    /*
16549
                       DTLSv1.3 note: We can't reset serverState to
16550
                       SERVER_FINISHED_COMPLETE with the goal that this connect
16551
                       blocks until the cert/cert_verify/finished flight gets ACKed
16552
                       by the server. The problem is that we will invoke
16553
                       ProcessReplyEx() in that case, but we came here from
16554
                       ProcessReplyEx() and it is not re-entrant safe (the input
16555
                       buffer would still have the certificate_request message). */
16556
16557
                    if (wolfSSL_connect_TLSv13(ssl) != WOLFSSL_SUCCESS) {
16558
                        ret = ssl->error;
16559
                        /* DTLS does not yet resume a blocked response */
16560
                        if (ret != WC_NO_ERR_TRACE(WC_PENDING_E) &&
16561
                                (ret != WC_NO_ERR_TRACE(WANT_WRITE) ||
16562
                                 ssl->options.dtls))
16563
                            ret = POST_HAND_AUTH_ERROR;
16564
                    }
16565
                }
16566
            }
16567
        }
16568
    #endif /* !NO_WOLFSSL_CLIENT && WOLFSSL_POST_HANDSHAKE_AUTH */
16569
0
    }
16570
16571
#ifdef WOLFSSL_DTLS13
16572
    if (ssl->options.dtls && !ssl->options.dtlsStateful) {
16573
        DtlsResetState(ssl);
16574
        if (DtlsIgnoreError(ret))
16575
            ret = 0;
16576
    }
16577
#endif
16578
16579
0
    WOLFSSL_LEAVE("DoTls13HandShakeMsgType()", ret);
16580
0
    return ret;
16581
0
}
16582
16583
16584
/* Handle a handshake message that has been received.
16585
 *
16586
 * ssl       The SSL/TLS object.
16587
 * input     The message buffer.
16588
 * inOutIdx  On entry, the index into the buffer of the current message.
16589
 *           On exit, the index into the buffer of the next message.
16590
 * totalSz   Length of remaining data in the message buffer.
16591
 * returns 0 on success and otherwise failure.
16592
 */
16593
int DoTls13HandShakeMsg(WOLFSSL* ssl, byte* input, word32* inOutIdx,
16594
                        word32 totalSz)
16595
0
{
16596
0
    int    ret = 0;
16597
0
    word32 inputLength;
16598
0
    byte   type;
16599
0
    word32 size = 0;
16600
#ifdef WOLFSSL_HAVE_HS_SUSPEND
16601
    /* Nonzero on entry: an earlier message's schedule is unfinished, so a
16602
     * pend from its pre-dispatch drain must re-present this message. */
16603
    byte   kdfStepEntry = ssl->kdfMsgStep;
16604
#endif
16605
16606
0
    WOLFSSL_ENTER("DoTls13HandShakeMsg");
16607
16608
    /* totalSz is now curStartIdx + curSize (content-only, padSz already
16609
     * subtracted in ProcessReply). */
16610
0
    if (*inOutIdx > totalSz)
16611
0
        return BUFFER_ERROR;
16612
0
    inputLength = totalSz - *inOutIdx;
16613
16614
    /* If there is a pending fragmented handshake message,
16615
     * pending message size will be non-zero. */
16616
0
    if (ssl->pendingMsgSz == 0) {
16617
    #ifdef WOLFSSL_HAVE_HS_SUSPEND
16618
        word32 startIdx = *inOutIdx;
16619
    #endif
16620
16621
0
        if (GetHandshakeHeader(ssl, input, inOutIdx, &type, &size,
16622
0
                               totalSz) != 0) {
16623
0
            WOLFSSL_ERROR_VERBOSE(PARSE_ERROR);
16624
0
            return PARSE_ERROR;
16625
0
        }
16626
16627
0
        ret = EarlySanityCheckMsgReceived(ssl, type,
16628
0
                (inputLength > HANDSHAKE_HEADER_SZ) ?
16629
0
                min(inputLength - HANDSHAKE_HEADER_SZ, size) : 0);
16630
0
        if (ret != 0) {
16631
0
            WOLFSSL_ERROR(ret);
16632
0
            return ret;
16633
0
        }
16634
16635
        /* Cap the maximum size of a handshake message to something reasonable.
16636
         * By default is the maximum size of a certificate message assuming
16637
         * nine 2048-bit RSA certificates in the chain. */
16638
0
        if (size > MAX_HANDSHAKE_SZ) {
16639
0
            WOLFSSL_MSG("Handshake message too large");
16640
0
            WOLFSSL_ERROR_VERBOSE(HANDSHAKE_SIZE_ERROR);
16641
0
            return HANDSHAKE_SIZE_ERROR;
16642
0
        }
16643
16644
        /* size is the size of the certificate message payload */
16645
0
        if (inputLength - HANDSHAKE_HEADER_SZ < size) {
16646
            /* Commit pending state only after the allocation succeeds. */
16647
0
            ssl->pendingMsg = (byte*)XMALLOC(size + HANDSHAKE_HEADER_SZ,
16648
0
                                             ssl->heap, DYNAMIC_TYPE_ARRAYS);
16649
0
            if (ssl->pendingMsg == NULL)
16650
0
                return MEMORY_E;
16651
0
            ssl->pendingMsgType = type;
16652
0
            ssl->pendingMsgSz = size + HANDSHAKE_HEADER_SZ;
16653
0
            XMEMCPY(ssl->pendingMsg,
16654
0
                    input + *inOutIdx - HANDSHAKE_HEADER_SZ,
16655
0
                    inputLength);
16656
0
            ssl->pendingMsgOffset = inputLength;
16657
0
            *inOutIdx += inputLength - HANDSHAKE_HEADER_SZ;
16658
0
            return 0;
16659
0
        }
16660
16661
0
        ret = DoTls13HandShakeMsgType(ssl, input, inOutIdx, type, size,
16662
0
                                      totalSz);
16663
    #ifdef WOLFSSL_HAVE_HS_SUSPEND
16664
        if (IsHsSuspendErr(ret) &&
16665
                (ret != WC_NO_ERR_TRACE(WC_PENDING_E) ||
16666
                 ((ssl->kdfMsgStep == 0 || kdfStepEntry != 0) &&
16667
                  ssl->options.processReply != 0 /* doProcessInit */))) {
16668
            /* Re-present for in-handler pends and pre-dispatch drain pends.
16669
             * Not for post-handler pends, which committed the message: a
16670
             * key-schedule pend (kdfMsgStep != 0) resumes through
16671
             * DoTls13MsgDerives(), and a post-handshake-auth send pend
16672
             * (processReply reset to doProcessInit) resumes through
16673
             * wolfSSL_negotiate(). */
16674
            *inOutIdx = startIdx;
16675
        }
16676
    #endif
16677
0
    }
16678
0
    else {
16679
0
        if (inputLength + ssl->pendingMsgOffset > ssl->pendingMsgSz) {
16680
0
            inputLength = ssl->pendingMsgSz - ssl->pendingMsgOffset;
16681
0
        }
16682
16683
0
        ret = EarlySanityCheckMsgReceived(ssl, ssl->pendingMsgType,
16684
0
                inputLength);
16685
0
        if (ret != 0) {
16686
0
            WOLFSSL_ERROR(ret);
16687
0
            return ret;
16688
0
        }
16689
16690
0
        XMEMCPY(ssl->pendingMsg + ssl->pendingMsgOffset,
16691
0
                input + *inOutIdx, inputLength);
16692
0
        ssl->pendingMsgOffset += inputLength;
16693
0
        *inOutIdx += inputLength;
16694
16695
0
        if (ssl->pendingMsgOffset == ssl->pendingMsgSz)
16696
0
        {
16697
0
            word32 idx = 0;
16698
0
            ret = DoTls13HandShakeMsgType(ssl,
16699
0
                                ssl->pendingMsg + HANDSHAKE_HEADER_SZ,
16700
0
                                &idx, ssl->pendingMsgType,
16701
0
                                ssl->pendingMsgSz - HANDSHAKE_HEADER_SZ,
16702
0
                                ssl->pendingMsgSz);
16703
        #ifdef WOLFSSL_HAVE_HS_SUSPEND
16704
            if (IsHsSuspendErr(ret) &&
16705
                (ret != WC_NO_ERR_TRACE(WC_PENDING_E) ||
16706
                 ((ssl->kdfMsgStep == 0 || kdfStepEntry != 0) &&
16707
                  ssl->options.processReply != 0 /* doProcessInit */))) {
16708
                /* Re-present the fragment; a post-handler pend falls
16709
                 * through and consumes the message. */
16710
                ssl->pendingMsgOffset -= inputLength;
16711
                *inOutIdx -= inputLength;
16712
            }
16713
            else
16714
        #endif
16715
0
            {
16716
0
                XFREE(ssl->pendingMsg, ssl->heap, DYNAMIC_TYPE_ARRAYS);
16717
0
                ssl->pendingMsg = NULL;
16718
0
                ssl->pendingMsgSz = 0;
16719
0
            }
16720
0
        }
16721
0
    }
16722
16723
0
    WOLFSSL_LEAVE("DoTls13HandShakeMsg", ret);
16724
0
    return ret;
16725
0
}
16726
16727
#ifndef NO_WOLFSSL_CLIENT
16728
16729
#if defined(HAVE_WRITE_DUP) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
16730
static int Tls13WriteDupPublishPhaHashes(WOLFSSL* ssl)
16731
{
16732
    int ret = 0;
16733
16734
    if ((ssl->hsHashes != NULL) && (ssl->dupWrite != NULL)) {
16735
        if (wc_LockMutex(&ssl->dupWrite->dupMutex) != 0) {
16736
            ret = BAD_MUTEX_E;
16737
        }
16738
        else {
16739
            ret = InitHandshakeHashesAndCopy(ssl, ssl->hsHashes,
16740
                &ssl->dupWrite->postHandshakeSyncedHashState);
16741
            if (ret != 0) {
16742
                /* Drop a partial copy so the read side never hashes onto it */
16743
                Free_HS_Hashes(ssl->dupWrite->postHandshakeSyncedHashState,
16744
                    ssl->heap);
16745
                ssl->dupWrite->postHandshakeSyncedHashState = NULL;
16746
            }
16747
            wc_UnLockMutex(&ssl->dupWrite->dupMutex);
16748
        }
16749
    }
16750
16751
    return ret;
16752
}
16753
#endif /* HAVE_WRITE_DUP && WOLFSSL_POST_HANDSHAKE_AUTH */
16754
16755
/* The client connecting to the server.
16756
 * The protocol version is expecting to be TLS v1.3.
16757
 * If the server downgrades, and older versions of the protocol are compiled
16758
 * in, the client will fallback to wolfSSL_connect().
16759
 * Please see note at top of README if you get an error from connect.
16760
 *
16761
 * ssl  The SSL/TLS object.
16762
 * returns WOLFSSL_SUCCESS on successful handshake, WOLFSSL_FATAL_ERROR when
16763
 * unrecoverable error occurs and 0 otherwise.
16764
 * For more error information use wolfSSL_get_error().
16765
 */
16766
int wolfSSL_connect_TLSv13(WOLFSSL* ssl)
16767
0
{
16768
0
    int advanceState;
16769
0
    int ret = 0;
16770
16771
0
    WOLFSSL_ENTER("wolfSSL_connect_TLSv13");
16772
16773
0
#ifdef HAVE_ERRNO_H
16774
0
    errno = 0;
16775
0
#endif
16776
16777
0
    if (ssl == NULL)
16778
0
        return BAD_FUNC_ARG;
16779
16780
0
    if (ssl->options.side != WOLFSSL_CLIENT_END) {
16781
0
        ssl->error = SIDE_ERROR;
16782
0
        WOLFSSL_ERROR(ssl->error);
16783
0
        return WOLFSSL_FATAL_ERROR;
16784
0
    }
16785
16786
    /* make sure this wolfSSL object has arrays and rng setup. Protects
16787
     * case where the WOLFSSL object is reused via wolfSSL_clear() */
16788
0
    if ((ret = ReinitSSL(ssl, ssl->ctx, 0)) != 0) {
16789
0
        return ret;
16790
0
    }
16791
16792
#ifdef WOLFSSL_DTLS
16793
    if (ssl->version.major == DTLS_MAJOR) {
16794
        ssl->options.dtls   = 1;
16795
        ssl->options.dtlsStateful = 1;
16796
    }
16797
#endif
16798
16799
#ifdef WOLFSSL_WOLFSENTRY_HOOKS
16800
    if ((ssl->ConnectFilter != NULL) &&
16801
        (ssl->options.connectState == CONNECT_BEGIN))
16802
    {
16803
        wolfSSL_netfilter_decision_t res;
16804
        if ((ssl->ConnectFilter(ssl, ssl->ConnectFilter_arg, &res) ==
16805
             WOLFSSL_SUCCESS) &&
16806
            (res == WOLFSSL_NETFILTER_REJECT)) {
16807
            ssl->error = SOCKET_FILTERED_E;
16808
            WOLFSSL_ERROR(ssl->error);
16809
            return WOLFSSL_FATAL_ERROR;
16810
        }
16811
    }
16812
#endif /* WOLFSSL_WOLFSENTRY_HOOKS */
16813
16814
    /* fragOffset is non-zero when sending fragments. On the last
16815
     * fragment, fragOffset is zero again, and the state can be
16816
     * advanced. Also, only advance from states in which we send data */
16817
0
    advanceState = (ssl->options.connectState == CONNECT_BEGIN ||
16818
0
            ssl->options.connectState == HELLO_AGAIN ||
16819
0
            (ssl->options.connectState >= FIRST_REPLY_DONE &&
16820
0
             ssl->options.connectState <= FIRST_REPLY_FOURTH));
16821
16822
#ifdef WOLFSSL_DTLS13
16823
    if (ssl->options.dtls)
16824
        advanceState = advanceState && !ssl->dtls13SendingFragments
16825
            && !ssl->dtls13SendingAckOrRtx;
16826
#endif /* WOLFSSL_DTLS13 */
16827
16828
0
    if (ssl->buffers.outputBuffer.length > 0
16829
    #ifdef WOLFSSL_HAVE_HS_SUSPEND
16830
        /* do not send buffered or advance state if the last error suspended
16831
           the handshake - advancing frees the saved state */
16832
        && !IsHsSuspendErr(ssl->error)
16833
    #endif
16834
0
    ) {
16835
0
        if ((ret = SendBuffered(ssl)) == 0) {
16836
0
            if (ssl->fragOffset == 0 && !ssl->options.buildingMsg) {
16837
0
                if (advanceState) {
16838
#ifdef WOLFSSL_DTLS13
16839
                    if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version) &&
16840
                        ssl->options.connectState == FIRST_REPLY_FOURTH) {
16841
                    /* WAIT_FINISHED_ACK is a state added afterwards, but it
16842
                       can't follow FIRST_REPLY_FOURTH in the enum order. Indeed
16843
                       the value of the enum ConnectState is stored in
16844
                       serialized session. This would make importing serialized
16845
                       session from other wolfSSL version incompatible */
16846
                        ssl->options.connectState = WAIT_FINISHED_ACK;
16847
                    }
16848
                    else
16849
#endif /* WOLFSSL_DTLS13 */
16850
0
                    {
16851
0
                        ssl->options.connectState++;
16852
0
                    }
16853
0
                    WOLFSSL_MSG("connect state: "
16854
0
                                "Advanced from last buffered fragment send");
16855
0
#ifdef WOLFSSL_ASYNC_IO
16856
0
                    FreeAsyncCtx(ssl, 0);
16857
0
#endif
16858
16859
0
                }
16860
0
            }
16861
0
            else {
16862
0
                WOLFSSL_MSG("connect state: "
16863
0
                            "Not advanced, more fragments to send");
16864
0
            }
16865
#ifdef WOLFSSL_DTLS13
16866
            if (ssl->options.dtls)
16867
                ssl->dtls13SendingAckOrRtx = 0;
16868
#endif /* WOLFSSL_DTLS13 */
16869
16870
0
        }
16871
0
        else {
16872
0
            ssl->error = ret;
16873
0
            WOLFSSL_ERROR(ssl->error);
16874
0
            return WOLFSSL_FATAL_ERROR;
16875
0
        }
16876
0
    }
16877
16878
0
    ret = RetrySendAlert(ssl);
16879
0
    if (ret != 0) {
16880
0
        ssl->error = ret;
16881
0
        WOLFSSL_ERROR(ssl->error);
16882
0
        return WOLFSSL_FATAL_ERROR;
16883
0
    }
16884
16885
#ifdef WOLFSSL_DTLS13
16886
    if (ssl->options.dtls && ssl->dtls13SendingFragments) {
16887
        if ((ssl->error = Dtls13FragmentsContinue(ssl)) != 0) {
16888
                WOLFSSL_ERROR(ssl->error);
16889
                return WOLFSSL_FATAL_ERROR;
16890
        }
16891
16892
        /* we sent all the fragments. Advance state. */
16893
        ssl->options.connectState++;
16894
    }
16895
#endif /* WOLFSSL_DTLS13 */
16896
16897
0
    switch (ssl->options.connectState) {
16898
16899
0
        case CONNECT_BEGIN:
16900
            /* Always send client hello first. */
16901
0
            if ((ssl->error = SendTls13ClientHello(ssl)) != 0) {
16902
0
                WOLFSSL_ERROR(ssl->error);
16903
0
                return WOLFSSL_FATAL_ERROR;
16904
0
            }
16905
16906
0
            ssl->options.connectState = CLIENT_HELLO_SENT;
16907
0
            WOLFSSL_MSG("TLSv13 connect state: CLIENT_HELLO_SENT");
16908
0
            FALL_THROUGH;
16909
16910
0
        case CLIENT_HELLO_SENT:
16911
    #ifdef WOLFSSL_EARLY_DATA
16912
            if (ssl->earlyData != no_early_data &&
16913
                ssl->options.handShakeState != CLIENT_HELLO_COMPLETE) {
16914
        #if defined(WOLFSSL_TLS13_MIDDLEBOX_COMPAT)
16915
                    if (!ssl->options.dtls && !ssl->options.sentChangeCipher
16916
                            && ssl->options.tls13MiddleBoxCompat) {
16917
                        ssl->error = SendChangeCipher(ssl);
16918
                        /* A short send leaves the record queued in the output
16919
                         * buffer, so a resumed connect must not build a second
16920
                         * one. Same on every other site. */
16921
                        if (ssl->error == 0 ||
16922
                                ssl->error == WC_NO_ERR_TRACE(WANT_WRITE)) {
16923
                            ssl->options.sentChangeCipher = 1;
16924
                        }
16925
                        if (ssl->error != 0) {
16926
                            WOLFSSL_ERROR(ssl->error);
16927
                            return WOLFSSL_FATAL_ERROR;
16928
                        }
16929
                    }
16930
        #endif
16931
                ssl->options.handShakeState = CLIENT_HELLO_COMPLETE;
16932
                return WOLFSSL_SUCCESS;
16933
            }
16934
    #endif
16935
            /* Get the response/s from the server. */
16936
0
            while (ssl->options.serverState <
16937
0
                    SERVER_HELLOVERIFYREQUEST_COMPLETE) {
16938
0
                if ((ssl->error = ProcessReply(ssl)) < 0) {
16939
0
                        WOLFSSL_ERROR(ssl->error);
16940
0
                        return WOLFSSL_FATAL_ERROR;
16941
0
                }
16942
16943
#ifdef WOLFSSL_DTLS13
16944
                if (ssl->options.dtls) {
16945
                    if ((ssl->error = Dtls13DoScheduledWork(ssl)) < 0) {
16946
                        WOLFSSL_ERROR(ssl->error);
16947
                        return WOLFSSL_FATAL_ERROR;
16948
                    }
16949
                }
16950
#endif /* WOLFSSL_DTLS13 */
16951
0
            }
16952
16953
0
            if (!ssl->options.tls1_3) {
16954
0
    #ifndef WOLFSSL_NO_TLS12
16955
0
                if (ssl->options.downgrade)
16956
0
                    return wolfSSL_connect(ssl);
16957
0
    #endif
16958
0
                WOLFSSL_MSG("Client using higher version, fatal error");
16959
0
                WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
16960
0
                return VERSION_ERROR;
16961
0
            }
16962
16963
0
            ssl->options.connectState = HELLO_AGAIN;
16964
0
            WOLFSSL_MSG("connect state: HELLO_AGAIN");
16965
0
            FALL_THROUGH;
16966
16967
0
        case HELLO_AGAIN:
16968
16969
0
            if (ssl->options.serverState ==
16970
0
                                          SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
16971
        #if defined(WOLFSSL_TLS13_MIDDLEBOX_COMPAT)
16972
                if (!ssl->options.dtls && !ssl->options.sentChangeCipher
16973
                    && ssl->options.tls13MiddleBoxCompat) {
16974
                    ssl->error = SendChangeCipher(ssl);
16975
                    if (ssl->error == 0 ||
16976
                            ssl->error == WC_NO_ERR_TRACE(WANT_WRITE)) {
16977
                        ssl->options.sentChangeCipher = 1;
16978
                    }
16979
                    if (ssl->error != 0) {
16980
                        /* The second ClientHello still has to follow, so hold
16981
                         * the state machine on this case while the record
16982
                         * drains. */
16983
                        ssl->options.buildingMsg = 1;
16984
                        WOLFSSL_ERROR(ssl->error);
16985
                        return WOLFSSL_FATAL_ERROR;
16986
                    }
16987
                }
16988
        #endif
16989
                /* Try again with different security parameters. */
16990
0
                if ((ssl->error = SendTls13ClientHello(ssl)) != 0) {
16991
0
                    WOLFSSL_ERROR(ssl->error);
16992
0
                    return WOLFSSL_FATAL_ERROR;
16993
0
                }
16994
0
            }
16995
16996
0
            ssl->options.connectState = HELLO_AGAIN_REPLY;
16997
0
            WOLFSSL_MSG("connect state: HELLO_AGAIN_REPLY");
16998
0
            FALL_THROUGH;
16999
17000
0
        case HELLO_AGAIN_REPLY:
17001
            /* Get the response/s from the server. */
17002
0
            while (ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
17003
#ifdef WOLFSSL_DTLS13
17004
                if (!IsAtLeastTLSv1_3(ssl->version)) {
17005
        #ifndef WOLFSSL_NO_TLS12
17006
                    if (ssl->options.downgrade)
17007
                        return wolfSSL_connect(ssl);
17008
        #endif
17009
                }
17010
#endif /* WOLFSSL_DTLS13 */
17011
0
                if ((ssl->error = ProcessReply(ssl)) < 0) {
17012
0
                        WOLFSSL_ERROR(ssl->error);
17013
0
                        return WOLFSSL_FATAL_ERROR;
17014
0
                }
17015
17016
#ifdef WOLFSSL_DTLS13
17017
                if (ssl->options.dtls) {
17018
                    if ((ssl->error = Dtls13DoScheduledWork(ssl)) < 0) {
17019
                        WOLFSSL_ERROR(ssl->error);
17020
                        return WOLFSSL_FATAL_ERROR;
17021
                    }
17022
                }
17023
#endif /* WOLFSSL_DTLS13 */
17024
0
            }
17025
17026
            /* Finish a key schedule the Finished handler left pending:
17027
             * it must complete before this side's sends advance the
17028
             * transcript the traffic secrets hash. */
17029
0
            if (ssl->kdfMsgStep > 0) {
17030
0
                ssl->error = DoTls13MsgDerives(ssl, ssl->kdfMsgType);
17031
0
                if (ssl->error != 0) {
17032
0
                    WOLFSSL_ERROR(ssl->error);
17033
0
                    return WOLFSSL_FATAL_ERROR;
17034
0
                }
17035
0
            }
17036
17037
0
            ssl->options.connectState = FIRST_REPLY_DONE;
17038
0
            WOLFSSL_MSG("connect state: FIRST_REPLY_DONE");
17039
0
            FALL_THROUGH;
17040
17041
0
        case FIRST_REPLY_DONE:
17042
0
            if (ssl->options.certOnly)
17043
0
                return WOLFSSL_SUCCESS;
17044
        #ifdef WOLFSSL_EARLY_DATA
17045
            /* Not on the post-handshake auth re-entry: a second
17046
             * EndOfEarlyData restarts the write sequence number at 0. */
17047
            if (!ssl->options.dtls && ssl->earlyData != no_early_data
17048
                && !TLS13_AFTER_HANDSHAKE(ssl) && !WOLFSSL_IS_QUIC(ssl)) {
17049
                if ((ssl->error = SendTls13EndOfEarlyData(ssl)) != 0) {
17050
                    WOLFSSL_ERROR(ssl->error);
17051
                    return WOLFSSL_FATAL_ERROR;
17052
                }
17053
                WOLFSSL_MSG("sent: end_of_early_data");
17054
            }
17055
        #endif
17056
17057
0
            ssl->options.connectState = FIRST_REPLY_FIRST;
17058
0
            WOLFSSL_MSG("connect state: FIRST_REPLY_FIRST");
17059
0
            FALL_THROUGH;
17060
17061
0
        case FIRST_REPLY_FIRST:
17062
        #if defined(WOLFSSL_TLS13_MIDDLEBOX_COMPAT)
17063
            if (!ssl->options.sentChangeCipher && !ssl->options.dtls
17064
                && ssl->options.tls13MiddleBoxCompat) {
17065
                ssl->error = SendChangeCipher(ssl);
17066
                if (ssl->error == 0 ||
17067
                        ssl->error == WC_NO_ERR_TRACE(WANT_WRITE)) {
17068
                    ssl->options.sentChangeCipher = 1;
17069
                }
17070
                if (ssl->error != 0) {
17071
                    WOLFSSL_ERROR(ssl->error);
17072
                    return WOLFSSL_FATAL_ERROR;
17073
                }
17074
            }
17075
        #endif
17076
17077
0
            ssl->options.connectState = FIRST_REPLY_SECOND;
17078
0
            WOLFSSL_MSG("connect state: FIRST_REPLY_SECOND");
17079
0
            FALL_THROUGH;
17080
17081
0
        case FIRST_REPLY_SECOND:
17082
            /* CLIENT: check peer authentication. */
17083
0
            if (!ssl->options.peerAuthGood) {
17084
0
                WOLFSSL_MSG("Server authentication did not happen");
17085
0
                WOLFSSL_ERROR_VERBOSE(WOLFSSL_FATAL_ERROR);
17086
0
                return WOLFSSL_FATAL_ERROR;
17087
0
            }
17088
0
        #ifndef NO_CERTS
17089
0
            if ((!ssl->options.resuming || TLS13_AFTER_HANDSHAKE(ssl)) &&
17090
0
                    ssl->options.sendVerify) {
17091
0
                ssl->error = SendTls13Certificate(ssl);
17092
0
                if (ssl->error != 0) {
17093
0
                    wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
17094
0
                    WOLFSSL_ERROR(ssl->error);
17095
0
                    return WOLFSSL_FATAL_ERROR;
17096
0
                }
17097
0
                WOLFSSL_MSG("sent: certificate");
17098
0
            }
17099
0
        #endif
17100
17101
0
            ssl->options.connectState = FIRST_REPLY_THIRD;
17102
0
            WOLFSSL_MSG("connect state: FIRST_REPLY_THIRD");
17103
0
            FALL_THROUGH;
17104
17105
0
        case FIRST_REPLY_THIRD:
17106
0
        #if (!defined(NO_CERTS) && (!defined(NO_RSA) || defined(HAVE_ECC) || \
17107
0
             defined(HAVE_ED25519) || defined(HAVE_ED448) || \
17108
0
             defined(HAVE_FALCON) || defined(WOLFSSL_HAVE_MLDSA) || \
17109
0
             defined(WOLFSSL_HAVE_SLHDSA))) && \
17110
0
             (!defined(NO_WOLFSSL_SERVER) || !defined(WOLFSSL_NO_CLIENT_AUTH))
17111
0
            if ((!ssl->options.resuming || TLS13_AFTER_HANDSHAKE(ssl)) &&
17112
0
                    ssl->options.sendVerify) {
17113
0
                ssl->error = SendTls13CertificateVerify(ssl);
17114
0
                if (ssl->error != 0) {
17115
0
                    wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
17116
0
                    WOLFSSL_ERROR(ssl->error);
17117
0
                    return WOLFSSL_FATAL_ERROR;
17118
0
                }
17119
0
                WOLFSSL_MSG("sent: certificate verify");
17120
0
            }
17121
0
        #endif
17122
17123
0
            ssl->options.connectState = FIRST_REPLY_FOURTH;
17124
0
            WOLFSSL_MSG("connect state: FIRST_REPLY_FOURTH");
17125
0
            FALL_THROUGH;
17126
17127
0
        case FIRST_REPLY_FOURTH:
17128
0
            if ((ssl->error = SendTls13Finished(ssl)) != 0) {
17129
0
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
17130
0
                WOLFSSL_ERROR(ssl->error);
17131
0
                return WOLFSSL_FATAL_ERROR;
17132
0
            }
17133
0
            WOLFSSL_MSG("sent: finished");
17134
17135
#ifdef WOLFSSL_DTLS13
17136
            ssl->options.connectState = WAIT_FINISHED_ACK;
17137
            WOLFSSL_MSG("connect state: WAIT_FINISHED_ACK");
17138
            FALL_THROUGH;
17139
17140
        case WAIT_FINISHED_ACK:
17141
            if (ssl->options.dtls) {
17142
                while (ssl->options.serverState != SERVER_FINISHED_ACKED) {
17143
                    if ((ssl->error = ProcessReply(ssl)) < 0) {
17144
                        WOLFSSL_ERROR(ssl->error);
17145
                        return WOLFSSL_FATAL_ERROR;
17146
                    }
17147
17148
                    if ((ssl->error = Dtls13DoScheduledWork(ssl)) < 0) {
17149
                        WOLFSSL_ERROR(ssl->error);
17150
                        return WOLFSSL_FATAL_ERROR;
17151
                    }
17152
                }
17153
            }
17154
#endif /* WOLFSSL_DTLS13 */
17155
0
            ssl->options.connectState = FINISHED_DONE;
17156
0
            WOLFSSL_MSG("connect state: FINISHED_DONE");
17157
0
            FALL_THROUGH;
17158
17159
0
        case FINISHED_DONE:
17160
        #if defined(HAVE_ECH)
17161
            /* RFC 9849 s6.1.6: if we offered ECH but the server rejected it,
17162
             * send ech_required alert and abort before returning to the app */
17163
            if (EchRejected(ssl)) {
17164
                if (ssl->echRetryConfigs != NULL) {
17165
                    ssl->options.echRetryConfigsAccepted = 1;
17166
                }
17167
                SendAlert(ssl, alert_fatal, ech_required);
17168
                ssl->error = ECH_REQUIRED_E;
17169
                WOLFSSL_ERROR_VERBOSE(ECH_REQUIRED_E);
17170
                return WOLFSSL_FATAL_ERROR;
17171
            }
17172
        #endif /* HAVE_ECH */
17173
17174
0
        #ifndef NO_HANDSHAKE_DONE_CB
17175
0
            if (ssl->hsDoneCb != NULL) {
17176
0
                int cbret = ssl->hsDoneCb(ssl, ssl->hsDoneCtx);
17177
0
                if (cbret < 0) {
17178
0
                    ssl->error = cbret;
17179
0
                    WOLFSSL_ERROR_VERBOSE(ssl->error);
17180
0
                    WOLFSSL_MSG("HandShake Done Cb don't continue error");
17181
0
                    return WOLFSSL_FATAL_ERROR;
17182
0
                }
17183
0
            }
17184
0
        #endif /* NO_HANDSHAKE_DONE_CB */
17185
17186
0
            if (!ssl->options.keepResources) {
17187
0
                FreeHandshakeResources(ssl);
17188
0
            }
17189
0
        #if defined(WOLFSSL_ASYNC_IO) && !defined(WOLFSSL_ASYNC_CRYPT)
17190
            /* Free the remaining async context if not using it for crypto */
17191
0
            FreeAsyncCtx(ssl, 1);
17192
0
        #endif
17193
17194
        #if defined(HAVE_WRITE_DUP) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
17195
            if (ssl->postHandshakeAuthPublish) {
17196
                ssl->postHandshakeAuthPublish = 0;
17197
                ssl->error = Tls13WriteDupPublishPhaHashes(ssl);
17198
                if (ssl->error != 0) {
17199
                    WOLFSSL_ERROR(ssl->error);
17200
                    return WOLFSSL_FATAL_ERROR;
17201
                }
17202
            }
17203
        #endif
17204
17205
0
            ssl->error = 0; /* clear the error */
17206
17207
0
            WOLFSSL_LEAVE("wolfSSL_connect_TLSv13", WOLFSSL_SUCCESS);
17208
0
            return WOLFSSL_SUCCESS;
17209
17210
0
        default:
17211
0
            WOLFSSL_MSG("Unknown connect state ERROR");
17212
0
            return WOLFSSL_FATAL_ERROR; /* unknown connect state */
17213
0
    }
17214
0
}
17215
#endif
17216
17217
#if defined(WOLFSSL_SEND_HRR_COOKIE)
17218
17219
/* Send a cookie with the HelloRetryRequest to avoid storing state.
17220
 *
17221
 * ssl       SSL/TLS object.
17222
 * secret    Secret to use when generating integrity check for cookie.
17223
 *           A value of NULL indicates to generate a new random secret.
17224
 * secretSz  Size of secret data in bytes.
17225
 *           Use a value of 0 to indicate use of default size.
17226
 * returns BAD_FUNC_ARG when ssl is NULL or not using TLS v1.3, SIDE_ERROR when
17227
 * called on a client, BAD_STATE_E when the DTLS handshake has already decided
17228
 * how to process this ClientHello; WOLFSSL_SUCCESS on success and otherwise
17229
 * failure.
17230
 */
17231
int wolfSSL_send_hrr_cookie(WOLFSSL* ssl, const unsigned char* secret,
17232
                            unsigned int secretSz)
17233
{
17234
#ifndef NO_WOLFSSL_SERVER
17235
    int ret;
17236
#endif
17237
17238
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
17239
        return BAD_FUNC_ARG;
17240
#ifndef NO_WOLFSSL_SERVER
17241
    if (ssl->options.side == WOLFSSL_CLIENT_END)
17242
        return SIDE_ERROR;
17243
    ret = CheckCookieState(ssl);
17244
    if (ret != WOLFSSL_SUCCESS)
17245
        return ret;
17246
17247
    /* On failure the previous secrets and policy are kept. */
17248
    return CookiePolicySet(ssl, secret, secretSz, 1);
17249
#else
17250
    (void)secret;
17251
    (void)secretSz;
17252
    return SIDE_ERROR;
17253
#endif
17254
}
17255
17256
int wolfSSL_disable_hrr_cookie(WOLFSSL* ssl)
17257
{
17258
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
17259
        return BAD_FUNC_ARG;
17260
17261
#ifdef NO_WOLFSSL_SERVER
17262
    return SIDE_ERROR;
17263
#else
17264
    return wolfSSL_disable_cookie(ssl);
17265
#endif /* NO_WOLFSSL_SERVER */
17266
}
17267
17268
/* Set a secondary HelloRetryRequest cookie secret used only when verifying a
17269
 * received cookie, and only if the primary secret (set by
17270
 * wolfSSL_send_hrr_cookie()) fails to verify it.
17271
 *
17272
 * This supports an application-driven cookie-secret rotation on a stateless
17273
 * DTLS 1.3 server: after rotating the primary secret, install the previous
17274
 * secret here so that cookies already issued under it are still accepted for
17275
 * an overlap window.  It is never used to issue cookies.
17276
 *
17277
 * This API is DTLS only - TLS 1.3 over a reliable transport does not operate
17278
 * statelessly across the HelloRetryRequest exchange, so a secondary cookie
17279
 * secret has no use there.
17280
 *
17281
 * ssl       SSL/TLS object.
17282
 * secret    Secondary secret to verify cookies against.  A value of NULL (or a
17283
 *           secretSz of 0) clears any previously set secondary secret.
17284
 * secretSz  Size of secret data in bytes.
17285
 * returns BAD_FUNC_ARG when ssl is NULL, not TLS v1.3 or not DTLS; SIDE_ERROR
17286
 * when called on a client; WOLFSSL_SUCCESS on success and otherwise failure.
17287
 */
17288
int wolfSSL_set_hrr_cookie_secret_secondary(WOLFSSL* ssl,
17289
    const unsigned char* secret, unsigned int secretSz)
17290
{
17291
    int ret;
17292
17293
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
17294
        return BAD_FUNC_ARG;
17295
#ifndef NO_WOLFSSL_SERVER
17296
    if (ssl->options.side == WOLFSSL_CLIENT_END)
17297
        return SIDE_ERROR;
17298
    /* DTLS only - TLS 1.3 does not verify cookies statelessly. */
17299
    if (!ssl->options.dtls) {
17300
        WOLFSSL_MSG("Secondary HRR cookie secret is DTLS only");
17301
        return BAD_FUNC_ARG;
17302
    }
17303
17304
    /* A NULL/empty secret just clears the secondary secret. */
17305
    if (secret == NULL || secretSz == 0) {
17306
        FreeCookieSecret(ssl, &ssl->buffers.tls13CookieSecretSecondary);
17307
        ret = WOLFSSL_SUCCESS;
17308
    }
17309
    else {
17310
        /* The replacement is built before the old secret is dropped, so a
17311
         * failed rotation leaves the secondary secret that was in use. */
17312
        ret = SetCookieSecret(ssl, &ssl->buffers.tls13CookieSecretSecondary,
17313
                secret, secretSz,
17314
                "wolfSSL_set_hrr_cookie_secret_secondary secret");
17315
        if (ret == 0)
17316
            ret = WOLFSSL_SUCCESS;
17317
    }
17318
#else
17319
    (void)secret;
17320
    (void)secretSz;
17321
17322
    ret = SIDE_ERROR;
17323
#endif
17324
17325
    return ret;
17326
}
17327
17328
#endif /* defined(WOLFSSL_SEND_HRR_COOKIE) */
17329
17330
#ifdef HAVE_SUPPORTED_CURVES
17331
/* Create a key share entry from group.
17332
 * Generates a key pair.
17333
 *
17334
 * ssl    The SSL/TLS object.
17335
 * group  The named group.
17336
 * returns 0 on success, otherwise failure.
17337
 *   for async can return WC_PENDING_E and should be called again
17338
 */
17339
int wolfSSL_UseKeyShare(WOLFSSL* ssl, word16 group)
17340
0
{
17341
0
    int ret;
17342
17343
0
    if (ssl == NULL)
17344
0
        return BAD_FUNC_ARG;
17345
17346
#ifdef WOLFSSL_ASYNC_CRYPT
17347
    ret = wolfSSL_AsyncPop(ssl, NULL);
17348
    if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) {
17349
        /* Check for error */
17350
        if (ret < 0)
17351
            return ret;
17352
    }
17353
#endif
17354
17355
0
#if defined(WOLFSSL_HAVE_MLKEM)
17356
0
    if (WOLFSSL_NAMED_GROUP_IS_PQC(group) ||
17357
0
        WOLFSSL_NAMED_GROUP_IS_PQC_HYBRID(group)) {
17358
17359
0
        if (!IsAtLeastTLSv1_3(ssl->version)) {
17360
0
            return BAD_FUNC_ARG;
17361
0
        }
17362
17363
0
        if (ssl->options.side == WOLFSSL_SERVER_END) {
17364
            /* If I am the server of a KEM connection, do not do keygen because
17365
             * I'm going to encapsulate with the client's public key. Note that
17366
             * I might be the client and ssl->option.side has not been properly
17367
             * set yet. In that case the KeyGen operation will be deferred to
17368
             * connection time. */
17369
0
            return WOLFSSL_SUCCESS;
17370
0
        }
17371
0
    }
17372
0
#endif
17373
#if defined(NO_TLS)
17374
    (void)ret;
17375
    (void)group;
17376
#else
17377
    /* Check if the group is supported. */
17378
0
    if (!TLSX_IsGroupSupported(group, ssl->options.side)) {
17379
0
        WOLFSSL_MSG("Group not supported.");
17380
0
        return BAD_FUNC_ARG;
17381
0
    }
17382
17383
0
    ret = TLSX_KeyShare_Use(ssl, group, 0, NULL, NULL, &ssl->extensions);
17384
0
    if (ret != 0)
17385
0
        return ret;
17386
0
#endif /* NO_TLS */
17387
0
    return WOLFSSL_SUCCESS;
17388
0
}
17389
17390
/* Send no key share entries - use HelloRetryRequest to negotiate shared group.
17391
 *
17392
 * ssl    The SSL/TLS object.
17393
 * returns 0 on success, otherwise failure.
17394
 */
17395
int wolfSSL_NoKeyShares(WOLFSSL* ssl)
17396
0
{
17397
0
    int ret;
17398
17399
0
    if (ssl == NULL)
17400
0
        return BAD_FUNC_ARG;
17401
0
    if (ssl->options.side == WOLFSSL_SERVER_END)
17402
0
        return SIDE_ERROR;
17403
#if defined(NO_TLS)
17404
    (void)ret;
17405
#else
17406
0
    ret = TLSX_KeyShare_Empty(ssl);
17407
0
    if (ret != 0)
17408
0
        return ret;
17409
0
#endif /* NO_TLS */
17410
0
    return WOLFSSL_SUCCESS;
17411
0
}
17412
#endif
17413
17414
#ifdef WOLFSSL_DUAL_ALG_CERTS
17415
int wolfSSL_UseCKS(WOLFSSL* ssl, byte *sigSpec, word16 sigSpecSz)
17416
{
17417
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->ctx->method->version) ||
17418
        sigSpec == NULL || sigSpecSz == 0)
17419
        return BAD_FUNC_ARG;
17420
17421
    ssl->sigSpec = sigSpec;
17422
    ssl->sigSpecSz = sigSpecSz;
17423
    return WOLFSSL_SUCCESS;
17424
}
17425
17426
int wolfSSL_CTX_UseCKS(WOLFSSL_CTX* ctx, byte *sigSpec, word16 sigSpecSz)
17427
{
17428
    if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version) ||
17429
        sigSpec == NULL || sigSpecSz == 0)
17430
        return BAD_FUNC_ARG;
17431
17432
    ctx->sigSpec = sigSpec;
17433
    ctx->sigSpecSz = sigSpecSz;
17434
    return WOLFSSL_SUCCESS;
17435
}
17436
#endif /* WOLFSSL_DUAL_ALG_CERTS */
17437
17438
/* Do not send a ticket after TLS v1.3 handshake for resumption.
17439
 *
17440
 * ctx  The SSL/TLS CTX object.
17441
 * returns BAD_FUNC_ARG when ctx is NULL and 0 on success.
17442
 */
17443
int wolfSSL_CTX_no_ticket_TLSv13(WOLFSSL_CTX* ctx)
17444
0
{
17445
0
    if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
17446
0
        return BAD_FUNC_ARG;
17447
0
    if (ctx->method->side == WOLFSSL_CLIENT_END)
17448
0
        return SIDE_ERROR;
17449
17450
#ifdef HAVE_SESSION_TICKET
17451
    ctx->noTicketTls13 = 1;
17452
#endif
17453
17454
0
    return 0;
17455
0
}
17456
17457
/* Do not send a ticket after TLS v1.3 handshake for resumption.
17458
 *
17459
 * ssl  The SSL/TLS object.
17460
 * returns BAD_FUNC_ARG when ssl is NULL, not using TLS v1.3, or called on
17461
 * a client and 0 on success.
17462
 */
17463
int wolfSSL_no_ticket_TLSv13(WOLFSSL* ssl)
17464
0
{
17465
0
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
17466
0
        return BAD_FUNC_ARG;
17467
0
    if (ssl->options.side == WOLFSSL_CLIENT_END)
17468
0
        return SIDE_ERROR;
17469
17470
#ifdef HAVE_SESSION_TICKET
17471
    ssl->options.noTicketTls13 = 1;
17472
#endif
17473
17474
0
    return 0;
17475
0
}
17476
17477
/* Disallow (EC)DHE key exchange when using pre-shared keys.
17478
 *
17479
 * ctx  The SSL/TLS CTX object.
17480
 * returns BAD_FUNC_ARG when ctx is NULL and 0 on success.
17481
 */
17482
int wolfSSL_CTX_no_dhe_psk(WOLFSSL_CTX* ctx)
17483
0
{
17484
0
    if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
17485
0
        return BAD_FUNC_ARG;
17486
17487
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
17488
    ctx->noPskDheKe = 1;
17489
#endif
17490
17491
0
    return 0;
17492
0
}
17493
17494
/* Disallow (EC)DHE key exchange when using pre-shared keys.
17495
 *
17496
 * ssl  The SSL/TLS object.
17497
 * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3 and 0 on
17498
 * success.
17499
 */
17500
int wolfSSL_no_dhe_psk(WOLFSSL* ssl)
17501
0
{
17502
0
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
17503
0
        return BAD_FUNC_ARG;
17504
17505
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
17506
    ssl->options.noPskDheKe = 1;
17507
    ssl->options.noPskDheKePolicy = 1;
17508
#endif
17509
17510
0
    return 0;
17511
0
}
17512
17513
#ifdef HAVE_SUPPORTED_CURVES
17514
/* Only allow (EC)DHE key exchange when using pre-shared keys.
17515
 *
17516
 * ctx  The SSL/TLS CTX object.
17517
 * returns BAD_FUNC_ARG when ctx is NULL and 0 on success.
17518
 */
17519
int wolfSSL_CTX_only_dhe_psk(WOLFSSL_CTX* ctx)
17520
0
{
17521
0
    if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
17522
0
        return BAD_FUNC_ARG;
17523
17524
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
17525
    ctx->onlyPskDheKe = 1;
17526
#endif
17527
17528
0
    return 0;
17529
0
}
17530
17531
/* Only allow (EC)DHE key exchange when using pre-shared keys.
17532
 *
17533
 * ssl  The SSL/TLS object.
17534
 * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3 and 0 on
17535
 * success.
17536
 */
17537
int wolfSSL_only_dhe_psk(WOLFSSL* ssl)
17538
0
{
17539
0
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
17540
0
        return BAD_FUNC_ARG;
17541
17542
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
17543
    ssl->options.onlyPskDheKe = 1;
17544
#endif
17545
17546
0
    return 0;
17547
0
}
17548
#endif /* HAVE_SUPPORTED_CURVES */
17549
17550
/* Require that an external Pre-Shared Key is negotiated for the handshake to
17551
 * succeed. TLS 1.3 / DTLS 1.3 only - in (D)TLS 1.2 the use of a PSK is
17552
 * determined by the negotiated cipher suite, so a mandatory PSK is configured
17553
 * there by restricting the cipher suite list to PSK suites.
17554
 *
17555
 * ctx  The SSL/TLS CTX object.
17556
 * returns BAD_FUNC_ARG when ctx is NULL or not at least TLS v1.3, 0 on success.
17557
 */
17558
int wolfSSL_CTX_require_psk(WOLFSSL_CTX* ctx)
17559
0
{
17560
0
    if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
17561
0
        return BAD_FUNC_ARG;
17562
17563
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
17564
    ctx->failNoPSK = 1;
17565
    /* The requirement can only be enforced for (D)TLS 1.3, so keep it
17566
     * fail-closed by disabling a version downgrade. Otherwise a
17567
     * downgrade-capable context (e.g. from a v23 method) could silently fall
17568
     * back to (D)TLS 1.2 and complete without any PSK. */
17569
    ctx->method->downgrade = 0;
17570
#endif
17571
17572
0
    return 0;
17573
0
}
17574
17575
/* Require that an external Pre-Shared Key is negotiated for the handshake to
17576
 * succeed. See wolfSSL_CTX_require_psk().
17577
 *
17578
 * ssl  The SSL/TLS object.
17579
 * returns BAD_FUNC_ARG when ssl is NULL or not at least TLS v1.3, 0 on success.
17580
 */
17581
int wolfSSL_require_psk(WOLFSSL* ssl)
17582
0
{
17583
0
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
17584
0
        return BAD_FUNC_ARG;
17585
17586
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
17587
    ssl->options.failNoPSK = 1;
17588
    /* See wolfSSL_CTX_require_psk() - keep the requirement fail-closed by
17589
     * disabling a version downgrade to (D)TLS 1.2. */
17590
    ssl->options.downgrade = 0;
17591
#endif
17592
17593
0
    return 0;
17594
0
}
17595
17596
int Tls13UpdateKeys(WOLFSSL* ssl)
17597
0
{
17598
0
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
17599
0
        return BAD_FUNC_ARG;
17600
17601
#ifdef WOLFSSL_QUIC
17602
    /* RFC 9001 Section 6: a QUIC connection must not send a TLS KeyUpdate;
17603
     * key updates are handled at the QUIC packet-protection layer. */
17604
    if (WOLFSSL_IS_QUIC(ssl))
17605
        return BAD_FUNC_ARG;
17606
#endif
17607
17608
#ifdef WOLFSSL_DTLS13
17609
    /* we are already waiting for the ack of a sent key update message. We can't
17610
       send another one before receiving its ack. Either wolfSSL_update_keys()
17611
       was invoked multiple times over a short period of time or we replied to a
17612
       KeyUpdate with update request. We'll just ignore sending this
17613
       KeyUpdate. */
17614
    /* TODO: add WOLFSSL_ERROR_ALREADY_IN_PROGRESS type of error here */
17615
    if (ssl->options.dtls && ssl->dtls13WaitKeyUpdateAck)
17616
        return 0;
17617
#endif /* WOLFSSL_DTLS13 */
17618
17619
0
    return SendTls13KeyUpdate(ssl);
17620
0
}
17621
17622
/* Update the keys for encryption and decryption.
17623
 * If using non-blocking I/O and WOLFSSL_ERROR_WANT_WRITE is returned then
17624
 * calling wolfSSL_write() will have the message sent when ready.
17625
 *
17626
 * ssl  The SSL/TLS object.
17627
 * returns BAD_FUNC_ARG when ssl is NULL, not using TLS v1.3, or running over
17628
 * QUIC (RFC 9001 handles key updates at the QUIC packet-protection layer),
17629
 * WOLFSSL_ERROR_WANT_WRITE when non-blocking I/O is not ready to write,
17630
 * WOLFSSL_SUCCESS on success and otherwise failure.
17631
 */
17632
int wolfSSL_update_keys(WOLFSSL* ssl)
17633
0
{
17634
0
    int ret;
17635
0
    ret = Tls13UpdateKeys(ssl);
17636
0
    if (ret == WC_NO_ERR_TRACE(WANT_WRITE))
17637
0
        ret = WOLFSSL_ERROR_WANT_WRITE;
17638
0
    else if (ret == 0)
17639
0
        ret = WOLFSSL_SUCCESS;
17640
0
    return ret;
17641
0
}
17642
17643
/* Whether a response is waiting for key update request.
17644
 *
17645
 * ssl        The SSL/TLS object.
17646
 * required   0 when no key update response required.
17647
 *            1 when no key update response required.
17648
 * return  0 on success.
17649
 * return  BAD_FUNC_ARG when ssl is NULL or not using TLS v1.3
17650
 */
17651
int wolfSSL_key_update_response(WOLFSSL* ssl, int* required)
17652
0
{
17653
0
    if (required == NULL || ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
17654
0
        return BAD_FUNC_ARG;
17655
17656
0
    *required = ssl->keys.updateResponseReq;
17657
17658
0
    return 0;
17659
0
}
17660
17661
#if !defined(NO_CERTS) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
17662
/* Allow post-handshake authentication in TLS v1.3 connections.
17663
 *
17664
 * ctx  The SSL/TLS CTX object.
17665
 * returns BAD_FUNC_ARG when ctx is NULL, SIDE_ERROR when not a client and
17666
 * 0 on success.
17667
 */
17668
int wolfSSL_CTX_allow_post_handshake_auth(WOLFSSL_CTX* ctx)
17669
{
17670
    if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
17671
        return BAD_FUNC_ARG;
17672
    if (ctx->method->side == WOLFSSL_SERVER_END)
17673
        return SIDE_ERROR;
17674
17675
    ctx->postHandshakeAuth = 1;
17676
17677
    return 0;
17678
}
17679
17680
/* Allow post-handshake authentication in TLS v1.3 connection.
17681
 *
17682
 * ssl  The SSL/TLS object.
17683
 * returns BAD_FUNC_ARG when ssl is NULL, not using TLS v1.3, or running over
17684
 * QUIC, SIDE_ERROR when not a client, BAD_STATE_E when called after the
17685
 * handshake has started, and 0 on success.
17686
 *
17687
 * Must be called before wolfSSL_connect() so the post_handshake_auth
17688
 * extension can be included in the ClientHello.
17689
 */
17690
int wolfSSL_allow_post_handshake_auth(WOLFSSL* ssl)
17691
{
17692
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
17693
        return BAD_FUNC_ARG;
17694
#ifdef WOLFSSL_QUIC
17695
    if (WOLFSSL_IS_QUIC(ssl))
17696
        return BAD_FUNC_ARG;
17697
#endif
17698
    if (ssl->options.side == WOLFSSL_SERVER_END)
17699
        return SIDE_ERROR;
17700
    if (ssl->options.handShakeState != NULL_STATE)
17701
        return BAD_STATE_E;
17702
17703
    ssl->options.postHandshakeAuth = 1;
17704
17705
    return 0;
17706
}
17707
17708
/* Request a certificate of the client.
17709
 * Can be called any time after handshake completion.
17710
 * A maximum of 256 requests can be sent on a connection.
17711
 *
17712
 * ssl  SSL/TLS object.
17713
 */
17714
int wolfSSL_request_certificate(WOLFSSL* ssl)
17715
{
17716
    int         ret;
17717
#ifndef NO_WOLFSSL_SERVER
17718
    CertReqCtx* certReqCtx;
17719
#endif
17720
17721
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
17722
        return BAD_FUNC_ARG;
17723
#ifdef WOLFSSL_QUIC
17724
    if (WOLFSSL_IS_QUIC(ssl))
17725
        return BAD_FUNC_ARG;
17726
#endif
17727
#ifndef NO_WOLFSSL_SERVER
17728
    if (ssl->options.side == WOLFSSL_CLIENT_END)
17729
        return SIDE_ERROR;
17730
    if (ssl->options.handShakeState != HANDSHAKE_DONE)
17731
        return NOT_READY_ERROR;
17732
    if (!ssl->options.postHandshakeAuth)
17733
        return POST_HAND_AUTH_ERROR;
17734
    if (ssl->certReqCtx != NULL) {
17735
        if (ssl->certReqCtx->len != 1)
17736
            return BAD_STATE_E;
17737
        /* We support sending up to 255 certificate requests */
17738
        if (ssl->certReqCtx->ctx == 255)
17739
            return BAD_STATE_E;
17740
    }
17741
17742
    certReqCtx = (CertReqCtx*)XMALLOC(sizeof(CertReqCtx), ssl->heap,
17743
                                                       DYNAMIC_TYPE_TMP_BUFFER);
17744
    if (certReqCtx == NULL)
17745
        return MEMORY_E;
17746
    XMEMSET(certReqCtx, 0, sizeof(CertReqCtx));
17747
    certReqCtx->next = ssl->certReqCtx;
17748
    certReqCtx->len = 1;
17749
    if (certReqCtx->next != NULL)
17750
        certReqCtx->ctx = certReqCtx->next->ctx + 1;
17751
    ssl->certReqCtx = certReqCtx;
17752
17753
    ssl->msgsReceived.got_certificate = 0;
17754
    ssl->msgsReceived.got_certificate_verify = 0;
17755
    ssl->msgsReceived.got_finished = 0;
17756
    /* Each round must prove possession again; these are only ever set to 1. */
17757
    ssl->options.havePeerCert = 0;
17758
    ssl->options.havePeerVerify = 0;
17759
17760
    ret = SendTls13CertificateRequest(ssl, &certReqCtx->ctx, certReqCtx->len);
17761
    /* Nothing follows a post-handshake request, so flush it even if grouped. */
17762
    if (ret == 0 && ssl->options.groupMessages)
17763
        ret = SendBuffered(ssl);
17764
    if (ret == WC_NO_ERR_TRACE(WANT_WRITE))
17765
        ret = WOLFSSL_ERROR_WANT_WRITE;
17766
    else if (ret == 0)
17767
        ret = WOLFSSL_SUCCESS;
17768
#else
17769
    ret = SIDE_ERROR;
17770
#endif
17771
17772
    return ret;
17773
}
17774
#endif /* !NO_CERTS && WOLFSSL_POST_HANDSHAKE_AUTH */
17775
17776
#if !defined(WOLFSSL_NO_SERVER_GROUPS_EXT)
17777
/* Get the preferred key exchange group.
17778
 *
17779
 * ssl  The SSL/TLS object.
17780
 * returns BAD_FUNC_ARG when ssl is NULL or not using TLS v1.3,
17781
 * SIDE_ERROR when not a client, NOT_READY_ERROR when handshake not complete
17782
 * and group number on success.
17783
 */
17784
int wolfSSL_preferred_group(WOLFSSL* ssl)
17785
0
{
17786
0
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
17787
0
        return BAD_FUNC_ARG;
17788
0
#ifndef NO_WOLFSSL_CLIENT
17789
0
    if (ssl->options.side == WOLFSSL_SERVER_END)
17790
0
        return SIDE_ERROR;
17791
0
    if (ssl->options.handShakeState != HANDSHAKE_DONE)
17792
0
        return NOT_READY_ERROR;
17793
17794
0
#ifdef HAVE_SUPPORTED_CURVES
17795
    /* Return supported groups only. */
17796
0
    return TLSX_SupportedCurve_Preferred(ssl, 1);
17797
#else
17798
    return 0;
17799
#endif
17800
#else
17801
    return SIDE_ERROR;
17802
#endif
17803
0
}
17804
#endif
17805
17806
#ifndef NO_PSK
17807
/* Set the PSK callback, that is passed the cipher suite, for a client to use
17808
 * against context object.
17809
 *
17810
 * @param [in, out] ctx  SSL/TLS context object.
17811
 * @param [in]      cb   Client PSK callback passed a cipher suite.
17812
 */
17813
void wolfSSL_CTX_set_psk_client_cs_callback(WOLFSSL_CTX* ctx,
17814
                                            wc_psk_client_cs_callback cb)
17815
{
17816
    WOLFSSL_ENTER("wolfSSL_CTX_set_psk_client_cs_callback");
17817
17818
    if (ctx == NULL)
17819
        return;
17820
17821
    ctx->havePSK = 1;
17822
    ctx->client_psk_cs_cb = cb;
17823
}
17824
17825
/* Set the PSK callback, that is passed the cipher suite, for a client to use
17826
 * against SSL object.
17827
 *
17828
 * @param [in, out] ssl  SSL/TLS object.
17829
 * @param [in]      cb   Client PSK callback passed a cipher suite.
17830
 */
17831
void wolfSSL_set_psk_client_cs_callback(WOLFSSL* ssl,
17832
                                        wc_psk_client_cs_callback cb)
17833
{
17834
    byte haveRSA = 1;
17835
    int  keySz   = 0;
17836
17837
    WOLFSSL_ENTER("wolfSSL_set_psk_client_cs_callback");
17838
17839
    if (ssl == NULL)
17840
        return;
17841
17842
    ssl->options.havePSK = 1;
17843
    ssl->options.client_psk_cs_cb = cb;
17844
17845
    #ifdef NO_RSA
17846
        haveRSA = 0;
17847
    #endif
17848
    #ifndef NO_CERTS
17849
        keySz = ssl->buffers.keySz;
17850
    #endif
17851
    if (AllocateSuites(ssl) != 0)
17852
        return;
17853
    InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE,
17854
               ssl->options.haveDH, ssl->options.haveECDSAsig,
17855
               ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
17856
               ssl->options.useAnon, TRUE, TRUE, TRUE, TRUE, ssl->options.side);
17857
}
17858
17859
/* Set the PSK callback that returns the cipher suite for a client to use
17860
 * against context object.
17861
 *
17862
 * @param [in, out] ctx  SSL/TLS context object.
17863
 * @param [in]      cb   Client PSK callback returning cipher suite.
17864
 */
17865
void wolfSSL_CTX_set_psk_client_tls13_callback(WOLFSSL_CTX* ctx,
17866
                                               wc_psk_client_tls13_callback cb)
17867
{
17868
    WOLFSSL_ENTER("wolfSSL_CTX_set_psk_client_tls13_callback");
17869
17870
    if (ctx == NULL)
17871
        return;
17872
17873
    ctx->havePSK = 1;
17874
    ctx->client_psk_tls13_cb = cb;
17875
}
17876
17877
/* Set the PSK callback that returns the cipher suite for a client to use
17878
 * against SSL object.
17879
 *
17880
 * @param [in, out] ssl  SSL/TLS object.
17881
 * @param [in]      cb   Client PSK callback returning cipher suite.
17882
 */
17883
void wolfSSL_set_psk_client_tls13_callback(WOLFSSL* ssl,
17884
                                           wc_psk_client_tls13_callback cb)
17885
{
17886
    byte haveRSA = 1;
17887
    int  keySz   = 0;
17888
17889
    WOLFSSL_ENTER("wolfSSL_set_psk_client_tls13_callback");
17890
17891
    if (ssl == NULL)
17892
        return;
17893
17894
    ssl->options.havePSK = 1;
17895
    ssl->options.client_psk_tls13_cb = cb;
17896
17897
    #ifdef NO_RSA
17898
        haveRSA = 0;
17899
    #endif
17900
    #ifndef NO_CERTS
17901
        keySz = ssl->buffers.keySz;
17902
    #endif
17903
    if (AllocateSuites(ssl) != 0)
17904
        return;
17905
    InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE,
17906
               ssl->options.haveDH, ssl->options.haveECDSAsig,
17907
               ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
17908
               ssl->options.useAnon, TRUE, TRUE, TRUE, TRUE, ssl->options.side);
17909
}
17910
17911
/* Set the PSK callback that returns the cipher suite for a server to use
17912
 * against context object.
17913
 *
17914
 * @param [in, out] ctx  SSL/TLS context object.
17915
 * @param [in]      cb   Server PSK callback returning cipher suite.
17916
 */
17917
void wolfSSL_CTX_set_psk_server_tls13_callback(WOLFSSL_CTX* ctx,
17918
                                               wc_psk_server_tls13_callback cb)
17919
{
17920
    WOLFSSL_ENTER("wolfSSL_CTX_set_psk_server_tls13_callback");
17921
    if (ctx == NULL)
17922
        return;
17923
    ctx->havePSK = 1;
17924
    ctx->server_psk_tls13_cb = cb;
17925
}
17926
17927
/* Set the PSK callback that returns the cipher suite for a server to use
17928
 * against SSL object.
17929
 *
17930
 * @param [in, out] ssl  SSL/TLS object.
17931
 * @param [in]      cb   Server PSK callback returning cipher suite.
17932
 */
17933
void wolfSSL_set_psk_server_tls13_callback(WOLFSSL* ssl,
17934
                                           wc_psk_server_tls13_callback cb)
17935
{
17936
    byte haveRSA = 1;
17937
    int  keySz   = 0;
17938
17939
    WOLFSSL_ENTER("wolfSSL_set_psk_server_tls13_callback");
17940
    if (ssl == NULL)
17941
        return;
17942
17943
    ssl->options.havePSK = 1;
17944
    ssl->options.server_psk_tls13_cb = cb;
17945
17946
    #ifdef NO_RSA
17947
        haveRSA = 0;
17948
    #endif
17949
    #ifndef NO_CERTS
17950
        keySz = ssl->buffers.keySz;
17951
    #endif
17952
    if (AllocateSuites(ssl) != 0)
17953
        return;
17954
    InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE,
17955
               ssl->options.haveDH, ssl->options.haveECDSAsig,
17956
               ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
17957
               ssl->options.useAnon, TRUE, TRUE, TRUE, TRUE, ssl->options.side);
17958
}
17959
17960
/* Get name of first supported cipher suite that uses the hash indicated.
17961
 *
17962
 * @param [in] ssl   SSL/TLS object.
17963
 * @param [in] hash  Name of hash algorithm. e.g. "SHA256", "SHA384"
17964
 * @return  Name of cipher suite.
17965
 * @return  NULL on failure.
17966
 */
17967
const char* wolfSSL_get_cipher_name_by_hash(WOLFSSL* ssl, const char* hash)
17968
{
17969
    const char* name = NULL;
17970
    byte mac = no_mac;
17971
    int i;
17972
    const Suites* suites;
17973
17974
    if (hash == NULL || ssl == NULL ||
17975
        (ssl->suites == NULL && ssl->ctx == NULL))
17976
        return NULL;
17977
17978
    suites = WOLFSSL_SUITES(ssl);
17979
    if (suites == NULL)
17980
        return NULL;
17981
17982
    if (XSTRCMP(hash, "SHA256") == 0) {
17983
        mac = sha256_mac;
17984
    }
17985
    else if (XSTRCMP(hash, "SHA384") == 0) {
17986
        mac = sha384_mac;
17987
    }
17988
    if (mac != no_mac) {
17989
        for (i = 0; i < suites->suiteSz; i += 2) {
17990
            if (SuiteMac(suites->suites + i) == mac) {
17991
                name = GetCipherNameInternal(suites->suites[i + 0],
17992
                                             suites->suites[i + 1]);
17993
                break;
17994
            }
17995
        }
17996
    }
17997
    return name;
17998
}
17999
#endif /* !NO_PSK */
18000
18001
18002
#ifndef NO_WOLFSSL_SERVER
18003
18004
/* Send the RFC 8446 Appendix D.4 ChangeCipherSpec a server owes a client that
18005
 * offered a non-empty legacy_session_id.
18006
 *
18007
 * ssl    The SSL/TLS object.
18008
 * flush  Force the record out on its own. A HelloRetryRequest needs this
18009
 *        because SendTls13ServerHello has already sent it, unlike a
18010
 *        ServerHello, which waits for the rest of its flight.
18011
 * returns 0 on success.
18012
 */
18013
static int SendTls13ServerChangeCipher(WOLFSSL* ssl, int flush)
18014
0
{
18015
0
    int ret;
18016
18017
    /* DoTls13ClientHello clears tls13MiddleBoxCompat for a QUIC peer, so the
18018
     * check here is a local backstop, 0 when QUIC is not built. */
18019
0
    if (ssl->options.dtls || WOLFSSL_IS_QUIC(ssl)
18020
0
            || !ssl->options.tls13MiddleBoxCompat
18021
0
            || ssl->options.sentChangeCipher) {
18022
0
        return 0;
18023
0
    }
18024
18025
0
    ret = SendChangeCipher(ssl);
18026
    /* A short send leaves the record queued in the output buffer. Mark it sent
18027
     * anyway, or the resumed accept, which comes back in at the ServerHello
18028
     * case, puts a second record on the wire. */
18029
0
    if (ret == 0 || ret == WC_NO_ERR_TRACE(WANT_WRITE))
18030
0
        ssl->options.sentChangeCipher = 1;
18031
0
    if (ret == 0 && flush && ssl->options.groupMessages)
18032
0
        ret = SendBuffered(ssl);
18033
18034
0
    return ret;
18035
0
}
18036
18037
/* The server accepting a connection from a client.
18038
 * The protocol version is expecting to be TLS v1.3.
18039
 * If the client downgrades, and older versions of the protocol are compiled
18040
 * in, the server will fallback to wolfSSL_accept().
18041
 * Please see note at top of README if you get an error from accept.
18042
 *
18043
 * ssl  The SSL/TLS object.
18044
 * returns WOLFSSL_SUCCESS on successful handshake, WOLFSSL_FATAL_ERROR when
18045
 * unrecoverable error occurs and 0 otherwise.
18046
 * For more error information use wolfSSL_get_error().
18047
 */
18048
int wolfSSL_accept_TLSv13(WOLFSSL* ssl)
18049
0
{
18050
#if !defined(NO_CERTS) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
18051
    word16 havePSK = 0;
18052
#endif
18053
0
    int ret = 0;
18054
18055
0
    WOLFSSL_ENTER("wolfSSL_accept_TLSv13");
18056
18057
0
#ifdef HAVE_ERRNO_H
18058
0
    errno = 0;
18059
0
#endif
18060
18061
0
    if (ssl == NULL)
18062
0
        return WOLFSSL_FATAL_ERROR;
18063
18064
#if !defined(NO_CERTS) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
18065
    havePSK = ssl->options.havePSK;
18066
#endif
18067
18068
0
    if (ssl->options.side != WOLFSSL_SERVER_END) {
18069
0
        ssl->error = SIDE_ERROR;
18070
0
        WOLFSSL_ERROR(ssl->error);
18071
0
        return WOLFSSL_FATAL_ERROR;
18072
0
    }
18073
18074
    /* make sure this wolfSSL object has arrays and rng setup. Protects
18075
     * case where the WOLFSSL object is reused via wolfSSL_clear() */
18076
0
    if ((ret = ReinitSSL(ssl, ssl->ctx, 0)) != 0) {
18077
0
        return ret;
18078
0
    }
18079
18080
#ifdef WOLFSSL_DTLS
18081
    if (ssl->version.major == DTLS_MAJOR) {
18082
        ssl->options.dtls   = 1;
18083
        if (!IsDtlsNotSctpMode(ssl) || !ssl->options.sendCookie)
18084
            ssl->options.dtlsStateful = 1;
18085
    #ifdef HAVE_ECH
18086
        if (!ssl->options.disableECH && ssl->ctx->echConfigs != NULL) {
18087
            WOLFSSL_MSG("ECH configs set but ECH is not supported with DTLS");
18088
            ssl->error = BAD_STATE_E;
18089
            WOLFSSL_ERROR(ssl->error);
18090
            return WOLFSSL_FATAL_ERROR;
18091
        }
18092
    #endif
18093
    }
18094
#endif
18095
18096
#ifdef WOLFSSL_WOLFSENTRY_HOOKS
18097
    if ((ssl->AcceptFilter != NULL) &&
18098
            ((ssl->options.acceptState == TLS13_ACCEPT_BEGIN)
18099
#ifdef HAVE_SECURE_RENEGOTIATION
18100
             || (ssl->options.acceptState == TLS13_ACCEPT_BEGIN_RENEG)
18101
#endif
18102
                ))
18103
    {
18104
        wolfSSL_netfilter_decision_t res;
18105
        if ((ssl->AcceptFilter(ssl, ssl->AcceptFilter_arg, &res) ==
18106
             WOLFSSL_SUCCESS) &&
18107
            (res == WOLFSSL_NETFILTER_REJECT)) {
18108
            ssl->error = SOCKET_FILTERED_E;
18109
            WOLFSSL_ERROR(ssl->error);
18110
            return WOLFSSL_FATAL_ERROR;
18111
        }
18112
    }
18113
#endif /* WOLFSSL_WOLFSENTRY_HOOKS */
18114
18115
0
#ifndef NO_CERTS
18116
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
18117
    if (!havePSK)
18118
#endif
18119
0
    {
18120
    #if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) || \
18121
        defined(WOLFSSL_NGINX) || defined (WOLFSSL_HAPROXY)
18122
        if (ssl->ctx->certSetupCb != NULL) {
18123
            WOLFSSL_MSG("CertSetupCb set. server cert and "
18124
                        "key not checked");
18125
        }
18126
        else
18127
    #endif
18128
0
        {
18129
0
            if (!ssl->buffers.certificate ||
18130
0
                !ssl->buffers.certificate->buffer) {
18131
18132
0
                WOLFSSL_MSG("accept error: server cert required");
18133
0
                ssl->error = NO_PRIVATE_KEY;
18134
0
                WOLFSSL_ERROR(ssl->error);
18135
0
                return WOLFSSL_FATAL_ERROR;
18136
0
            }
18137
18138
0
            if (!ssl->buffers.key || !ssl->buffers.key->buffer) {
18139
                /* allow no private key if using existing key */
18140
            #ifdef WOLF_PRIVATE_KEY_ID
18141
                if (ssl->devId != INVALID_DEVID
18142
                #ifdef HAVE_PK_CALLBACKS
18143
                    || wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)
18144
                #endif
18145
                ) {
18146
                    WOLFSSL_MSG("Allowing no server private key (external)");
18147
                }
18148
                else
18149
            #endif
18150
0
                {
18151
0
                    WOLFSSL_MSG("accept error: server key required");
18152
0
                    ssl->error = NO_PRIVATE_KEY;
18153
0
                    WOLFSSL_ERROR(ssl->error);
18154
0
                    return WOLFSSL_FATAL_ERROR;
18155
0
                }
18156
0
            }
18157
0
        }
18158
0
    }
18159
0
#endif /* NO_CERTS */
18160
18161
0
    if (ssl->buffers.outputBuffer.length > 0
18162
    #ifdef WOLFSSL_HAVE_HS_SUSPEND
18163
        /* do not send buffered or advance state if the last error suspended
18164
           the handshake - advancing frees the saved state */
18165
        && !IsHsSuspendErr(ssl->error)
18166
    #endif
18167
0
    ) {
18168
18169
        /* fragOffset is non-zero when sending fragments. On the last
18170
         * fragment, fragOffset is zero again, and the state can be
18171
         * advanced. */
18172
0
        int advanceState =
18173
0
            (ssl->options.acceptState == TLS13_ACCEPT_CLIENT_HELLO_DONE ||
18174
0
                ssl->options.acceptState ==
18175
0
                    TLS13_ACCEPT_HELLO_RETRY_REQUEST_DONE ||
18176
0
                ssl->options.acceptState == TLS13_ACCEPT_SECOND_REPLY_DONE ||
18177
0
                ssl->options.acceptState == TLS13_SERVER_HELLO_SENT ||
18178
0
                ssl->options.acceptState == TLS13_ACCEPT_THIRD_REPLY_DONE ||
18179
0
                ssl->options.acceptState == TLS13_SERVER_EXTENSIONS_SENT ||
18180
0
                ssl->options.acceptState == TLS13_CERT_REQ_SENT ||
18181
0
                ssl->options.acceptState == TLS13_CERT_SENT ||
18182
0
                ssl->options.acceptState == TLS13_CERT_VERIFY_SENT ||
18183
0
                ssl->options.acceptState == TLS13_ACCEPT_FINISHED_SENT ||
18184
0
                ssl->options.acceptState == TLS13_ACCEPT_FINISHED_DONE);
18185
18186
#ifdef WOLFSSL_DTLS13
18187
        if (ssl->options.dtls)
18188
            advanceState = advanceState && !ssl->dtls13SendingFragments
18189
                && !ssl->dtls13SendingAckOrRtx;
18190
#endif /* WOLFSSL_DTLS13 */
18191
18192
0
        ret = SendBuffered(ssl);
18193
0
        if (ret == 0) {
18194
0
            if (ssl->fragOffset == 0 && !ssl->options.buildingMsg) {
18195
0
                if (advanceState) {
18196
0
                    ssl->options.acceptState++;
18197
0
                    WOLFSSL_MSG("accept state: "
18198
0
                                "Advanced from last buffered fragment send");
18199
0
#ifdef WOLFSSL_ASYNC_IO
18200
0
                    FreeAsyncCtx(ssl, 0);
18201
0
#endif
18202
0
                }
18203
0
            }
18204
0
            else {
18205
0
                WOLFSSL_MSG("accept state: "
18206
0
                            "Not advanced, more fragments to send");
18207
0
            }
18208
18209
#ifdef WOLFSSL_DTLS13
18210
            if (ssl->options.dtls)
18211
                ssl->dtls13SendingAckOrRtx = 0;
18212
#endif /* WOLFSSL_DTLS13 */
18213
18214
0
        }
18215
0
        else {
18216
0
            ssl->error = ret;
18217
0
            WOLFSSL_ERROR(ssl->error);
18218
0
            return WOLFSSL_FATAL_ERROR;
18219
0
        }
18220
0
    }
18221
18222
0
    ret = RetrySendAlert(ssl);
18223
0
    if (ret != 0) {
18224
0
        ssl->error = ret;
18225
0
        WOLFSSL_ERROR(ssl->error);
18226
0
        return WOLFSSL_FATAL_ERROR;
18227
0
    }
18228
#ifdef WOLFSSL_DTLS13
18229
    if (ssl->options.dtls && ssl->dtls13SendingFragments) {
18230
        if ((ssl->error = Dtls13FragmentsContinue(ssl)) != 0) {
18231
                WOLFSSL_ERROR(ssl->error);
18232
                return WOLFSSL_FATAL_ERROR;
18233
        }
18234
18235
        /* we sent all the fragments. Advance state. */
18236
        ssl->options.acceptState++;
18237
    }
18238
#endif /* WOLFSSL_DTLS13 */
18239
18240
0
    switch (ssl->options.acceptState) {
18241
18242
#ifdef HAVE_SECURE_RENEGOTIATION
18243
        case TLS13_ACCEPT_BEGIN_RENEG:
18244
#endif
18245
0
        case TLS13_ACCEPT_BEGIN :
18246
            /* get client_hello */
18247
18248
0
            while (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
18249
0
                if ((ssl->error = ProcessReply(ssl)) < 0) {
18250
0
                    WOLFSSL_ERROR(ssl->error);
18251
0
                    return WOLFSSL_FATAL_ERROR;
18252
0
                }
18253
18254
#ifdef WOLFSSL_DTLS13
18255
                if (ssl->options.dtls) {
18256
                    if ((ssl->error = Dtls13DoScheduledWork(ssl)) < 0) {
18257
                        WOLFSSL_ERROR(ssl->error);
18258
                        return WOLFSSL_FATAL_ERROR;
18259
                    }
18260
                }
18261
#endif /* WOLFSSL_DTLS13 */
18262
18263
0
            }
18264
18265
#ifdef WOLFSSL_DTLS13
18266
            /* Notify once at the first CH transition, not while reassembling
18267
             * or processing the second CH after a key-share HRR. */
18268
            if (ssl->options.acceptState == TLS13_ACCEPT_BEGIN) {
18269
                if ((ssl->error = DtlsNoCookieChGood(ssl)) < 0) {
18270
                    WOLFSSL_ERROR(ssl->error);
18271
                    return WOLFSSL_FATAL_ERROR;
18272
                }
18273
            }
18274
#endif
18275
0
            ssl->options.acceptState = TLS13_ACCEPT_CLIENT_HELLO_DONE;
18276
0
            WOLFSSL_MSG("accept state ACCEPT_CLIENT_HELLO_DONE");
18277
0
            if (!IsAtLeastTLSv1_3(ssl->version))
18278
0
                return wolfSSL_accept(ssl);
18279
0
            FALL_THROUGH;
18280
18281
0
        case TLS13_ACCEPT_CLIENT_HELLO_DONE :
18282
0
            if (ssl->options.serverState ==
18283
0
                                          SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
18284
0
                if ((ssl->error = SendTls13ServerHello(ssl,
18285
0
                                                   hello_retry_request)) != 0) {
18286
0
                    WOLFSSL_ERROR(ssl->error);
18287
0
                    return WOLFSSL_FATAL_ERROR;
18288
0
                }
18289
0
            }
18290
18291
0
            ssl->options.acceptState = TLS13_ACCEPT_HELLO_RETRY_REQUEST_DONE;
18292
0
            WOLFSSL_MSG("accept state ACCEPT_HELLO_RETRY_REQUEST_DONE");
18293
0
            FALL_THROUGH;
18294
18295
0
        case TLS13_ACCEPT_HELLO_RETRY_REQUEST_DONE :
18296
0
            if (ssl->options.serverState ==
18297
0
                                          SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
18298
0
                ssl->error = SendTls13ServerChangeCipher(ssl, 1);
18299
0
                if (ssl->error != 0) {
18300
0
                    WOLFSSL_ERROR(ssl->error);
18301
0
                    return WOLFSSL_FATAL_ERROR;
18302
0
                }
18303
0
            }
18304
0
            ssl->options.acceptState = TLS13_ACCEPT_FIRST_REPLY_DONE;
18305
0
            WOLFSSL_MSG("accept state ACCEPT_FIRST_REPLY_DONE");
18306
0
            FALL_THROUGH;
18307
18308
0
        case TLS13_ACCEPT_FIRST_REPLY_DONE :
18309
0
            if (ssl->options.serverState ==
18310
0
                                          SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
18311
0
                ssl->options.clientState = CLIENT_HELLO_RETRY;
18312
0
                while (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
18313
0
                    if ((ssl->error = ProcessReply(ssl)) < 0) {
18314
0
                        WOLFSSL_ERROR(ssl->error);
18315
0
                        return WOLFSSL_FATAL_ERROR;
18316
0
                    }
18317
18318
#ifdef WOLFSSL_DTLS13
18319
                if (ssl->options.dtls) {
18320
                    if ((ssl->error = Dtls13DoScheduledWork(ssl)) < 0) {
18321
                        WOLFSSL_ERROR(ssl->error);
18322
                        return WOLFSSL_FATAL_ERROR;
18323
                    }
18324
                }
18325
#endif /* WOLFSSL_DTLS13 */
18326
18327
0
                }
18328
0
            }
18329
18330
0
            ssl->options.acceptState = TLS13_ACCEPT_SECOND_REPLY_DONE;
18331
0
            WOLFSSL_MSG("accept state ACCEPT_SECOND_REPLY_DONE");
18332
0
            FALL_THROUGH;
18333
18334
0
        case TLS13_ACCEPT_SECOND_REPLY_DONE :
18335
0
            if (ssl->options.returnOnGoodCh) {
18336
                /* Higher level in stack wants us to return. Simulate a
18337
                 * WANT_WRITE to accomplish this. */
18338
0
                ssl->error = WANT_WRITE;
18339
0
                return WOLFSSL_FATAL_ERROR;
18340
0
            }
18341
18342
0
            if ((ssl->error = SendTls13ServerHello(ssl, server_hello)) != 0) {
18343
0
                WOLFSSL_ERROR(ssl->error);
18344
0
                return WOLFSSL_FATAL_ERROR;
18345
0
            }
18346
0
            ssl->options.acceptState = TLS13_SERVER_HELLO_SENT;
18347
0
            WOLFSSL_MSG("accept state SERVER_HELLO_SENT");
18348
0
            FALL_THROUGH;
18349
18350
0
        case TLS13_SERVER_HELLO_SENT :
18351
0
            ssl->error = SendTls13ServerChangeCipher(ssl, 0);
18352
0
            if (ssl->error != 0) {
18353
0
                WOLFSSL_ERROR(ssl->error);
18354
0
                return WOLFSSL_FATAL_ERROR;
18355
0
            }
18356
18357
0
            ssl->options.acceptState = TLS13_ACCEPT_THIRD_REPLY_DONE;
18358
0
            WOLFSSL_MSG("accept state ACCEPT_THIRD_REPLY_DONE");
18359
0
            FALL_THROUGH;
18360
18361
0
        case TLS13_ACCEPT_THIRD_REPLY_DONE :
18362
0
    #ifdef HAVE_SUPPORTED_CURVES
18363
        #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
18364
            if (!ssl->options.noPskDheKe)
18365
        #endif
18366
0
            {
18367
0
                ssl->error = TLSX_KeyShare_DeriveSecret(ssl);
18368
0
                if (ssl->error != 0)
18369
0
                    return WOLFSSL_FATAL_ERROR;
18370
0
            }
18371
0
    #endif
18372
18373
0
            if ((ssl->error = SendTls13EncryptedExtensions(ssl)) != 0) {
18374
0
                WOLFSSL_ERROR(ssl->error);
18375
0
                return WOLFSSL_FATAL_ERROR;
18376
0
            }
18377
0
            ssl->options.acceptState = TLS13_SERVER_EXTENSIONS_SENT;
18378
0
            WOLFSSL_MSG("accept state SERVER_EXTENSIONS_SENT");
18379
0
            FALL_THROUGH;
18380
18381
0
        case TLS13_SERVER_EXTENSIONS_SENT :
18382
0
#ifndef NO_CERTS
18383
0
            if (!ssl->options.resuming) {
18384
0
                if (ssl->options.verifyPeer && !ssl->options.usingPSK_cipher
18385
    #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
18386
                    && !ssl->options.verifyPostHandshake
18387
    #endif
18388
0
                   ) {
18389
0
                    ssl->error = SendTls13CertificateRequest(ssl, NULL, 0);
18390
0
                    if (ssl->error != 0) {
18391
0
                        WOLFSSL_ERROR(ssl->error);
18392
0
                        return WOLFSSL_FATAL_ERROR;
18393
0
                    }
18394
0
                }
18395
0
                else {
18396
                    /* SERVER: Peer auth good if not verifying client. */
18397
0
                    ssl->options.peerAuthGood = 1;
18398
0
                }
18399
0
            }
18400
0
#endif
18401
0
            ssl->options.acceptState = TLS13_CERT_REQ_SENT;
18402
0
            WOLFSSL_MSG("accept state CERT_REQ_SENT");
18403
0
            FALL_THROUGH;
18404
18405
0
        case TLS13_CERT_REQ_SENT :
18406
0
#ifndef NO_CERTS
18407
0
            if (!ssl->options.resuming && ssl->options.sendVerify) {
18408
0
                if ((ssl->error = SendTls13Certificate(ssl)) != 0) {
18409
0
                    WOLFSSL_ERROR(ssl->error);
18410
0
                    return WOLFSSL_FATAL_ERROR;
18411
0
                }
18412
0
            }
18413
0
#endif
18414
0
            ssl->options.acceptState = TLS13_CERT_SENT;
18415
0
            WOLFSSL_MSG("accept state CERT_SENT");
18416
0
            FALL_THROUGH;
18417
18418
0
        case TLS13_CERT_SENT :
18419
0
#if !defined(NO_CERTS) && (!defined(NO_RSA) || defined(HAVE_ECC) || \
18420
0
     defined(HAVE_ED25519) || defined(HAVE_ED448) || defined(HAVE_FALCON) || \
18421
0
     defined(WOLFSSL_HAVE_MLDSA) || defined(WOLFSSL_HAVE_SLHDSA))
18422
0
            if (!ssl->options.resuming && ssl->options.sendVerify) {
18423
0
                if ((ssl->error = SendTls13CertificateVerify(ssl)) != 0) {
18424
0
                    WOLFSSL_ERROR(ssl->error);
18425
0
                    return WOLFSSL_FATAL_ERROR;
18426
0
                }
18427
0
            }
18428
0
#endif
18429
0
            ssl->options.acceptState = TLS13_CERT_VERIFY_SENT;
18430
0
            WOLFSSL_MSG("accept state CERT_VERIFY_SENT");
18431
0
            FALL_THROUGH;
18432
18433
0
        case TLS13_CERT_VERIFY_SENT :
18434
0
            if ((ssl->error = SendTls13Finished(ssl)) != 0) {
18435
0
                WOLFSSL_ERROR(ssl->error);
18436
0
                return WOLFSSL_FATAL_ERROR;
18437
0
            }
18438
18439
0
            ssl->options.acceptState = TLS13_ACCEPT_FINISHED_SENT;
18440
0
            WOLFSSL_MSG("accept state ACCEPT_FINISHED_SENT");
18441
0
            FALL_THROUGH;
18442
18443
0
        case TLS13_ACCEPT_FINISHED_SENT:
18444
#ifdef WOLFSSL_EARLY_DATA
18445
            if (ssl->earlyData != no_early_data &&
18446
                    ssl->options.handShakeState != SERVER_FINISHED_COMPLETE) {
18447
                ssl->options.handShakeState = SERVER_FINISHED_COMPLETE;
18448
                return WOLFSSL_SUCCESS;
18449
            }
18450
#endif
18451
#ifdef HAVE_SESSION_TICKET
18452
    #ifdef WOLFSSL_TLS13_TICKET_BEFORE_FINISHED
18453
            if ((!ssl->options.verifyPeer || ssl->options.usingPSK_cipher) &&
18454
                    !ssl->options.noTicketTls13 &&
18455
                    ssl->ctx->ticketEncCb != NULL &&
18456
                    ssl->options.maxTicketTls13 > 0) {
18457
                if ((ssl->error = SendTls13NewSessionTicket(ssl)) != 0) {
18458
                    WOLFSSL_ERROR(ssl->error);
18459
                    return WOLFSSL_FATAL_ERROR;
18460
                }
18461
                ssl->options.ticketsSent = 1;
18462
            }
18463
    #endif
18464
#endif /* HAVE_SESSION_TICKET */
18465
0
            ssl->options.acceptState = TLS13_PRE_TICKET_SENT;
18466
0
            WOLFSSL_MSG("accept state  TICKET_SENT");
18467
0
            FALL_THROUGH;
18468
18469
0
        case TLS13_PRE_TICKET_SENT :
18470
0
            while (ssl->options.clientState < CLIENT_FINISHED_COMPLETE) {
18471
0
                if ( (ssl->error = ProcessReply(ssl)) < 0) {
18472
0
                        WOLFSSL_ERROR(ssl->error);
18473
0
                        return WOLFSSL_FATAL_ERROR;
18474
0
                    }
18475
18476
#ifdef WOLFSSL_DTLS13
18477
                if (ssl->options.dtls) {
18478
                    if ((ssl->error = Dtls13DoScheduledWork(ssl)) < 0) {
18479
                        WOLFSSL_ERROR(ssl->error);
18480
                        return WOLFSSL_FATAL_ERROR;
18481
                    }
18482
                }
18483
#endif /* WOLFSSL_DTLS13 */
18484
0
            }
18485
18486
            /* Finish a key schedule the Finished handler left pending:
18487
             * it must complete before this side's sends advance the
18488
             * transcript the traffic secrets hash. */
18489
0
            if (ssl->kdfMsgStep > 0) {
18490
0
                ssl->error = DoTls13MsgDerives(ssl, ssl->kdfMsgType);
18491
0
                if (ssl->error != 0) {
18492
0
                    WOLFSSL_ERROR(ssl->error);
18493
0
                    return WOLFSSL_FATAL_ERROR;
18494
0
                }
18495
0
            }
18496
18497
0
            ssl->options.acceptState = TLS13_ACCEPT_FINISHED_DONE;
18498
0
            WOLFSSL_MSG("accept state ACCEPT_FINISHED_DONE");
18499
0
            FALL_THROUGH;
18500
18501
0
        case TLS13_ACCEPT_FINISHED_DONE :
18502
            /* SERVER: When not resuming and verifying peer but no certificate
18503
             * received and none was required then peer auth good.
18504
             */
18505
0
            if (!ssl->options.resuming && ssl->options.verifyPeer &&
18506
        #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
18507
                !ssl->options.verifyPostHandshake &&
18508
        #endif
18509
0
                !ssl->options.havePeerCert &&
18510
0
                !ClientAuthRequired(ssl, ssl->options.usingPSK_cipher)) {
18511
0
                ssl->options.peerAuthGood = 1;
18512
0
            }
18513
            /* SERVER: check peer authentication. */
18514
0
            if (!ssl->options.peerAuthGood) {
18515
0
                WOLFSSL_MSG("Client authentication did not happen");
18516
0
                return WOLFSSL_FATAL_ERROR;
18517
0
            }
18518
#ifdef HAVE_SESSION_TICKET
18519
            while (ssl->options.ticketsSent < ssl->options.maxTicketTls13) {
18520
                if (!ssl->options.noTicketTls13 && ssl->ctx->ticketEncCb
18521
                        != NULL) {
18522
                    if ((ssl->error = SendTls13NewSessionTicket(ssl)) != 0) {
18523
                        WOLFSSL_ERROR(ssl->error);
18524
                        return WOLFSSL_FATAL_ERROR;
18525
                    }
18526
                }
18527
                ssl->options.ticketsSent++;
18528
18529
                /* only one session ticket is sent on session resumption */
18530
                if (ssl->options.resuming) {
18531
                    break;
18532
                }
18533
            }
18534
#endif /* HAVE_SESSION_TICKET */
18535
0
            ssl->options.acceptState = TLS13_TICKET_SENT;
18536
0
            WOLFSSL_MSG("accept state TICKET_SENT");
18537
0
            FALL_THROUGH;
18538
18539
0
        case TLS13_TICKET_SENT :
18540
0
#ifndef NO_HANDSHAKE_DONE_CB
18541
0
            if (ssl->hsDoneCb) {
18542
0
                int cbret = ssl->hsDoneCb(ssl, ssl->hsDoneCtx);
18543
0
                if (cbret < 0) {
18544
0
                    ssl->error = cbret;
18545
0
                    WOLFSSL_MSG("HandShake Done Cb don't continue error");
18546
0
                    return WOLFSSL_FATAL_ERROR;
18547
0
                }
18548
0
            }
18549
0
#endif /* NO_HANDSHAKE_DONE_CB */
18550
18551
0
            if (!ssl->options.keepResources) {
18552
0
                FreeHandshakeResources(ssl);
18553
0
            }
18554
18555
#ifdef WOLFSSL_HAVE_HS_SUSPEND
18556
            /* A post-handshake Certificate may be suspended in ssl->async.
18557
             * Keep it and the error so wolfSSL_read() can resume it. */
18558
            if (!IsHsSuspendErr(ssl->error))
18559
#endif
18560
0
            {
18561
0
#if defined(WOLFSSL_ASYNC_IO) && !defined(WOLFSSL_ASYNC_CRYPT)
18562
                /* Free the remaining async context if not using it for
18563
                 * crypto */
18564
0
                FreeAsyncCtx(ssl, 1);
18565
0
#endif
18566
0
                ssl->error = 0; /* clear the error */
18567
0
            }
18568
18569
0
            WOLFSSL_LEAVE("wolfSSL_accept", WOLFSSL_SUCCESS);
18570
0
            return WOLFSSL_SUCCESS;
18571
18572
0
        default:
18573
0
            WOLFSSL_MSG("Unknown accept state ERROR");
18574
0
            return WOLFSSL_FATAL_ERROR;
18575
0
    }
18576
0
}
18577
#endif
18578
18579
#if !defined(NO_WOLFSSL_SERVER) && defined(HAVE_SESSION_TICKET)
18580
/* Server sends a session ticket to the peer.
18581
 *
18582
 * RFC 8446, section 4.6.1, para 1.
18583
 *
18584
 * ssl  The SSL/TLS object.
18585
 * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3,
18586
 *         SIDE_ERROR when not a server,
18587
 *         NOT_READY_ERROR when handshake not complete,
18588
 *         MISSING_HANDSHAKE_DATA when the ClientHello had no
18589
 *         psk_key_exchange_modes extension and
18590
 *         WOLFSSL_TLS13_TICKET_CHECK_PSK_MODES is defined,
18591
 *         PSK_KEY_ERROR when no advertised PSK key exchange mode is usable and
18592
 *         WOLFSSL_TLS13_TICKET_CHECK_PSK_MODES is defined,
18593
 *         WOLFSSL_FATAL_ERROR when creating or sending message fails, and
18594
 *         WOLFSSL_SUCCESS on success.
18595
 */
18596
int wolfSSL_send_SessionTicket(WOLFSSL* ssl)
18597
{
18598
    int ret;
18599
18600
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
18601
        return BAD_FUNC_ARG;
18602
    if (ssl->options.side == WOLFSSL_CLIENT_END)
18603
        return SIDE_ERROR;
18604
    if (ssl->options.handShakeState != HANDSHAKE_DONE)
18605
        return NOT_READY_ERROR;
18606
    ret = CheckTls13TicketPskModes(ssl);
18607
    if (ret != 0) {
18608
        WOLFSSL_ERROR_VERBOSE(ret);
18609
        return ret;
18610
    }
18611
18612
    if ((ssl->error = SendTls13NewSessionTicket(ssl)) != 0) {
18613
        WOLFSSL_ERROR(ssl->error);
18614
        return WOLFSSL_FATAL_ERROR;
18615
    }
18616
    ssl->options.ticketsSent++;
18617
18618
    return WOLFSSL_SUCCESS;
18619
}
18620
#endif
18621
18622
#ifdef WOLFSSL_EARLY_DATA
18623
/* Sets the maximum amount of early data that can be seen by server when using
18624
 * session tickets for resumption.
18625
 * A value of zero indicates no early data is to be sent by client using session
18626
 * tickets.
18627
 *
18628
 * The default value is zero: per RFC 8446 Appendix E.5, TLS implementations
18629
 * "MUST NOT enable 0-RTT (either sending or accepting) unless specifically
18630
 * requested by the application." Servers must explicitly opt in by calling
18631
 * this function (or the per-SSL equivalent) with a non-zero value.
18632
 *
18633
 * ctx  The SSL/TLS CTX object.
18634
 * sz   Maximum size of the early data.
18635
 * returns BAD_FUNC_ARG when ctx is NULL, SIDE_ERROR when not a server and
18636
 * 0 on success.
18637
 */
18638
int wolfSSL_CTX_set_max_early_data(WOLFSSL_CTX* ctx, unsigned int sz)
18639
{
18640
    if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
18641
        return BAD_FUNC_ARG;
18642
    if (ctx->method->side == WOLFSSL_CLIENT_END)
18643
        return SIDE_ERROR;
18644
18645
    ctx->maxEarlyDataSz = sz;
18646
18647
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_ERROR_CODE_OPENSSL)
18648
    /* 1 on success in OpenSSL*/
18649
    return WOLFSSL_SUCCESS;
18650
#else
18651
    return 0;
18652
#endif
18653
}
18654
18655
/* Disable the RFC 8446 Section 8.2 fresh start protection. Early data is
18656
 * then accepted for tickets minted before this ctx was created. Only use
18657
 * this when the anti-replay state reliably survives server restarts.
18658
 *
18659
 * The check needs TimeNowInMilliseconds() to be comparable across restarts.
18660
 * On ports where it counts from boot the check never fires for tickets
18661
 * minted before a reboot.
18662
 *
18663
 * ctx  The SSL/TLS CTX object.
18664
 * returns BAD_FUNC_ARG when ctx is NULL or not TLS v1.3, SIDE_ERROR when
18665
 * called with a client and 0 on success.
18666
 */
18667
int wolfSSL_CTX_no_early_data_fresh_start_check(WOLFSSL_CTX* ctx)
18668
{
18669
    if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
18670
        return BAD_FUNC_ARG;
18671
    if (ctx->method->side == WOLFSSL_CLIENT_END)
18672
        return SIDE_ERROR;
18673
18674
#ifdef HAVE_SESSION_TICKET
18675
    ctx->noFreshStartCheck = 1;
18676
#endif
18677
18678
    return 0;
18679
}
18680
18681
/* Sets the maximum amount of early data that a client or server would like
18682
 * to exchange. Servers will advertise this value in session tickets sent
18683
 * to a client.
18684
 * A value of zero indicates no early data will be sent by a client, or
18685
 * no early data is accepted by a server (and announced as such in send out
18686
 * session tickets).
18687
 *
18688
 * ssl  The SSL/TLS object.
18689
 * sz   Maximum size of the early data.
18690
 * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3,
18691
 * and 0 on success.
18692
 */
18693
int wolfSSL_set_max_early_data(WOLFSSL* ssl, unsigned int sz)
18694
{
18695
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
18696
        return BAD_FUNC_ARG;
18697
18698
    ssl->options.maxEarlyDataSz = sz;
18699
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_ERROR_CODE_OPENSSL)
18700
    /* 1 on success in OpenSSL*/
18701
    return WOLFSSL_SUCCESS;
18702
#else
18703
    return 0;
18704
#endif
18705
}
18706
18707
/* Gets the maximum amount of early data that can be seen by server when using
18708
 * session tickets for resumption.
18709
 * A value of zero indicates no early data is to be sent by client using session
18710
 * tickets.
18711
 *
18712
 * ctx  The SSL/TLS CTX object.
18713
 * returns BAD_FUNC_ARG when ctx is NULL, SIDE_ERROR when not a server and
18714
 * returns the maximum amount of early data to be set
18715
 */
18716
int wolfSSL_CTX_get_max_early_data(WOLFSSL_CTX* ctx)
18717
{
18718
    if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
18719
        return BAD_FUNC_ARG;
18720
    if (ctx->method->side == WOLFSSL_CLIENT_END)
18721
        return SIDE_ERROR;
18722
18723
    return ctx->maxEarlyDataSz;
18724
}
18725
18726
/* Gets the maximum amount of early data that can be seen by server when using
18727
 * session tickets for resumption.
18728
 * A value of zero indicates no early data is to be sent by client using session
18729
 * tickets.
18730
 *
18731
 * ssl  The SSL/TLS object.
18732
 * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3,
18733
 * SIDE_ERROR when not a server and
18734
 * returns the maximum amount of early data to be set
18735
 */
18736
int wolfSSL_get_max_early_data(WOLFSSL* ssl)
18737
{
18738
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
18739
        return BAD_FUNC_ARG;
18740
18741
    return ssl->options.maxEarlyDataSz;
18742
}
18743
18744
/* Write early data to the server.
18745
 *
18746
 * ssl    The SSL/TLS object.
18747
 * data   Early data to write
18748
 * sz     The size of the early data in bytes.
18749
 * outSz  The number of early data bytes written.
18750
 * returns BAD_FUNC_ARG when: ssl, data or outSz is NULL; sz is negative;
18751
 * or not using TLS v1.3. SIDE ERROR when not a server. BAD_STATE_E if invoked
18752
 * without a valid session or without a valid PSK CB.
18753
 * Otherwise the number of early data bytes written.
18754
 */
18755
int wolfSSL_write_early_data(WOLFSSL* ssl, const void* data, int sz, int* outSz)
18756
{
18757
    int ret = 0;
18758
18759
    WOLFSSL_ENTER("wolfSSL_write_early_data");
18760
18761
    if (ssl == NULL || data == NULL || sz < 0 || outSz == NULL)
18762
        return BAD_FUNC_ARG;
18763
    if (!IsAtLeastTLSv1_3(ssl->version))
18764
        return BAD_FUNC_ARG;
18765
18766
    *outSz = 0;
18767
18768
#ifndef NO_WOLFSSL_CLIENT
18769
    if (ssl->options.side == WOLFSSL_SERVER_END)
18770
        return SIDE_ERROR;
18771
18772
    /* Early data requires PSK or session resumption */
18773
    if (!EarlyDataPossible(ssl)) {
18774
        return BAD_STATE_E;
18775
    }
18776
18777
    if (ssl->options.handShakeState == NULL_STATE) {
18778
        /* avoid re-setting ssl->earlyData if we re-enter the function because
18779
         * of WC_PENDING_E, WANT_WRITE or WANT_READ */
18780
        if (ssl->error == 0)
18781
            ssl->earlyData = expecting_early_data;
18782
        ret = wolfSSL_connect_TLSv13(ssl);
18783
        if (ret != WOLFSSL_SUCCESS)
18784
            return WOLFSSL_FATAL_ERROR;
18785
        /* on client side, status is set to rejected        */
18786
        /* until sever accepts the early data extension.    */
18787
        ssl->earlyDataStatus = WOLFSSL_EARLY_DATA_REJECTED;
18788
    }
18789
    if (ssl->options.handShakeState == CLIENT_HELLO_COMPLETE) {
18790
#ifdef OPENSSL_EXTRA
18791
        /* when processed early data exceeds max size */
18792
        if (ssl->session->maxEarlyDataSz > 0 &&
18793
            (ssl->earlyDataSz + sz > ssl->session->maxEarlyDataSz)) {
18794
            ssl->error = TOO_MUCH_EARLY_DATA;
18795
            return WOLFSSL_FATAL_ERROR;
18796
        }
18797
#endif
18798
        ret = SendData(ssl, data, sz);
18799
        if (ret > 0) {
18800
            *outSz = ret;
18801
            /* store amount of processed early data from client */
18802
            ssl->earlyDataSz += ret;
18803
        }
18804
    }
18805
#else
18806
    return SIDE_ERROR;
18807
#endif
18808
18809
    WOLFSSL_LEAVE("wolfSSL_write_early_data", ret);
18810
18811
    if (ret < 0)
18812
        ret = WOLFSSL_FATAL_ERROR;
18813
    return ret;
18814
}
18815
18816
/* Read the any early data from the client.
18817
 *
18818
 * ssl    The SSL/TLS object.
18819
 * data   Buffer to put the early data into.
18820
 * sz     The size of the buffer in bytes.
18821
 * outSz  The number of early data bytes read.
18822
 * returns BAD_FUNC_ARG when: ssl, data or outSz is NULL; sz is negative;
18823
 * or not using TLS v1.3. SIDE ERROR when not a server. Otherwise the number of
18824
 * early data bytes read.
18825
 */
18826
int wolfSSL_read_early_data(WOLFSSL* ssl, void* data, int sz, int* outSz)
18827
{
18828
    int ret = 0;
18829
18830
    WOLFSSL_ENTER("wolfSSL_read_early_data");
18831
18832
18833
    if (ssl == NULL || data == NULL || sz < 0 || outSz == NULL)
18834
        return BAD_FUNC_ARG;
18835
    if (!IsAtLeastTLSv1_3(ssl->version))
18836
        return BAD_FUNC_ARG;
18837
18838
    *outSz = 0;
18839
#ifndef NO_WOLFSSL_SERVER
18840
    if (ssl->options.side == WOLFSSL_CLIENT_END)
18841
        return SIDE_ERROR;
18842
18843
    if (ssl->options.handShakeState == NULL_STATE) {
18844
        /* the server flight can return WANT_WRITE and we re-enter here after
18845
         * setting ssl->earlyData = process_early_data, set earlyData to
18846
         * expecting_early_data just once */
18847
        if (ssl->earlyData < expecting_early_data)
18848
            ssl->earlyData = expecting_early_data;
18849
        /* this used to be: ret = wolfSSL_accept_TLSv13(ssl);
18850
         * However, wolfSSL_accept_TLSv13() expects a certificate to
18851
         * be installed already, which is not the case in servers
18852
         * such as HAProxy. They do it after inspecting the ClientHello.
18853
         * The common wolfssl_accept() allows that. */
18854
        ret = wolfSSL_accept(ssl);
18855
        if (ret <= 0)
18856
            return WOLFSSL_FATAL_ERROR;
18857
    }
18858
    if (ssl->options.handShakeState == SERVER_FINISHED_COMPLETE) {
18859
        ssl->options.clientInEarlyData = 1;
18860
        ret = ReceiveData(ssl, (byte*)data, (size_t)sz, FALSE);
18861
        ssl->options.clientInEarlyData = 0;
18862
        if (ret > 0)
18863
            *outSz = ret;
18864
        /* Only a failed read means the handshake finished during the early
18865
         * data read. ssl->error may still hold APP_DATA_READY from an earlier
18866
         * wolfSSL_accept() while data was actually read. */
18867
        if ((ret < 0) && (ssl->error == WC_NO_ERR_TRACE(APP_DATA_READY))) {
18868
            ret = 0;
18869
            ssl->error = WOLFSSL_ERROR_NONE;
18870
#ifdef WOLFSSL_DTLS13
18871
            if (ssl->options.dtls) {
18872
                ret = Dtls13DoScheduledWork(ssl);
18873
                if (ret  < 0) {
18874
                    ssl->error = ret;
18875
                    WOLFSSL_ERROR(ssl->error);
18876
                    return WOLFSSL_FATAL_ERROR;
18877
                }
18878
            }
18879
#endif /* WOLFSSL_DTLS13 */
18880
        }
18881
    }
18882
#ifdef WOLFSSL_DTLS13
18883
    else if (ssl->buffers.outputBuffer.length > 0 &&
18884
        ssl->options.dtls && ssl->dtls13SendingAckOrRtx) {
18885
        ret = SendBuffered(ssl);
18886
        if (ret == 0) {
18887
            ssl->dtls13SendingAckOrRtx = 0;
18888
        }
18889
        else {
18890
            ssl->error = ret;
18891
            WOLFSSL_ERROR(ssl->error);
18892
            return WOLFSSL_FATAL_ERROR;
18893
        }
18894
    }
18895
#endif /* WOLFSSL_DTLS13 */
18896
    else
18897
        ret = 0;
18898
#else
18899
    return SIDE_ERROR;
18900
#endif
18901
18902
    WOLFSSL_LEAVE("wolfSSL_read_early_data", ret);
18903
18904
    if (ret < 0)
18905
        ret = WOLFSSL_FATAL_ERROR;
18906
    return ret;
18907
}
18908
18909
/* Returns early data status
18910
 *
18911
 * ssl    The SSL/TLS object.
18912
 * returns WOLFSSL_EARLY_DATA_ACCEPTED if the data was accepted
18913
 *         WOLFSSL_EARLY_DATA_REJECTED if the data was rejected
18914
 *         WOLFSSL_EARLY_DATA_NOT_SENT if no early data was sent
18915
 */
18916
int wolfSSL_get_early_data_status(const WOLFSSL* ssl)
18917
{
18918
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
18919
        return BAD_FUNC_ARG;
18920
18921
    return ssl->earlyDataStatus;
18922
}
18923
#endif
18924
18925
#ifdef HAVE_SECRET_CALLBACK
18926
int wolfSSL_set_tls13_secret_cb(WOLFSSL* ssl, Tls13SecretCb cb, void* ctx)
18927
{
18928
    WOLFSSL_ENTER("wolfSSL_set_tls13_secret_cb");
18929
    if (ssl == NULL)
18930
        return WOLFSSL_FATAL_ERROR;
18931
18932
    ssl->tls13SecretCb = cb;
18933
    ssl->tls13SecretCtx = ctx;
18934
18935
    return WOLFSSL_SUCCESS;
18936
}
18937
18938
#if defined(SHOW_SECRETS) && defined(WOLFSSL_SSLKEYLOGFILE)
18939
int tls13ShowSecrets(WOLFSSL* ssl, int id, const unsigned char* secret,
18940
    int secretSz, void* ctx)
18941
{
18942
    int i;
18943
    const char* str = NULL;
18944
    byte clientRandom[RAN_LEN];
18945
    int clientRandomSz;
18946
    XFILE fp;
18947
#if defined(WOLFSSL_SSLKEYLOGFILE_OUTPUT) && defined(WOLFSSL_SSLKEYLOGFILE_USE_ENV)
18948
    const char* keyLogFile;
18949
#endif
18950
18951
    (void) ctx;
18952
#ifdef WOLFSSL_SSLKEYLOGFILE_OUTPUT
18953
#ifdef WOLFSSL_SSLKEYLOGFILE_USE_ENV
18954
    /* RFC 9850: prefer the SSLKEYLOGFILE environment variable so tools such as
18955
     * curl and Wireshark can share the path, else use the compile-time path.
18956
     * XGETENV resolves to NULL where environment access is unavailable. Opt-in
18957
     * so a build with the variable exported for other applications is not
18958
     * affected. */
18959
    keyLogFile = XGETENV("SSLKEYLOGFILE");
18960
    if (keyLogFile == NULL || keyLogFile[0] == '\0')
18961
        keyLogFile = WOLFSSL_SSLKEYLOGFILE_OUTPUT;
18962
    fp = XFOPEN(keyLogFile, "ab");
18963
#else
18964
    fp = XFOPEN(WOLFSSL_SSLKEYLOGFILE_OUTPUT, "ab");
18965
#endif
18966
    if (fp == XBADFILE) {
18967
        return BAD_FUNC_ARG;
18968
    }
18969
#else
18970
    fp = stderr;
18971
#endif
18972
18973
    clientRandomSz = (int)wolfSSL_get_client_random(ssl, clientRandom,
18974
        sizeof(clientRandom));
18975
18976
    if (clientRandomSz <= 0) {
18977
        printf("Error getting server random %d\n", clientRandomSz);
18978
        return BAD_FUNC_ARG;
18979
    }
18980
18981
#if 0
18982
    printf("TLS Server Secret CB: Rand %d, Secret %d\n",
18983
        serverRandomSz, secretSz);
18984
#endif
18985
18986
    switch (id) {
18987
        case CLIENT_EARLY_TRAFFIC_SECRET:
18988
            str = "CLIENT_EARLY_TRAFFIC_SECRET"; break;
18989
        case EARLY_EXPORTER_SECRET:
18990
            str = "EARLY_EXPORTER_SECRET"; break;
18991
        case CLIENT_HANDSHAKE_TRAFFIC_SECRET:
18992
            str = "CLIENT_HANDSHAKE_TRAFFIC_SECRET"; break;
18993
        case SERVER_HANDSHAKE_TRAFFIC_SECRET:
18994
            str = "SERVER_HANDSHAKE_TRAFFIC_SECRET"; break;
18995
        case CLIENT_TRAFFIC_SECRET:
18996
            str = "CLIENT_TRAFFIC_SECRET_0"; break;
18997
        case SERVER_TRAFFIC_SECRET:
18998
            str = "SERVER_TRAFFIC_SECRET_0"; break;
18999
        case EXPORTER_SECRET:
19000
            str = "EXPORTER_SECRET"; break;
19001
#ifdef HAVE_ECH
19002
        case ECH_SECRET:
19003
            str = "ECH_SECRET"; break;
19004
        case ECH_CONFIG:
19005
            str = "ECH_CONFIG"; break;
19006
#endif
19007
        default:
19008
#ifdef WOLFSSL_SSLKEYLOGFILE_OUTPUT
19009
            XFCLOSE(fp);
19010
#endif
19011
            return BAD_FUNC_ARG;
19012
            break;
19013
    }
19014
19015
    fprintf(fp, "%s ", str);
19016
    for (i = 0; i < (int)clientRandomSz; i++) {
19017
        fprintf(fp, "%02x", clientRandom[i]);
19018
    }
19019
    fprintf(fp, " ");
19020
    for (i = 0; i < secretSz; i++) {
19021
        fprintf(fp, "%02x", secret[i]);
19022
    }
19023
    fprintf(fp, "\n");
19024
19025
#ifdef WOLFSSL_SSLKEYLOGFILE_OUTPUT
19026
    XFCLOSE(fp);
19027
#endif
19028
19029
    return 0;
19030
}
19031
#endif
19032
#endif
19033
19034
#undef ERROR_OUT
19035
19036
#endif /* !WOLFCRYPT_ONLY */
19037
19038
#endif /* !NO_TLS && WOLFSSL_TLS13 */