Coverage Report

Created: 2026-09-27 06:31

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: Require client certificate        default: off
64
 * WOLFSSL_CERT_SETUP_CB:    Certificate setup callback            default: off
65
 * WOLFSSL_ALLOW_BAD_TLS_LEGACY_VERSION: Allow bad legacy version  default: off
66
 *
67
 * Security:
68
 * WOLFSSL_BLIND_PRIVATE_KEY: Blind private key during signing     default: off
69
 * WOLFSSL_CHECK_SIG_FAULTS: Verify signature after ECC signing    default: off
70
 *                            to detect fault injection attacks
71
 * WOLFSSL_CIPHER_TEXT_CHECK: Verify ciphertext integrity          default: off
72
 * WOLFSSL_TLS13_NULL_CIPHER_IN_DEFAULT: Include RFC 9150 suites   default: off
73
 *                            in the default cipher suite list (requires
74
 *                            HAVE_NULL_CIPHER). Without it the integrity-only
75
 *                            suites must be requested explicitly in the
76
 *                            cipher list, by name or with "eNULL".
77
 *
78
 * TLS 1.3 PSK:
79
 * WOLFSSL_PSK_ONE_ID:       Single PSK identity per connect       default: off
80
 * WOLFSSL_PSK_MULTI_ID_PER_CS: Multiple PSK IDs per cipher suite default: off
81
 * WOLFSSL_PRIORITIZE_PSK:   Prioritize PSK over ciphersuite order default: off
82
 *
83
 * TLS 1.3 Session Tickets:
84
 * WOLFSSL_TICKET_HAVE_ID:   Session tickets include ID            default: off
85
 *                            Forced on when WOLFSSL_EARLY_DATA is set.
86
 * WOLFSSL_TICKET_NONCE_MALLOC: Dynamically allocate ticket nonce  default: off
87
 * WOLFSSL_TLS13_TICKET_CHECK_PSK_MODES: Withhold NewSessionTicket default: off
88
 *                            when the ClientHello advertised no usable
89
 *                            psk_key_exchange_modes, as RFC 9846 Sections
90
 *                            4.3.9 and 4.7.1 require. Off by default: a peer
91
 *                            that omits the extension but expects a ticket
92
 *                            stops getting one.
93
 *
94
 * TLS 1.3 Key Exchange:
95
 * HAVE_KEYING_MATERIAL:     Export keying material (RFC 8446 7.5) default: off
96
 * WOLFSSL_HAVE_TLS_UNIQUE:  Enable tls-unique channel binding     default: off
97
 *
98
 * TLS 1.3 Hash/Signature:
99
 * WOLFSSL_TLS13_SHA512:     Allow SHA-512 in TLS 1.3 handshake   default: off
100
 *                            (no ciphersuite requires it currently)
101
 * WOLFSSL_ERROR_CODE_OPENSSL: Use OpenSSL-compatible error codes  default: off
102
 * WOLFSSL_SSLKEYLOGFILE_OUTPUT: Set key log output file path      default: off
103
 * WOLFSSL_SSLKEYLOGFILE_USE_ENV: Use SSLKEYLOGFILE env var path   default: off
104
 * WOLFSSL_RW_THREADED:      Enable read/write threading support   default: off
105
 * WOLFSSL_ASYNC_IO:         Enable async I/O operations           default: off
106
 * WOLFSSL_NONBLOCK_OCSP:    Non-blocking OCSP processing          default: off
107
 * WOLFSSL_TLS_OCSP_MULTI:   Multiple OCSP responses               default: off
108
 * WOLFSSL_WOLFSENTRY_HOOKS: wolfSentry integration hooks          default: off
109
 */
110
111
#if !defined(NO_TLS) && defined(WOLFSSL_TLS13)
112
113
/* 0-RTT anti-replay eviction needs the session cache. */
114
#if defined(WOLFSSL_EARLY_DATA) && defined(HAVE_SESSION_TICKET) && \
115
    defined(NO_SESSION_CACHE) && !defined(NO_WOLFSSL_SERVER) && \
116
    !defined(WOLFSSL_EARLY_DATA_NO_ANTI_REPLAY)
117
#error "WOLFSSL_EARLY_DATA with tickets requires !NO_SESSION_CACHE, or " \
118
       "define WOLFSSL_EARLY_DATA_NO_ANTI_REPLAY to opt out."
119
#endif
120
121
#ifndef WOLFCRYPT_ONLY
122
123
#ifdef HAVE_ERRNO_H
124
    #include <errno.h>
125
#endif
126
127
#if defined(__MACH__) || defined(__FreeBSD__) || \
128
    defined(__INCLUDE_NUTTX_CONFIG_H) || defined(WOLFSSL_RIOT_OS)
129
#include <sys/time.h>
130
#endif /* __MACH__ || __FreeBSD__ ||
131
          __INCLUDE_NUTTX_CONFIG_H || WOLFSSL_RIOT_OS */
132
133
134
#include <wolfssl/internal.h>
135
#include <wolfssl/error-ssl.h>
136
#include <wolfssl/wolfcrypt/asn.h>
137
#include <wolfssl/wolfcrypt/dh.h>
138
#include <wolfssl/wolfcrypt/kdf.h>
139
#include <wolfssl/wolfcrypt/signature.h>
140
#ifdef NO_INLINE
141
    #include <wolfssl/wolfcrypt/misc.h>
142
#else
143
    #define WOLFSSL_MISC_INCLUDED
144
    #include <wolfcrypt/src/misc.c>
145
#endif
146
147
#ifdef __sun
148
    #include <sys/filio.h>
149
#endif
150
151
#ifndef TRUE
152
    #define TRUE  1
153
#endif
154
#ifndef FALSE
155
    #define FALSE 0
156
#endif
157
158
#ifndef HAVE_AEAD
159
    #if !defined(_MSC_VER) && !defined(__TASKING__)
160
        #error "The build option HAVE_AEAD is required for TLS 1.3"
161
    #else
162
        #pragma \
163
        message("error: The build option HAVE_AEAD is required for TLS 1.3")
164
    #endif
165
#endif
166
167
#ifndef HAVE_HKDF
168
    #if !defined(_MSC_VER) && !defined(__TASKING__)
169
        #error "The build option HAVE_HKDF is required for TLS 1.3"
170
    #else
171
        #pragma message("error: The build option HAVE_HKDF is required for TLS 1.3")
172
    #endif
173
#endif
174
175
#ifndef HAVE_TLS_EXTENSIONS
176
    #if !defined(_MSC_VER) && !defined(__TASKING__)
177
        #error "The build option HAVE_TLS_EXTENSIONS is required for TLS 1.3"
178
    #else
179
        #pragma message("error: The build option HAVE_TLS_EXTENSIONS is required for TLS 1.3")
180
    #endif
181
#endif
182
183
184
/* Set ret to error value and jump to label.
185
 *
186
 * err     The error value to set.
187
 * eLabel  The label to jump to.
188
 */
189
0
#define ERROR_OUT(err, eLabel) { ret = (err); goto eLabel; }
190
191
/* Senders suspend/resume a pending record build only on the re-invoke path;
192
 * poll-completing backends block inside EncryptTls13() as before. */
193
#if defined(WOLFSSL_ASYNC_REINVOKE) && !defined(WOLF_CRYPTO_CB_ASYNC_POLL)
194
    #define TLS13_HS_ASYNC_OKAY 1
195
#else
196
0
    #define TLS13_HS_ASYNC_OKAY 0
197
#endif
198
199
#ifdef WOLFSSL_ASYNC_REINVOKE
200
/* Arm ssl->kdfAsyncDev for a key-schedule op that may pend, retiring this
201
 * connection's previous KDF event first (re-pushing a queued event would
202
 * self-link the event list). Returns 0 on success. */
203
static int Tls13KdfAsyncInit(WOLFSSL* ssl)
204
{
205
    int ret;
206
207
    if (ssl->asyncDev == &ssl->kdfAsyncDev) {
208
        ret = wolfSSL_AsyncPop(ssl, NULL);
209
        if (ret != 0 && ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E) &&
210
                ret != WC_NO_ERR_TRACE(WC_PENDING_E)) {
211
            return ret;
212
        }
213
    }
214
215
#if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_ASYNC_POLL)
216
    /* Never poll-routed: a zeroed cryptocbDevId would look poll-stamped to
217
     * wolfSSL_AsyncPop() and stop the resume state advancing. */
218
    ssl->kdfAsyncDev.cryptocbDevId = INVALID_DEVID;
219
#endif
220
    return wolfSSL_AsyncInit(ssl, &ssl->kdfAsyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
221
}
222
223
#endif /* WOLFSSL_ASYNC_REINVOKE */
224
225
/* Cap on re-invoking a callback for a record the caller cannot resume
226
 * (alerts, asyncOkay = 0 senders); bounds the otherwise unbounded spin. */
227
#ifndef WOLFSSL_ASYNC_MAX_REINVOKE
228
#define WOLFSSL_ASYNC_MAX_REINVOKE 1000
229
#endif
230
231
/* Size of the TLS v1.3 label use when deriving keys. */
232
0
#define TLS13_PROTOCOL_LABEL_SZ    6
233
/* The protocol label for TLS v1.3. */
234
static const byte tls13ProtocolLabel[TLS13_PROTOCOL_LABEL_SZ + 1] = "tls13 ";
235
236
#ifdef WOLFSSL_DTLS13
237
#define DTLS13_PROTOCOL_LABEL_SZ    6
238
static const byte dtls13ProtocolLabel[DTLS13_PROTOCOL_LABEL_SZ + 1] = "dtls13";
239
#endif /* WOLFSSL_DTLS13 */
240
241
#if defined(HAVE_ECH)
242
#define ECH_ACCEPT_CONFIRMATION_LABEL_SZ 23
243
#define ECH_HRR_ACCEPT_CONFIRMATION_LABEL_SZ 27
244
static const byte
245
    echAcceptConfirmationLabel[ECH_ACCEPT_CONFIRMATION_LABEL_SZ + 1] =
246
    "ech accept confirmation";
247
static const byte
248
    echHrrAcceptConfirmationLabel[ECH_HRR_ACCEPT_CONFIRMATION_LABEL_SZ + 1] =
249
    "hrr ech accept confirmation";
250
#endif
251
252
#ifndef NO_CERTS
253
#if !defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
254
    defined(HAVE_ED448) || defined(HAVE_FALCON) || defined(WOLFSSL_HAVE_MLDSA) || \
255
    defined(WOLFSSL_HAVE_SLHDSA)
256
257
static WC_INLINE int GetMsgHash(WOLFSSL* ssl, byte* hash);
258
259
#endif
260
#endif
261
262
/* Expand data using HMAC, salt and label and info.
263
 * TLS v1.3 defines this function. Use callback if available. */
264
static int Tls13HKDFExpandLabel(WOLFSSL* ssl, byte* okm, word32 okmLen,
265
                                const byte* prk, word32 prkLen,
266
                                const byte* protocol, word32 protocolLen,
267
                                const byte* label, word32 labelLen,
268
                                const byte* info, word32 infoLen,
269
                                int digest)
270
0
{
271
0
    int ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN);
272
#ifdef WOLFSSL_ASYNC_REINVOKE
273
    int aret;
274
275
    /* Armed before the provider runs so a pending from the PK callback or
276
     * wolfCrypt path falls through to the single push below. */
277
    aret = Tls13KdfAsyncInit(ssl);
278
    if (aret != 0)
279
        return aret;
280
#endif
281
282
#if defined(HAVE_PK_CALLBACKS)
283
    if (ssl->ctx && ssl->ctx->HKDFExpandLabelCb) {
284
        ret = ssl->ctx->HKDFExpandLabelCb(okm, okmLen, prk, prkLen,
285
                                          protocol, protocolLen,
286
                                          label, labelLen,
287
                                          info, infoLen, digest,
288
                                          WOLFSSL_CLIENT_END /* ignored */);
289
    }
290
291
    if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN))
292
#endif
293
0
    {
294
0
    PRIVATE_KEY_UNLOCK();
295
0
#if !defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(6,0))
296
0
    ret = wc_Tls13_HKDF_Expand_Label_ex(okm, okmLen, prk, prkLen,
297
0
                                     protocol, protocolLen,
298
0
                                     label, labelLen,
299
0
                                     info, infoLen, digest,
300
0
                                     ssl->heap, ssl->devId);
301
#else
302
    (void)ssl;
303
    ret = wc_Tls13_HKDF_Expand_Label(okm, okmLen, prk, prkLen,
304
                                     protocol, protocolLen,
305
                                     label, labelLen,
306
                                     info, infoLen, digest);
307
#endif
308
0
    PRIVATE_KEY_LOCK();
309
0
    }
310
#ifdef WOLFSSL_ASYNC_REINVOKE
311
    /* HKDF has no key object to carry a WC_ASYNC_DEV, so queue the
312
     * SSL-owned KDF device; without it the pop finds nothing pending and
313
     * replays the handshake message. CALL_AGAIN keeps the state put. */
314
    if (ret == WC_NO_ERR_TRACE(WC_PENDING_E))
315
        ret = wolfSSL_AsyncPush(ssl, &ssl->kdfAsyncDev);
316
#endif
317
0
    return ret;
318
0
}
319
320
/* Same as above, but pass in the side we are expanding for:
321
 * side: either WOLFSSL_CLIENT_END or WOLFSSL_SERVER_END.
322
 */
323
static int Tls13HKDFExpandKeyLabel(WOLFSSL* ssl, byte* okm, word32 okmLen,
324
                                   const byte* prk, word32 prkLen,
325
                                   const byte* protocol, word32 protocolLen,
326
                                   const byte* label, word32 labelLen,
327
                                   const byte* info, word32 infoLen,
328
                                   int digest, int side)
329
0
{
330
0
    int ret;
331
#ifdef WOLFSSL_ASYNC_REINVOKE
332
    ret = Tls13KdfAsyncInit(ssl);
333
    if (ret != 0)
334
        return ret;
335
#endif
336
337
#if defined(HAVE_PK_CALLBACKS)
338
    ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN);
339
    if (ssl->ctx && ssl->ctx->HKDFExpandLabelCb) {
340
        ret = ssl->ctx->HKDFExpandLabelCb(okm, okmLen, prk, prkLen,
341
                                         protocol, protocolLen,
342
                                         label, labelLen,
343
                                         info, infoLen,
344
                                         digest, side);
345
    }
346
    /* No early return: a pending here must reach the push at the end. */
347
    if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN))
348
#endif
349
0
    {
350
351
0
#if !defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(6,0))
352
0
    ret = wc_Tls13_HKDF_Expand_Label_ex(okm, okmLen, prk, prkLen,
353
0
                                      protocol, protocolLen,
354
0
                                      label, labelLen,
355
0
                                      info, infoLen, digest,
356
0
                                      ssl->heap, ssl->devId);
357
358
#elif defined(HAVE_FIPS) && defined(wc_Tls13_HKDF_Expand_Label)
359
    ret = wc_Tls13_HKDF_Expand_Label_fips(okm, okmLen, prk, prkLen,
360
                                      protocol, protocolLen,
361
                                      label, labelLen,
362
                                      info, infoLen, digest);
363
#else
364
    ret = wc_Tls13_HKDF_Expand_Label(okm, okmLen, prk, prkLen,
365
                                      protocol, protocolLen,
366
                                      label, labelLen,
367
                                      info, infoLen, digest);
368
#endif
369
0
    }
370
#ifdef WOLFSSL_ASYNC_REINVOKE
371
    /* HKDF has no key object to carry a WC_ASYNC_DEV, so queue the
372
     * SSL-owned KDF device; without it the pop finds nothing pending and
373
     * replays the handshake message. CALL_AGAIN keeps the state put. */
374
    if (ret == WC_NO_ERR_TRACE(WC_PENDING_E))
375
        ret = wolfSSL_AsyncPush(ssl, &ssl->kdfAsyncDev);
376
#endif
377
0
    (void)ssl;
378
0
    (void)side;
379
0
    return ret;
380
0
}
381
382
383
/* Derive a key from a message.
384
 *
385
 * ssl        The SSL/TLS object.
386
 * output     The buffer to hold the derived key.
387
 * outputLen  The length of the derived key.
388
 * secret     The secret used to derive the key (HMAC secret).
389
 * label      The label used to distinguish the context.
390
 * labelLen   The length of the label.
391
 * msg        The message data to derive key from.
392
 * msgLen     The length of the message data to derive key from.
393
 * hashAlgo   The hash algorithm to use in the HMAC.
394
 * returns 0 on success, otherwise failure.
395
 */
396
static int DeriveKeyMsg(WOLFSSL* ssl, byte* output, int outputLen,
397
                        const byte* secret, const byte* label, word32 labelLen,
398
                        byte* msg, int msgLen, int hashAlgo)
399
0
{
400
0
    byte        hash[WC_MAX_DIGEST_SIZE];
401
0
    Digest      digest;
402
0
    word32      hashSz = 0;
403
0
    const byte* protocol;
404
0
    word32      protocolLen;
405
0
    int         digestAlg = -1;
406
0
    int         ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG);
407
408
0
    switch (hashAlgo) {
409
0
#ifndef NO_SHA256
410
0
        case sha256_mac:
411
0
            ret = wc_InitSha256_ex(&digest.sha256, ssl->heap, ssl->devId);
412
0
            if (ret == 0) {
413
0
                    ret = wc_Sha256Update(&digest.sha256, msg, (word32)msgLen);
414
0
                if (ret == 0)
415
0
                    ret = wc_Sha256Final(&digest.sha256, hash);
416
0
                wc_Sha256Free(&digest.sha256);
417
0
            }
418
0
            hashSz = WC_SHA256_DIGEST_SIZE;
419
0
            digestAlg = WC_SHA256;
420
0
            break;
421
0
#endif
422
0
#ifdef WOLFSSL_SHA384
423
0
        case sha384_mac:
424
0
            ret = wc_InitSha384_ex(&digest.sha384, ssl->heap, ssl->devId);
425
0
            if (ret == 0) {
426
0
                ret = wc_Sha384Update(&digest.sha384, msg, (word32)msgLen);
427
0
                if (ret == 0)
428
0
                    ret = wc_Sha384Final(&digest.sha384, hash);
429
0
                wc_Sha384Free(&digest.sha384);
430
0
            }
431
0
            hashSz = WC_SHA384_DIGEST_SIZE;
432
0
            digestAlg = WC_SHA384;
433
0
            break;
434
0
#endif
435
#ifdef WOLFSSL_TLS13_SHA512
436
        case sha512_mac:
437
            ret = wc_InitSha512_ex(&digest.sha512, ssl->heap, ssl->devId);
438
            if (ret == 0) {
439
                ret = wc_Sha512Update(&digest.sha512, msg, (word32)msgLen);
440
                if (ret == 0)
441
                    ret = wc_Sha512Final(&digest.sha512, hash);
442
                wc_Sha512Free(&digest.sha512);
443
            }
444
            hashSz = WC_SHA512_DIGEST_SIZE;
445
            digestAlg = WC_SHA512;
446
            break;
447
#endif
448
#ifdef WOLFSSL_SM3
449
        case sm3_mac:
450
            ret = wc_InitSm3(&digest.sm3, ssl->heap, ssl->devId);
451
            if (ret == 0) {
452
                ret = wc_Sm3Update(&digest.sm3, msg, (word32)msgLen);
453
                if (ret == 0)
454
                    ret = wc_Sm3Final(&digest.sm3, hash);
455
                wc_Sm3Free(&digest.sm3);
456
            }
457
            hashSz = WC_SM3_DIGEST_SIZE;
458
            digestAlg = WC_SM3;
459
            break;
460
#endif
461
0
        default:
462
0
            ret = BAD_FUNC_ARG;
463
0
            digestAlg = -1;
464
0
            break;
465
0
    }
466
467
0
    if (digestAlg < 0)
468
0
        return HASH_TYPE_E;
469
470
0
    if (ret != 0)
471
0
        return ret;
472
473
0
    switch (ssl->version.minor) {
474
0
        case TLSv1_3_MINOR:
475
0
            protocol = tls13ProtocolLabel;
476
0
            protocolLen = TLS13_PROTOCOL_LABEL_SZ;
477
0
            break;
478
#ifdef WOLFSSL_DTLS13
479
        case DTLSv1_3_MINOR:
480
            if (!ssl->options.dtls)
481
                return VERSION_ERROR;
482
483
            protocol = dtls13ProtocolLabel;
484
            protocolLen = DTLS13_PROTOCOL_LABEL_SZ;
485
            break;
486
#endif /* WOLFSSL_DTLS13 */
487
0
        default:
488
0
            return VERSION_ERROR;
489
0
    }
490
0
    if (outputLen == -1)
491
0
        outputLen = (int)hashSz;
492
493
0
    ret = Tls13HKDFExpandLabel(ssl, output, (word32)outputLen, secret, hashSz,
494
0
                               protocol, protocolLen, label, labelLen,
495
0
                               hash, hashSz, digestAlg);
496
0
    return ret;
497
0
}
498
499
/* Derive a key.
500
 *
501
 * ssl          The SSL/TLS object.
502
 * output       The buffer to hold the derived key.
503
 * outputLen    The length of the derived key.
504
 * secret       The secret used to derive the key (HMAC secret).
505
 * label        The label used to distinguish the context.
506
 * labelLen     The length of the label.
507
 * hashAlgo     The hash algorithm to use in the HMAC.
508
 * includeMsgs  Whether to include a hash of the handshake messages so far.
509
 * side         The side that we are deriving the secret for.
510
 * returns 0 on success, otherwise failure.
511
 */
512
int Tls13DeriveKey(WOLFSSL* ssl, byte* output, int outputLen,
513
                   const byte* secret, const byte* label, word32 labelLen,
514
                   int hashAlgo, int includeMsgs, int side)
515
0
{
516
0
    int         ret = 0;
517
0
    byte        hash[WC_MAX_DIGEST_SIZE];
518
0
    word32      hashSz = 0;
519
0
    word32      hashOutSz = 0;
520
0
    const byte* protocol;
521
0
    word32      protocolLen;
522
0
    int         digestAlg = 0;
523
524
525
0
    switch (hashAlgo) {
526
0
    #ifndef NO_SHA256
527
0
        case sha256_mac:
528
0
            hashSz    = WC_SHA256_DIGEST_SIZE;
529
0
            digestAlg = WC_SHA256;
530
0
            if (includeMsgs)
531
0
                ret = wc_Sha256GetHash(&ssl->hsHashes->hashSha256, hash);
532
0
            break;
533
0
    #endif
534
535
0
    #ifdef WOLFSSL_SHA384
536
0
        case sha384_mac:
537
0
            hashSz    = WC_SHA384_DIGEST_SIZE;
538
0
            digestAlg = WC_SHA384;
539
0
            if (includeMsgs)
540
0
                ret = wc_Sha384GetHash(&ssl->hsHashes->hashSha384, hash);
541
0
            break;
542
0
    #endif
543
544
    #ifdef WOLFSSL_TLS13_SHA512
545
        case sha512_mac:
546
            hashSz    = WC_SHA512_DIGEST_SIZE;
547
            digestAlg = WC_SHA512;
548
            if (includeMsgs)
549
                ret = wc_Sha512GetHash(&ssl->hsHashes->hashSha512, hash);
550
            break;
551
    #endif
552
553
    #ifdef WOLFSSL_SM3
554
        case sm3_mac:
555
            hashSz    = WC_SM3_DIGEST_SIZE;
556
            digestAlg = WC_SM3;
557
            if (includeMsgs)
558
                ret = wc_Sm3GetHash(&ssl->hsHashes->hashSm3, hash);
559
            break;
560
    #endif
561
562
0
        default:
563
0
            ret = HASH_TYPE_E;
564
0
            break;
565
0
    }
566
0
    if (ret != 0)
567
0
        return ret;
568
569
0
    protocol = tls13ProtocolLabel;
570
0
    protocolLen = TLS13_PROTOCOL_LABEL_SZ;
571
572
#ifdef WOLFSSL_DTLS13
573
    if (ssl->options.dtls) {
574
         protocol = dtls13ProtocolLabel;
575
         protocolLen = DTLS13_PROTOCOL_LABEL_SZ;
576
    }
577
#endif /* WOLFSSL_DTLS13 */
578
579
0
    if (outputLen == -1) {
580
0
        outputLen = (int)hashSz;
581
0
    }
582
0
    if (includeMsgs) {
583
0
        hashOutSz = hashSz;
584
0
    }
585
0
    else {
586
        /* Appease static analyzers by making sure hash is cleared, since it is
587
         * passed into expand key label where older wc_Tls13_HKDF_Expand_Label
588
         * will unconditionally try to call a memcpy on it, however length will
589
         * always be 0. */
590
0
        XMEMSET(hash, 0, sizeof(hash));
591
0
        hashOutSz = 0;
592
0
    }
593
594
0
    PRIVATE_KEY_UNLOCK();
595
0
    ret = Tls13HKDFExpandKeyLabel(ssl, output, (word32)outputLen, secret, hashSz,
596
0
                                  protocol, protocolLen, label, labelLen,
597
0
                                  hash, hashOutSz, digestAlg, side);
598
0
    PRIVATE_KEY_LOCK();
599
600
#ifdef WOLFSSL_CHECK_MEM_ZERO
601
    wc_MemZero_Add("TLS 1.3 derived key", output, outputLen);
602
#endif
603
0
    return ret;
604
0
}
605
606
/* Convert TLS mac ID to a hash algorithm ID
607
 *
608
 * mac Mac ID to convert
609
 * returns hash ID on success, or the NONE type.
610
 */
611
static WC_INLINE int mac2hash(int mac)
612
0
{
613
0
    int hash;
614
0
    switch (mac) {
615
0
        #ifndef NO_SHA256
616
0
        case sha256_mac:
617
0
            hash = WC_SHA256;
618
0
            break;
619
0
        #endif
620
621
0
        #ifdef WOLFSSL_SHA384
622
0
        case sha384_mac:
623
0
            hash = WC_SHA384;
624
0
            break;
625
0
        #endif
626
627
        #ifdef WOLFSSL_TLS13_SHA512
628
        case sha512_mac:
629
            hash = WC_SHA512;
630
            break;
631
        #endif
632
633
        #ifdef WOLFSSL_SM3
634
        case sm3_mac:
635
            hash = WC_SM3;
636
            break;
637
        #endif
638
639
0
    default:
640
0
        hash = WC_HASH_TYPE_NONE;
641
0
    }
642
0
    return hash;
643
0
}
644
645
#ifndef NO_PSK
646
/* The length of the binder key label. */
647
#define BINDER_KEY_LABEL_SZ         10
648
/* The binder key label. */
649
static const byte binderKeyLabel[BINDER_KEY_LABEL_SZ + 1] =
650
    "ext binder";
651
652
/* Derive the binder key.
653
 *
654
 * ssl  The SSL/TLS object.
655
 * key  The derived key.
656
 * returns 0 on success, otherwise failure.
657
 */
658
static int DeriveBinderKey(WOLFSSL* ssl, byte* key)
659
{
660
    WOLFSSL_MSG("Derive Binder Key");
661
    if (ssl == NULL || ssl->arrays == NULL) {
662
        return BAD_FUNC_ARG;
663
    }
664
    return DeriveKeyMsg(ssl, key, -1, ssl->arrays->secret,
665
                        binderKeyLabel, BINDER_KEY_LABEL_SZ,
666
                        NULL, 0, ssl->specs.mac_algorithm);
667
}
668
#endif /* !NO_PSK */
669
670
#if defined(HAVE_SESSION_TICKET) && \
671
    (!defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER))
672
/* The length of the binder key resume label. */
673
#define BINDER_KEY_RESUME_LABEL_SZ  10
674
/* The binder key resume label. */
675
static const byte binderKeyResumeLabel[BINDER_KEY_RESUME_LABEL_SZ + 1] =
676
    "res binder";
677
678
/* Derive the binder resumption key.
679
 *
680
 * ssl  The SSL/TLS object.
681
 * key  The derived key.
682
 * returns 0 on success, otherwise failure.
683
 */
684
static int DeriveBinderKeyResume(WOLFSSL* ssl, byte* key)
685
{
686
    WOLFSSL_MSG("Derive Binder Key - Resumption");
687
    if (ssl == NULL || ssl->arrays == NULL) {
688
        return BAD_FUNC_ARG;
689
    }
690
    return DeriveKeyMsg(ssl, key, -1, ssl->arrays->secret,
691
                        binderKeyResumeLabel, BINDER_KEY_RESUME_LABEL_SZ,
692
                        NULL, 0, ssl->specs.mac_algorithm);
693
}
694
#endif /* HAVE_SESSION_TICKET && (!NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER) */
695
696
#ifdef WOLFSSL_EARLY_DATA
697
698
/* The length of the early traffic label. */
699
#define EARLY_TRAFFIC_LABEL_SZ      11
700
/* The early traffic label. */
701
static const byte earlyTrafficLabel[EARLY_TRAFFIC_LABEL_SZ + 1] =
702
    "c e traffic";
703
704
/* Derive the early traffic key.
705
 *
706
 * ssl  The SSL/TLS object.
707
 * key  The derived key.
708
 * side The side that we are deriving the secret for.
709
 * returns 0 on success, otherwise failure.
710
 */
711
static int DeriveEarlyTrafficSecret(WOLFSSL* ssl, byte* key, int side)
712
{
713
    int ret;
714
    WOLFSSL_MSG("Derive Early Traffic Secret");
715
    if (ssl == NULL || ssl->arrays == NULL) {
716
        return BAD_FUNC_ARG;
717
    }
718
719
#if defined(WOLFSSL_SNIFFER) && defined(WOLFSSL_SNIFFER_KEYLOGFILE)
720
    /* If this is called from a sniffer session with keylog file support,
721
     * obtain the appropriate secret from the callback */
722
    if (ssl->snifferSecretCb != NULL) {
723
        return ssl->snifferSecretCb(ssl->arrays->clientRandom,
724
                                    SNIFFER_SECRET_CLIENT_EARLY_TRAFFIC_SECRET,
725
                                    key);
726
    }
727
#endif /* WOLFSSL_SNIFFER && WOLFSSL_SNIFFER_KEYLOGFILE */
728
729
    ret = Tls13DeriveKey(ssl, key, -1, ssl->arrays->secret,
730
                    earlyTrafficLabel, EARLY_TRAFFIC_LABEL_SZ,
731
                    ssl->specs.mac_algorithm, 1, side);
732
#ifdef HAVE_SECRET_CALLBACK
733
    if (ret == 0 && ssl->tls13SecretCb != NULL) {
734
        ret = ssl->tls13SecretCb(ssl, CLIENT_EARLY_TRAFFIC_SECRET, key,
735
                                 ssl->specs.hash_size, ssl->tls13SecretCtx);
736
        if (ret != 0) {
737
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
738
            return TLS13_SECRET_CB_E;
739
        }
740
    }
741
#ifdef OPENSSL_EXTRA
742
    if (ret == 0 && ssl->tls13KeyLogCb != NULL) {
743
        ret = ssl->tls13KeyLogCb(ssl, CLIENT_EARLY_TRAFFIC_SECRET, key,
744
                                ssl->specs.hash_size, NULL);
745
        if (ret != 0) {
746
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
747
            return TLS13_SECRET_CB_E;
748
        }
749
    }
750
#endif /* OPENSSL_EXTRA */
751
#endif /* HAVE_SECRET_CALLBACK */
752
    return ret;
753
}
754
755
#endif
756
757
/* The length of the client handshake label. */
758
0
#define CLIENT_HANDSHAKE_LABEL_SZ   12
759
/* The client handshake label. */
760
static const byte clientHandshakeLabel[CLIENT_HANDSHAKE_LABEL_SZ + 1] =
761
    "c hs traffic";
762
763
/* Derive the client handshake key.
764
 *
765
 * ssl  The SSL/TLS object.
766
 * key  The derived key.
767
 * returns 0 on success, otherwise failure.
768
 */
769
static int DeriveClientHandshakeSecret(WOLFSSL* ssl, byte* key)
770
0
{
771
0
    int ret;
772
0
    WOLFSSL_MSG("Derive Client Handshake Secret");
773
0
    if (ssl == NULL || ssl->arrays == NULL) {
774
0
        return BAD_FUNC_ARG;
775
0
    }
776
777
#if defined(WOLFSSL_SNIFFER) && defined(WOLFSSL_SNIFFER_KEYLOGFILE)
778
    /* If this is called from a sniffer session with keylog file support,
779
     * obtain the appropriate secret from the callback */
780
    if (ssl->snifferSecretCb != NULL) {
781
        return ssl->snifferSecretCb(ssl->arrays->clientRandom,
782
                               SNIFFER_SECRET_CLIENT_HANDSHAKE_TRAFFIC_SECRET,
783
                               key);
784
    }
785
#endif /* WOLFSSL_SNIFFER && WOLFSSL_SNIFFER_KEYLOGFILE */
786
787
0
    ret = Tls13DeriveKey(ssl, key, -1, ssl->arrays->preMasterSecret,
788
0
                    clientHandshakeLabel, CLIENT_HANDSHAKE_LABEL_SZ,
789
0
                    ssl->specs.mac_algorithm, 1, WOLFSSL_CLIENT_END);
790
#ifdef HAVE_SECRET_CALLBACK
791
    if (ret == 0 && ssl->tls13SecretCb != NULL) {
792
        ret = ssl->tls13SecretCb(ssl, CLIENT_HANDSHAKE_TRAFFIC_SECRET, key,
793
                                 ssl->specs.hash_size, ssl->tls13SecretCtx);
794
        if (ret != 0) {
795
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
796
            return TLS13_SECRET_CB_E;
797
        }
798
    }
799
#ifdef OPENSSL_EXTRA
800
    if (ret == 0 && ssl->tls13KeyLogCb != NULL) {
801
        ret = ssl->tls13KeyLogCb(ssl, CLIENT_HANDSHAKE_TRAFFIC_SECRET, key,
802
                                ssl->specs.hash_size, NULL);
803
        if (ret != 0) {
804
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
805
            return TLS13_SECRET_CB_E;
806
        }
807
    }
808
#endif /* OPENSSL_EXTRA */
809
#endif /* HAVE_SECRET_CALLBACK */
810
0
    return ret;
811
0
}
812
813
/* The length of the server handshake label. */
814
0
#define SERVER_HANDSHAKE_LABEL_SZ   12
815
/* The server handshake label. */
816
static const byte serverHandshakeLabel[SERVER_HANDSHAKE_LABEL_SZ + 1] =
817
    "s hs traffic";
818
819
/* Derive the server handshake key.
820
 *
821
 * ssl  The SSL/TLS object.
822
 * key  The derived key.
823
 * returns 0 on success, otherwise failure.
824
 */
825
static int DeriveServerHandshakeSecret(WOLFSSL* ssl, byte* key)
826
0
{
827
0
    int ret;
828
0
    WOLFSSL_MSG("Derive Server Handshake Secret");
829
0
    if (ssl == NULL || ssl->arrays == NULL) {
830
0
        return BAD_FUNC_ARG;
831
0
    }
832
833
#if defined(WOLFSSL_SNIFFER) && defined(WOLFSSL_SNIFFER_KEYLOGFILE)
834
    /* If this is called from a sniffer session with keylog file support,
835
     * obtain the appropriate secret from the callback */
836
    if (ssl->snifferSecretCb != NULL) {
837
        return ssl->snifferSecretCb(ssl->arrays->clientRandom,
838
                                SNIFFER_SECRET_SERVER_HANDSHAKE_TRAFFIC_SECRET,
839
                                key);
840
    }
841
#endif /* WOLFSSL_SNIFFER && WOLFSSL_SNIFFER_KEYLOGFILE */
842
843
0
    ret = Tls13DeriveKey(ssl, key, -1, ssl->arrays->preMasterSecret,
844
0
                    serverHandshakeLabel, SERVER_HANDSHAKE_LABEL_SZ,
845
0
                    ssl->specs.mac_algorithm, 1, WOLFSSL_SERVER_END);
846
847
#ifdef HAVE_SECRET_CALLBACK
848
    if (ret == 0 && ssl->tls13SecretCb != NULL) {
849
        ret = ssl->tls13SecretCb(ssl, SERVER_HANDSHAKE_TRAFFIC_SECRET, key,
850
                                 ssl->specs.hash_size, ssl->tls13SecretCtx);
851
        if (ret != 0) {
852
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
853
            return TLS13_SECRET_CB_E;
854
        }
855
    }
856
#ifdef OPENSSL_EXTRA
857
    if (ret == 0 && ssl->tls13KeyLogCb != NULL) {
858
        ret = ssl->tls13KeyLogCb(ssl, SERVER_HANDSHAKE_TRAFFIC_SECRET, key,
859
                                ssl->specs.hash_size, NULL);
860
        if (ret != 0) {
861
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
862
            return TLS13_SECRET_CB_E;
863
        }
864
    }
865
#endif /* OPENSSL_EXTRA */
866
#endif /* HAVE_SECRET_CALLBACK */
867
0
    return ret;
868
0
}
869
870
/* The length of the client application traffic label. */
871
0
#define CLIENT_APP_LABEL_SZ         12
872
/* The client application traffic label. */
873
static const byte clientAppLabel[CLIENT_APP_LABEL_SZ + 1] =
874
    "c ap traffic";
875
876
/* Derive the client application traffic key.
877
 *
878
 * ssl  The SSL/TLS object.
879
 * key  The derived key.
880
 * returns 0 on success, otherwise failure.
881
 */
882
static int DeriveClientTrafficSecret(WOLFSSL* ssl, byte* key)
883
0
{
884
0
    int ret;
885
0
    WOLFSSL_MSG("Derive Client Traffic Secret");
886
0
    if (ssl == NULL || ssl->arrays == NULL) {
887
0
        return BAD_FUNC_ARG;
888
0
    }
889
890
#if defined(WOLFSSL_SNIFFER) && defined(WOLFSSL_SNIFFER_KEYLOGFILE)
891
    /* If this is called from a sniffer session with keylog file support,
892
     * obtain the appropriate secret from the callback */
893
    if (ssl->snifferSecretCb != NULL) {
894
        return ssl->snifferSecretCb(ssl->arrays->clientRandom,
895
                                    SNIFFER_SECRET_CLIENT_TRAFFIC_SECRET,
896
                                    key);
897
    }
898
#endif /* WOLFSSL_SNIFFER && WOLFSSL_SNIFFER_KEYLOGFILE */
899
900
0
    ret = Tls13DeriveKey(ssl, key, -1, ssl->arrays->masterSecret,
901
0
                    clientAppLabel, CLIENT_APP_LABEL_SZ,
902
0
                    ssl->specs.mac_algorithm, 1, WOLFSSL_CLIENT_END);
903
904
#ifdef HAVE_SECRET_CALLBACK
905
    if (ret == 0 && ssl->tls13SecretCb != NULL) {
906
        ret = ssl->tls13SecretCb(ssl, CLIENT_TRAFFIC_SECRET, key,
907
                                 ssl->specs.hash_size, ssl->tls13SecretCtx);
908
        if (ret != 0) {
909
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
910
            return TLS13_SECRET_CB_E;
911
        }
912
    }
913
#ifdef OPENSSL_EXTRA
914
    if (ret == 0 && ssl->tls13KeyLogCb != NULL) {
915
        ret = ssl->tls13KeyLogCb(ssl, CLIENT_TRAFFIC_SECRET, key,
916
                                ssl->specs.hash_size, NULL);
917
        if (ret != 0) {
918
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
919
            return TLS13_SECRET_CB_E;
920
        }
921
    }
922
#endif /* OPENSSL_EXTRA */
923
#endif /* HAVE_SECRET_CALLBACK */
924
0
    return ret;
925
0
}
926
927
/* The length of the server application traffic label. */
928
0
#define SERVER_APP_LABEL_SZ         12
929
/* The  server application traffic label. */
930
static const byte serverAppLabel[SERVER_APP_LABEL_SZ + 1] =
931
    "s ap traffic";
932
933
/* Derive the server application traffic key.
934
 *
935
 * ssl  The SSL/TLS object.
936
 * key  The derived key.
937
 * returns 0 on success, otherwise failure.
938
 */
939
static int DeriveServerTrafficSecret(WOLFSSL* ssl, byte* key)
940
0
{
941
0
    int ret;
942
0
    WOLFSSL_MSG("Derive Server Traffic Secret");
943
0
    if (ssl == NULL || ssl->arrays == NULL) {
944
0
        return BAD_FUNC_ARG;
945
0
    }
946
947
#if defined(WOLFSSL_SNIFFER) && defined(WOLFSSL_SNIFFER_KEYLOGFILE)
948
    /* If this is called from a sniffer session with keylog file support,
949
     * obtain the appropriate secret from the callback */
950
    if (ssl->snifferSecretCb != NULL) {
951
        return ssl->snifferSecretCb(ssl->arrays->clientRandom,
952
                                    SNIFFER_SECRET_SERVER_TRAFFIC_SECRET,
953
                                    key);
954
    }
955
#endif /* WOLFSSL_SNIFFER && WOLFSSL_SNIFFER_KEYLOGFILE */
956
957
0
    ret = Tls13DeriveKey(ssl, key, -1, ssl->arrays->masterSecret,
958
0
                    serverAppLabel, SERVER_APP_LABEL_SZ,
959
0
                    ssl->specs.mac_algorithm, 1, WOLFSSL_SERVER_END);
960
961
#ifdef HAVE_SECRET_CALLBACK
962
    if (ret == 0 && ssl->tls13SecretCb != NULL) {
963
        ret = ssl->tls13SecretCb(ssl, SERVER_TRAFFIC_SECRET, key,
964
                                 ssl->specs.hash_size, ssl->tls13SecretCtx);
965
        if (ret != 0) {
966
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
967
            return TLS13_SECRET_CB_E;
968
        }
969
    }
970
#ifdef OPENSSL_EXTRA
971
    if (ret == 0 && ssl->tls13KeyLogCb != NULL) {
972
        ret = ssl->tls13KeyLogCb(ssl, SERVER_TRAFFIC_SECRET, key,
973
                                ssl->specs.hash_size, NULL);
974
        if (ret != 0) {
975
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
976
            return TLS13_SECRET_CB_E;
977
        }
978
    }
979
#endif /* OPENSSL_EXTRA */
980
#endif /* HAVE_SECRET_CALLBACK */
981
0
    return ret;
982
0
}
983
984
#ifdef HAVE_KEYING_MATERIAL
985
/* The length of the exporter master secret label. */
986
#define EXPORTER_MASTER_LABEL_SZ    10
987
/* The exporter master secret label. */
988
static const byte exporterMasterLabel[EXPORTER_MASTER_LABEL_SZ + 1] =
989
    "exp master";
990
991
/* Derive the exporter secret.
992
 *
993
 * ssl  The SSL/TLS object.
994
 * key  The derived key.
995
 * returns 0 on success, otherwise failure.
996
 */
997
static int DeriveExporterSecret(WOLFSSL* ssl, byte* key)
998
{
999
    int ret;
1000
    WOLFSSL_ENTER("Derive Exporter Secret");
1001
    if (ssl == NULL || ssl->arrays == NULL) {
1002
        return BAD_FUNC_ARG;
1003
    }
1004
    ret = Tls13DeriveKey(ssl, key, -1, ssl->arrays->masterSecret,
1005
                        exporterMasterLabel, EXPORTER_MASTER_LABEL_SZ,
1006
                        ssl->specs.mac_algorithm, 1, 0 /* Unused */);
1007
#ifdef HAVE_SECRET_CALLBACK
1008
    if (ret == 0 && ssl->tls13SecretCb != NULL) {
1009
        ret = ssl->tls13SecretCb(ssl, EXPORTER_SECRET, key,
1010
                                 ssl->specs.hash_size, ssl->tls13SecretCtx);
1011
        if (ret != 0) {
1012
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
1013
            return TLS13_SECRET_CB_E;
1014
        }
1015
    }
1016
#ifdef OPENSSL_EXTRA
1017
    if (ret == 0 && ssl->tls13KeyLogCb != NULL) {
1018
        ret = ssl->tls13KeyLogCb(ssl, EXPORTER_SECRET, key,
1019
                                ssl->specs.hash_size, NULL);
1020
        if (ret != 0) {
1021
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
1022
            return TLS13_SECRET_CB_E;
1023
        }
1024
    }
1025
#endif /* OPENSSL_EXTRA */
1026
#endif /* HAVE_SECRET_CALLBACK */
1027
    return ret;
1028
}
1029
1030
/* The length of the exporter label. */
1031
#define EXPORTER_LABEL_SZ    8
1032
/* The exporter label. */
1033
static const byte exporterLabel[EXPORTER_LABEL_SZ + 1] =
1034
    "exporter";
1035
/* Hash("") */
1036
#ifndef NO_SHA256
1037
static const byte emptySHA256Hash[] = {
1038
    0xE3, 0xB0, 0xC4, 0x42, 0x98, 0xFC, 0x1C, 0x14, 0x9A, 0xFB, 0xF4, 0xC8,
1039
    0x99, 0x6F, 0xB9, 0x24, 0x27, 0xAE, 0x41, 0xE4, 0x64, 0x9B, 0x93, 0x4C,
1040
    0xA4, 0x95, 0x99, 0x1B, 0x78, 0x52, 0xB8, 0x55
1041
};
1042
#endif
1043
#ifdef WOLFSSL_SHA384
1044
static const byte emptySHA384Hash[] = {
1045
    0x38, 0xB0, 0x60, 0xA7, 0x51, 0xAC, 0x96, 0x38, 0x4C, 0xD9, 0x32, 0x7E,
1046
    0xB1, 0xB1, 0xE3, 0x6A, 0x21, 0xFD, 0xB7, 0x11, 0x14, 0xBE, 0x07, 0x43,
1047
    0x4C, 0x0C, 0xC7, 0xBF, 0x63, 0xF6, 0xE1, 0xDA, 0x27, 0x4E, 0xDE, 0xBF,
1048
    0xE7, 0x6F, 0x65, 0xFB, 0xD5, 0x1A, 0xD2, 0xF1, 0x48, 0x98, 0xB9, 0x5B
1049
};
1050
#endif
1051
#ifdef WOLFSSL_TLS13_SHA512
1052
static const byte emptySHA512Hash[] = {
1053
    0xCF, 0x83, 0xE1, 0x35, 0x7E, 0xEF, 0xB8, 0xBD, 0xF1, 0x54, 0x28, 0x50,
1054
    0xD6, 0x6D, 0x80, 0x07, 0xD6, 0x20, 0xE4, 0x05, 0x0B, 0x57, 0x15, 0xDC,
1055
    0x83, 0xF4, 0xA9, 0x21, 0xD3, 0x6C, 0xE9, 0xCE, 0x47, 0xD0, 0xD1, 0x3C,
1056
    0x5D, 0x85, 0xF2, 0xB0, 0xFF, 0x83, 0x18, 0xD2, 0x87, 0x7E, 0xEC, 0x2F,
1057
    0x63, 0xB9, 0x31, 0xBD, 0x47, 0x41, 0x7A, 0x81, 0xA5, 0x38, 0x32, 0x7A,
1058
    0xF9, 0x27, 0xDA, 0x3E
1059
};
1060
#endif
1061
#ifdef WOLFSSL_SM3
1062
static const byte emptySM3Hash[] = {
1063
    0x1A, 0xB2, 0x1D, 0x83, 0x55, 0xCF, 0xA1, 0x7F, 0x8E, 0x61, 0x19, 0x48,
1064
    0x31, 0xE8, 0x1A, 0x8F, 0x22, 0xBE, 0xC8, 0xC7, 0x28, 0xFE, 0xFB, 0x74,
1065
    0x7E, 0xD0, 0x35, 0xEB, 0x50, 0x82, 0xAA, 0x2B
1066
};
1067
#endif
1068
/**
1069
 * Implement section 7.5 of RFC 8446
1070
 * @return  0 on success
1071
 *         <0 on failure
1072
 */
1073
int Tls13_Exporter(WOLFSSL* ssl, unsigned char *out, size_t outLen,
1074
        const char *label, size_t labelLen,
1075
        const unsigned char *context, size_t contextLen)
1076
{
1077
    int                 ret;
1078
    enum wc_HashType    hashType = WC_HASH_TYPE_NONE;
1079
    word32              hashLen = 0;
1080
    byte                hashOut[WC_MAX_DIGEST_SIZE];
1081
    const byte*         emptyHash = NULL;
1082
    byte                firstExpand[WC_MAX_DIGEST_SIZE];
1083
    const byte*         protocol = tls13ProtocolLabel;
1084
    word32              protocolLen = TLS13_PROTOCOL_LABEL_SZ;
1085
1086
    if (ssl->options.dtls && ssl->version.minor != DTLSv1_3_MINOR)
1087
        return VERSION_ERROR;
1088
1089
    if (!ssl->options.dtls && ssl->version.minor != TLSv1_3_MINOR)
1090
        return VERSION_ERROR;
1091
1092
#ifdef WOLFSSL_DTLS13
1093
    if (ssl->options.dtls) {
1094
        protocol = dtls13ProtocolLabel;
1095
        protocolLen = DTLS13_PROTOCOL_LABEL_SZ;
1096
    }
1097
#endif /* WOLFSSL_DTLS13 */
1098
1099
    /* Sanity check contextLen to prevent truncation when cast to word32. */
1100
    if (contextLen > WOLFSSL_MAX_32BIT)
1101
        return BAD_FUNC_ARG;
1102
    /* RFC 8446 HkdfLabel encodes the output length as a uint16, so requested
1103
     * lengths > 65535 cannot be represented and must be rejected. */
1104
    if (outLen > WOLFSSL_MAX_16BIT)
1105
        return BAD_FUNC_ARG;
1106
    /* RFC 8446 HkdfLabel encodes the label length in a single byte, so
1107
     * anything > 255 cannot be represented and must be rejected.
1108
     * The protocol length is included in the label. */
1109
    if ((labelLen +  protocolLen) > WOLFSSL_MAX_8BIT)
1110
        return BAD_FUNC_ARG;
1111
1112
    switch (ssl->specs.mac_algorithm) {
1113
        #ifndef NO_SHA256
1114
        case sha256_mac:
1115
            hashType  = WC_HASH_TYPE_SHA256;
1116
            hashLen   = WC_SHA256_DIGEST_SIZE;
1117
            emptyHash = emptySHA256Hash;
1118
            break;
1119
        #endif
1120
1121
        #ifdef WOLFSSL_SHA384
1122
        case sha384_mac:
1123
            hashType  = WC_HASH_TYPE_SHA384;
1124
            hashLen   = WC_SHA384_DIGEST_SIZE;
1125
            emptyHash = emptySHA384Hash;
1126
            break;
1127
        #endif
1128
1129
        #ifdef WOLFSSL_TLS13_SHA512
1130
        case sha512_mac:
1131
            hashType  = WC_HASH_TYPE_SHA512;
1132
            hashLen   = WC_SHA512_DIGEST_SIZE;
1133
            emptyHash = emptySHA512Hash;
1134
            break;
1135
        #endif
1136
1137
        #ifdef WOLFSSL_SM3
1138
        case sm3_mac:
1139
            hashType  = WC_HASH_TYPE_SM3;
1140
            hashLen   = WC_SM3_DIGEST_SIZE;
1141
            emptyHash = emptySM3Hash;
1142
            break;
1143
        #endif
1144
1145
        default:
1146
            return BAD_FUNC_ARG;
1147
    }
1148
1149
#ifdef WOLFSSL_CHECK_MEM_ZERO
1150
    /* Poison and register firstExpand before it is written so that any path
1151
     * below (all of which funnel through cleanup) is covered. */
1152
    XMEMSET(firstExpand, 0xff, sizeof(firstExpand));
1153
    wc_MemZero_Add("Tls13_Exporter firstExpand", firstExpand,
1154
                   sizeof(firstExpand));
1155
#endif
1156
1157
    /* Derive-Secret(Secret, label, "") */
1158
    ret = Tls13HKDFExpandLabel(ssl, firstExpand, hashLen,
1159
            ssl->arrays->exporterSecret, hashLen,
1160
            protocol, protocolLen, (byte*)label, (word32)labelLen,
1161
            emptyHash, hashLen, (int)hashType);
1162
    if (ret != 0)
1163
        goto cleanup;
1164
1165
    /* Hash(context_value) */
1166
    ret = wc_Hash(hashType, context, (word32)contextLen, hashOut, WC_MAX_DIGEST_SIZE);
1167
    if (ret != 0)
1168
        goto cleanup;
1169
1170
    ret = Tls13HKDFExpandLabel(ssl, out, (word32)outLen, firstExpand, hashLen,
1171
            protocol, protocolLen, exporterLabel, EXPORTER_LABEL_SZ,
1172
            hashOut, hashLen, (int)hashType);
1173
1174
cleanup:
1175
    /* firstExpand is the per-label Derive-Secret PRK and hashOut holds
1176
     * Hash(context_value); wipe both before the stack frame is reclaimed. */
1177
    ForceZero(firstExpand, sizeof(firstExpand));
1178
    ForceZero(hashOut, sizeof(hashOut));
1179
#ifdef WOLFSSL_CHECK_MEM_ZERO
1180
    wc_MemZero_Check(firstExpand, sizeof(firstExpand));
1181
#endif
1182
    return ret;
1183
}
1184
#endif
1185
1186
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
1187
/* The length of the resumption master secret label. */
1188
#define RESUME_MASTER_LABEL_SZ      10
1189
/* The resumption master secret label. */
1190
static const byte resumeMasterLabel[RESUME_MASTER_LABEL_SZ + 1] =
1191
    "res master";
1192
1193
/* Derive the resumption secret.
1194
 *
1195
 * ssl  The SSL/TLS object.
1196
 * key  The derived key.
1197
 * returns 0 on success, otherwise failure.
1198
 */
1199
int DeriveResumptionSecret(WOLFSSL* ssl, byte* key)
1200
{
1201
    byte* masterSecret;
1202
1203
    WOLFSSL_MSG("Derive Resumption Secret");
1204
    if (ssl == NULL) {
1205
        return BAD_FUNC_ARG;
1206
    }
1207
    if (ssl->arrays != NULL) {
1208
        masterSecret = ssl->arrays->masterSecret;
1209
    }
1210
    else {
1211
        masterSecret = ssl->session->masterSecret;
1212
    }
1213
    return Tls13DeriveKey(ssl, key, -1, masterSecret, resumeMasterLabel,
1214
                     RESUME_MASTER_LABEL_SZ, ssl->specs.mac_algorithm, 1,
1215
                     0 /* Unused */);
1216
}
1217
#endif
1218
1219
/* Length of the finished label. */
1220
0
#define FINISHED_LABEL_SZ           8
1221
/* Finished label for generating finished key. */
1222
static const byte finishedLabel[FINISHED_LABEL_SZ+1] = "finished";
1223
/* Derive the finished secret.
1224
 *
1225
 * ssl     The SSL/TLS object.
1226
 * key     The key to use with the HMAC.
1227
 * secret  The derived secret.
1228
 * side    The side that we are deriving the secret for.
1229
 * returns 0 on success, otherwise failure.
1230
 */
1231
static int DeriveFinishedSecret(WOLFSSL* ssl, byte* key, byte* secret,
1232
                                int side)
1233
0
{
1234
0
    WOLFSSL_MSG("Derive Finished Secret");
1235
0
    return Tls13DeriveKey(ssl, secret, -1, key, finishedLabel,
1236
0
                          FINISHED_LABEL_SZ,  ssl->specs.mac_algorithm, 0,
1237
0
                          side);
1238
0
}
1239
1240
/* The length of the application traffic label. */
1241
0
#define APP_TRAFFIC_LABEL_SZ        11
1242
/* The application traffic label. */
1243
static const byte appTrafficLabel[APP_TRAFFIC_LABEL_SZ + 1] =
1244
    "traffic upd";
1245
1246
/* Update the traffic secret.
1247
 *
1248
 * ssl     The SSL/TLS object.
1249
 * secret  The previous secret and derived secret.
1250
 * side    The side that we are deriving the secret for.
1251
 * returns 0 on success, otherwise failure.
1252
 */
1253
static int DeriveTrafficSecret(WOLFSSL* ssl, byte* secret, int side)
1254
0
{
1255
0
    WOLFSSL_MSG("Derive New Application Traffic Secret");
1256
0
    return Tls13DeriveKey(ssl, secret, -1, secret,
1257
0
                     appTrafficLabel, APP_TRAFFIC_LABEL_SZ,
1258
0
                     ssl->specs.mac_algorithm, 0, side);
1259
0
}
1260
1261
1262
static int Tls13_HKDF_Extract(WOLFSSL *ssl, byte* prk, const byte* salt,
1263
                              int saltLen, byte* ikm, int ikmLen, int digest)
1264
0
{
1265
0
    int ret;
1266
#ifdef HAVE_PK_CALLBACKS
1267
    void *cb_ctx;
1268
    CallbackHKDFExtract cb;
1269
#endif
1270
1271
#ifdef WOLFSSL_ASYNC_REINVOKE
1272
    ret = Tls13KdfAsyncInit(ssl);
1273
    if (ret != 0)
1274
        return ret;
1275
#endif
1276
1277
#ifdef HAVE_PK_CALLBACKS
1278
    cb_ctx = ssl->HkdfExtractCtx;
1279
    cb = ssl->ctx->HkdfExtractCb;
1280
    if (cb != NULL) {
1281
        ret = cb(prk, salt, (word32)saltLen, ikm, (word32)ikmLen, digest, cb_ctx);
1282
    }
1283
    else
1284
#endif
1285
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
1286
    if ((int)ssl->arrays->psk_keySz < 0) {
1287
        ret = PSK_KEY_ERROR;
1288
    }
1289
    else
1290
#endif
1291
0
    {
1292
0
    #if !defined(HAVE_FIPS) || \
1293
0
        (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(6,0))
1294
0
        ret = wc_Tls13_HKDF_Extract_ex(prk, salt, (word32)saltLen, ikm, (word32)ikmLen, digest,
1295
0
            ssl->heap, ssl->devId);
1296
    #else
1297
        ret = wc_Tls13_HKDF_Extract(prk, salt, saltLen, ikm, ikmLen, digest);
1298
        (void)ssl;
1299
    #endif
1300
0
    }
1301
#ifdef WOLFSSL_ASYNC_REINVOKE
1302
    if (ret == WC_NO_ERR_TRACE(WC_PENDING_E))
1303
        ret = wolfSSL_AsyncPush(ssl, &ssl->kdfAsyncDev);
1304
#endif
1305
0
    return ret;
1306
0
}
1307
1308
/* Derive the early secret using HKDF Extract.
1309
 *
1310
 * ssl  The SSL/TLS object.
1311
 */
1312
int DeriveEarlySecret(WOLFSSL* ssl)
1313
0
{
1314
0
    int ret;
1315
1316
0
    WOLFSSL_MSG("Derive Early Secret");
1317
0
    if (ssl == NULL || ssl->arrays == NULL) {
1318
0
        return BAD_FUNC_ARG;
1319
0
    }
1320
#if defined(WOLFSSL_RENESAS_TSIP_TLS)
1321
    ret = tsip_Tls13DeriveEarlySecret(ssl);
1322
    if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE))
1323
        return ret;
1324
#endif
1325
0
    PRIVATE_KEY_UNLOCK();
1326
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
1327
    ret = Tls13_HKDF_Extract(ssl, ssl->arrays->secret, NULL, 0,
1328
            ssl->arrays->psk_key, (int)ssl->arrays->psk_keySz,
1329
            mac2hash(ssl->specs.mac_algorithm));
1330
#else
1331
0
    ret = Tls13_HKDF_Extract(ssl, ssl->arrays->secret, NULL, 0,
1332
0
            ssl->arrays->masterSecret, 0, mac2hash(ssl->specs.mac_algorithm));
1333
0
#endif
1334
0
    PRIVATE_KEY_LOCK();
1335
0
    return ret;
1336
0
}
1337
1338
/* The length of the derived label. */
1339
0
#define DERIVED_LABEL_SZ        7
1340
/* The derived label. */
1341
static const byte derivedLabel[DERIVED_LABEL_SZ + 1] =
1342
    "derived";
1343
1344
/* Derive the handshake secret using HKDF Extract.
1345
 *
1346
 * ssl  The SSL/TLS object.
1347
 */
1348
int DeriveHandshakeSecret(WOLFSSL* ssl)
1349
0
{
1350
0
    byte key[WC_MAX_DIGEST_SIZE];
1351
0
    int ret;
1352
0
    WOLFSSL_MSG("Derive Handshake Secret");
1353
0
    if (ssl == NULL || ssl->arrays == NULL) {
1354
0
        return BAD_FUNC_ARG;
1355
0
    }
1356
#if defined(WOLFSSL_RENESAS_TSIP_TLS)
1357
    ret = tsip_Tls13DeriveHandshakeSecret(ssl);
1358
    if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE))
1359
        return ret;
1360
#endif
1361
1362
    /* Derive-Secret(., "derived", "") per RFC 8446 Section 7.1.
1363
     * Empty hash (NULL, 0) is required by the TLS 1.3 key schedule. */
1364
0
    ret = DeriveKeyMsg(ssl, key, -1, ssl->arrays->secret,
1365
0
                        derivedLabel, DERIVED_LABEL_SZ,
1366
0
                        NULL, 0, ssl->specs.mac_algorithm);
1367
0
    if (ret == 0) {
1368
0
        PRIVATE_KEY_UNLOCK();
1369
0
        ret = Tls13_HKDF_Extract(ssl, ssl->arrays->preMasterSecret,
1370
0
                key, ssl->specs.hash_size,
1371
0
                ssl->arrays->preMasterSecret, (int)ssl->arrays->preMasterSz,
1372
0
                mac2hash(ssl->specs.mac_algorithm));
1373
0
        PRIVATE_KEY_LOCK();
1374
0
    }
1375
1376
#ifdef WOLFSSL_CHECK_MEM_ZERO
1377
    wc_MemZero_Add("DeriveHandshakeSecret key", key, WC_MAX_DIGEST_SIZE);
1378
#endif
1379
0
    ForceZero(key, sizeof(key));
1380
#ifdef WOLFSSL_CHECK_MEM_ZERO
1381
    wc_MemZero_Check(key, sizeof(key));
1382
#endif
1383
0
    return ret;
1384
0
}
1385
1386
/* Derive the master secret using HKDF Extract.
1387
 *
1388
 * ssl  The SSL/TLS object.
1389
 */
1390
int DeriveMasterSecret(WOLFSSL* ssl)
1391
0
{
1392
0
    byte key[WC_MAX_DIGEST_SIZE];
1393
0
    int ret;
1394
0
    WOLFSSL_MSG("Derive Master Secret");
1395
0
    if (ssl == NULL || ssl->arrays == NULL) {
1396
0
        return BAD_FUNC_ARG;
1397
0
    }
1398
1399
#if defined(WOLFSSL_RENESAS_TSIP_TLS)
1400
    ret = tsip_Tls13DeriveMasterSecret(ssl);
1401
    if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE))
1402
        return ret;
1403
#endif
1404
1405
    /* Derive-Secret(., "derived", "") per RFC 8446 Section 7.1.
1406
     * Empty hash (NULL, 0) is required by the TLS 1.3 key schedule. */
1407
0
    ret = DeriveKeyMsg(ssl, key, -1, ssl->arrays->preMasterSecret,
1408
0
                        derivedLabel, DERIVED_LABEL_SZ,
1409
0
                        NULL, 0, ssl->specs.mac_algorithm);
1410
0
    if (ret == 0) {
1411
0
        PRIVATE_KEY_UNLOCK();
1412
0
        ret = Tls13_HKDF_Extract(ssl, ssl->arrays->masterSecret,
1413
0
                                 key, ssl->specs.hash_size,
1414
0
                                 ssl->arrays->masterSecret, 0,
1415
0
                                 mac2hash(ssl->specs.mac_algorithm));
1416
0
        PRIVATE_KEY_LOCK();
1417
0
    }
1418
1419
#ifdef WOLFSSL_CHECK_MEM_ZERO
1420
    wc_MemZero_Add("DeriveMasterSecret key", key, WC_MAX_DIGEST_SIZE);
1421
#endif
1422
0
    ForceZero(key, sizeof(key));
1423
#ifdef WOLFSSL_CHECK_MEM_ZERO
1424
    wc_MemZero_Check(key, sizeof(key));
1425
#endif
1426
1427
#ifdef HAVE_KEYING_MATERIAL
1428
    if (ret != 0)
1429
        return ret;
1430
    /* Calculate exporter secret only when saving arrays */
1431
    if (ssl->options.saveArrays)
1432
        ret = DeriveExporterSecret(ssl, ssl->arrays->exporterSecret);
1433
#endif
1434
1435
0
    return ret;
1436
0
}
1437
1438
#if defined(HAVE_SESSION_TICKET)
1439
/* Length of the resumption label. */
1440
#define RESUMPTION_LABEL_SZ         10
1441
/* Resumption label for generating PSK associated with the ticket. */
1442
static const byte resumptionLabel[RESUMPTION_LABEL_SZ+1] = "resumption";
1443
1444
/* Derive the PSK associated with the ticket.
1445
 *
1446
 * ssl       The SSL/TLS object.
1447
 * nonce     The nonce to derive with.
1448
 * nonceLen  The length of the nonce to derive with.
1449
 * secret    The derived secret.
1450
 * returns 0 on success, otherwise failure.
1451
 */
1452
int DeriveResumptionPSK(WOLFSSL* ssl, byte* nonce, byte nonceLen, byte* secret)
1453
{
1454
    int         digestAlg;
1455
    /* Only one protocol version defined at this time. */
1456
    const byte* protocol    = tls13ProtocolLabel;
1457
    word32      protocolLen = TLS13_PROTOCOL_LABEL_SZ;
1458
    int         ret;
1459
1460
    WOLFSSL_MSG("Derive Resumption PSK");
1461
1462
#ifdef WOLFSSL_DTLS13
1463
    if (ssl->options.dtls) {
1464
        protocol = dtls13ProtocolLabel;
1465
        protocolLen = DTLS13_PROTOCOL_LABEL_SZ;
1466
    }
1467
#endif /* WOLFSSL_DTLS13 */
1468
1469
    switch (ssl->specs.mac_algorithm) {
1470
        #ifndef NO_SHA256
1471
        case sha256_mac:
1472
            digestAlg = WC_SHA256;
1473
            break;
1474
        #endif
1475
1476
        #ifdef WOLFSSL_SHA384
1477
        case sha384_mac:
1478
            digestAlg = WC_SHA384;
1479
            break;
1480
        #endif
1481
1482
        #ifdef WOLFSSL_TLS13_SHA512
1483
        case sha512_mac:
1484
            digestAlg = WC_SHA512;
1485
            break;
1486
        #endif
1487
1488
        #ifdef WOLFSSL_SM3
1489
        case sm3_mac:
1490
            digestAlg = WC_SM3;
1491
            break;
1492
        #endif
1493
1494
        default:
1495
            return BAD_FUNC_ARG;
1496
    }
1497
1498
#if defined(WOLFSSL_TICKET_NONCE_MALLOC) &&                                    \
1499
    (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
1500
    PRIVATE_KEY_UNLOCK();
1501
    ret = wc_Tls13_HKDF_Expand_Label_Alloc(secret, ssl->specs.hash_size,
1502
        ssl->session->masterSecret, ssl->specs.hash_size, protocol, protocolLen,
1503
        resumptionLabel, RESUMPTION_LABEL_SZ, nonce, nonceLen, digestAlg,
1504
        ssl->heap);
1505
    PRIVATE_KEY_LOCK();
1506
#else
1507
    ret = Tls13HKDFExpandLabel(ssl, secret, ssl->specs.hash_size,
1508
                               ssl->session->masterSecret, ssl->specs.hash_size,
1509
                               protocol, protocolLen, resumptionLabel,
1510
                               RESUMPTION_LABEL_SZ, nonce, nonceLen, digestAlg);
1511
#endif /* !defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3) */
1512
    return ret;
1513
}
1514
#endif /* HAVE_SESSION_TICKET */
1515
1516
1517
/* Calculate the HMAC of message data to this point.
1518
 *
1519
 * ssl   The SSL/TLS object.
1520
 * key   The HMAC key.
1521
 * hash  The hash result - verify data.
1522
 * returns length of verify data generated.
1523
 */
1524
#if defined(WOLFSSL_ASYNC_REINVOKE) && !defined(NO_HMAC)
1525
/* Release the held transcript Hmac and its resume state. */
1526
void Tls13FreeHsHmac(WOLFSSL* ssl)
1527
{
1528
    if (ssl->hsHmac != NULL) {
1529
        wc_HmacFree(ssl->hsHmac);
1530
        XFREE(ssl->hsHmac, ssl->heap, DYNAMIC_TYPE_HMAC);
1531
        ssl->hsHmac = NULL;
1532
    }
1533
    ssl->hsHmacStep = 0;
1534
    ssl->hsHmacOut = NULL;
1535
}
1536
#endif /* WOLFSSL_ASYNC_REINVOKE && !NO_HMAC */
1537
1538
static int BuildTls13HandshakeHmac(WOLFSSL* ssl, byte* key, byte* hash,
1539
    word32* pHashSz)
1540
0
{
1541
0
#ifndef WOLFSSL_ASYNC_REINVOKE
1542
0
    WC_DECLARE_VAR(verifyHmac, Hmac, 1, 0);
1543
0
#endif
1544
0
    int  hashType = WC_SHA256;
1545
0
    int  hashSz = WC_SHA256_DIGEST_SIZE;
1546
0
    int  ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG);
1547
1548
0
    if (ssl == NULL || key == NULL || hash == NULL) {
1549
0
        return BAD_FUNC_ARG;
1550
0
    }
1551
1552
    /* Get the hash of the previous handshake messages. */
1553
0
    switch (ssl->specs.mac_algorithm) {
1554
0
    #ifndef NO_SHA256
1555
0
        case sha256_mac:
1556
0
            hashType = WC_SHA256;
1557
0
            hashSz = WC_SHA256_DIGEST_SIZE;
1558
0
            ret = wc_Sha256GetHash(&ssl->hsHashes->hashSha256, hash);
1559
0
            break;
1560
0
    #endif /* !NO_SHA256 */
1561
0
    #ifdef WOLFSSL_SHA384
1562
0
        case sha384_mac:
1563
0
            hashType = WC_SHA384;
1564
0
            hashSz = WC_SHA384_DIGEST_SIZE;
1565
0
            ret = wc_Sha384GetHash(&ssl->hsHashes->hashSha384, hash);
1566
0
            break;
1567
0
    #endif /* WOLFSSL_SHA384 */
1568
    #ifdef WOLFSSL_TLS13_SHA512
1569
        case sha512_mac:
1570
            hashType = WC_SHA512;
1571
            hashSz = WC_SHA512_DIGEST_SIZE;
1572
            ret = wc_Sha512GetHash(&ssl->hsHashes->hashSha512, hash);
1573
            break;
1574
    #endif /* WOLFSSL_TLS13_SHA512 */
1575
    #ifdef WOLFSSL_SM3
1576
        case sm3_mac:
1577
            hashType = WC_SM3;
1578
            hashSz = WC_SM3_DIGEST_SIZE;
1579
            ret = wc_Sm3GetHash(&ssl->hsHashes->hashSm3, hash);
1580
            break;
1581
    #endif /* WOLFSSL_SM3 */
1582
0
        default:
1583
0
            ret = BAD_FUNC_ARG;
1584
0
            break;
1585
0
    }
1586
0
    if (ret != 0)
1587
0
        return ret;
1588
1589
#ifdef WOLFSSL_DEBUG_TLS
1590
    WOLFSSL_MSG("  Key");
1591
    WOLFSSL_BUFFER(key, ssl->specs.hash_size);
1592
    WOLFSSL_MSG("  Msg Hash");
1593
    WOLFSSL_BUFFER(hash, hashSz);
1594
#endif
1595
1596
#ifdef WOLFSSL_ASYNC_REINVOKE
1597
    /* Held on the SSL object so a crypto callback WC_PENDING_E resumes by
1598
     * re-invoking the same Hmac with identical arguments; the transcript
1599
     * hash input is recomputed deterministically by the caller's retry.
1600
     * Bound to the output buffer: a replayed caller that computes several
1601
     * HMACs (the PSK binder list) must not resume one request against
1602
     * another's key, so a different output discards the held state. */
1603
    if (ssl->hsHmac != NULL && ssl->hsHmacOut != hash)
1604
        Tls13FreeHsHmac(ssl);
1605
    if (ssl->hsHmac == NULL) {
1606
        ssl->hsHmac = (Hmac*)XMALLOC(sizeof(Hmac), ssl->heap,
1607
                                     DYNAMIC_TYPE_HMAC);
1608
        if (ssl->hsHmac == NULL)
1609
            return MEMORY_E;
1610
        ret = wc_HmacInit(ssl->hsHmac, ssl->heap, ssl->devId);
1611
        if (ret != 0) {
1612
            Tls13FreeHsHmac(ssl);
1613
            return ret;
1614
        }
1615
        ssl->hsHmacStep = 0;
1616
        ssl->hsHmacOut = hash;
1617
    }
1618
    /* Armed before the operations, matching the HKDF helpers. */
1619
    ret = Tls13KdfAsyncInit(ssl);
1620
    if (ret != 0) {
1621
        Tls13FreeHsHmac(ssl);
1622
        return ret;
1623
    }
1624
    if (ssl->hsHmacStep == 0) {
1625
        ret = wc_HmacSetKey(ssl->hsHmac, hashType, key,
1626
                            ssl->specs.hash_size);
1627
        if (ret == 0)
1628
            ssl->hsHmacStep = 1;
1629
    }
1630
    if (ret == 0 && ssl->hsHmacStep == 1) {
1631
        ret = wc_HmacUpdate(ssl->hsHmac, hash, (word32)hashSz);
1632
        if (ret == 0)
1633
            ssl->hsHmacStep = 2;
1634
    }
1635
    if (ret == 0 && ssl->hsHmacStep == 2)
1636
        ret = wc_HmacFinal(ssl->hsHmac, hash);
1637
    if (ret == WC_NO_ERR_TRACE(WC_PENDING_E))
1638
        return wolfSSL_AsyncPush(ssl, &ssl->kdfAsyncDev);
1639
    Tls13FreeHsHmac(ssl);
1640
#else
1641
0
    WC_ALLOC_VAR_EX(verifyHmac, Hmac, 1, NULL, DYNAMIC_TYPE_HMAC,
1642
0
        return MEMORY_E);
1643
1644
    /* Calculate the verify data. */
1645
0
    ret = wc_HmacInit(verifyHmac, ssl->heap, ssl->devId);
1646
0
    if (ret == 0) {
1647
0
        ret = wc_HmacSetKey(verifyHmac, hashType, key, ssl->specs.hash_size);
1648
0
        if (ret == 0)
1649
0
            ret = wc_HmacUpdate(verifyHmac, hash, (word32)hashSz);
1650
0
        if (ret == 0)
1651
0
            ret = wc_HmacFinal(verifyHmac, hash);
1652
0
        wc_HmacFree(verifyHmac);
1653
0
    }
1654
1655
0
    WC_FREE_VAR_EX(verifyHmac, NULL, DYNAMIC_TYPE_HMAC);
1656
0
#endif /* WOLFSSL_ASYNC_REINVOKE */
1657
1658
#ifdef WOLFSSL_DEBUG_TLS
1659
    WOLFSSL_MSG("  Hash");
1660
    WOLFSSL_BUFFER(hash, hashSz);
1661
#endif
1662
1663
0
    if (pHashSz)
1664
0
        *pHashSz = (word32)hashSz;
1665
1666
0
    return ret;
1667
0
}
1668
1669
/* The length of the label to use when deriving keys. */
1670
0
#define WRITE_KEY_LABEL_SZ     3
1671
/* The length of the label to use when deriving IVs. */
1672
0
#define WRITE_IV_LABEL_SZ      2
1673
/* The label to use when deriving keys. */
1674
static const byte writeKeyLabel[WRITE_KEY_LABEL_SZ+1] = "key";
1675
/* The label to use when deriving IVs. */
1676
static const byte writeIVLabel[WRITE_IV_LABEL_SZ+1]   = "iv";
1677
1678
/* Derive the keys and IVs for TLS v1.3.
1679
 *
1680
 * ssl      The SSL/TLS object.
1681
 * secret   early_data_key when deriving the key and IV for encrypting early
1682
 *          data application data and end_of_early_data messages.
1683
 *          handshake_key when deriving keys and IVs for encrypting handshake
1684
 *          messages.
1685
 *          traffic_key when deriving first keys and IVs for encrypting
1686
 *          traffic messages.
1687
 *          update_traffic_key when deriving next keys and IVs for encrypting
1688
 *          traffic messages.
1689
 *          no_key when deriving keys and IVs from existing secrets without
1690
 *          re-deriving the secrets. Used during early data transitions.
1691
 * side     ENCRYPT_SIDE_ONLY when only encryption secret needs to be derived.
1692
 *          DECRYPT_SIDE_ONLY when only decryption secret needs to be derived.
1693
 *          ENCRYPT_AND_DECRYPT_SIDE when both secret needs to be derived.
1694
 * store    1 indicates to derive the keys and IVs from derived secret and
1695
 *          store ready for provisioning.
1696
 * returns 0 on success, otherwise failure.
1697
 */
1698
int DeriveTls13Keys(WOLFSSL* ssl, int secret, int side, int store)
1699
0
{
1700
0
    int   ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); /* Assume failure */
1701
0
    int   i = 0;
1702
0
    WC_DECLARE_VAR(key_dig, byte, MAX_PRF_DIG, 0);
1703
0
    int   provision;
1704
1705
#if defined(WOLFSSL_RENESAS_TSIP_TLS)
1706
    ret = tsip_Tls13DeriveKeys(ssl, secret, side);
1707
    if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
1708
        return ret;
1709
    }
1710
    ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG); /* Assume failure */
1711
#endif
1712
1713
0
    WC_ALLOC_VAR_EX(key_dig, byte, MAX_PRF_DIG, ssl->heap,
1714
0
        DYNAMIC_TYPE_DIGEST, return MEMORY_E);
1715
1716
#ifdef WOLFSSL_CHECK_MEM_ZERO
1717
    XMEMSET(key_dig, 0xff, MAX_PRF_DIG);
1718
    wc_MemZero_Add("DeriveTls13Keys key_dig", key_dig, MAX_PRF_DIG);
1719
#endif
1720
1721
0
    if (side == ENCRYPT_AND_DECRYPT_SIDE) {
1722
0
        provision = PROVISION_CLIENT_SERVER;
1723
0
    }
1724
0
    else {
1725
0
        provision = ((ssl->options.side != WOLFSSL_CLIENT_END) ^
1726
0
                     (side == ENCRYPT_SIDE_ONLY)) ? PROVISION_CLIENT :
1727
0
                                                    PROVISION_SERVER;
1728
0
    }
1729
1730
    /* Derive the appropriate secret to use in the HKDF. */
1731
0
    switch (secret) {
1732
#ifdef WOLFSSL_EARLY_DATA
1733
        case early_data_key:
1734
            ret = DeriveEarlyTrafficSecret(ssl, ssl->clientSecret,
1735
                                           WOLFSSL_CLIENT_END);
1736
            if (ret != 0)
1737
                goto end;
1738
            break;
1739
#endif
1740
1741
0
        case handshake_key:
1742
0
            if (provision & PROVISION_CLIENT) {
1743
0
                ret = DeriveClientHandshakeSecret(ssl,
1744
0
                                                  ssl->clientSecret);
1745
0
                if (ret != 0)
1746
0
                    goto end;
1747
0
            }
1748
0
            if (provision & PROVISION_SERVER) {
1749
0
                ret = DeriveServerHandshakeSecret(ssl,
1750
0
                                                  ssl->serverSecret);
1751
0
                if (ret != 0)
1752
0
                    goto end;
1753
0
            }
1754
0
            break;
1755
1756
0
        case traffic_key:
1757
0
            if (provision & PROVISION_CLIENT) {
1758
0
                ret = DeriveClientTrafficSecret(ssl, ssl->clientSecret);
1759
0
                if (ret != 0)
1760
0
                    goto end;
1761
0
            }
1762
0
            if (provision & PROVISION_SERVER) {
1763
0
                ret = DeriveServerTrafficSecret(ssl, ssl->serverSecret);
1764
0
                if (ret != 0)
1765
0
                    goto end;
1766
0
            }
1767
0
            break;
1768
1769
0
        case update_traffic_key:
1770
0
            if (provision & PROVISION_CLIENT) {
1771
0
                ret = DeriveTrafficSecret(ssl, ssl->clientSecret,
1772
0
                                          WOLFSSL_CLIENT_END);
1773
0
                if (ret != 0)
1774
0
                    goto end;
1775
0
            }
1776
0
            if (provision & PROVISION_SERVER) {
1777
0
                ret = DeriveTrafficSecret(ssl, ssl->serverSecret,
1778
0
                                          WOLFSSL_SERVER_END);
1779
0
                if (ret != 0)
1780
0
                    goto end;
1781
0
            }
1782
0
            break;
1783
1784
0
        case no_key:
1785
            /* Called with early data to derive keys from existing secrets
1786
             * without re-deriving the secrets themselves. */
1787
0
            ret = 0;
1788
0
            break;
1789
1790
0
        default:
1791
0
            ret = BAD_FUNC_ARG;
1792
0
            break;
1793
0
    }
1794
1795
#ifdef WOLFSSL_QUIC
1796
    if (WOLFSSL_IS_QUIC(ssl)) {
1797
        ret = wolfSSL_quic_forward_secrets(ssl, secret, side);
1798
        if (ret != 0)
1799
            goto end;
1800
    }
1801
#endif /* WOLFSSL_QUIC */
1802
1803
0
    if (!store)
1804
0
        goto end;
1805
1806
    /* Key data = client key | server key | client IV | server IV */
1807
1808
0
    if (provision & PROVISION_CLIENT) {
1809
        /* Derive the client key.  */
1810
0
        WOLFSSL_MSG("Derive Client Key");
1811
0
        ret = Tls13DeriveKey(ssl, &key_dig[i], ssl->specs.key_size,
1812
0
                        ssl->clientSecret, writeKeyLabel,
1813
0
                        WRITE_KEY_LABEL_SZ, ssl->specs.mac_algorithm, 0,
1814
0
                        WOLFSSL_CLIENT_END);
1815
0
        if (ret != 0)
1816
0
            goto end;
1817
0
        i += ssl->specs.key_size;
1818
0
    }
1819
1820
0
    if (provision & PROVISION_SERVER) {
1821
        /* Derive the server key.  */
1822
0
        WOLFSSL_MSG("Derive Server Key");
1823
0
        ret = Tls13DeriveKey(ssl, &key_dig[i], ssl->specs.key_size,
1824
0
                        ssl->serverSecret, writeKeyLabel,
1825
0
                        WRITE_KEY_LABEL_SZ, ssl->specs.mac_algorithm, 0,
1826
0
                        WOLFSSL_SERVER_END);
1827
0
        if (ret != 0)
1828
0
            goto end;
1829
0
        i += ssl->specs.key_size;
1830
0
    }
1831
1832
0
    if (provision & PROVISION_CLIENT) {
1833
        /* Derive the client IV.  */
1834
0
        WOLFSSL_MSG("Derive Client IV");
1835
0
        ret = Tls13DeriveKey(ssl, &key_dig[i], ssl->specs.iv_size,
1836
0
                        ssl->clientSecret, writeIVLabel,
1837
0
                        WRITE_IV_LABEL_SZ, ssl->specs.mac_algorithm, 0,
1838
0
                        WOLFSSL_CLIENT_END);
1839
0
        if (ret != 0)
1840
0
            goto end;
1841
0
        i += ssl->specs.iv_size;
1842
0
    }
1843
1844
0
    if (provision & PROVISION_SERVER) {
1845
        /* Derive the server IV.  */
1846
0
        WOLFSSL_MSG("Derive Server IV");
1847
0
        ret = Tls13DeriveKey(ssl, &key_dig[i], ssl->specs.iv_size,
1848
0
                        ssl->serverSecret, writeIVLabel,
1849
0
                        WRITE_IV_LABEL_SZ, ssl->specs.mac_algorithm, 0,
1850
0
                        WOLFSSL_SERVER_END);
1851
0
        if (ret != 0)
1852
0
            goto end;
1853
        /* Server IV is the last key material written to key_dig, so i is not
1854
         * advanced here; the whole buffer is zeroed at end regardless. */
1855
0
    }
1856
1857
    /* Store keys and IVs but don't activate them. */
1858
0
    ret = StoreKeys(ssl, key_dig, provision);
1859
1860
#ifdef WOLFSSL_DTLS13
1861
    if (ret != 0)
1862
      goto end;
1863
1864
    if (ssl->options.dtls) {
1865
        w64wrapper epochNumber;
1866
        ret = Dtls13DeriveSnKeys(ssl, provision);
1867
        if (ret != 0)
1868
            goto end;
1869
1870
        switch (secret) {
1871
            case early_data_key:
1872
                epochNumber = w64From32(0, DTLS13_EPOCH_EARLYDATA);
1873
                break;
1874
            case handshake_key:
1875
                epochNumber = w64From32(0, DTLS13_EPOCH_HANDSHAKE);
1876
                break;
1877
            case traffic_key:
1878
            case no_key:
1879
                epochNumber = w64From32(0, DTLS13_EPOCH_TRAFFIC0);
1880
                break;
1881
            case update_traffic_key:
1882
                if (side == ENCRYPT_SIDE_ONLY) {
1883
                    epochNumber = ssl->dtls13Epoch;
1884
                }
1885
                else if (side == DECRYPT_SIDE_ONLY) {
1886
                    epochNumber = ssl->dtls13PeerEpoch;
1887
                }
1888
                else {
1889
                    ret = BAD_STATE_E;
1890
                    goto end;
1891
                }
1892
                w64Increment(&epochNumber);
1893
                break;
1894
            default:
1895
                ret = BAD_STATE_E;
1896
                goto end;
1897
        }
1898
        ret = Dtls13NewEpoch(ssl, epochNumber, side);
1899
        if (ret != 0)
1900
            goto end;
1901
    }
1902
1903
#endif /* WOLFSSL_DTLS13 */
1904
1905
0
end:
1906
    /* Zero the whole key_dig buffer (not just the i bytes derived) so no
1907
     * key-schedule material can linger in the unused tail. */
1908
0
    ForceZero(key_dig, MAX_PRF_DIG);
1909
#ifdef WOLFSSL_SMALL_STACK
1910
    XFREE(key_dig, ssl->heap, DYNAMIC_TYPE_DIGEST);
1911
#elif defined(WOLFSSL_CHECK_MEM_ZERO)
1912
    wc_MemZero_Check(key_dig, MAX_PRF_DIG);
1913
#endif
1914
1915
0
    if (ret != 0) {
1916
0
        WOLFSSL_ERROR_VERBOSE(ret);
1917
0
    }
1918
1919
0
    return ret;
1920
0
}
1921
1922
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK) || defined(WOLFSSL_DTLS13)
1923
#ifdef WOLFSSL_32BIT_MILLI_TIME
1924
#ifndef NO_ASN_TIME
1925
#if defined(USER_TICKS)
1926
#if 0
1927
    word32 TimeNowInMilliseconds(void)
1928
    {
1929
        /*
1930
        write your own clock tick function if don't want gettimeofday()
1931
        needs millisecond accuracy but doesn't have to correlated to EPOCH
1932
        */
1933
    }
1934
#endif
1935
1936
#elif defined(TIME_OVERRIDES)
1937
#if !defined(NO_ASN) && !defined(NO_ASN_TIME)
1938
    word32 TimeNowInMilliseconds(void)
1939
    {
1940
        return (word32) wc_Time(0) * 1000;
1941
    }
1942
#else
1943
    #ifndef HAVE_TIME_T_TYPE
1944
        typedef long time_t;
1945
    #endif
1946
    extern time_t XTIME(time_t * timer);
1947
1948
    /* The time in milliseconds.
1949
     * Used for tickets to represent difference between when first seen and when
1950
     * sending.
1951
     *
1952
     * returns the time in milliseconds as a 32-bit value.
1953
     */
1954
    word32 TimeNowInMilliseconds(void)
1955
    {
1956
        return (word32) XTIME(0) * 1000;
1957
    }
1958
#endif
1959
1960
#elif defined(XTIME_MS)
1961
    word32 TimeNowInMilliseconds(void)
1962
    {
1963
        return (word32)XTIME_MS(0);
1964
    }
1965
1966
#elif defined(USE_WINDOWS_API)
1967
    /* The time in milliseconds.
1968
     * Used for tickets to represent difference between when first seen and when
1969
     * sending.
1970
     *
1971
     * returns the time in milliseconds as a 32-bit value.
1972
     */
1973
    word32 TimeNowInMilliseconds(void)
1974
    {
1975
        static int           init = 0;
1976
        static LARGE_INTEGER freq;
1977
        LARGE_INTEGER        count;
1978
1979
        if (!init) {
1980
            QueryPerformanceFrequency(&freq);
1981
            init = 1;
1982
        }
1983
1984
        QueryPerformanceCounter(&count);
1985
1986
        return (word32)(count.QuadPart / (freq.QuadPart / 1000));
1987
    }
1988
1989
#elif defined(HAVE_RTP_SYS)
1990
    #include "rtptime.h"
1991
1992
    /* The time in milliseconds.
1993
     * Used for tickets to represent difference between when first seen and when
1994
     * sending.
1995
     *
1996
     * returns the time in milliseconds as a 32-bit value.
1997
     */
1998
    word32 TimeNowInMilliseconds(void)
1999
    {
2000
        return (word32)rtp_get_system_sec() * 1000;
2001
    }
2002
#elif defined(WOLFSSL_DEOS)
2003
    word32 TimeNowInMilliseconds(void)
2004
    {
2005
        const word32 systemTickTimeInHz = 1000000 / systemTickInMicroseconds();
2006
        word32 *systemTickPtr = systemTickPointer();
2007
2008
        return (word32) (*systemTickPtr/systemTickTimeInHz) * 1000;
2009
    }
2010
#elif defined(MICRIUM)
2011
    /* The time in milliseconds.
2012
     * Used for tickets to represent difference between when first seen and when
2013
     * sending.
2014
     *
2015
     * returns the time in milliseconds as a 32-bit value.
2016
     */
2017
    word32 TimeNowInMilliseconds(void)
2018
    {
2019
        OS_TICK ticks = 0;
2020
        OS_ERR  err;
2021
2022
        ticks = OSTimeGet(&err);
2023
2024
        return (word32) (ticks / OSCfg_TickRate_Hz) * 1000;
2025
    }
2026
#elif defined(MICROCHIP_TCPIP_V5)
2027
    /* The time in milliseconds.
2028
     * Used for tickets to represent difference between when first seen and when
2029
     * sending.
2030
     *
2031
     * returns the time in milliseconds as a 32-bit value.
2032
     */
2033
    word32 TimeNowInMilliseconds(void)
2034
    {
2035
        return (word32) (TickGet() / (TICKS_PER_SECOND / 1000));
2036
    }
2037
#elif defined(MICROCHIP_TCPIP)
2038
    #if defined(MICROCHIP_MPLAB_HARMONY)
2039
        #include <system/tmr/sys_tmr.h>
2040
2041
    /* The time in milliseconds.
2042
     * Used for tickets to represent difference between when first seen and when
2043
     * sending.
2044
     *
2045
     * returns the time in milliseconds as a 32-bit value.
2046
     */
2047
    word32 TimeNowInMilliseconds(void)
2048
    {
2049
        return (word32)(SYS_TMR_TickCountGet() /
2050
                        (SYS_TMR_TickCounterFrequencyGet() / 1000));
2051
    }
2052
    #else
2053
    /* The time in milliseconds.
2054
     * Used for tickets to represent difference between when first seen and when
2055
     * sending.
2056
     *
2057
     * returns the time in milliseconds as a 32-bit value.
2058
     */
2059
    word32 TimeNowInMilliseconds(void)
2060
    {
2061
        return (word32)(SYS_TICK_Get() / (SYS_TICK_TicksPerSecondGet() / 1000));
2062
    }
2063
2064
    #endif
2065
2066
#elif defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX)
2067
    /* The time in milliseconds.
2068
     * Used for tickets to represent difference between when first seen and when
2069
     * sending.
2070
     *
2071
     * returns the time in milliseconds as a 32-bit value.
2072
     */
2073
    word32 TimeNowInMilliseconds(void)
2074
    {
2075
        TIME_STRUCT mqxTime;
2076
2077
        _time_get_elapsed(&mqxTime);
2078
2079
        return (word32) mqxTime.SECONDS * 1000;
2080
    }
2081
#elif defined(FREESCALE_FREE_RTOS) || defined(FREESCALE_KSDK_FREERTOS)
2082
    #include "include/task.h"
2083
2084
    /* The time in milliseconds.
2085
     * Used for tickets to represent difference between when first seen and when
2086
     * sending.
2087
     *
2088
     * returns the time in milliseconds as a 32-bit value.
2089
     */
2090
    word32 TimeNowInMilliseconds(void)
2091
    {
2092
        return (unsigned int)(((float)xTaskGetTickCount()) /
2093
                              (configTICK_RATE_HZ / 1000));
2094
    }
2095
#elif defined(FREESCALE_KSDK_BM)
2096
    #include "lwip/sys.h" /* lwIP */
2097
2098
    /* The time in milliseconds.
2099
     * Used for tickets to represent difference between when first seen and when
2100
     * sending.
2101
     *
2102
     * returns the time in milliseconds as a 32-bit value.
2103
     */
2104
    word32 TimeNowInMilliseconds(void)
2105
    {
2106
        return sys_now();
2107
    }
2108
2109
#elif defined(WOLFSSL_CMSIS_RTOS) || defined(WOLFSSL_CMSIS_RTOSv2)
2110
2111
    word32 TimeNowInMilliseconds(void)
2112
    {
2113
        return (word32)osKernelGetTickCount();
2114
    }
2115
2116
#elif defined(WOLFSSL_TIRTOS)
2117
    /* The time in milliseconds.
2118
     * Used for tickets to represent difference between when first seen and when
2119
     * sending.
2120
     *
2121
     * returns the time in milliseconds as a 32-bit value.
2122
     */
2123
    word32 TimeNowInMilliseconds(void)
2124
    {
2125
        return (word32) Seconds_get() * 1000;
2126
    }
2127
#elif defined(WOLFSSL_UTASKER)
2128
    /* The time in milliseconds.
2129
     * Used for tickets to represent difference between when first seen and when
2130
     * sending.
2131
     *
2132
     * returns the time in milliseconds as a 32-bit value.
2133
     */
2134
    word32 TimeNowInMilliseconds(void)
2135
    {
2136
        return (word32)(uTaskerSystemTick / (TICK_RESOLUTION / 1000));
2137
    }
2138
#elif defined(WOLFSSL_LINUXKM)
2139
    word32 TimeNowInMilliseconds(void)
2140
    {
2141
        s64 t;
2142
#if LINUX_VERSION_CODE < KERNEL_VERSION(4, 0, 0)
2143
        struct timespec ts;
2144
        getnstimeofday(&ts);
2145
        t = ts.tv_sec * (s64)1000;
2146
        t += ts.tv_nsec / (s64)1000000;
2147
#else
2148
        struct timespec64 ts;
2149
#if LINUX_VERSION_CODE < KERNEL_VERSION(5, 0, 0)
2150
        ts = current_kernel_time64();
2151
#else
2152
        ktime_get_coarse_real_ts64(&ts);
2153
#endif
2154
        t = ts.tv_sec * 1000L;
2155
        t += ts.tv_nsec / 1000000L;
2156
#endif
2157
        return (word32)t;
2158
    }
2159
#elif defined(WOLFSSL_QNX_CAAM)
2160
    word32 TimeNowInMilliseconds(void)
2161
    {
2162
        struct timespec now;
2163
        clock_gettime(CLOCK_REALTIME, &now);
2164
        return (word32)(now.tv_sec * 1000 + now.tv_nsec / 1000000);
2165
    }
2166
#elif defined(FUSION_RTOS)
2167
    /* The time in milliseconds.
2168
     * Used for tickets to represent difference between when first seen and when
2169
     * sending.
2170
     *
2171
     * returns the time in milliseconds as a 32-bit value.
2172
     */
2173
    word32 TimeNowInMilliseconds(void)
2174
    {
2175
        struct timeval now;
2176
        if (FCL_GETTIMEOFDAY(&now, 0) < 0)
2177
            return 0;
2178
2179
        /* Convert to milliseconds number. */
2180
        return (word32)(now.tv_sec * 1000 + now.tv_usec / 1000);
2181
    }
2182
#elif defined(WOLFSSL_ZEPHYR)
2183
    word32 TimeNowInMilliseconds(void)
2184
    {
2185
        int64_t t;
2186
    #if defined(CONFIG_ARCH_POSIX)
2187
        k_cpu_idle();
2188
    #endif
2189
        t = k_uptime_get(); /* returns current uptime in milliseconds */
2190
        return (word32)t;
2191
    }
2192
#elif defined(FREERTOS)
2193
    word32 TimeNowInMilliseconds(void)
2194
    {
2195
        return (word32)((uint64_t)(xTaskGetTickCount() * 1000) /
2196
            configTICK_RATE_HZ);
2197
    }
2198
#else
2199
    /* The time in milliseconds.
2200
     * Used for tickets to represent difference between when first seen and when
2201
     * sending.
2202
     *
2203
     * returns the time in milliseconds as a 32-bit value.
2204
     */
2205
    word32 TimeNowInMilliseconds(void)
2206
    {
2207
        struct timeval now;
2208
2209
        if (gettimeofday(&now, 0) < 0)
2210
            return 0;
2211
2212
        /* Convert to milliseconds number. */
2213
        return (word32)(now.tv_sec * 1000 + now.tv_usec / 1000);
2214
    }
2215
#endif
2216
#else
2217
    /* user must supply time in milliseconds function:
2218
     *   word32 TimeNowInMilliseconds(void);
2219
     * The response is milliseconds elapsed
2220
     */
2221
#endif /* !NO_ASN_TIME */
2222
#else
2223
#ifndef NO_ASN_TIME
2224
#if defined(USER_TICKS)
2225
#if 0
2226
    sword64 TimeNowInMilliseconds(void)
2227
    {
2228
        /*
2229
        write your own clock tick function if don't want gettimeofday()
2230
        needs millisecond accuracy but doesn't have to correlated to EPOCH
2231
        */
2232
    }
2233
#endif
2234
2235
#elif defined(TIME_OVERRIDES)
2236
#if !defined(NO_ASN) && !defined(NO_ASN_TIME)
2237
    sword64 TimeNowInMilliseconds(void)
2238
    {
2239
        return (sword64) wc_Time(0) * 1000;
2240
    }
2241
#else
2242
    #ifndef HAVE_TIME_T_TYPE
2243
        typedef long time_t;
2244
    #endif
2245
    extern time_t XTIME(time_t * timer);
2246
2247
    /* The time in milliseconds.
2248
     * Used for tickets to represent difference between when first seen and when
2249
     * sending.
2250
     *
2251
     * returns the time in milliseconds as a 32-bit value.
2252
     */
2253
    sword64 TimeNowInMilliseconds(void)
2254
    {
2255
        return (sword64) XTIME(0) * 1000;
2256
    }
2257
#endif
2258
2259
#elif defined(XTIME_MS)
2260
    sword64 TimeNowInMilliseconds(void)
2261
    {
2262
        return (sword64)XTIME_MS(0);
2263
    }
2264
2265
#elif defined(USE_WINDOWS_API)
2266
    /* The time in milliseconds.
2267
     * Used for tickets to represent difference between when first seen and when
2268
     * sending.
2269
     *
2270
     * returns the time in milliseconds as a 64-bit value.
2271
     */
2272
    sword64 TimeNowInMilliseconds(void)
2273
    {
2274
        static int           init = 0;
2275
        static LARGE_INTEGER freq;
2276
        LARGE_INTEGER        count;
2277
2278
        if (!init) {
2279
            QueryPerformanceFrequency(&freq);
2280
            init = 1;
2281
        }
2282
2283
        QueryPerformanceCounter(&count);
2284
2285
        return (sword64)(count.QuadPart / (freq.QuadPart / 1000));
2286
    }
2287
2288
#elif defined(HAVE_RTP_SYS)
2289
    #include "rtptime.h"
2290
2291
    /* The time in milliseconds.
2292
     * Used for tickets to represent difference between when first seen and when
2293
     * sending.
2294
     *
2295
     * returns the time in milliseconds as a 64-bit value.
2296
     */
2297
    sword64 TimeNowInMilliseconds(void)
2298
    {
2299
        return (sword64)rtp_get_system_sec() * 1000;
2300
    }
2301
#elif defined(WOLFSSL_DEOS)
2302
    sword64 TimeNowInMilliseconds(void)
2303
    {
2304
        const word32 systemTickTimeInHz = 1000000 / systemTickInMicroseconds();
2305
        word32 *systemTickPtr = systemTickPointer();
2306
2307
        return (sword64) (*systemTickPtr/systemTickTimeInHz) * 1000;
2308
    }
2309
#elif defined(MICRIUM)
2310
    /* The time in milliseconds.
2311
     * Used for tickets to represent difference between when first seen and when
2312
     * sending.
2313
     *
2314
     * returns the time in milliseconds as a 64-bit value.
2315
     */
2316
    sword64 TimeNowInMilliseconds(void)
2317
    {
2318
        OS_TICK ticks = 0;
2319
        OS_ERR  err;
2320
2321
        ticks = OSTimeGet(&err);
2322
2323
        return (sword64) (ticks / OSCfg_TickRate_Hz) * 1000;
2324
    }
2325
#elif defined(MICROCHIP_TCPIP_V5)
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 64-bit value.
2331
     */
2332
    sword64 TimeNowInMilliseconds(void)
2333
    {
2334
        return (sword64) (TickGet() / (TICKS_PER_SECOND / 1000));
2335
    }
2336
#elif defined(MICROCHIP_TCPIP)
2337
    #if defined(MICROCHIP_MPLAB_HARMONY)
2338
        #include <system/tmr/sys_tmr.h>
2339
2340
    /* The time in milliseconds.
2341
     * Used for tickets to represent difference between when first seen and when
2342
     * sending.
2343
     *
2344
     * returns the time in milliseconds as a 64-bit value.
2345
     */
2346
    sword64 TimeNowInMilliseconds(void)
2347
    {
2348
        return (sword64)SYS_TMR_TickCountGet() /
2349
                        (SYS_TMR_TickCounterFrequencyGet() / 1000);
2350
    }
2351
    #else
2352
    /* The time in milliseconds.
2353
     * Used for tickets to represent difference between when first seen and when
2354
     * sending.
2355
     *
2356
     * returns the time in milliseconds as a 64-bit value.
2357
     */
2358
    sword64 TimeNowInMilliseconds(void)
2359
    {
2360
        return (sword64)SYS_TICK_Get() / (SYS_TICK_TicksPerSecondGet() / 1000);
2361
    }
2362
2363
    #endif
2364
2365
#elif defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX)
2366
    /* The time in milliseconds.
2367
     * Used for tickets to represent difference between when first seen and when
2368
     * sending.
2369
     *
2370
     * returns the time in milliseconds as a 64-bit value.
2371
     */
2372
    sword64 TimeNowInMilliseconds(void)
2373
    {
2374
        TIME_STRUCT mqxTime;
2375
2376
        _time_get_elapsed(&mqxTime);
2377
2378
        return (sword64) mqxTime.SECONDS * 1000;
2379
    }
2380
#elif defined(FREESCALE_FREE_RTOS) || defined(FREESCALE_KSDK_FREERTOS)
2381
    #include "include/task.h"
2382
2383
    /* The time in milliseconds.
2384
     * Used for tickets to represent difference between when first seen and when
2385
     * sending.
2386
     *
2387
     * returns the time in milliseconds as a 64-bit value.
2388
     */
2389
    sword64 TimeNowInMilliseconds(void)
2390
    {
2391
        return (sword64)xTaskGetTickCount() / (configTICK_RATE_HZ / 1000);
2392
    }
2393
#elif defined(FREESCALE_KSDK_BM)
2394
    #include "lwip/sys.h" /* lwIP */
2395
2396
    /* The time in milliseconds.
2397
     * Used for tickets to represent difference between when first seen and when
2398
     * sending.
2399
     *
2400
     * returns the time in milliseconds as a 64-bit value.
2401
     */
2402
    sword64 TimeNowInMilliseconds(void)
2403
    {
2404
        return sys_now();
2405
    }
2406
2407
#elif defined(WOLFSSL_CMSIS_RTOS) || defined(WOLFSSL_CMSIS_RTOSv2)
2408
2409
    sword64 TimeNowInMilliseconds(void)
2410
    {
2411
        return (sword64)osKernelGetTickCount();
2412
    }
2413
2414
#elif defined(WOLFSSL_TIRTOS)
2415
    /* The time in milliseconds.
2416
     * Used for tickets to represent difference between when first seen and when
2417
     * sending.
2418
     *
2419
     * returns the time in milliseconds as a 64-bit value.
2420
     */
2421
    sword64 TimeNowInMilliseconds(void)
2422
    {
2423
        return (sword64) Seconds_get() * 1000;
2424
    }
2425
#elif defined(WOLFSSL_UTASKER)
2426
    /* The time in milliseconds.
2427
     * Used for tickets to represent difference between when first seen and when
2428
     * sending.
2429
     *
2430
     * returns the time in milliseconds as a 64-bit value.
2431
     */
2432
    sword64 TimeNowInMilliseconds(void)
2433
    {
2434
        return (sword64)(uTaskerSystemTick / (TICK_RESOLUTION / 1000));
2435
    }
2436
#elif defined(WOLFSSL_LINUXKM)
2437
    sword64 TimeNowInMilliseconds(void)
2438
    {
2439
        s64 t;
2440
#if LINUX_VERSION_CODE < KERNEL_VERSION(4, 0, 0)
2441
        struct timespec ts;
2442
        getnstimeofday(&ts);
2443
        t = ts.tv_sec * (s64)1000;
2444
        t += ts.tv_nsec / (s64)1000000;
2445
#else
2446
        struct timespec64 ts;
2447
#if LINUX_VERSION_CODE < KERNEL_VERSION(5, 0, 0)
2448
        ts = current_kernel_time64();
2449
#else
2450
        ktime_get_coarse_real_ts64(&ts);
2451
#endif
2452
        t = ts.tv_sec * 1000L;
2453
        t += ts.tv_nsec / 1000000L;
2454
#endif
2455
        return (sword64)t;
2456
    }
2457
#elif defined(WOLFSSL_QNX_CAAM)
2458
    sword64 TimeNowInMilliseconds(void)
2459
    {
2460
        struct timespec now;
2461
        clock_gettime(CLOCK_REALTIME, &now);
2462
        return (sword64)(now.tv_sec * 1000 + now.tv_nsec / 1000000);
2463
    }
2464
#elif defined(FUSION_RTOS)
2465
    /* The time in milliseconds.
2466
     * Used for tickets to represent difference between when first seen and when
2467
     * sending.
2468
     *
2469
     * returns the time in milliseconds as a 64-bit value.
2470
     */
2471
    sword64 TimeNowInMilliseconds(void)
2472
    {
2473
        struct timeval now;
2474
        if (FCL_GETTIMEOFDAY(&now, 0) < 0)
2475
            return 0;
2476
2477
        /* Convert to milliseconds number. */
2478
        return (sword64)now.tv_sec * 1000 + now.tv_usec / 1000;
2479
    }
2480
#elif defined(WOLFSSL_ZEPHYR)
2481
    sword64 TimeNowInMilliseconds(void)
2482
    {
2483
        int64_t t;
2484
    #if defined(CONFIG_ARCH_POSIX)
2485
        k_cpu_idle();
2486
    #endif
2487
        t = k_uptime_get(); /* returns current uptime in milliseconds */
2488
        return (sword64)t;
2489
    }
2490
#elif defined(FREERTOS)
2491
    sword64 TimeNowInMilliseconds(void)
2492
    {
2493
        return (sword64)((uint64_t)(xTaskGetTickCount() * 1000) /
2494
            configTICK_RATE_HZ);
2495
    }
2496
#else
2497
    /* The time in milliseconds.
2498
     * Used for tickets to represent difference between when first seen and when
2499
     * sending.
2500
     *
2501
     * returns the time in milliseconds as a 64-bit value.
2502
     */
2503
    sword64 TimeNowInMilliseconds(void)
2504
    {
2505
        struct timeval now;
2506
2507
        if (gettimeofday(&now, 0) < 0)
2508
            return 0;
2509
2510
        /* Convert to milliseconds number. */
2511
        return (sword64)now.tv_sec * 1000 + now.tv_usec / 1000;
2512
    }
2513
#endif
2514
#else
2515
    /* user must supply time in milliseconds function:
2516
     *   sword64 TimeNowInMilliseconds(void);
2517
     * The response is milliseconds elapsed
2518
     */
2519
#endif /* !NO_ASN_TIME */
2520
#endif /* WOLFSSL_32BIT_MILLI_TIME */
2521
#endif /* HAVE_SESSION_TICKET || !NO_PSK || WOLFSSL_DTLS13 */
2522
2523
/* Add record layer header to message.
2524
 *
2525
 * output  The buffer to write the record layer header into.
2526
 * length  The length of the record data.
2527
 * type    The type of record message.
2528
 * ssl     The SSL/TLS object.
2529
 */
2530
static void AddTls13RecordHeader(byte* output, word32 length, byte type,
2531
                                 WOLFSSL* ssl)
2532
0
{
2533
0
    RecordLayerHeader* rl;
2534
2535
0
    rl = (RecordLayerHeader*)output;
2536
0
    rl->type    = type;
2537
0
    rl->pvMajor = ssl->version.major;
2538
    /* NOTE: May be TLSv1_MINOR when sending first ClientHello. */
2539
0
    rl->pvMinor = TLSv1_2_MINOR;
2540
0
    c16toa((word16)length, rl->length);
2541
0
}
2542
2543
/* Add handshake header to message.
2544
 *
2545
 * output      The buffer to write the handshake header into.
2546
 * length      The length of the handshake data.
2547
 * fragOffset  The offset of the fragment data. (DTLS)
2548
 * fragLength  The length of the fragment data. (DTLS)
2549
 * type        The type of handshake message.
2550
 * ssl         The SSL/TLS object. (DTLS)
2551
 */
2552
static void AddTls13HandShakeHeader(byte* output, word32 length,
2553
                                    word32 fragOffset, word32 fragLength,
2554
                                    byte type, WOLFSSL* ssl)
2555
0
{
2556
0
    HandShakeHeader* hs;
2557
0
    (void)fragOffset;
2558
0
    (void)fragLength;
2559
0
    (void)ssl;
2560
2561
#ifdef WOLFSSL_DTLS13
2562
    /* message_hash type is used for a synthetic message that replaces the first
2563
       ClientHello in the hash transcript when using HelloRetryRequest. It will
2564
       never be transmitted and, as the DTLS-only fields must not be considered
2565
       when computing the hash transcript, we can avoid to use the DTLS
2566
       handshake header. */
2567
    if (ssl->options.dtls && type != message_hash) {
2568
        Dtls13HandshakeAddHeader(ssl, output, (enum HandShakeType)type, length);
2569
        return;
2570
    }
2571
#endif /* WOLFSSL_DTLS13 */
2572
2573
    /* handshake header */
2574
0
    hs = (HandShakeHeader*)output;
2575
0
    hs->type = type;
2576
0
    c32to24(length, hs->length);
2577
0
}
2578
2579
2580
/* Add both record layer and handshake header to message.
2581
 *
2582
 * output      The buffer to write the headers into.
2583
 * length      The length of the handshake data.
2584
 * type        The type of record layer message.
2585
 * ssl         The SSL/TLS object. (DTLS)
2586
 */
2587
static void AddTls13Headers(byte* output, word32 length, byte type,
2588
                            WOLFSSL* ssl)
2589
0
{
2590
0
    word32 lengthAdj = HANDSHAKE_HEADER_SZ;
2591
0
    word32 outputAdj = RECORD_HEADER_SZ;
2592
2593
#ifdef WOLFSSL_DTLS13
2594
    if (ssl->options.dtls) {
2595
        Dtls13AddHeaders(output, length, (enum HandShakeType)type, ssl);
2596
        return;
2597
    }
2598
#endif /* WOLFSSL_DTLS13 */
2599
2600
0
    AddTls13RecordHeader(output, length + lengthAdj, handshake, ssl);
2601
0
    AddTls13HandShakeHeader(output + outputAdj, length, 0, length, type, ssl);
2602
0
}
2603
2604
#if (!defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER)) \
2605
    && !defined(NO_CERTS)
2606
/* Add both record layer and fragment handshake header to message.
2607
 *
2608
 * output      The buffer to write the headers into.
2609
 * fragOffset  The offset of the fragment data. (DTLS)
2610
 * fragLength  The length of the fragment data. (DTLS)
2611
 * length      The length of the handshake data.
2612
 * type        The type of record layer message.
2613
 * ssl         The SSL/TLS object. (DTLS)
2614
 */
2615
static void AddTls13FragHeaders(byte* output, word32 fragSz, word32 fragOffset,
2616
                                word32 length, byte type, WOLFSSL* ssl)
2617
0
{
2618
0
    word32 lengthAdj = HANDSHAKE_HEADER_SZ;
2619
0
    word32 outputAdj = RECORD_HEADER_SZ;
2620
0
    (void)fragSz;
2621
2622
#ifdef WOLFSSL_DTLS13
2623
    /* we ignore fragmentation fields here because fragmentation logic for
2624
       DTLS1.3 is inside dtls13_handshake_send(). */
2625
    if (ssl->options.dtls) {
2626
        Dtls13AddHeaders(output, length, (enum HandShakeType)type, ssl);
2627
        return;
2628
    }
2629
#endif /* WOLFSSL_DTLS13 */
2630
2631
0
    AddTls13RecordHeader(output, fragSz + lengthAdj, handshake, ssl);
2632
0
    AddTls13HandShakeHeader(output + outputAdj, length, fragOffset, fragSz,
2633
0
                            type, ssl);
2634
0
}
2635
#endif /* (!NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER) && !NO_CERTS */
2636
2637
/* Write the sequence number into the buffer.
2638
 * No DTLS v1.3 support.
2639
 *
2640
 * ssl          The SSL/TLS object.
2641
 * verifyOrder  Which set of sequence numbers to use.
2642
 * out          The buffer to write into.
2643
 */
2644
static WC_INLINE void WriteSEQTls13(WOLFSSL* ssl, int verifyOrder, byte* out)
2645
0
{
2646
0
    word32 seq[2] = {0, 0};
2647
2648
0
    if (ssl->options.dtls) {
2649
#ifdef WOLFSSL_DTLS13
2650
        Dtls13GetSeq(ssl, verifyOrder, seq, 1);
2651
#endif /* WOLFSSL_DTLS13 */
2652
0
    }
2653
0
    else if (verifyOrder == PEER_ORDER) {
2654
0
        seq[0] = ssl->keys.peer_sequence_number_hi;
2655
0
        seq[1] = ssl->keys.peer_sequence_number_lo++;
2656
        /* handle rollover */
2657
0
        if (seq[1] > ssl->keys.peer_sequence_number_lo)
2658
0
            ssl->keys.peer_sequence_number_hi++;
2659
0
    }
2660
0
    else {
2661
0
        seq[0] = ssl->keys.sequence_number_hi;
2662
0
        seq[1] = ssl->keys.sequence_number_lo++;
2663
        /* handle rollover */
2664
0
        if (seq[1] > ssl->keys.sequence_number_lo)
2665
0
            ssl->keys.sequence_number_hi++;
2666
0
    }
2667
#ifdef WOLFSSL_DEBUG_TLS
2668
    WOLFSSL_MSG_EX("TLS 1.3 Write Sequence %d %d", seq[0], seq[1]);
2669
#endif
2670
2671
0
    c32toa(seq[0], out);
2672
0
    c32toa(seq[1], out + OPAQUE32_LEN);
2673
0
}
2674
2675
/* Build the nonce for TLS v1.3 encryption and decryption.
2676
 *
2677
 * ssl    The SSL/TLS object.
2678
 * nonce  The nonce data to use when encrypting or decrypting.
2679
 * iv     The derived IV.
2680
 * order  The side on which the message is to be or was sent.
2681
 */
2682
static WC_INLINE void BuildTls13Nonce(WOLFSSL* ssl, byte* nonce, const byte* iv,
2683
                                   int ivSz, int order)
2684
0
{
2685
0
    int seq_offset;
2686
    /* Ensure minimum nonce size for standard AEAD ciphers */
2687
0
    if (ivSz < AEAD_NONCE_SZ)
2688
0
        ivSz = AEAD_NONCE_SZ;
2689
0
    seq_offset = ivSz - SEQ_SZ;
2690
    /* The nonce is the IV with the sequence XORed into the last bytes. */
2691
0
    WriteSEQTls13(ssl, order, nonce + seq_offset);
2692
0
    XMEMCPY(nonce, iv, seq_offset);
2693
0
    xorbuf(nonce + seq_offset, iv + seq_offset, SEQ_SZ);
2694
0
}
2695
2696
#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
2697
/* Encrypt with ChaCha20 and create authentication tag with Poly1305.
2698
 *
2699
 * ssl     The SSL/TLS object.
2700
 * output  The buffer to write encrypted data and authentication tag into.
2701
 *         May be the same pointer as input.
2702
 * input   The data to encrypt.
2703
 * sz      The number of bytes to encrypt.
2704
 * nonce   The nonce to use with ChaCha20.
2705
 * aad     The additional authentication data.
2706
 * aadSz   The size of the addition authentication data.
2707
 * tag     The authentication tag buffer.
2708
 * returns 0 on success, otherwise failure.
2709
 */
2710
static int ChaCha20Poly1305_Encrypt(WOLFSSL* ssl, byte* output,
2711
                                    const byte* input, word16 sz, byte* nonce,
2712
                                    const byte* aad, word16 aadSz, byte* tag)
2713
0
{
2714
    /* Persistent-key stitched helper: derives the per-record Poly1305 key from
2715
     * the keyed ChaCha, then encrypts and authenticates in one pass (the IFMA
2716
     * stitch for large records, else two-pass).  TLS 1.3 is always RFC 8439. */
2717
0
    return wc_ChaCha20Poly1305_Encrypt_ex(ssl->encrypt.chacha,
2718
0
        ssl->auth.poly1305, output, input, sz, nonce, tag, aad, aadSz);
2719
0
}
2720
#endif
2721
2722
#ifdef HAVE_NULL_CIPHER
2723
/* Create authentication tag and copy data over input.
2724
 *
2725
 * ssl     The SSL/TLS object.
2726
 * output  The buffer to copy data into.
2727
 *         May be the same pointer as input.
2728
 * input   The data.
2729
 * sz      The number of bytes of data.
2730
 * nonce   The nonce to use with authentication.
2731
 * aad     The additional authentication data.
2732
 * aadSz   The size of the addition authentication data.
2733
 * tag     The authentication tag buffer.
2734
 * returns 0 on success, otherwise failure.
2735
 */
2736
static int Tls13IntegrityOnly_Encrypt(WOLFSSL* ssl, byte* output,
2737
                                      const byte* input, word16 sz,
2738
                                      const byte* nonce,
2739
                                      const byte* aad, word16 aadSz, byte* tag)
2740
{
2741
    int ret;
2742
2743
    /* HMAC: nonce | aad | input  */
2744
    ret = wc_HmacUpdate(ssl->encrypt.hmac, nonce, ssl->specs.iv_size);
2745
    if (ret == 0)
2746
        ret = wc_HmacUpdate(ssl->encrypt.hmac, aad, aadSz);
2747
    if (ret == 0)
2748
        ret = wc_HmacUpdate(ssl->encrypt.hmac, input, sz);
2749
    if (ret == 0)
2750
        ret = wc_HmacFinal(ssl->encrypt.hmac, tag);
2751
    /* Copy the input to output if not the same buffer */
2752
    if (ret == 0 && output != input)
2753
        XMEMCPY(output, input, sz);
2754
    return ret;
2755
}
2756
#endif
2757
2758
/* Encrypt data for TLS v1.3.
2759
 *
2760
 * ssl     The SSL/TLS object.
2761
 * output  The buffer to write encrypted data and authentication tag into.
2762
 *         May be the same pointer as input.
2763
 * input   The record header and data to encrypt.
2764
 * sz      The number of bytes to encrypt.
2765
 * aad     The additional authentication data.
2766
 * aadSz   The size of the addition authentication data.
2767
 * asyncOkay If non-zero can return WC_PENDING_E, otherwise blocks on crypto
2768
 * returns 0 on success, otherwise failure.
2769
 */
2770
static int EncryptTls13(WOLFSSL* ssl, byte* output, const byte* input,
2771
                        word16 sz, const byte* aad, word16 aadSz, int asyncOkay)
2772
0
{
2773
0
    int    ret    = 0;
2774
0
    word16 dataSz;
2775
0
    word16 macSz  = ssl->specs.aead_mac_size;
2776
0
    word32 nonceSz = 0;
2777
#ifdef WOLFSSL_ASYNC_CRYPT
2778
    /* Only AES-GCM/AES-CCM assign asyncDev, so only they may pend under a
2779
     * poll-completing device; the crypto-callback re-invoke path returns
2780
     * before the push and is not limited this way. */
2781
    WC_ASYNC_DEV* asyncDev = NULL;
2782
    word32 event_flags = WC_ASYNC_FLAG_CALL_AGAIN;
2783
#endif
2784
2785
0
    WOLFSSL_ENTER("EncryptTls13");
2786
0
    if (sz < ssl->specs.aead_mac_size)
2787
0
        return BUFFER_E;
2788
0
    dataSz = sz - ssl->specs.aead_mac_size;
2789
2790
0
    (void)output;
2791
0
    (void)input;
2792
0
    (void)sz;
2793
0
    (void)dataSz;
2794
0
    (void)macSz;
2795
0
    (void)asyncOkay;
2796
0
    (void)nonceSz;
2797
2798
#ifdef WOLFSSL_ASYNC_CRYPT
2799
    if (ssl->error == WC_NO_ERR_TRACE(WC_PENDING_E)) {
2800
        ssl->error = 0; /* clear async */
2801
    }
2802
#endif
2803
#if defined(WOLFSSL_RENESAS_TSIP_TLS)
2804
    ret = tsip_Tls13AesEncrypt(ssl, output, input, dataSz);
2805
    if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
2806
        if (ret > 0) {
2807
            ret = 0; /* tsip_Tls13AesEncrypt returns output size */
2808
        }
2809
        return ret;
2810
    }
2811
    ret = 0;
2812
#endif /* WOLFSSL_RENESAS_TSIP_TLS */
2813
2814
0
    switch (ssl->encrypt.state) {
2815
0
        case CIPHER_STATE_BEGIN:
2816
0
        {
2817
        #ifdef WOLFSSL_DEBUG_TLS
2818
            WOLFSSL_MSG("Data to encrypt");
2819
            WOLFSSL_BUFFER(input, dataSz);
2820
            WOLFSSL_MSG("Additional Authentication Data");
2821
            WOLFSSL_BUFFER(aad, aadSz);
2822
        #endif
2823
2824
        #ifdef WOLFSSL_CIPHER_TEXT_CHECK
2825
            if (ssl->specs.bulk_cipher_algorithm != wolfssl_cipher_null &&
2826
                    dataSz >= sizeof(ssl->encrypt.sanityCheck)) {
2827
                XMEMCPY(ssl->encrypt.sanityCheck, input,
2828
                    sizeof(ssl->encrypt.sanityCheck));
2829
            }
2830
        #endif
2831
2832
0
        #ifdef CIPHER_NONCE
2833
0
            if (ssl->encrypt.nonce == NULL) {
2834
0
                ssl->encrypt.nonce = (byte*)XMALLOC(AEAD_MAX_IMP_SZ,
2835
0
                                                ssl->heap, DYNAMIC_TYPE_CIPHER);
2836
            #ifdef WOLFSSL_CHECK_MEM_ZERO
2837
                if (ssl->encrypt.nonce != NULL) {
2838
                    wc_MemZero_Add("EncryptTls13 nonce", ssl->encrypt.nonce,
2839
                        ssl->specs.iv_size);
2840
                }
2841
            #endif
2842
0
            }
2843
0
            if (ssl->encrypt.nonce == NULL)
2844
0
                return MEMORY_E;
2845
2846
0
            BuildTls13Nonce(ssl, ssl->encrypt.nonce, ssl->keys.aead_enc_imp_IV,
2847
0
                            ssl->specs.iv_size, CUR_ORDER);
2848
0
        #endif
2849
2850
            /* Advance state and proceed */
2851
0
            ssl->encrypt.state = CIPHER_STATE_DO;
2852
0
        }
2853
0
        FALL_THROUGH;
2854
2855
0
        case CIPHER_STATE_DO:
2856
0
        {
2857
0
            switch (ssl->specs.bulk_cipher_algorithm) {
2858
0
            #ifdef BUILD_AESGCM
2859
0
                case wolfssl_aes_gcm:
2860
                #ifdef WOLFSSL_ASYNC_CRYPT
2861
                    /* initialize event */
2862
                    asyncDev = &ssl->encrypt.aes->asyncDev;
2863
                    ret = wolfSSL_AsyncInit(ssl, asyncDev, event_flags);
2864
                    if (ret != 0)
2865
                        break;
2866
                #endif
2867
2868
0
                    nonceSz = AESGCM_NONCE_SZ;
2869
2870
                #if defined(HAVE_PK_CALLBACKS)
2871
                    ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN);
2872
                    if (ssl->ctx && ssl->ctx->PerformTlsRecordProcessingCb) {
2873
                        ret = ssl->ctx->PerformTlsRecordProcessingCb(ssl, 1,
2874
                                  output, input, dataSz,
2875
                                  ssl->encrypt.nonce, nonceSz,
2876
                                  output + dataSz, macSz,
2877
                                  aad, aadSz);
2878
                    }
2879
                    if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN))
2880
                #endif
2881
0
                    {
2882
2883
                #if ((defined(HAVE_FIPS) || defined(HAVE_SELFTEST)) && \
2884
                    (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2)))
2885
                        ret = wc_AesGcmEncrypt(ssl->encrypt.aes, output, input,
2886
                            dataSz, ssl->encrypt.nonce, nonceSz,
2887
                            output + dataSz, macSz, aad, aadSz);
2888
                #else
2889
0
                        ret = wc_AesGcmSetExtIV(ssl->encrypt.aes,
2890
0
                                ssl->encrypt.nonce, nonceSz);
2891
0
                        if (ret == 0) {
2892
0
                            ret = wc_AesGcmEncrypt_ex(ssl->encrypt.aes, output,
2893
0
                                    input, dataSz, ssl->encrypt.nonce, nonceSz,
2894
0
                                    output + dataSz, macSz, aad, aadSz);
2895
0
                        }
2896
0
                #endif
2897
0
                    }
2898
0
                    break;
2899
0
            #endif
2900
2901
            #ifdef HAVE_AESCCM
2902
                case wolfssl_aes_ccm:
2903
                #ifdef WOLFSSL_ASYNC_CRYPT
2904
                    /* initialize event */
2905
                    asyncDev = &ssl->encrypt.aes->asyncDev;
2906
                    ret = wolfSSL_AsyncInit(ssl, asyncDev, event_flags);
2907
                    if (ret != 0)
2908
                        break;
2909
                #endif
2910
2911
                    nonceSz = AESCCM_NONCE_SZ;
2912
                #if defined(HAVE_PK_CALLBACKS)
2913
                    ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN);
2914
                    if (ssl->ctx && ssl->ctx->PerformTlsRecordProcessingCb) {
2915
                        ret = ssl->ctx->PerformTlsRecordProcessingCb(ssl, 1,
2916
                                  output, input, dataSz,
2917
                                  ssl->encrypt.nonce, nonceSz,
2918
                                  output + dataSz, macSz,
2919
                                  aad, aadSz);
2920
                    }
2921
                    if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN))
2922
                #endif
2923
                    {
2924
                #if ((defined(HAVE_FIPS) || defined(HAVE_SELFTEST)) && \
2925
                    (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2)))
2926
                        ret = wc_AesCcmEncrypt(ssl->encrypt.aes, output, input,
2927
                            dataSz, ssl->encrypt.nonce, nonceSz,
2928
                            output + dataSz, macSz, aad, aadSz);
2929
                #else
2930
                        ret = wc_AesCcmSetNonce(ssl->encrypt.aes,
2931
                                ssl->encrypt.nonce, nonceSz);
2932
                        if (ret == 0) {
2933
                            ret = wc_AesCcmEncrypt_ex(ssl->encrypt.aes, output,
2934
                                    input, dataSz, ssl->encrypt.nonce, nonceSz,
2935
                                    output + dataSz, macSz, aad, aadSz);
2936
                        }
2937
                #endif
2938
                    }
2939
                    break;
2940
            #endif
2941
2942
0
            #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
2943
0
                case wolfssl_chacha:
2944
0
                    ret = ChaCha20Poly1305_Encrypt(ssl, output, input, dataSz,
2945
0
                        ssl->encrypt.nonce, aad, aadSz, output + dataSz);
2946
0
                    break;
2947
0
            #endif
2948
2949
            #ifdef WOLFSSL_SM4_GCM
2950
                case wolfssl_sm4_gcm:
2951
                    nonceSz = SM4_GCM_NONCE_SZ;
2952
                    ret = wc_Sm4GcmEncrypt(ssl->encrypt.sm4, output, input,
2953
                        dataSz, ssl->encrypt.nonce, nonceSz, output + dataSz,
2954
                        macSz, aad, aadSz);
2955
                    break;
2956
            #endif
2957
2958
            #ifdef WOLFSSL_SM4_CCM
2959
                case wolfssl_sm4_ccm:
2960
                    nonceSz = SM4_CCM_NONCE_SZ;
2961
                    ret = wc_Sm4CcmEncrypt(ssl->encrypt.sm4, output, input,
2962
                        dataSz, ssl->encrypt.nonce, nonceSz, output + dataSz,
2963
                        macSz, aad, aadSz);
2964
                    break;
2965
            #endif
2966
2967
            #ifdef HAVE_NULL_CIPHER
2968
                case wolfssl_cipher_null:
2969
                    ret = Tls13IntegrityOnly_Encrypt(ssl, output, input, dataSz,
2970
                        ssl->encrypt.nonce, aad, aadSz, output + dataSz);
2971
                    break;
2972
            #endif
2973
2974
0
                default:
2975
0
                    WOLFSSL_MSG("wolfSSL Encrypt programming error");
2976
0
                    return ENCRYPT_ERROR;
2977
0
            }
2978
2979
        #ifdef WOLFSSL_ASYNC_CRYPT
2980
            if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
2981
                /* if async is not okay, then block */
2982
                if (!asyncOkay) {
2983
                #if defined(WOLFSSL_ASYNC_REINVOKE) && \
2984
                    !defined(WOLF_CRYPTO_CB_ASYNC_POLL)
2985
                    /* wc_AsyncWait() never runs a callback: leave the state
2986
                     * at CIPHER_STATE_DO for the caller to re-invoke. */
2987
                    return ret;
2988
                #else
2989
                    ret = wc_AsyncWait(ret, asyncDev, event_flags);
2990
                #endif
2991
                }
2992
                else {
2993
                #if !defined(WOLFSSL_ASYNC_REINVOKE) || \
2994
                    defined(WOLF_CRYPTO_CB_ASYNC_POLL)
2995
                    /* Poll completes into output; the resume must skip the
2996
                     * in-place AEAD or it would encrypt its own output. */
2997
                    ssl->encrypt.state = CIPHER_STATE_END;
2998
                #endif
2999
                    /* Else stay at CIPHER_STATE_DO: the retry must re-invoke
3000
                     * the callback or the record goes out unencrypted. */
3001
                    return wolfSSL_AsyncPush(ssl, asyncDev);
3002
                }
3003
            }
3004
        #endif
3005
3006
            /* Advance state */
3007
0
            ssl->encrypt.state = CIPHER_STATE_END;
3008
0
        }
3009
0
        FALL_THROUGH;
3010
3011
0
        case CIPHER_STATE_END:
3012
0
        {
3013
        #ifdef WOLFSSL_DEBUG_TLS
3014
            #ifdef CIPHER_NONCE
3015
                WOLFSSL_MSG("Nonce");
3016
                WOLFSSL_BUFFER(ssl->encrypt.nonce, ssl->specs.iv_size);
3017
            #endif
3018
                WOLFSSL_MSG("Encrypted data");
3019
                WOLFSSL_BUFFER(output, dataSz);
3020
                WOLFSSL_MSG("Authentication Tag");
3021
                WOLFSSL_BUFFER(output + dataSz, macSz);
3022
        #endif
3023
3024
        #ifdef WOLFSSL_CIPHER_TEXT_CHECK
3025
            if (ssl->specs.bulk_cipher_algorithm != wolfssl_cipher_null &&
3026
                    dataSz >= sizeof(ssl->encrypt.sanityCheck) &&
3027
                XMEMCMP(output, ssl->encrypt.sanityCheck,
3028
                    sizeof(ssl->encrypt.sanityCheck)) == 0) {
3029
3030
                WOLFSSL_MSG("EncryptTls13 sanity check failed! Glitch?");
3031
                return ENCRYPT_ERROR;
3032
            }
3033
            ForceZero(ssl->encrypt.sanityCheck,
3034
                sizeof(ssl->encrypt.sanityCheck));
3035
        #endif
3036
        #ifdef WOLFSSL_CHECK_MEM_ZERO
3037
            if ((ssl->specs.bulk_cipher_algorithm != wolfssl_cipher_null) &&
3038
                    (output != input) && (ret == 0)) {
3039
                wc_MemZero_Add("TLS 1.3 Encrypt plaintext", input, sz);
3040
            }
3041
        #endif
3042
3043
0
        #ifdef CIPHER_NONCE
3044
0
            ForceZero(ssl->encrypt.nonce, ssl->specs.iv_size);
3045
0
        #endif
3046
3047
0
            break;
3048
0
        }
3049
3050
0
        default:
3051
0
            break;
3052
0
    }
3053
3054
3055
    /* Reset state */
3056
0
    ssl->encrypt.state = CIPHER_STATE_BEGIN;
3057
3058
0
    return ret;
3059
0
}
3060
3061
#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
3062
/* Decrypt with ChaCha20 and check authentication tag with Poly1305.
3063
 *
3064
 * ssl     The SSL/TLS object.
3065
 * output  The buffer to write decrypted data into.
3066
 *         May be the same pointer as input.
3067
 * input   The data to decrypt.
3068
 * sz      The number of bytes to decrypt.
3069
 * nonce   The nonce to use with ChaCha20.
3070
 * aad     The additional authentication data.
3071
 * aadSz   The size of the addition authentication data.
3072
 * tagIn   The authentication tag data from packet.
3073
 * returns 0 on success, otherwise failure.
3074
 */
3075
static int ChaCha20Poly1305_Decrypt(WOLFSSL* ssl, byte* output,
3076
                                    const byte* input, word16 sz, byte* nonce,
3077
                                    const byte* aad, word16 aadSz,
3078
                                    const byte* tagIn)
3079
0
{
3080
0
    int ret;
3081
3082
    /* Persistent-key stitched helper: verifies the Poly1305 tag over
3083
     * aad+ciphertext and decrypts in one pass (the IFMA decrypt stitch for
3084
     * large records, else two-pass); it zeroes output on tag mismatch. */
3085
0
    ret = wc_ChaCha20Poly1305_Decrypt_ex(ssl->decrypt.chacha,
3086
0
        ssl->auth.poly1305, output, input, sz, nonce, tagIn, aad, aadSz);
3087
0
    if (ret == WC_NO_ERR_TRACE(MAC_CMP_FAILED_E)) {
3088
0
        WOLFSSL_MSG("MAC did not match");
3089
0
        ret = VERIFY_MAC_ERROR;
3090
0
    }
3091
3092
0
    return ret;
3093
0
}
3094
#endif
3095
3096
#ifdef HAVE_NULL_CIPHER
3097
/* Check HMAC tag and copy over input.
3098
 *
3099
 * ssl     The SSL/TLS object.
3100
 * output  The buffer to copy data into.
3101
 *         May be the same pointer as input.
3102
 * input   The data.
3103
 * sz      The number of bytes of data.
3104
 * nonce   The nonce to use with authentication.
3105
 * aad     The additional authentication data.
3106
 * aadSz   The size of the addition authentication data.
3107
 * tagIn   The authentication tag data from packet.
3108
 * returns 0 on success, otherwise failure.
3109
 */
3110
static int Tls13IntegrityOnly_Decrypt(WOLFSSL* ssl, byte* output,
3111
                                      const byte* input, word16 sz,
3112
                                      const byte* nonce,
3113
                                      const byte* aad, word16 aadSz,
3114
                                      const byte* tagIn)
3115
{
3116
    int ret;
3117
    byte hmac[WC_MAX_DIGEST_SIZE];
3118
3119
    /* HMAC: nonce | aad | input  */
3120
    ret = wc_HmacUpdate(ssl->decrypt.hmac, nonce, ssl->specs.iv_size);
3121
    if (ret == 0)
3122
        ret = wc_HmacUpdate(ssl->decrypt.hmac, aad, aadSz);
3123
    if (ret == 0)
3124
        ret = wc_HmacUpdate(ssl->decrypt.hmac, input, sz);
3125
    if (ret == 0)
3126
        ret = wc_HmacFinal(ssl->decrypt.hmac, hmac);
3127
    /* Check authentication tag matches */
3128
    if (ret == 0 && ConstantCompare(tagIn, hmac, ssl->specs.hash_size) != 0)
3129
        ret = DECRYPT_ERROR;
3130
    /* Copy the input to output if not the same buffer */
3131
    if (ret == 0 && output != input)
3132
        XMEMCPY(output, input, sz);
3133
    ForceZero(hmac, sizeof(hmac));
3134
    return ret;
3135
}
3136
#endif
3137
3138
/* Decrypt data for TLS v1.3.
3139
 *
3140
 * ssl     The SSL/TLS object.
3141
 * output  The buffer to write decrypted data into.
3142
 *         May be the same pointer as input.
3143
 * input   The data to decrypt and authentication tag.
3144
 * sz      The length of the encrypted data plus authentication tag.
3145
 * aad     The additional authentication data.
3146
 * aadSz   The size of the addition authentication data.
3147
 * returns 0 on success, otherwise failure.
3148
 */
3149
int DecryptTls13(WOLFSSL* ssl, byte* output, const byte* input, word16 sz,
3150
                 const byte* aad, word16 aadSz)
3151
0
{
3152
0
    int    ret    = 0;
3153
0
    word16 dataSz;
3154
0
    word16 macSz  = ssl->specs.aead_mac_size;
3155
0
    word32 nonceSz = 0;
3156
3157
0
    WOLFSSL_ENTER("DecryptTls13");
3158
0
    if (sz < ssl->specs.aead_mac_size) {
3159
0
        return BAD_FUNC_ARG;
3160
0
    }
3161
0
    dataSz = sz - ssl->specs.aead_mac_size;
3162
3163
#if defined(WOLFSSL_RENESAS_TSIP_TLS)
3164
    ret = tsip_Tls13AesDecrypt(ssl, output, input, sz);
3165
3166
    if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
3167
        #ifndef WOLFSSL_EARLY_DATA
3168
        if (ret < 0) {
3169
            ret = VERIFY_MAC_ERROR;
3170
            WOLFSSL_ERROR_VERBOSE(ret);
3171
        }
3172
        #endif
3173
        return ret;
3174
    }
3175
#endif
3176
3177
#ifdef WOLFSSL_ASYNC_CRYPT
3178
    ret = wolfSSL_AsyncPop(ssl, &ssl->decrypt.state);
3179
    if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) {
3180
        /* check for still pending */
3181
        if (ret == WC_NO_ERR_TRACE(WC_PENDING_E))
3182
            return ret;
3183
3184
        ssl->error = 0; /* clear async */
3185
3186
        /* let failures through so CIPHER_STATE_END logic is run */
3187
    }
3188
    else
3189
#endif
3190
0
    {
3191
        /* Reset state */
3192
0
        ret = 0;
3193
0
        ssl->decrypt.state = CIPHER_STATE_BEGIN;
3194
0
    }
3195
3196
0
    (void)output;
3197
0
    (void)input;
3198
0
    (void)sz;
3199
0
    (void)dataSz;
3200
0
    (void)macSz;
3201
0
    (void)nonceSz;
3202
3203
0
    switch (ssl->decrypt.state) {
3204
0
        case CIPHER_STATE_BEGIN:
3205
0
        {
3206
        #ifdef WOLFSSL_DEBUG_TLS
3207
            WOLFSSL_MSG("Data to decrypt");
3208
            WOLFSSL_BUFFER(input, dataSz);
3209
            WOLFSSL_MSG("Additional Authentication Data");
3210
            WOLFSSL_BUFFER(aad, aadSz);
3211
            WOLFSSL_MSG("Authentication tag");
3212
            WOLFSSL_BUFFER(input + dataSz, macSz);
3213
        #endif
3214
3215
0
        #ifdef CIPHER_NONCE
3216
0
            if (ssl->decrypt.nonce == NULL) {
3217
0
                ssl->decrypt.nonce = (byte*)XMALLOC(AEAD_MAX_IMP_SZ,
3218
0
                                                ssl->heap, DYNAMIC_TYPE_CIPHER);
3219
            #ifdef WOLFSSL_CHECK_MEM_ZERO
3220
                if (ssl->decrypt.nonce != NULL) {
3221
                    wc_MemZero_Add("DecryptTls13 nonce", ssl->decrypt.nonce,
3222
                        ssl->specs.iv_size);
3223
                }
3224
            #endif
3225
0
            }
3226
0
            if (ssl->decrypt.nonce == NULL)
3227
0
                return MEMORY_E;
3228
3229
0
            BuildTls13Nonce(ssl, ssl->decrypt.nonce, ssl->keys.aead_dec_imp_IV,
3230
0
                            ssl->specs.iv_size, PEER_ORDER);
3231
0
        #endif
3232
3233
            /* Advance state and proceed */
3234
0
            ssl->decrypt.state = CIPHER_STATE_DO;
3235
0
        }
3236
0
        FALL_THROUGH;
3237
3238
0
        case CIPHER_STATE_DO:
3239
0
        {
3240
0
            switch (ssl->specs.bulk_cipher_algorithm) {
3241
0
            #ifdef BUILD_AESGCM
3242
0
                case wolfssl_aes_gcm:
3243
                #ifdef WOLFSSL_ASYNC_CRYPT
3244
                    /* initialize event */
3245
                    ret = wolfSSL_AsyncInit(ssl, &ssl->decrypt.aes->asyncDev,
3246
                        WC_ASYNC_FLAG_NONE);
3247
                    if (ret != 0)
3248
                        break;
3249
                #endif
3250
3251
0
                    nonceSz = AESGCM_NONCE_SZ;
3252
3253
                #if defined(HAVE_PK_CALLBACKS)
3254
                    ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN);
3255
                    if (ssl->ctx && ssl->ctx->PerformTlsRecordProcessingCb) {
3256
                        ret = ssl->ctx->PerformTlsRecordProcessingCb(ssl, 0,
3257
                                  output, input, dataSz,
3258
                                  ssl->decrypt.nonce, nonceSz,
3259
                                  (byte *)(input + dataSz), macSz,
3260
                                  aad, aadSz);
3261
                    }
3262
                    if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN))
3263
                #endif
3264
0
                    {
3265
3266
0
                        ret = wc_AesGcmDecrypt(ssl->decrypt.aes, output, input,
3267
0
                            dataSz, ssl->decrypt.nonce, nonceSz,
3268
0
                            input + dataSz, macSz, aad, aadSz);
3269
3270
                #ifdef WOLFSSL_ASYNC_CRYPT
3271
                        if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
3272
                            ret = wolfSSL_AsyncPush(ssl,
3273
                                &ssl->decrypt.aes->asyncDev);
3274
                        }
3275
                #endif
3276
3277
0
                    }
3278
0
                    break;
3279
0
            #endif
3280
3281
            #ifdef HAVE_AESCCM
3282
                case wolfssl_aes_ccm:
3283
                #ifdef WOLFSSL_ASYNC_CRYPT
3284
                    /* initialize event */
3285
                    ret = wolfSSL_AsyncInit(ssl, &ssl->decrypt.aes->asyncDev,
3286
                        WC_ASYNC_FLAG_NONE);
3287
                    if (ret != 0)
3288
                        break;
3289
                #endif
3290
3291
                    nonceSz = AESCCM_NONCE_SZ;
3292
                #if defined(HAVE_PK_CALLBACKS)
3293
                    ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN);
3294
                    if (ssl->ctx && ssl->ctx->PerformTlsRecordProcessingCb) {
3295
                        ret = ssl->ctx->PerformTlsRecordProcessingCb(ssl, 0,
3296
                                  output, input, dataSz,
3297
                                  ssl->decrypt.nonce, nonceSz,
3298
                                  (byte *)(input + dataSz), macSz,
3299
                                  aad, aadSz);
3300
                    }
3301
                    if (ret == WC_NO_ERR_TRACE(NOT_COMPILED_IN))
3302
                #endif
3303
                    {
3304
                        ret = wc_AesCcmDecrypt(ssl->decrypt.aes, output, input,
3305
                            dataSz, ssl->decrypt.nonce, nonceSz,
3306
                            input + dataSz, macSz, aad, aadSz);
3307
                #ifdef WOLFSSL_ASYNC_CRYPT
3308
                        if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
3309
                            ret = wolfSSL_AsyncPush(ssl,
3310
                                &ssl->decrypt.aes->asyncDev);
3311
                        }
3312
                #endif
3313
                    }
3314
                    break;
3315
            #endif
3316
3317
0
            #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
3318
0
                case wolfssl_chacha:
3319
0
                    ret = ChaCha20Poly1305_Decrypt(ssl, output, input, dataSz,
3320
0
                        ssl->decrypt.nonce, aad, aadSz, input + dataSz);
3321
0
                    break;
3322
0
            #endif
3323
3324
            #ifdef WOLFSSL_SM4_GCM
3325
                case wolfssl_sm4_gcm:
3326
                    nonceSz = SM4_GCM_NONCE_SZ;
3327
                    ret = wc_Sm4GcmDecrypt(ssl->decrypt.sm4, output, input,
3328
                        dataSz, ssl->decrypt.nonce, nonceSz, input + dataSz,
3329
                        macSz, aad, aadSz);
3330
                    break;
3331
            #endif
3332
3333
            #ifdef WOLFSSL_SM4_CCM
3334
                case wolfssl_sm4_ccm:
3335
                    nonceSz = SM4_CCM_NONCE_SZ;
3336
                    ret = wc_Sm4CcmDecrypt(ssl->decrypt.sm4, output, input,
3337
                        dataSz, ssl->decrypt.nonce, nonceSz, input + dataSz,
3338
                        macSz, aad, aadSz);
3339
                    break;
3340
            #endif
3341
3342
            #ifdef HAVE_NULL_CIPHER
3343
                case wolfssl_cipher_null:
3344
                    ret = Tls13IntegrityOnly_Decrypt(ssl, output, input, dataSz,
3345
                        ssl->decrypt.nonce, aad, aadSz, input + dataSz);
3346
                    break;
3347
            #endif
3348
0
                default:
3349
0
                    WOLFSSL_MSG("wolfSSL Decrypt programming error");
3350
0
                    return DECRYPT_ERROR;
3351
0
            }
3352
3353
        #ifdef WOLFSSL_ASYNC_CRYPT
3354
            if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
3355
            #if !defined(WOLFSSL_ASYNC_REINVOKE) || \
3356
                defined(WOLF_CRYPTO_CB_ASYNC_POLL)
3357
                /* The poll completes the operation into the output buffer,
3358
                 * so the resume must not run the AEAD again: advance past
3359
                 * it now (the pop does not, the event is CALL_AGAIN). */
3360
                ssl->decrypt.state = CIPHER_STATE_END;
3361
            #else
3362
                /* Crypto callback re-invocation: leave the state at
3363
                 * CIPHER_STATE_DO so the retry re-enters the AEAD;
3364
                 * advancing would hand back the undecrypted record. */
3365
            #endif
3366
                return ret;
3367
            }
3368
        #endif
3369
3370
            /* Advance state */
3371
0
            ssl->decrypt.state = CIPHER_STATE_END;
3372
0
        }
3373
0
        FALL_THROUGH;
3374
3375
0
        case CIPHER_STATE_END:
3376
0
        {
3377
        #ifdef WOLFSSL_DEBUG_TLS
3378
            #ifdef CIPHER_NONCE
3379
                WOLFSSL_MSG("Nonce");
3380
                WOLFSSL_BUFFER(ssl->decrypt.nonce, ssl->specs.iv_size);
3381
            #endif
3382
                WOLFSSL_MSG("Decrypted data");
3383
                WOLFSSL_BUFFER(output, dataSz);
3384
        #endif
3385
        #ifdef WOLFSSL_CHECK_MEM_ZERO
3386
            if ((ssl->specs.bulk_cipher_algorithm != wolfssl_cipher_null) &&
3387
                    (ret == 0)) {
3388
                wc_MemZero_Add("TLS 1.3 Decrypted data", output, sz);
3389
            }
3390
        #endif
3391
3392
0
        #ifdef CIPHER_NONCE
3393
0
            ForceZero(ssl->decrypt.nonce, ssl->specs.iv_size);
3394
0
        #endif
3395
3396
0
            break;
3397
0
        }
3398
3399
0
       default:
3400
0
            break;
3401
0
    }
3402
3403
0
    if (ret < 0) {
3404
0
        WOLFSSL_ERROR_VERBOSE(ret);
3405
0
    }
3406
3407
0
    return ret;
3408
0
}
3409
3410
/* Build SSL Message, encrypted.
3411
 * TLS v1.3 encryption is AEAD only.
3412
 *
3413
 * ssl         The SSL/TLS object.
3414
 * output      The buffer to write record message to.
3415
 * outSz       Size of the buffer being written into.
3416
 * input       The record data to encrypt (excluding record header).
3417
 * inSz        The size of the record data.
3418
 * type        The recorder header content type.
3419
 * hashOutput  Whether to hash the unencrypted record data.
3420
 * sizeOnly    Only want the size of the record message.
3421
 * asyncOkay   If non-zero can return WC_PENDING_E, otherwise blocks on crypto
3422
 * returns the size of the encrypted record message or negative value on error.
3423
 */
3424
int BuildTls13Message(WOLFSSL* ssl, byte* output, int outSz, const byte* input,
3425
                int inSz, int type, int hashOutput, int sizeOnly, int asyncOkay)
3426
0
{
3427
0
    int ret;
3428
0
    BuildMsgArgs* args;
3429
0
    BuildMsgArgs  lcl_args;
3430
3431
0
    WOLFSSL_ENTER("BuildTls13Message");
3432
3433
0
    if (ssl == NULL) {
3434
0
        return BAD_FUNC_ARG;
3435
0
    }
3436
3437
#ifdef WOLFSSL_ASYNC_CRYPT
3438
    ret = WC_NO_PENDING_E;
3439
    if (asyncOkay) {
3440
        if (ssl->async == NULL) {
3441
            ssl->async = (struct WOLFSSL_ASYNC*)
3442
                    XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
3443
                            DYNAMIC_TYPE_ASYNC);
3444
            if (ssl->async == NULL)
3445
                return MEMORY_E;
3446
            XMEMSET(ssl->async, 0, sizeof(struct WOLFSSL_ASYNC));
3447
        }
3448
        /* Not ssl->async->args: that buffer belongs to the handler that
3449
         * called down into the record builder. */
3450
        args = &ssl->async->buildArgs;
3451
3452
        ret = wolfSSL_AsyncPop(ssl, &ssl->options.buildMsgState);
3453
        if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) {
3454
            /* Check for error */
3455
            if (ret < 0)
3456
                goto exit_buildmsg;
3457
        }
3458
    }
3459
    else
3460
#endif
3461
0
    {
3462
0
        args = &lcl_args;
3463
0
    }
3464
3465
    /* buildArgs13Set, not the pop result, marks a resume: the handler
3466
     * already popped the pending, and resetting on the pop result would
3467
     * rebuild a half-built record (transcript/sequence advance twice). */
3468
#ifdef WOLFSSL_ASYNC_CRYPT
3469
    if (!asyncOkay || !ssl->options.buildArgs13Set)
3470
#endif
3471
0
    {
3472
        /* Note: these hit ssl->options even for a sizeOnly probe, where every
3473
         * other result goes to lcl_args, so a probe destroys the resume point
3474
         * of a suspended asynchronous build. wolfssl_local_GetRecordSize() is
3475
         * the only sizeOnly caller and restores them; a new one must too. */
3476
0
        ret = 0;
3477
0
        ssl->options.buildMsgState = BUILD_MSG_BEGIN;
3478
        /* A fresh record must not inherit a suspended build's mid-way
3479
         * cipher state. Not for sizeOnly probes: GetRecordSize() does not
3480
         * save this field and rewinding would re-run the AEAD. */
3481
0
        if (!sizeOnly)
3482
0
            ssl->encrypt.state = CIPHER_STATE_BEGIN;
3483
0
        XMEMSET(args, 0, sizeof(BuildMsgArgs));
3484
3485
0
        args->headerSz = RECORD_HEADER_SZ;
3486
#ifdef WOLFSSL_DTLS13
3487
        if (ssl->options.dtls)
3488
            args->headerSz = Dtls13GetRlHeaderLength(ssl, 1);
3489
#endif /* WOLFSSL_DTLS13 */
3490
3491
0
        args->sz = args->headerSz + (word32)inSz;
3492
0
        args->idx  = args->headerSz;
3493
0
    }
3494
3495
#ifdef WOLFSSL_ASYNC_CRYPT
3496
    if (ret == WC_NO_ERR_TRACE(WC_NO_PENDING_E))
3497
        ret = 0;
3498
#endif
3499
3500
0
    switch (ssl->options.buildMsgState) {
3501
0
        case BUILD_MSG_BEGIN:
3502
0
        {
3503
           /* catch mistaken sizeOnly parameter */
3504
0
            if (sizeOnly) {
3505
0
                if (output || input) {
3506
0
                    WOLFSSL_MSG("BuildTls13Message with sizeOnly "
3507
0
                                "doesn't need input or output");
3508
0
                    return BAD_FUNC_ARG;
3509
0
                }
3510
0
            }
3511
0
            else if (output == NULL || input == NULL) {
3512
0
                return BAD_FUNC_ARG;
3513
0
            }
3514
3515
            /* Record layer content type at the end of record data. */
3516
0
            args->sz++;
3517
            /* Authentication data at the end. */
3518
0
            args->sz += ssl->specs.aead_mac_size;
3519
#ifdef WOLFSSL_DTLS13
3520
            /* Pad to minimum length */
3521
            if (ssl->options.dtls &&
3522
                    args->sz < (word32)Dtls13MinimumRecordLength(ssl)) {
3523
                args->pad = Dtls13MinimumRecordLength(ssl) - args->sz;
3524
                args->sz = Dtls13MinimumRecordLength(ssl);
3525
            }
3526
#endif
3527
0
            if (sizeOnly)
3528
0
                return (int)args->sz;
3529
3530
0
            if (args->sz > (word32)outSz) {
3531
0
                WOLFSSL_MSG("Oops, want to write past output buffer size");
3532
0
                return BUFFER_E;
3533
0
            }
3534
3535
            /* Record data length. */
3536
0
            args->size = (word16)(args->sz - args->headerSz);
3537
            /* Write/update the record header with the new size.
3538
             * Always have the content type as application data for encrypted
3539
             * messages in TLS v1.3.
3540
             */
3541
3542
0
            if (ssl->options.dtls) {
3543
#ifdef WOLFSSL_DTLS13
3544
                Dtls13RlAddCiphertextHeader(ssl, output, args->size);
3545
#endif /* WOLFSSL_DTLS13 */
3546
0
            }
3547
0
            else {
3548
0
                AddTls13RecordHeader(output, args->size, application_data, ssl);
3549
0
            }
3550
3551
            /* TLS v1.3 can do in place encryption. */
3552
0
            if (input != output + args->idx)
3553
0
                XMEMCPY(output + args->idx, input, (size_t)inSz);
3554
0
            args->idx += (word32)inSz;
3555
3556
    #ifdef WOLFSSL_ASYNC_CRYPT
3557
            /* Set only after the argument checks above cannot return any
3558
             * more: an early error return must not leave the resume marker
3559
             * set, or the next build would reuse stale args. */
3560
            if (asyncOkay)
3561
                ssl->options.buildArgs13Set = 1;
3562
    #endif
3563
0
            ssl->options.buildMsgState = BUILD_MSG_HASH;
3564
0
        }
3565
0
        FALL_THROUGH;
3566
3567
0
        case BUILD_MSG_HASH:
3568
0
        {
3569
0
            if (hashOutput) {
3570
0
                ret = HashOutput(ssl, output, (int)args->headerSz + inSz, 0);
3571
0
                if (ret != 0)
3572
0
                    goto exit_buildmsg;
3573
0
            }
3574
3575
            /* The real record content type goes at the end of the data. */
3576
0
            output[args->idx++] = (byte)type;
3577
            /* Double check that any necessary padding is zero'd out */
3578
0
            XMEMSET(output + args->idx, 0, args->pad);
3579
0
            args->idx += args->pad;
3580
3581
0
            ssl->options.buildMsgState = BUILD_MSG_ENCRYPT;
3582
0
        }
3583
0
        FALL_THROUGH;
3584
3585
0
        case BUILD_MSG_ENCRYPT:
3586
0
        {
3587
#ifdef WOLFSSL_QUIC
3588
            if (WOLFSSL_IS_QUIC(ssl)) {
3589
                /* QUIC does not use encryption of the TLS Record Layer.
3590
                 * Return the original length + added headers
3591
                 * and restore it in the record header. */
3592
                AddTls13RecordHeader(output, (word32)inSz, (byte)type, ssl);
3593
                ret = (int)args->headerSz + inSz;
3594
                goto exit_buildmsg;
3595
            }
3596
#endif
3597
        #ifdef ATOMIC_USER
3598
            if (ssl->ctx->MacEncryptCb) {
3599
                /* User Record Layer Callback handling */
3600
                byte* mac = output + args->idx;
3601
                output += args->headerSz;
3602
3603
                ret = ssl->ctx->MacEncryptCb(ssl, mac, output, (unsigned int)inSz, (byte)type, 0,
3604
                        output, output, args->size, ssl->MacEncryptCtx);
3605
            }
3606
            else
3607
        #endif
3608
0
            {
3609
0
                const byte* aad = output;
3610
0
                output += args->headerSz;
3611
0
                ret = EncryptTls13(ssl, output, output, args->size, aad,
3612
0
                                   (word16)args->headerSz, asyncOkay);
3613
            #ifdef WOLFSSL_ASYNC_REINVOKE
3614
                /* Non-resumable caller (alerts): finish the encryption by
3615
                 * re-invoking; devices were already waited on above. */
3616
                if (!asyncOkay) {
3617
                    int reinvoke = 0;
3618
3619
                    while (ret == WC_NO_ERR_TRACE(WC_PENDING_E) &&
3620
                            reinvoke++ < WOLFSSL_ASYNC_MAX_REINVOKE) {
3621
                        ret = EncryptTls13(ssl, output, output, args->size,
3622
                                           aad, (word16)args->headerSz,
3623
                                           asyncOkay);
3624
                    }
3625
                    if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
3626
                        /* A device that never completes would otherwise spin
3627
                         * here forever, which is what wc_AsyncWait() used to
3628
                         * do. Report it instead. */
3629
                        WOLFSSL_MSG("Crypto callback still pending after "
3630
                                    "retry limit on a blocking record");
3631
                        ret = WC_HW_WAIT_E;
3632
                    }
3633
                }
3634
            #endif
3635
0
                if (ret != 0) {
3636
                #ifdef WOLFSSL_ASYNC_CRYPT
3637
                    if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
3638
                #endif
3639
0
                    {
3640
                        /* Zeroize plaintext. */
3641
0
                        ForceZero(output, args->size);
3642
0
                    }
3643
0
                }
3644
#ifdef WOLFSSL_DTLS13
3645
                if (ret == 0 && ssl->options.dtls) {
3646
                    /* AAD points to the header. Reuse the variable  */
3647
                    ret = Dtls13EncryptRecordNumber(ssl, (byte*)aad,
3648
                                                    (word16)args->sz);
3649
                }
3650
#endif /* WOLFSSL_DTLS13 */
3651
0
            }
3652
0
            break;
3653
0
        }
3654
3655
0
        default:
3656
0
            break;
3657
0
    }
3658
3659
0
exit_buildmsg:
3660
3661
0
    WOLFSSL_LEAVE("BuildTls13Message", ret);
3662
3663
#ifdef WOLFSSL_ASYNC_CRYPT
3664
    if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
3665
        return ret;
3666
    }
3667
#endif
3668
3669
    /* make sure build message state is reset */
3670
0
    ssl->options.buildMsgState = BUILD_MSG_BEGIN;
3671
3672
    /* return sz on success */
3673
0
    if (ret == 0) {
3674
0
        ret = (int)args->sz;
3675
0
    }
3676
0
    else {
3677
0
        WOLFSSL_ERROR_VERBOSE(ret);
3678
0
    }
3679
3680
    /* Final cleanup */
3681
#ifdef WOLFSSL_ASYNC_CRYPT
3682
    if (asyncOkay)
3683
        ssl->options.buildArgs13Set = 0;
3684
#endif
3685
3686
0
    return ret;
3687
0
}
3688
3689
#if !defined(NO_WOLFSSL_CLIENT) || (!defined(NO_WOLFSSL_SERVER) && \
3690
    (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)) && \
3691
    (defined(WOLFSSL_PSK_ONE_ID) || defined(WOLFSSL_PRIORITIZE_PSK)))
3692
/* Find the cipher suite in the suites set in the SSL.
3693
 *
3694
 * ssl    SSL/TLS object.
3695
 * suite  Cipher suite to look for.
3696
 * returns 1 when suite is found in SSL/TLS object's list and 0 otherwise.
3697
 */
3698
int FindSuiteSSL(const WOLFSSL* ssl, byte* suite)
3699
0
{
3700
0
    word16 i;
3701
0
    const Suites* suites = WOLFSSL_SUITES(ssl);
3702
3703
0
    for (i = 0; i < suites->suiteSz; i += 2) {
3704
0
        if (suites->suites[i+0] == suite[0] &&
3705
0
                suites->suites[i+1] == suite[1]) {
3706
0
            return 1;
3707
0
        }
3708
0
    }
3709
3710
0
    return 0;
3711
0
}
3712
#endif
3713
3714
#ifndef NO_PSK
3715
/* Get the MAC algorithm for the TLS 1.3 cipher suite.
3716
 *
3717
 * @param [in] suite.
3718
 * @return  A value from wc_MACAlgorithm enumeration.
3719
 */
3720
byte SuiteMac(const byte* suite)
3721
{
3722
    byte mac = no_mac;
3723
3724
    if (suite[0] == TLS13_BYTE) {
3725
        switch (suite[1]) {
3726
        #ifdef BUILD_TLS_AES_128_GCM_SHA256
3727
            case TLS_AES_128_GCM_SHA256:
3728
                mac = sha256_mac;
3729
                break;
3730
        #endif
3731
        #ifdef BUILD_TLS_CHACHA20_POLY1305_SHA256
3732
            case TLS_CHACHA20_POLY1305_SHA256:
3733
                mac = sha256_mac;
3734
                break;
3735
        #endif
3736
        #ifdef BUILD_TLS_AES_128_CCM_SHA256
3737
            case TLS_AES_128_CCM_SHA256:
3738
                mac = sha256_mac;
3739
                break;
3740
        #endif
3741
        #ifdef BUILD_TLS_AES_128_CCM_8_SHA256
3742
            case TLS_AES_128_CCM_8_SHA256:
3743
                mac = sha256_mac;
3744
                break;
3745
        #endif
3746
        #ifdef BUILD_TLS_AES_256_GCM_SHA384
3747
            case TLS_AES_256_GCM_SHA384:
3748
                mac = sha384_mac;
3749
                break;
3750
        #endif
3751
            default:
3752
                break;
3753
        }
3754
    }
3755
#if (defined(WOLFSSL_SM4_GCM) || defined(WOLFSSL_SM4_CCM)) && \
3756
     defined(WOLFSSL_SM3)
3757
    else if (suite[0] == CIPHER_BYTE) {
3758
        switch (suite[1]) {
3759
        #ifdef BUILD_TLS_SM4_GCM_SM3
3760
            case TLS_SM4_GCM_SM3:
3761
                mac = sm3_mac;
3762
                break;
3763
        #endif
3764
        #ifdef BUILD_TLS_SM4_CCM_SM3
3765
            case TLS_SM4_CCM_SM3:
3766
                mac = sm3_mac;
3767
                break;
3768
        #endif
3769
            default:
3770
                break;
3771
        }
3772
    }
3773
#endif
3774
#ifdef HAVE_NULL_CIPHER
3775
    else if (suite[0] == ECC_BYTE) {
3776
        switch (suite[1]) {
3777
        #ifdef BUILD_TLS_SHA256_SHA256
3778
            case TLS_SHA256_SHA256:
3779
                mac = sha256_mac;
3780
                break;
3781
        #endif
3782
        #ifdef BUILD_TLS_SHA384_SHA384
3783
            case TLS_SHA384_SHA384:
3784
                mac = sha384_mac;
3785
                break;
3786
        #endif
3787
            default:
3788
                break;
3789
        }
3790
    }
3791
#endif
3792
3793
    return mac;
3794
}
3795
#endif
3796
3797
#if defined(WOLFSSL_SEND_HRR_COOKIE) && !defined(NO_WOLFSSL_SERVER)
3798
/* Create Cookie extension using the hash of the first ClientHello.
3799
 *
3800
 * ssl     SSL/TLS object.
3801
 * hash    The hash data.
3802
 * hashSz  The size of the hash data in bytes.
3803
 * returns 0 on success, otherwise failure.
3804
 */
3805
int CreateCookieExt(const WOLFSSL* ssl, byte* hash, word16 hashSz,
3806
                    TLSX** exts, byte cipherSuite0, byte cipherSuite)
3807
{
3808
    int  ret;
3809
    byte mac[WC_MAX_DIGEST_SIZE] = {0};
3810
    WC_DECLARE_VAR(cookieHmac, Hmac, 1, ssl->heap);
3811
    byte cookieType = 0;
3812
    byte macSz = 0;
3813
    byte cookie[OPAQUE8_LEN + WC_MAX_DIGEST_SIZE + OPAQUE16_LEN * 2];
3814
    TLSX* ext;
3815
    word16 cookieSz = 0;
3816
3817
    if (hash == NULL || hashSz == 0) {
3818
        return BAD_FUNC_ARG;
3819
    }
3820
3821
    if (ssl->buffers.tls13CookieSecret.buffer == NULL ||
3822
            ssl->buffers.tls13CookieSecret.length == 0) {
3823
        WOLFSSL_MSG("Missing DTLS 1.3 cookie secret");
3824
        return COOKIE_ERROR;
3825
    }
3826
3827
    /* Cookie Data = Hash Len | Hash | CS | KeyShare Group */
3828
    cookie[cookieSz++] = (byte)hashSz;
3829
    XMEMCPY(cookie + cookieSz, hash, hashSz);
3830
    cookieSz += hashSz;
3831
    cookie[cookieSz++] = cipherSuite0;
3832
    cookie[cookieSz++] = cipherSuite;
3833
    if ((ext = TLSX_Find(*exts, TLSX_KEY_SHARE)) != NULL) {
3834
        KeyShareEntry* kse = (KeyShareEntry*)ext->data;
3835
        if (kse == NULL) {
3836
            WOLFSSL_MSG("KeyShareEntry can't be empty when negotiating "
3837
                        "parameters");
3838
            return BAD_STATE_E;
3839
        }
3840
        c16toa(kse->group, cookie + cookieSz);
3841
        cookieSz += OPAQUE16_LEN;
3842
    }
3843
3844
#ifndef NO_SHA256
3845
    cookieType = WC_SHA256;
3846
    macSz = WC_SHA256_DIGEST_SIZE;
3847
#elif defined(WOLFSSL_SHA384)
3848
    cookieType = WC_SHA384;
3849
    macSz = WC_SHA384_DIGEST_SIZE;
3850
#elif defined(WOLFSSL_TLS13_SHA512)
3851
    cookieType = WC_SHA512;
3852
    macSz = WC_SHA512_DIGEST_SIZE;
3853
#elif defined(WOLFSSL_SM3)
3854
    cookieType = WC_SM3;
3855
    macSz = WC_SM3_DIGEST_SIZE;
3856
#else
3857
    #error "No digest to available to use with HMAC for cookies."
3858
#endif /* NO_SHA */
3859
3860
    WC_ALLOC_VAR_EX(cookieHmac, Hmac, 1, ssl->heap, DYNAMIC_TYPE_HMAC,
3861
                    return MEMORY_E);
3862
3863
    ret = wc_HmacInit(cookieHmac, ssl->heap, ssl->devId);
3864
    if (ret == 0) {
3865
        ret = wc_HmacSetKey(cookieHmac, cookieType,
3866
                            ssl->buffers.tls13CookieSecret.buffer,
3867
                            ssl->buffers.tls13CookieSecret.length);
3868
    }
3869
    if (ret == 0)
3870
        ret = wc_HmacUpdate(cookieHmac, cookie, cookieSz);
3871
#ifdef WOLFSSL_DTLS13
3872
    /* Tie cookie to peer address */
3873
    if (ret == 0) {
3874
        /* peerLock not necessary. Still in handshake phase. */
3875
        if (ssl->options.dtls && ssl->buffers.dtlsCtx.peer.sz > 0) {
3876
            ret = wc_HmacUpdate(cookieHmac,
3877
                (byte*)ssl->buffers.dtlsCtx.peer.sa,
3878
                ssl->buffers.dtlsCtx.peer.sz);
3879
        }
3880
    }
3881
#endif
3882
    if (ret == 0)
3883
        ret = wc_HmacFinal(cookieHmac, mac);
3884
3885
    wc_HmacFree(cookieHmac);
3886
    WC_FREE_VAR_EX(cookieHmac, ssl->heap, DYNAMIC_TYPE_HMAC);
3887
    if (ret != 0)
3888
        return ret;
3889
3890
    /* The cookie data is the hash and the integrity check. */
3891
    return TLSX_Cookie_Use(ssl, cookie, cookieSz, mac, macSz, 1, exts);
3892
}
3893
#endif
3894
3895
#ifdef WOLFSSL_DTLS13
3896
#define HRR_MAX_HS_HEADER_SZ DTLS_HANDSHAKE_HEADER_SZ
3897
#else
3898
#define HRR_MAX_HS_HEADER_SZ HANDSHAKE_HEADER_SZ
3899
#endif /* WOLFSSL_DTLS13 */
3900
3901
static int CreateCookie(const WOLFSSL* ssl, byte** hash, byte* hashSz,
3902
                            Hashes* hashes, TLSX** exts)
3903
0
{
3904
0
    int    ret = 0;
3905
3906
0
    (void)exts;
3907
3908
0
    *hash = NULL;
3909
0
    switch (ssl->specs.mac_algorithm) {
3910
0
    #ifndef NO_SHA256
3911
0
        case sha256_mac:
3912
0
            *hash = hashes->sha256;
3913
0
            break;
3914
0
    #endif
3915
0
    #ifdef WOLFSSL_SHA384
3916
0
        case sha384_mac:
3917
0
            *hash = hashes->sha384;
3918
0
            break;
3919
0
    #endif
3920
    #ifdef WOLFSSL_TLS13_SHA512
3921
        case sha512_mac:
3922
            *hash = hashes->sha512;
3923
            break;
3924
    #endif
3925
    #ifdef WOLFSSL_SM3
3926
        case sm3_mac:
3927
            *hash = hashes->sm3;
3928
            break;
3929
    #endif
3930
0
    }
3931
0
    *hashSz = ssl->specs.hash_size;
3932
3933
    /* check hash */
3934
0
    if (*hash == NULL && *hashSz > 0)
3935
0
        return BAD_FUNC_ARG;
3936
3937
#if defined(WOLFSSL_SEND_HRR_COOKIE) && !defined(NO_WOLFSSL_SERVER)
3938
    if (ssl->options.sendCookie && ssl->options.side == WOLFSSL_SERVER_END)
3939
        ret = CreateCookieExt(ssl, *hash, *hashSz, exts,
3940
                ssl->options.cipherSuite0, ssl->options.cipherSuite);
3941
#endif
3942
0
    return ret;
3943
0
}
3944
3945
/* Restart the handshake hash with a hash of the previous messages.
3946
 *
3947
 * ssl The SSL/TLS object.
3948
 * returns 0 on success, otherwise failure.
3949
 */
3950
int RestartHandshakeHash(WOLFSSL* ssl)
3951
0
{
3952
0
    int    ret;
3953
0
    byte   header[HANDSHAKE_HEADER_SZ] = {0};
3954
0
    Hashes hashes;
3955
0
    byte*  hash = NULL;
3956
0
    byte   hashSz = 0;
3957
3958
0
    ret = BuildCertHashes(ssl, &hashes);
3959
0
    if (ret != 0)
3960
0
        return ret;
3961
0
    ret = CreateCookie(ssl, &hash, &hashSz, &hashes, &ssl->extensions);
3962
0
    if (ret != 0)
3963
0
        return ret;
3964
#if defined(WOLFSSL_SEND_HRR_COOKIE) && !defined(NO_WOLFSSL_SERVER)
3965
    if (ssl->options.sendCookie && ssl->options.side == WOLFSSL_SERVER_END)
3966
        return 0;
3967
#endif
3968
3969
0
    AddTls13HandShakeHeader(header, hashSz, 0, 0, message_hash, ssl);
3970
3971
#ifdef WOLFSSL_DEBUG_TLS
3972
    WOLFSSL_MSG("Restart Hash");
3973
    WOLFSSL_BUFFER(hash, hashSz);
3974
#endif
3975
3976
0
    ret = InitHandshakeHashes(ssl);
3977
0
    if (ret != 0)
3978
0
        return ret;
3979
0
    ret = HashRaw(ssl, header, sizeof(header));
3980
0
    if (ret != 0)
3981
0
        return ret;
3982
0
    return HashRaw(ssl, hash, hashSz);
3983
0
}
3984
3985
#if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER)
3986
/* The value in the random field of a ServerHello to indicate
3987
 * HelloRetryRequest.
3988
 */
3989
static byte helloRetryRequestRandom[] = {
3990
    0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11,
3991
    0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91,
3992
    0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E,
3993
    0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C
3994
};
3995
#endif
3996
3997
#ifdef HAVE_ECH
3998
/* returns the index of the first supported cipher suite, -1 if none */
3999
int EchConfigGetSupportedCipherSuite(WOLFSSL_EchConfig* config)
4000
{
4001
    int i = 0;
4002
4003
    if (!wc_HpkeKemIsSupported(config->kemId)) {
4004
        WOLFSSL_MSG("ECH config: KEM not supported");
4005
        return WOLFSSL_FATAL_ERROR;
4006
    }
4007
4008
    for (i = 0; i < config->numCipherSuites; i++) {
4009
        if (wc_HpkeKdfIsSupported(config->cipherSuites[i].kdfId) &&
4010
                wc_HpkeAeadIsSupported(config->cipherSuites[i].aeadId)) {
4011
            return i;
4012
        }
4013
    }
4014
4015
    WOLFSSL_MSG("ECH config: KDF or AEAD not supported");
4016
    return WOLFSSL_FATAL_ERROR;
4017
}
4018
4019
/* Hash the inner client hello, initializing the hsHashesEch field if needed.
4020
 * This should receive the client hello without outer_extensions 'encoding'
4021
 *
4022
 * ssl      SSL/TLS object.
4023
 * ech      ECH object.
4024
 * returns 0 on success and otherwise failure.
4025
 */
4026
static int EchHashHelloInner(WOLFSSL* ssl, WOLFSSL_ECH* ech)
4027
{
4028
    int ret = 0;
4029
    int headerSz;
4030
    word32 realSz;
4031
    HS_Hashes* tmpHashes;
4032
#ifndef NO_WOLFSSL_CLIENT
4033
    byte falseHeader[HRR_MAX_HS_HEADER_SZ];
4034
#endif
4035
4036
    if (ssl == NULL || ech == NULL) {
4037
        return BAD_FUNC_ARG;
4038
    }
4039
4040
#ifdef WOLFSSL_DTLS13
4041
    headerSz = ssl->options.dtls ? DTLS13_HANDSHAKE_HEADER_SZ :
4042
                                   HANDSHAKE_HEADER_SZ;
4043
#else
4044
    headerSz = HANDSHAKE_HEADER_SZ;
4045
#endif
4046
4047
    realSz = ech->innerClientHelloLen;
4048
4049
    tmpHashes = ssl->hsHashes;
4050
4051
    ssl->hsHashes = ssl->hsHashesEch;
4052
    if (ssl->hsHashes == NULL) {
4053
        ret = InitHandshakeHashes(ssl);
4054
        if (ret == 0) {
4055
            ssl->hsHashesEch = ssl->hsHashes;
4056
        }
4057
    }
4058
4059
    if (ret == 0) {
4060
#ifndef NO_WOLFSSL_CLIENT
4061
        if (ssl->options.side == WOLFSSL_CLIENT_END) {
4062
            /* client-side: innerClientHello contains body only */
4063
            AddTls13HandShakeHeader(falseHeader, realSz, 0, 0, client_hello,
4064
                                    ssl);
4065
            ret = HashRaw(ssl, falseHeader, headerSz);
4066
            if (ret == 0) {
4067
                ret = HashRaw(ssl, ech->innerClientHello, realSz);
4068
            }
4069
        }
4070
#endif
4071
#ifndef NO_WOLFSSL_SERVER
4072
        if (ssl->options.side == WOLFSSL_SERVER_END) {
4073
            /* server-side: innerClientHello contains header + body */
4074
            ret = HashRaw(ssl, ech->innerClientHello, headerSz + realSz);
4075
        }
4076
#endif
4077
    }
4078
4079
    ssl->hsHashes = tmpHashes;
4080
    return ret;
4081
}
4082
4083
/* Calculate the 8 ECH confirmation bytes.
4084
 *
4085
 * ssl            SSL/TLS object.
4086
 * label          Ascii string describing ECH acceptance or rejection.
4087
 * labelSz        Length of label excluding NULL character.
4088
 * input          The buffer to calculate confirmation off of.
4089
 * acceptOffset   Where the 8 ECH confirmation bytes start.
4090
 * helloSz        Size of hello message.
4091
 * isHrr          Whether message is a HelloRetryRequest or not.
4092
 * acceptExpanded An 8 byte array to store calculated confirmation to.
4093
 * returns 0 on success and otherwise failure.
4094
 */
4095
static int EchCalcAcceptance(WOLFSSL* ssl, byte* label, word16 labelSz,
4096
    const byte* input, int acceptOffset, int helloSz, byte isHrr,
4097
    byte* acceptExpanded)
4098
{
4099
    int ret = 0;
4100
    int digestType = 0;
4101
    int digestSize = 0;
4102
    int hashSz = 0;
4103
    int headerSz;
4104
    HS_Hashes* tmpHashes;
4105
    HS_Hashes* acceptHash = NULL;
4106
    byte zeros[WC_MAX_DIGEST_SIZE];
4107
    byte transcriptEchConf[WC_MAX_DIGEST_SIZE];
4108
    byte clientHelloInnerHash[WC_MAX_DIGEST_SIZE];
4109
    byte expandLabelPrk[WC_MAX_DIGEST_SIZE];
4110
    byte messageHashHeader[HRR_MAX_HS_HEADER_SZ];
4111
4112
    XMEMSET(zeros, 0, sizeof(zeros));
4113
    XMEMSET(transcriptEchConf, 0, sizeof(transcriptEchConf));
4114
    XMEMSET(clientHelloInnerHash, 0, sizeof(clientHelloInnerHash));
4115
    XMEMSET(expandLabelPrk, 0, sizeof(expandLabelPrk));
4116
4117
#ifdef WOLFSSL_CHECK_MEM_ZERO
4118
    wc_MemZero_Add("ECH PRK", expandLabelPrk, sizeof(expandLabelPrk));
4119
#endif
4120
4121
    tmpHashes = ssl->hsHashes;
4122
    ssl->hsHashes = ssl->hsHashesEch;
4123
4124
#ifdef WOLFSSL_DTLS13
4125
    headerSz = ssl->options.dtls ? DTLS13_HANDSHAKE_HEADER_SZ :
4126
                                   HANDSHAKE_HEADER_SZ;
4127
#else
4128
    headerSz = HANDSHAKE_HEADER_SZ;
4129
#endif
4130
4131
    if (isHrr) {
4132
        /* the transcript hash of ClientHelloInner1 */
4133
        ret = GetMsgHash(ssl, clientHelloInnerHash);
4134
        if (ret > 0) {
4135
            hashSz = ret;
4136
            ret = 0;
4137
        }
4138
        else if (ret == 0) {
4139
            ret = HASH_TYPE_E;
4140
        }
4141
4142
        /* restart ECH transcript hash, similar to RestartHandshakeHash but
4143
         * don't add a cookie */
4144
        if (ret == 0) {
4145
            ret = InitHandshakeHashes(ssl);
4146
            ssl->hsHashesEch = ssl->hsHashes;
4147
        }
4148
        if (ret == 0) {
4149
            AddTls13HandShakeHeader(messageHashHeader, (word32)hashSz, 0, 0,
4150
                message_hash, ssl);
4151
            ret = HashRaw(ssl, messageHashHeader, headerSz);
4152
        }
4153
        if (ret == 0) {
4154
            ret = HashRaw(ssl, clientHelloInnerHash, (word32)hashSz);
4155
        }
4156
    }
4157
4158
    /* hash with zeros for confirmation computation */
4159
    if (ret == 0) {
4160
        ret = InitHandshakeHashesAndCopy(ssl, ssl->hsHashesEch, &acceptHash);
4161
    }
4162
    if (ret == 0) {
4163
        ssl->hsHashes = acceptHash;
4164
        ret = HashRaw(ssl, input, acceptOffset);
4165
    }
4166
    if (ret == 0) {
4167
        ret = HashRaw(ssl, zeros, ECH_ACCEPT_CONFIRMATION_SZ);
4168
    }
4169
    if (ret == 0) {
4170
        ret = HashRaw(ssl, input + acceptOffset + ECH_ACCEPT_CONFIRMATION_SZ,
4171
            helloSz + headerSz - (acceptOffset + ECH_ACCEPT_CONFIRMATION_SZ));
4172
    }
4173
4174
    /* get the modified transcript hash */
4175
    if (ret == 0) {
4176
        ret = GetMsgHash(ssl, transcriptEchConf);
4177
        if (ret > 0) {
4178
            ret = 0;
4179
        }
4180
        else if (ret == 0) {
4181
            ret = HASH_TYPE_E;
4182
        }
4183
    }
4184
4185
    /* pick the right type and size based on mac_algorithm */
4186
    if (ret == 0) {
4187
        switch (ssl->specs.mac_algorithm) {
4188
#ifndef NO_SHA256
4189
            case sha256_mac:
4190
                digestType = WC_SHA256;
4191
                digestSize = WC_SHA256_DIGEST_SIZE;
4192
                break;
4193
#endif /* !NO_SHA256 */
4194
#ifdef WOLFSSL_SHA384
4195
            case sha384_mac:
4196
                digestType = WC_SHA384;
4197
                digestSize = WC_SHA384_DIGEST_SIZE;
4198
                break;
4199
#endif /* WOLFSSL_SHA384 */
4200
#ifdef WOLFSSL_TLS13_SHA512
4201
            case sha512_mac:
4202
                digestType = WC_SHA512;
4203
                digestSize = WC_SHA512_DIGEST_SIZE;
4204
                break;
4205
#endif /* WOLFSSL_TLS13_SHA512 */
4206
#ifdef WOLFSSL_SM3
4207
            case sm3_mac:
4208
                digestType = WC_SM3;
4209
                digestSize = WC_SM3_DIGEST_SIZE;
4210
                break;
4211
#endif /* WOLFSSL_SM3 */
4212
            default:
4213
                ret = WOLFSSL_FATAL_ERROR;
4214
                break;
4215
        }
4216
    }
4217
4218
    /* extract clientRandomInner with a key of all zeros */
4219
    if (ret == 0) {
4220
        PRIVATE_KEY_UNLOCK();
4221
    #if !defined(HAVE_FIPS) || \
4222
        (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(6,0))
4223
        ret = wc_HKDF_Extract_ex(digestType, zeros, (word32)digestSize,
4224
            ssl->arrays->clientRandomInner, RAN_LEN, expandLabelPrk,
4225
            ssl->heap, ssl->devId);
4226
    #else
4227
        ret = wc_HKDF_Extract(digestType, zeros, digestSize,
4228
            ssl->arrays->clientRandomInner, RAN_LEN, expandLabelPrk);
4229
    #endif
4230
        PRIVATE_KEY_LOCK();
4231
    }
4232
4233
    /* tls expand with the confirmation label */
4234
    if (ret == 0) {
4235
        PRIVATE_KEY_UNLOCK();
4236
#ifdef WOLFSSL_DTLS13
4237
        if (ssl->options.dtls) {
4238
            ret = Tls13HKDFExpandKeyLabel(ssl, acceptExpanded,
4239
                ECH_ACCEPT_CONFIRMATION_SZ, expandLabelPrk, (word32)digestSize,
4240
                dtls13ProtocolLabel, DTLS13_PROTOCOL_LABEL_SZ, label, labelSz,
4241
                transcriptEchConf, (word32)digestSize, digestType,
4242
                WOLFSSL_SERVER_END);
4243
        }
4244
        else
4245
#endif
4246
        {
4247
            ret = Tls13HKDFExpandKeyLabel(ssl, acceptExpanded,
4248
                ECH_ACCEPT_CONFIRMATION_SZ, expandLabelPrk, (word32)digestSize,
4249
                tls13ProtocolLabel, TLS13_PROTOCOL_LABEL_SZ, label, labelSz,
4250
                transcriptEchConf, (word32)digestSize, digestType,
4251
                WOLFSSL_SERVER_END);
4252
        }
4253
        PRIVATE_KEY_LOCK();
4254
    }
4255
4256
    if (acceptHash != NULL) {
4257
        ssl->hsHashes = acceptHash;
4258
        FreeHandshakeHashes(ssl);
4259
    }
4260
4261
    ssl->hsHashes = tmpHashes;
4262
    ForceZero(expandLabelPrk, sizeof(expandLabelPrk));
4263
#ifdef WOLFSSL_CHECK_MEM_ZERO
4264
    wc_MemZero_Check(expandLabelPrk, sizeof(expandLabelPrk));
4265
#endif
4266
    return ret;
4267
}
4268
#endif
4269
4270
#if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG) && \
4271
    (!defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER))
4272
/* Record whether the peer's advertised algorithms permit SHA-1 signed
4273
 * certificates.
4274
 *
4275
 * RFC 8446 Section 4.2.3 has signature_algorithms cover certificate signatures
4276
 * when signature_algorithms_cert is absent.
4277
 *
4278
 * ssl         The SSL/TLS object.
4279
 * peerSuites  The peer's signature_algorithms list.
4280
 */
4281
static void SetPeerSha1CertOk(WOLFSSL* ssl, const Suites* peerSuites)
4282
0
{
4283
0
    const byte* list = NULL;
4284
0
    word16      listSz = 0;
4285
0
    word16      i;
4286
4287
0
    ssl->options.peerSha1CertOk = 0;
4288
4289
0
    if (ssl->certHashSigAlgoSz > 0) {
4290
0
        list = ssl->certHashSigAlgo;
4291
0
        listSz = ssl->certHashSigAlgoSz;
4292
0
    }
4293
0
    else if (peerSuites != NULL) {
4294
0
        list = peerSuites->hashSigAlgo;
4295
0
        listSz = peerSuites->hashSigAlgoSz;
4296
0
    }
4297
0
    else {
4298
0
        return;
4299
0
    }
4300
4301
0
    for (i = 0; i + 2 <= listSz; i += 2) {
4302
        /* Only rsa_pkcs1_sha1, dsa_sha1 and ecdsa_sha1 carry sha_mac as the
4303
         * first byte of the signature scheme. */
4304
0
        if (list[i] == sha_mac) {
4305
0
            ssl->options.peerSha1CertOk = 1;
4306
0
            break;
4307
0
        }
4308
0
    }
4309
0
}
4310
#endif /* !NO_CERTS && !WOLFSSL_NO_SIGALG && (client || server) */
4311
4312
#ifndef NO_WOLFSSL_CLIENT
4313
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
4314
#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_PSK_ONE_ID) && \
4315
    !defined(NO_PSK)
4316
/**
4317
* convert mac algorithm to WOLFSSL_EVP_MD
4318
* @param mac_alg mac algorithm
4319
* @return const WOLFSSL_EVP_MD on successful, otherwise NULL
4320
*/
4321
static const WOLFSSL_EVP_MD* ssl_handshake_md(const byte mac_alg)
4322
{
4323
    switch(mac_alg) {
4324
        case no_mac:
4325
            return NULL;
4326
    #ifndef NO_MD5
4327
        case md5_mac:
4328
            return wolfSSL_EVP_md5();
4329
    #endif
4330
    #ifndef NO_SHA
4331
        case sha_mac:
4332
            return wolfSSL_EVP_sha1();
4333
    #endif
4334
    #ifdef WOLFSSL_SHA224
4335
        case sha224_mac:
4336
            return wolfSSL_EVP_sha224();
4337
    #endif
4338
        case sha256_mac:
4339
            return wolfSSL_EVP_sha256();
4340
    #ifdef WOLFSSL_SHA384
4341
        case sha384_mac:
4342
            return wolfSSL_EVP_sha384();
4343
    #endif
4344
    #ifdef WOLFSSL_SHA512
4345
        case sha512_mac:
4346
            return wolfSSL_EVP_sha512();
4347
    #endif
4348
        case rmd_mac:
4349
        case blake2b_mac:
4350
            WOLFSSL_MSG("no suitable EVP_MD");
4351
            return NULL;
4352
        default:
4353
            WOLFSSL_MSG("Unknown mac algorithm");
4354
            return NULL;
4355
    }
4356
}
4357
#endif
4358
/* Setup pre-shared key based on the details in the extension data.
4359
 *
4360
 * ssl          SSL/TLS object.
4361
 * psk          Pre-shared key extension data.
4362
 * clientHello  Whether called from client_hello construction.
4363
 * returns 0 on success, PSK_KEY_ERROR when the client PSK callback fails and
4364
 * other negative value on failure.
4365
 */
4366
static int SetupPskKey(WOLFSSL* ssl, PreSharedKey* psk, int clientHello)
4367
{
4368
#if defined(HAVE_SESSION_TICKET) || !defined(WOLFSSL_PSK_ONE_ID)
4369
    int ret;
4370
#endif
4371
    byte suite[2];
4372
4373
    if (psk == NULL)
4374
        return BAD_FUNC_ARG;
4375
4376
    if (!HaveUniqueSessionObj(ssl)) {
4377
        WOLFSSL_MSG("Unable to have unique session object");
4378
        WOLFSSL_ERROR_VERBOSE(MEMORY_ERROR);
4379
        return MEMORY_ERROR;
4380
    }
4381
4382
    suite[0] = ssl->options.cipherSuite0;
4383
    suite[1] = ssl->options.cipherSuite;
4384
4385
#ifdef HAVE_SESSION_TICKET
4386
    if (psk->resumption) {
4387
        if (clientHello) {
4388
            suite[0] = psk->cipherSuite0;
4389
            suite[1] = psk->cipherSuite;
4390
4391
            /* Ensure cipher suite is supported or changed suite to one with
4392
             * the same MAC algorithm. */
4393
            if (!FindSuiteSSL(ssl, suite)) {
4394
                WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
4395
                return PSK_KEY_ERROR;
4396
            }
4397
4398
            ssl->options.cipherSuite0 = suite[0];
4399
            ssl->options.cipherSuite = suite[1];
4400
4401
            /* Setting mac for binder and keys for deriving EarlyData. */
4402
            ret = SetCipherSpecs(ssl);
4403
            if (ret != 0)
4404
                return ret;
4405
        }
4406
4407
    #ifdef WOLFSSL_EARLY_DATA
4408
        if (ssl->session->maxEarlyDataSz == 0)
4409
            ssl->earlyData = no_early_data;
4410
    #endif
4411
        /* Resumption PSK is master secret. */
4412
        ssl->arrays->psk_keySz = ssl->specs.hash_size;
4413
        if ((ret = DeriveResumptionPSK(ssl, ssl->session->ticketNonce.data,
4414
                   ssl->session->ticketNonce.len, ssl->arrays->psk_key)) != 0) {
4415
            return ret;
4416
        }
4417
        if (!clientHello) {
4418
            /* CLIENT: using secret in ticket for peer authentication. */
4419
            ssl->options.peerAuthGood = 1;
4420
        }
4421
    }
4422
#endif
4423
#ifndef NO_PSK
4424
    if (!psk->resumption) {
4425
        /* Get the pre-shared key. */
4426
#ifndef WOLFSSL_PSK_ONE_ID
4427
        const char* cipherName = NULL;
4428
    #ifdef OPENSSL_EXTRA
4429
        WOLFSSL_SESSION* psksession = NULL;
4430
    #endif
4431
4432
        /* Set the client identity to use. */
4433
        if (psk->identityLen > MAX_PSK_ID_LEN)
4434
            return PSK_KEY_ERROR;
4435
        XMEMSET(ssl->arrays->client_identity, 0,
4436
            sizeof(ssl->arrays->client_identity));
4437
        XMEMCPY(ssl->arrays->client_identity, psk->identity, psk->identityLen);
4438
4439
    #ifdef WOLFSSL_DEBUG_TLS
4440
        WOLFSSL_MSG("PSK cipher suite:");
4441
        WOLFSSL_MSG(GetCipherNameInternal(psk->cipherSuite0, psk->cipherSuite));
4442
    #endif
4443
4444
        /* Get the pre-shared key. */
4445
    #ifdef OPENSSL_EXTRA
4446
        if (ssl->options.session_psk_cb != NULL) {
4447
            const unsigned char* id = NULL;
4448
            size_t idlen = 0;
4449
            const WOLFSSL_EVP_MD* handshake_md = NULL;
4450
4451
            if (ssl->msgsReceived.got_hello_retry_request >= 1) {
4452
                handshake_md = ssl_handshake_md(ssl->specs.mac_algorithm);
4453
            }
4454
            /* OpenSSL compatible callback that gets cached session. */
4455
            if (ssl->options.session_psk_cb(ssl, handshake_md, &id, &idlen,
4456
                                                            &psksession) == 0) {
4457
                wolfSSL_FreeSession(ssl->ctx, psksession);
4458
                WOLFSSL_MSG("psk session callback failed");
4459
                return PSK_KEY_ERROR;
4460
            }
4461
            if (psksession != NULL) {
4462
                if (idlen > MAX_PSK_KEY_LEN) {
4463
                    wolfSSL_FreeSession(ssl->ctx, psksession);
4464
                    WOLFSSL_MSG("psk key length is too long");
4465
                    WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
4466
                    return PSK_KEY_ERROR;
4467
                }
4468
4469
                ssl->arrays->psk_keySz = (word32)idlen;
4470
                XMEMCPY(ssl->arrays->psk_key, id, idlen);
4471
                suite[0] = psksession->cipherSuite0;
4472
                suite[1] = psksession->cipherSuite;
4473
                /* Not needed anymore. */
4474
                wolfSSL_FreeSession(ssl->ctx, psksession);
4475
                /* Leave pointer not NULL to indicate success with callback. */
4476
            }
4477
        }
4478
        if (psksession != NULL) {
4479
            /* Don't try other callbacks - we have an answer. */
4480
        }
4481
        else
4482
    #endif /* OPENSSL_EXTRA */
4483
        if (ssl->options.client_psk_cs_cb != NULL) {
4484
        #ifdef WOLFSSL_PSK_MULTI_ID_PER_CS
4485
            ssl->arrays->client_identity[0] = 0;
4486
        #endif
4487
            /* Lookup key again for next identity. */
4488
            ssl->arrays->psk_keySz = ssl->options.client_psk_cs_cb(
4489
                ssl, ssl->arrays->server_hint,
4490
                ssl->arrays->client_identity, MAX_PSK_ID_LEN,
4491
                ssl->arrays->psk_key, MAX_PSK_KEY_LEN,
4492
                GetCipherNameInternal(psk->cipherSuite0, psk->cipherSuite));
4493
            if (clientHello) {
4494
                /* Use PSK cipher suite. */
4495
                ssl->options.cipherSuite0 = psk->cipherSuite0;
4496
                ssl->options.cipherSuite  = psk->cipherSuite;
4497
            }
4498
            else {
4499
                byte pskCS[2];
4500
                pskCS[0] = psk->cipherSuite0;
4501
                pskCS[1] = psk->cipherSuite;
4502
4503
                /* Ensure PSK and negotiated cipher suites have same hash. */
4504
                if (SuiteMac(pskCS) != SuiteMac(suite)) {
4505
                    WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
4506
                    return PSK_KEY_ERROR;
4507
                }
4508
                /* Negotiated cipher suite is to be used - update PSK. */
4509
                psk->cipherSuite0 = suite[0];
4510
                psk->cipherSuite  = suite[1];
4511
            }
4512
        }
4513
        else if (ssl->options.client_psk_tls13_cb != NULL) {
4514
            byte cipherSuite0;
4515
            byte cipherSuite;
4516
            int cipherSuiteFlags = WOLFSSL_CIPHER_SUITE_FLAG_NONE;
4517
4518
            ssl->arrays->psk_keySz = ssl->options.client_psk_tls13_cb(ssl,
4519
                    ssl->arrays->server_hint, ssl->arrays->client_identity,
4520
                    MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN,
4521
                    &cipherName);
4522
            if (GetCipherSuiteFromName(cipherName, &cipherSuite0,
4523
                            &cipherSuite, NULL, NULL, &cipherSuiteFlags) != 0) {
4524
                WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
4525
                return PSK_KEY_ERROR;
4526
            }
4527
            ssl->options.cipherSuite0 = cipherSuite0;
4528
            ssl->options.cipherSuite  = cipherSuite;
4529
            (void)cipherSuiteFlags;
4530
        }
4531
        else {
4532
            ssl->arrays->psk_keySz = ssl->options.client_psk_cb(ssl,
4533
                    ssl->arrays->server_hint, ssl->arrays->client_identity,
4534
                    MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN);
4535
            ssl->options.cipherSuite0 = TLS13_BYTE;
4536
            ssl->options.cipherSuite  = WOLFSSL_DEF_PSK_CIPHER;
4537
        }
4538
        if (ssl->arrays->psk_keySz == 0 ||
4539
                (ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN &&
4540
            (int)ssl->arrays->psk_keySz != WC_NO_ERR_TRACE(USE_HW_PSK))) {
4541
            WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
4542
            return PSK_KEY_ERROR;
4543
        }
4544
4545
        ret = SetCipherSpecs(ssl);
4546
        if (ret != 0)
4547
            return ret;
4548
#else
4549
        /* PSK information loaded during setting of default TLS extensions. */
4550
#endif /* !WOLFSSL_PSK_ONE_ID */
4551
4552
        if (!clientHello && (psk->cipherSuite0 != suite[0] ||
4553
                             psk->cipherSuite  != suite[1])) {
4554
            WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
4555
            return PSK_KEY_ERROR;
4556
        }
4557
4558
        if (!clientHello) {
4559
#ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
4560
            if (ssl->options.certWithExternPsk) {
4561
                /* Certificate authentication is still required. */
4562
                ssl->options.peerAuthGood = 0;
4563
            }
4564
            else
4565
#endif
4566
            {
4567
                /* CLIENT: using PSK for peer authentication. */
4568
                ssl->options.peerAuthGood = 1;
4569
            }
4570
        }
4571
    }
4572
#endif
4573
4574
#ifdef HAVE_SUPPORTED_CURVES
4575
    if (!clientHello) {
4576
        TLSX* ext;
4577
        word32 modes;
4578
        KeyShareEntry* kse = NULL;
4579
4580
        /* Get the PSK key exchange modes the client wants to negotiate. */
4581
        ext = TLSX_Find(ssl->extensions, TLSX_PSK_KEY_EXCHANGE_MODES);
4582
        if (ext == NULL) {
4583
            WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
4584
            return PSK_KEY_ERROR;
4585
        }
4586
        modes = ext->val;
4587
4588
        ext = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
4589
        if (ext != NULL) {
4590
            kse = (KeyShareEntry*)ext->data;
4591
        }
4592
        /* Use (EC)DHE for forward-security if possible. */
4593
        if (((modes & (1 << PSK_DHE_KE)) != 0) && (!ssl->options.noPskDheKe) &&
4594
                                                (kse != NULL) && kse->derived) {
4595
            if ((kse->session != 0) && (kse->session != kse->group)) {
4596
                WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
4597
                return PSK_KEY_ERROR;
4598
            }
4599
        }
4600
        else if (ssl->options.onlyPskDheKe ||
4601
                 (ssl->options.failNoPSK && !psk->resumption)) {
4602
            /* A mandatory external PSK (failNoPSK) must be combined with
4603
             * (EC)DHE for forward secrecy, so reject a pure psk_ke
4604
             * negotiation. Session-ticket resumption is exempt. */
4605
            WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
4606
            return PSK_KEY_ERROR;
4607
        }
4608
        else if (ssl->options.noPskDheKe) {
4609
            ssl->arrays->preMasterSz = 0;
4610
        }
4611
    }
4612
    else
4613
#endif
4614
    if (ssl->options.noPskDheKe) {
4615
        ssl->arrays->preMasterSz = 0;
4616
    }
4617
4618
    /* Derive the early secret using the PSK. */
4619
    return DeriveEarlySecret(ssl);
4620
}
4621
4622
/* Derive and write the binders into the ClientHello in space left when
4623
 * writing the Pre-Shared Key extension.
4624
 *
4625
 * ssl     The SSL/TLS object.
4626
 * output  The buffer containing the ClientHello.
4627
 * idx     The index at the end of the completed ClientHello.
4628
 * returns 0 on success and otherwise failure.
4629
 */
4630
static int WritePSKBinders(WOLFSSL* ssl, byte* output, word32 idx)
4631
{
4632
    int           ret;
4633
    TLSX*         ext;
4634
    PreSharedKey* current;
4635
    byte          binderKey[WC_MAX_DIGEST_SIZE];
4636
    word16        len;
4637
4638
    WOLFSSL_ENTER("WritePSKBinders");
4639
4640
    if (idx > WOLFSSL_MAX_16BIT) {
4641
        return INPUT_SIZE_E;
4642
    }
4643
4644
    ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
4645
    if (ext == NULL)
4646
        return SANITY_MSG_E;
4647
4648
    /* Get the size of the binders to determine where to write binders. */
4649
    ret = TLSX_PreSharedKey_GetSizeBinders((PreSharedKey*)ext->data,
4650
                                                            client_hello, &len);
4651
    if (ret < 0)
4652
        return ret;
4653
    idx -= len;
4654
4655
    /* Hash truncated ClientHello - up to binders. */
4656
#ifdef WOLFSSL_DTLS13
4657
    if (ssl->options.dtls)
4658
        ret = Dtls13HashHandshake(ssl, output + Dtls13GetRlHeaderLength(ssl, 0),
4659
                                 (word16)idx - Dtls13GetRlHeaderLength(ssl, 0));
4660
    else
4661
#endif /* WOLFSSL_DTLS13 */
4662
        ret = HashOutput(ssl, output, (int)idx, 0);
4663
4664
    if (ret != 0)
4665
        return ret;
4666
4667
    current = (PreSharedKey*)ext->data;
4668
#ifdef WOLFSSL_CHECK_MEM_ZERO
4669
    if (current != NULL) {
4670
        wc_MemZero_Add("WritePSKBinders binderKey", binderKey,
4671
            sizeof(binderKey));
4672
    }
4673
#endif
4674
    /* Calculate the binder for each identity based on previous handshake data.
4675
     */
4676
    while (current != NULL) {
4677
        if ((ret = SetupPskKey(ssl, current, 1)) != 0)
4678
            break;
4679
4680
    #ifdef HAVE_SESSION_TICKET
4681
        if (current->resumption)
4682
            ret = DeriveBinderKeyResume(ssl, binderKey);
4683
    #endif
4684
    #ifndef NO_PSK
4685
        if (!current->resumption)
4686
            ret = DeriveBinderKey(ssl, binderKey);
4687
    #endif
4688
        if (ret != 0)
4689
            break;
4690
4691
        /* Derive the Finished message secret. */
4692
        ret = DeriveFinishedSecret(ssl, binderKey,
4693
                                   ssl->keys.client_write_MAC_secret,
4694
                                   0 /* neither end */);
4695
        if (ret != 0)
4696
            break;
4697
4698
        /* Build the HMAC of the handshake message data = binder. */
4699
        ret = BuildTls13HandshakeHmac(ssl, ssl->keys.client_write_MAC_secret,
4700
            current->binder, &current->binderLen);
4701
        if (ret != 0)
4702
            break;
4703
4704
        current = current->next;
4705
    }
4706
4707
    ForceZero(binderKey, sizeof(binderKey));
4708
#ifdef WOLFSSL_CHECK_MEM_ZERO
4709
    wc_MemZero_Check(binderKey, sizeof(binderKey));
4710
#endif
4711
    if (ret != 0)
4712
        return ret;
4713
4714
    /* Data entered into extension, now write to message. */
4715
    ret = TLSX_PreSharedKey_WriteBinders((PreSharedKey*)ext->data, output + idx,
4716
                                                            client_hello, &len);
4717
    if (ret < 0)
4718
        return ret;
4719
4720
    /* Hash binders to complete the hash of the ClientHello. */
4721
    ret = HashRaw(ssl, output + idx, len);
4722
    if (ret < 0)
4723
        return ret;
4724
4725
    #ifdef WOLFSSL_EARLY_DATA
4726
    if (ssl->earlyData != no_early_data) {
4727
        if ((ret = SetupPskKey(ssl, (PreSharedKey*)ext->data, 1)) != 0)
4728
            return ret;
4729
4730
        /* Derive early data encryption key. */
4731
        ret = DeriveTls13Keys(ssl, early_data_key, ENCRYPT_SIDE_ONLY, 1);
4732
        if (ret != 0)
4733
            return ret;
4734
        if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
4735
            return ret;
4736
4737
    }
4738
    #endif
4739
4740
    WOLFSSL_LEAVE("WritePSKBinders", ret);
4741
4742
    return ret;
4743
}
4744
#endif
4745
4746
static void GetTls13SessionId(WOLFSSL* ssl, byte* output, word32* idx)
4747
0
{
4748
0
    if (ssl->session->sessionIDSz > 0) {
4749
        /* Session resumption for old versions of protocol. */
4750
0
        if (ssl->session->sessionIDSz <= ID_LEN) {
4751
0
            if (output != NULL)
4752
0
                output[*idx] = ssl->session->sessionIDSz;
4753
0
            (*idx)++;
4754
0
            if (output != NULL) {
4755
0
                XMEMCPY(output + *idx, ssl->session->sessionID,
4756
0
                    ssl->session->sessionIDSz);
4757
0
            }
4758
0
            *idx += ssl->session->sessionIDSz;
4759
0
        }
4760
0
        else {
4761
            /* Invalid session ID length. Reset it. */
4762
0
            ssl->session->sessionIDSz = 0;
4763
0
            if (output != NULL)
4764
0
                output[*idx] = 0;
4765
0
            (*idx)++;
4766
0
        }
4767
0
    }
4768
0
    else {
4769
    #ifdef WOLFSSL_TLS13_MIDDLEBOX_COMPAT
4770
        if (ssl->options.tls13MiddleBoxCompat) {
4771
            if (output != NULL)
4772
                output[*idx] = ID_LEN;
4773
            (*idx)++;
4774
            if (output != NULL)
4775
                XMEMCPY(output + *idx, ssl->arrays->clientRandom, ID_LEN);
4776
            *idx += ID_LEN;
4777
        }
4778
        else
4779
    #endif /* WOLFSSL_TLS13_MIDDLEBOX_COMPAT */
4780
0
        {
4781
            /* TLS v1.3 does not use session id - 0 length. */
4782
0
            if (output != NULL)
4783
0
                output[*idx] = 0;
4784
0
            (*idx)++;
4785
0
        }
4786
0
    }
4787
0
}
4788
4789
/* handle generation of TLS 1.3 client_hello (1) */
4790
/* Send a ClientHello message to the server.
4791
 * Include the information required to start a handshake with servers using
4792
 * protocol versions less than TLS v1.3.
4793
 * Only a client will send this message.
4794
 *
4795
 * ssl  The SSL/TLS object.
4796
 * returns 0 on success and otherwise failure.
4797
 */
4798
4799
typedef struct Sch13Args {
4800
    byte*  output;
4801
    word32 idx;
4802
    int    sendSz;
4803
    word32 length;
4804
#if defined(HAVE_ECH)
4805
    int clientRandomOffset;
4806
    word32 preXLength;
4807
    word32 expandedInnerLen;
4808
    WOLFSSL_ECH* ech;
4809
#endif
4810
} Sch13Args;
4811
4812
#ifdef WOLFSSL_EARLY_DATA
4813
/* Check if early data can potentially be sent.
4814
 * Returns 1 if early data is possible, 0 otherwise.
4815
 */
4816
static int EarlyDataPossible(WOLFSSL* ssl)
4817
{
4818
    /* Need session resumption OR PSK callback configured */
4819
    if (ssl->options.resuming) {
4820
        return 1;
4821
    }
4822
#ifndef NO_PSK
4823
    if (ssl->options.client_psk_tls13_cb != NULL ||
4824
        ssl->options.client_psk_cb != NULL) {
4825
        return 1;
4826
    }
4827
#endif
4828
    return 0;
4829
}
4830
#endif /* WOLFSSL_EARLY_DATA */
4831
4832
int SendTls13ClientHello(WOLFSSL* ssl)
4833
0
{
4834
0
    int ret;
4835
#ifdef WOLFSSL_ASYNC_CRYPT
4836
    Sch13Args* args = NULL;
4837
    WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
4838
#else
4839
0
    Sch13Args  args[1];
4840
0
#endif
4841
0
    byte major, tls12minor;
4842
0
    const Suites* suites;
4843
4844
0
    WOLFSSL_START(WC_FUNC_CLIENT_HELLO_SEND);
4845
0
    WOLFSSL_ENTER("SendTls13ClientHello");
4846
4847
0
    if (ssl == NULL) {
4848
0
        return BAD_FUNC_ARG;
4849
0
    }
4850
4851
0
#if defined(HAVE_SECURE_RENEGOTIATION) || defined(HAVE_SERVER_RENEGOTIATION_INFO)
4852
    /* Re-establish renegotiation_info advertising for a reused object
4853
     * (wolfSSL_clear frees it) so a TLS 1.2 downgrade still enforces what the
4854
     * ClientHello advertised. Only when absent, to keep any existing state. */
4855
0
    if (ssl->secure_renegotiation == NULL) {
4856
0
        ret = SetupClientSecureRenegotiation(ssl);
4857
0
        if (ret != WOLFSSL_SUCCESS)
4858
0
            return ret;
4859
0
    }
4860
0
#endif
4861
4862
0
    ssl->options.buildingMsg = 1;
4863
0
    major = SSLv3_MAJOR;
4864
0
    tls12minor = TLSv1_2_MINOR;
4865
4866
#ifdef WOLFSSL_DTLS13
4867
    if (ssl->options.dtls) {
4868
        major = DTLS_MAJOR;
4869
        tls12minor = DTLSv1_2_MINOR;
4870
    }
4871
#endif /* WOLFSSL_DTLS */
4872
4873
0
    if (ssl->options.resuming &&
4874
0
            ssl->session->version.major != 0 &&
4875
0
            (ssl->session->version.major != ssl->version.major ||
4876
0
             ssl->session->version.minor != ssl->version.minor)) {
4877
0
    #ifndef WOLFSSL_NO_TLS12
4878
0
        if (ssl->session->version.major == ssl->version.major &&
4879
0
            ssl->session->version.minor < ssl->version.minor) {
4880
            /* Cannot resume with a different protocol version. */
4881
0
            ssl->options.resuming = 0;
4882
0
            ssl->version.major = ssl->session->version.major;
4883
0
            ssl->version.minor = ssl->session->version.minor;
4884
0
            return SendClientHello(ssl);
4885
0
        }
4886
0
        else
4887
0
    #endif
4888
0
        {
4889
0
            WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
4890
0
            return VERSION_ERROR;
4891
0
        }
4892
0
    }
4893
4894
0
    suites = WOLFSSL_SUITES(ssl);
4895
0
    if (suites == NULL) {
4896
0
        WOLFSSL_MSG("Bad suites pointer in SendTls13ClientHello");
4897
0
        return SUITES_ERROR;
4898
0
    }
4899
4900
#ifdef WOLFSSL_ASYNC_CRYPT
4901
    if (ssl->async == NULL) {
4902
        ssl->async = (struct WOLFSSL_ASYNC*)
4903
                XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
4904
                        DYNAMIC_TYPE_ASYNC);
4905
        if (ssl->async == NULL)
4906
            return MEMORY_E;
4907
        ssl->async->freeArgs = NULL;
4908
    }
4909
    args = (Sch13Args*)ssl->async->args;
4910
4911
    ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
4912
    if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) {
4913
        /* Check for error */
4914
        if (ret < 0)
4915
            return ret;
4916
    }
4917
    else
4918
#endif
4919
0
    {
4920
        /* Reset state */
4921
0
        ssl->options.asyncState = TLS_ASYNC_BEGIN;
4922
0
        XMEMSET(args, 0, sizeof(Sch13Args));
4923
0
    }
4924
4925
0
    switch (ssl->options.asyncState) {
4926
0
    case TLS_ASYNC_BEGIN:
4927
0
    {
4928
0
    word32 sessIdSz = 0;
4929
4930
0
    args->idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
4931
4932
#ifdef WOLFSSL_DTLS13
4933
    if (ssl->options.dtls)
4934
        args->idx += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
4935
#endif /* WOLFSSL_DTLS13 */
4936
4937
    /* Version | Random | Cipher Suites | Compression */
4938
0
    args->length = VERSION_SZ + RAN_LEN + suites->suiteSz +
4939
0
            SUITE_LEN + COMP_LEN + ENUM_LEN;
4940
#ifdef WOLFSSL_QUIC
4941
    if (WOLFSSL_IS_QUIC(ssl)) {
4942
        /* RFC 9001 ch. 8.4 sessionID in ClientHello MUST be 0 length */
4943
        ssl->session->sessionIDSz = 0;
4944
        ssl->options.tls13MiddleBoxCompat = 0;
4945
    }
4946
#endif
4947
#ifdef WOLFSSL_DTLS13
4948
    if (ssl->options.dtls) {
4949
        /* RFC 9147 Section 5: DTLS implementations do not use the
4950
         *                     TLS 1.3 "compatibility mode" */
4951
        ssl->options.tls13MiddleBoxCompat = 0;
4952
    }
4953
#endif
4954
0
    GetTls13SessionId(ssl, NULL, &sessIdSz);
4955
0
    args->length += (word16)sessIdSz;
4956
4957
#ifdef WOLFSSL_DTLS13
4958
    if (ssl->options.dtls) {
4959
        /* legacy_cookie_id len */
4960
        args->length += ENUM_LEN;
4961
4962
        /* server sent us an HelloVerifyRequest and we allow downgrade  */
4963
        if (ssl->arrays->cookieSz > 0 && ssl->options.downgrade)
4964
            args->length += ssl->arrays->cookieSz;
4965
    }
4966
#endif /* WOLFSSL_DTLS13 */
4967
4968
    /* Advance state and proceed */
4969
0
    ssl->options.asyncState = TLS_ASYNC_BUILD;
4970
0
    } /* case TLS_ASYNC_BEGIN */
4971
0
    FALL_THROUGH;
4972
4973
0
    case TLS_ASYNC_BUILD:
4974
0
    case TLS_ASYNC_DO:
4975
0
    {
4976
    /* Auto populate extensions supported unless user defined. */
4977
0
    if ((ret = TLSX_PopulateExtensions(ssl, 0)) != 0)
4978
0
        return ret;
4979
4980
    /* Advance state and proceed */
4981
0
    ssl->options.asyncState = TLS_ASYNC_FINALIZE;
4982
0
    } /* case TLS_ASYNC_BUILD */
4983
0
    FALL_THROUGH;
4984
4985
0
    case TLS_ASYNC_FINALIZE:
4986
0
    {
4987
#ifdef WOLFSSL_EARLY_DATA
4988
    if (!EarlyDataPossible(ssl))
4989
        ssl->earlyData = no_early_data;
4990
    if (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST_COMPLETE)
4991
        ssl->earlyData = no_early_data;
4992
    if (ssl->earlyData == no_early_data)
4993
        TLSX_Remove(&ssl->extensions, TLSX_EARLY_DATA, ssl->heap);
4994
    if (ssl->earlyData != no_early_data &&
4995
        (ret = TLSX_EarlyData_Use(ssl, 0, 0)) < 0) {
4996
        return ret;
4997
    }
4998
#endif
4999
#ifdef WOLFSSL_QUIC
5000
    if (WOLFSSL_IS_QUIC(ssl) && IsAtLeastTLSv1_3(ssl->version)) {
5001
        ret = wolfSSL_quic_add_transport_extensions(ssl, client_hello);
5002
        if (ret != 0)
5003
            return ret;
5004
    }
5005
#endif
5006
5007
    /* find length of outer and inner */
5008
#if defined(HAVE_ECH)
5009
    if (!ssl->options.disableECH) {
5010
        TLSX* echX = TLSX_Find(ssl->extensions, TLSX_ECH);
5011
        void* hostName = NULL;
5012
        word16 nameLen;
5013
        if (echX == NULL)
5014
            return WOLFSSL_FATAL_ERROR;
5015
5016
        args->ech = (WOLFSSL_ECH*)echX->data;
5017
        if (args->ech == NULL)
5018
            return WOLFSSL_FATAL_ERROR;
5019
5020
        /* if ECH was rejected by the HRR then the server MUST stop
5021
         * decrypting ECH, so send a GREASE ECH for the follow-up CH */
5022
        if (ssl->echConfigs != NULL && !ssl->options.echAccepted &&
5023
                ssl->options.serverState ==
5024
                    SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
5025
            args->ech->state = ECH_WRITE_GREASE;
5026
        }
5027
5028
        /* only prepare if we have a chance at acceptance (real ECH only) */
5029
        if (ssl->echConfigs != NULL &&
5030
                (ssl->options.echAccepted || args->ech->innerCount == 0)) {
5031
            word32 encodedLen;
5032
            byte downgrade;
5033
5034
            /* ensure that a version less than TLS1.3 is never offered  */
5035
            downgrade = ssl->options.downgrade;
5036
            ssl->options.downgrade = 0;
5037
5038
            /* set the type to inner */
5039
            args->ech->type = ECH_TYPE_INNER;
5040
            args->preXLength = args->length;
5041
5042
            /* get expanded inner size (used for transcript) */
5043
            ret = TLSX_GetRequestSize(ssl, client_hello, &args->length);
5044
            if (ret != 0) {
5045
                args->ech->type = ECH_TYPE_OUTER;
5046
                ssl->options.downgrade = downgrade;
5047
                return ret;
5048
            }
5049
5050
            /* args->expandedInnerLen carries the length for the hash */
5051
            args->expandedInnerLen = args->length;
5052
            if (args->expandedInnerLen > 0xFFFF) {
5053
                args->ech->type = ECH_TYPE_OUTER;
5054
                ssl->options.downgrade = downgrade;
5055
                return BUFFER_E;
5056
            }
5057
5058
            /* get encoded inner size */
5059
            args->ech->writeEncoded = 1;
5060
            encodedLen = args->preXLength;
5061
            ret = TLSX_GetRequestSize(ssl, client_hello, &encodedLen);
5062
            args->ech->writeEncoded = 0;
5063
            /* set the type to outer */
5064
            args->ech->type = ECH_TYPE_OUTER;
5065
            ssl->options.downgrade = downgrade;
5066
            if (ret != 0)
5067
                return ret;
5068
5069
            /* calculate padding (RFC 9849, section 6.1.3) */
5070
            nameLen = TLSX_SNI_GetRequest(ssl->extensions,
5071
                WOLFSSL_SNI_HOST_NAME, &hostName, 1);
5072
            if (nameLen == 0 && ssl->ctx != NULL)
5073
                nameLen = TLSX_SNI_GetRequest(ssl->ctx->extensions,
5074
                    WOLFSSL_SNI_HOST_NAME, &hostName, 1);
5075
5076
            if (nameLen != 0) {
5077
                if (nameLen > args->ech->echConfig->maxNameLen)
5078
                    args->ech->paddingLen = 0;
5079
                else
5080
                    args->ech->paddingLen =
5081
                        (word16)args->ech->echConfig->maxNameLen - nameLen;
5082
            }
5083
            else {
5084
                /* maxNameLen + length of the SNI extension */
5085
                args->ech->paddingLen = args->ech->echConfig->maxNameLen + 9;
5086
            }
5087
5088
            /* innerClientHelloLen and padding are based on the
5089
             * encoded (sealed) inner */
5090
            args->ech->paddingLen +=
5091
                ECH_PADDING_TO_32(encodedLen + args->ech->paddingLen);
5092
            args->ech->innerClientHelloLen = encodedLen +
5093
                args->ech->paddingLen + args->ech->hpke->Nt;
5094
5095
            if (args->ech->innerClientHelloLen > 0xFFFF)
5096
                return BUFFER_E;
5097
5098
            /* restore the length to pre-ClientHelloInner computations */
5099
            args->length = args->preXLength;
5100
        }
5101
    }
5102
#endif
5103
5104
0
    {
5105
#ifdef WOLFSSL_DTLS_CH_FRAG
5106
        word16 maxFrag = wolfssl_local_GetMaxPlaintextSize(ssl);
5107
        word16 lenWithoutExts = args->length;
5108
#endif
5109
5110
        /* Include length of TLS extensions. */
5111
0
        ret = TLSX_GetRequestSize(ssl, client_hello, &args->length);
5112
0
        if (ret != 0)
5113
0
            return ret;
5114
5115
        /* Total message size. */
5116
0
        args->sendSz =
5117
0
                (int)(args->length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ);
5118
5119
#ifdef WOLFSSL_DTLS13
5120
        if (ssl->options.dtls)
5121
            args->sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
5122
#endif /* WOLFSSL_DTLS13 */
5123
5124
#ifdef WOLFSSL_DTLS_CH_FRAG
5125
        /* Only empty the key share on the first CH; this avoids first CH
5126
         * fragmentation (wolfSSL refuses them) */
5127
        if (ssl->options.dtls && args->sendSz > maxFrag &&
5128
                ssl->options.serverState !=
5129
                    SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
5130
            /* Try again with an empty key share if we would be fragmenting */
5131
            ret = TLSX_KeyShare_Empty(ssl);
5132
            if (ret != 0)
5133
                return ret;
5134
            args->length = lenWithoutExts;
5135
            ret = TLSX_GetRequestSize(ssl, client_hello, &args->length);
5136
            if (ret != 0)
5137
                return ret;
5138
            args->sendSz = (int)(args->length +
5139
                    DTLS_HANDSHAKE_HEADER_SZ + DTLS_RECORD_HEADER_SZ);
5140
            if (args->sendSz > maxFrag) {
5141
                WOLFSSL_MSG("Can't fit first CH in one fragment.");
5142
                return BUFFER_ERROR;
5143
            }
5144
            WOLFSSL_MSG("Sending empty key share so we don't fragment CH1");
5145
        }
5146
#endif
5147
0
    }
5148
5149
    /* Check buffers are big enough and grow if needed. */
5150
0
    if ((ret = CheckAvailableSize(ssl, args->sendSz)) != 0)
5151
0
        return ret;
5152
5153
    /* Get position in output buffer to write new message to. */
5154
0
    args->output = GetOutputBuffer(ssl);
5155
5156
    /* Put the record and handshake headers on. */
5157
0
    AddTls13Headers(args->output, args->length, client_hello, ssl);
5158
5159
    /* Protocol version - negotiation now in extension: supported_versions. */
5160
0
    args->output[args->idx++] = major;
5161
0
    args->output[args->idx++] = tls12minor;
5162
5163
    /* Keep for downgrade. */
5164
0
    ssl->chVersion = ssl->version;
5165
5166
0
    if (ssl->arrays == NULL) {
5167
0
        return BAD_FUNC_ARG;
5168
0
    }
5169
    /* Client Random */
5170
0
    if (ssl->options.connectState == CONNECT_BEGIN) {
5171
0
        ret = wc_RNG_GenerateBlock(ssl->rng, args->output + args->idx, RAN_LEN);
5172
0
        if (ret != 0)
5173
0
            return ret;
5174
5175
        /* Store random for possible second ClientHello. */
5176
0
        XMEMCPY(ssl->arrays->clientRandom, args->output + args->idx, RAN_LEN);
5177
0
    }
5178
0
    else
5179
0
        XMEMCPY(args->output + args->idx, ssl->arrays->clientRandom, RAN_LEN);
5180
5181
#if defined(HAVE_ECH)
5182
    args->clientRandomOffset = (int)args->idx;
5183
#endif
5184
5185
0
    args->idx += RAN_LEN;
5186
5187
0
    GetTls13SessionId(ssl, args->output, &args->idx);
5188
5189
#ifdef WOLFSSL_DTLS13
5190
    if (ssl->options.dtls) {
5191
        args->output[args->idx++] = ssl->arrays->cookieSz;
5192
5193
        if (ssl->arrays->cookieSz > 0) {
5194
            /* We have a cookie saved, so the server sent us an
5195
             * HelloVerifyRequest, it means it is a v1.2 server */
5196
            if (!ssl->options.downgrade)
5197
                return VERSION_ERROR;
5198
            XMEMCPY(args->output + args->idx, ssl->arrays->cookie,
5199
                ssl->arrays->cookieSz);
5200
            args->idx += ssl->arrays->cookieSz;
5201
        }
5202
    }
5203
#endif /* WOLFSSL_DTLS13 */
5204
5205
    /* Cipher suites */
5206
0
    c16toa(suites->suiteSz, args->output + args->idx);
5207
0
    args->idx += OPAQUE16_LEN;
5208
0
    XMEMCPY(args->output + args->idx, &suites->suites,
5209
0
        suites->suiteSz);
5210
0
    args->idx += suites->suiteSz;
5211
#ifdef WOLFSSL_DEBUG_TLS
5212
    {
5213
        int ii;
5214
        WOLFSSL_MSG("Ciphers:");
5215
        for (ii = 0 ; ii < suites->suiteSz; ii += 2) {
5216
            WOLFSSL_MSG(GetCipherNameInternal(suites->suites[ii+0],
5217
                                              suites->suites[ii+1]));
5218
        }
5219
    }
5220
#endif
5221
5222
    /* Compression not supported in TLS v1.3. */
5223
0
    args->output[args->idx++] = COMP_LEN;
5224
0
    args->output[args->idx++] = NO_COMPRESSION;
5225
5226
#if defined(HAVE_ECH)
5227
    /* Build the expanded inner ClientHello */
5228
    if (ssl->echConfigs != NULL && !ssl->options.disableECH &&
5229
            (ssl->options.echAccepted || args->ech->innerCount == 0)) {
5230
        byte downgrade;
5231
5232
        /* calculate maximum buffer size needed */
5233
        word32 encodedBodyLen = args->ech->innerClientHelloLen -
5234
            args->ech->hpke->Nt;
5235
        word32 innerBufSize = args->expandedInnerLen;
5236
        if (encodedBodyLen > innerBufSize)
5237
            innerBufSize = encodedBodyLen;
5238
5239
        /* set the type to inner */
5240
        args->ech->type = ECH_TYPE_INNER;
5241
        /* innerClientHello may already exist from hrr, free if it does */
5242
        if (args->ech->innerClientHello != NULL) {
5243
            XFREE(args->ech->innerClientHello, ssl->heap,
5244
                DYNAMIC_TYPE_TMP_BUFFER);
5245
        }
5246
        /* allocate the inner */
5247
        args->ech->innerClientHello =
5248
            (byte*)XMALLOC(innerBufSize, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
5249
        if (args->ech->innerClientHello == NULL) {
5250
            args->ech->type = ECH_TYPE_OUTER;
5251
            return MEMORY_E;
5252
        }
5253
        /* copy everything before extensions into the innerClientHello
5254
         * ignore record and handshake headers */
5255
        XMEMCPY(args->ech->innerClientHello,
5256
            args->output + RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ,
5257
            args->preXLength);
5258
        /* copy the client random to inner - only for first CH, not after HRR */
5259
        if (!ssl->options.echAccepted) {
5260
            XMEMCPY(ssl->arrays->clientRandomInner, ssl->arrays->clientRandom,
5261
                RAN_LEN);
5262
        }
5263
        else {
5264
            /* After HRR, use the same inner random as CH1 */
5265
            XMEMCPY(args->ech->innerClientHello + VERSION_SZ,
5266
                ssl->arrays->clientRandomInner, RAN_LEN);
5267
        }
5268
        /* change the outer client random */
5269
        ret = wc_RNG_GenerateBlock(ssl->rng, args->output +
5270
            args->clientRandomOffset, RAN_LEN);
5271
        if (ret != 0) {
5272
            args->ech->type = ECH_TYPE_OUTER;
5273
            return ret;
5274
        }
5275
        /* copy the new client random */
5276
        XMEMCPY(ssl->arrays->clientRandom, args->output +
5277
            args->clientRandomOffset, RAN_LEN);
5278
5279
        /* ensure that a version less than TLS1.3 is never offered  */
5280
        downgrade = ssl->options.downgrade;
5281
        ssl->options.downgrade = 0;
5282
5283
        /* write the expanded extensions into the inner buffer */
5284
        args->length = 0;
5285
        ret = TLSX_WriteRequest(ssl,
5286
            args->ech->innerClientHello + args->preXLength, client_hello,
5287
            &args->length);
5288
        if (ret != 0) {
5289
            args->ech->type = ECH_TYPE_OUTER;
5290
            ssl->options.downgrade = downgrade;
5291
            return ret;
5292
        }
5293
5294
        /* hash expanded form */
5295
        args->ech->innerClientHelloLen = args->expandedInnerLen;
5296
        ret = EchHashHelloInner(ssl, args->ech);
5297
        args->ech->innerClientHelloLen = encodedBodyLen + args->ech->hpke->Nt;
5298
        if (ret != 0) {
5299
            args->ech->type = ECH_TYPE_OUTER;
5300
            ssl->options.downgrade = downgrade;
5301
            return ret;
5302
        }
5303
5304
        /* zero padding bytes sealed with the inner hello */
5305
        XMEMSET(args->ech->innerClientHello +
5306
            args->ech->innerClientHelloLen - args->ech->hpke->Nt -
5307
            args->ech->paddingLen, 0, args->ech->paddingLen);
5308
        /* Rewrite inner buffer with the encoded form for sealing */
5309
        args->ech->writeEncoded = 1;
5310
        args->length = 0;
5311
        ret = TLSX_WriteRequest(ssl,
5312
            args->ech->innerClientHello + args->preXLength, client_hello,
5313
            &args->length);
5314
        args->ech->writeEncoded = 0;
5315
        /* set the type to outer */
5316
        args->ech->type = ECH_TYPE_OUTER;
5317
        ssl->options.downgrade = downgrade;
5318
        if (ret != 0)
5319
            return ret;
5320
    }
5321
#endif
5322
5323
    /* Write out extensions for a request. */
5324
0
    args->length = 0;
5325
0
    ret = TLSX_WriteRequest(ssl, args->output + args->idx, client_hello,
5326
0
        &args->length);
5327
0
    if (ret != 0)
5328
0
        return ret;
5329
5330
0
    args->idx += args->length;
5331
5332
#if defined(HAVE_ECH)
5333
    /* HPKE-seal inner hello and place into outer ECH extension's payload */
5334
    if (ssl->echConfigs != NULL && !ssl->options.disableECH &&
5335
            (ssl->options.echAccepted || args->ech->innerCount == 0)) {
5336
#if defined(WOLFSSL_TEST_ECH)
5337
        if (ssl->echInnerHelloCb != NULL) {
5338
            ret = ssl->echInnerHelloCb(args->ech->innerClientHello,
5339
                args->ech->innerClientHelloLen - args->ech->hpke->Nt);
5340
            if (ret != 0)
5341
                return ret;
5342
        }
5343
#endif
5344
        ret = TLSX_FinalizeEch(ssl, args->ech,
5345
            args->output + RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ,
5346
            (word32)(args->sendSz - (RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ)));
5347
5348
        if (ret != 0)
5349
            return ret;
5350
    }
5351
    /* Mark CH1 done for any ECH extension (real or GREASE) */
5352
    if (args->ech != NULL)
5353
        args->ech->innerCount = 1;
5354
#endif
5355
5356
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
5357
    /* Resumption has a specific set of extensions and binder is calculated
5358
     * for each identity.
5359
     */
5360
    if (TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY)) {
5361
        ret = WritePSKBinders(ssl, args->output, args->idx);
5362
    }
5363
    else
5364
#endif
5365
0
    {
5366
#ifdef WOLFSSL_DTLS13
5367
        if (ssl->options.dtls)
5368
            ret = Dtls13HashHandshake(ssl,
5369
                args->output + Dtls13GetRlHeaderLength(ssl, 0),
5370
                (word16)args->idx - Dtls13GetRlHeaderLength(ssl, 0));
5371
        else
5372
#endif /* WOLFSSL_DTLS13 */
5373
0
        {
5374
            /* compute the outer hash */
5375
0
            ret = HashOutput(ssl, args->output, (int)args->idx, 0);
5376
0
        }
5377
0
    }
5378
0
    if (ret != 0)
5379
0
        return ret;
5380
5381
0
    ssl->options.clientState = CLIENT_HELLO_COMPLETE;
5382
5383
#if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
5384
    if (ssl->hsInfoOn) AddPacketName(ssl, "ClientHello");
5385
    if (ssl->toInfoOn) {
5386
        ret = AddPacketInfo(ssl, "ClientHello", handshake, args->output,
5387
                      args->sendSz, WRITE_PROTO, 0, ssl->heap);
5388
        if (ret != 0)
5389
            return ret;
5390
    }
5391
#endif
5392
5393
0
    ssl->options.buildingMsg = 0;
5394
#ifdef WOLFSSL_DTLS13
5395
    if (ssl->options.dtls) {
5396
        ret = Dtls13HandshakeSend(ssl, args->output, (word16)args->sendSz,
5397
                                  (word16)args->idx, client_hello, 0);
5398
        break;
5399
    }
5400
#endif /* WOLFSSL_DTLS13 */
5401
5402
0
    ssl->buffers.outputBuffer.length += (word32)args->sendSz;
5403
5404
    /* Advance state and proceed */
5405
0
    ssl->options.asyncState = TLS_ASYNC_END;
5406
0
    }
5407
    /* case TLS_ASYNC_BUILD */
5408
0
    FALL_THROUGH;
5409
5410
0
    case TLS_ASYNC_END:
5411
0
    {
5412
#ifdef WOLFSSL_EARLY_DATA_GROUP
5413
    /* QUIC needs to forward records at their encryption level
5414
     * and is therefore unable to group here */
5415
    if (ssl->earlyData == no_early_data || WOLFSSL_IS_QUIC(ssl))
5416
#endif
5417
0
        ret = SendBuffered(ssl);
5418
5419
0
    break;
5420
0
    }
5421
0
    default:
5422
0
        ret = INPUT_CASE_ERROR;
5423
0
    } /* switch (ssl->options.asyncState) */
5424
5425
#ifdef WOLFSSL_ASYNC_CRYPT
5426
    if (ret == 0)
5427
        FreeAsyncCtx(ssl, 0);
5428
#endif
5429
5430
0
    WOLFSSL_LEAVE("SendTls13ClientHello", ret);
5431
0
    WOLFSSL_END(WC_FUNC_CLIENT_HELLO_SEND);
5432
5433
0
    return ret;
5434
0
}
5435
5436
#if defined(WOLFSSL_DTLS13) && !defined(NO_WOLFSSL_CLIENT)
5437
static int Dtls13ClientDoDowngrade(WOLFSSL* ssl)
5438
{
5439
    int ret;
5440
    if (ssl->dtls13ClientHello == NULL)
5441
        return BAD_STATE_E;
5442
5443
    /* v1.3 and v1.2 hash messages to compute the transcript hash. When we are
5444
     * using DTLSv1.3 we hash the first clientHello following v1.3 but the
5445
     * server can negotiate a lower version. So we need to re-hash the
5446
     * clientHello to adhere to DTLS <= v1.2 rules. */
5447
    ret = InitHandshakeHashes(ssl);
5448
    if (ret != 0)
5449
        return ret;
5450
    ret = HashRaw(ssl, ssl->dtls13ClientHello, ssl->dtls13ClientHelloSz);
5451
    XFREE(ssl->dtls13ClientHello, ssl->heap, DYNAMIC_TYPE_DTLS_MSG);
5452
    ssl->dtls13ClientHello = NULL;
5453
    ssl->dtls13ClientHelloSz = 0;
5454
    ssl->keys.dtls_sequence_number_hi =
5455
        (word16)w64GetHigh32(ssl->dtls13EncryptEpoch->nextSeqNumber);
5456
    ssl->keys.dtls_sequence_number_lo =
5457
        w64GetLow32(ssl->dtls13EncryptEpoch->nextSeqNumber);
5458
    return ret;
5459
}
5460
#endif /* WOLFSSL_DTLS13 && !NO_WOLFSSL_CLIENT*/
5461
5462
#if defined(HAVE_ECH)
5463
/* Calculate ECH acceptance and verify the server accepted ECH.
5464
 *
5465
 * ssl          SSL/TLS object.
5466
 * label        Ascii string describing ECH acceptance type.
5467
 * labelSz      Length of label excluding NULL character.
5468
 * input        The buffer to calculate confirmation off of.
5469
 * acceptOffset Where the 8 ECH confirmation bytes start.
5470
 * helloSz      Size of hello message.
5471
 * returns 0 on success and otherwise failure.
5472
 */
5473
static int EchCheckAcceptance(WOLFSSL* ssl, byte* label, word16 labelSz,
5474
    const byte* input, int acceptOffset, int helloSz, byte msgType)
5475
{
5476
    int ret = 0;
5477
    int headerSz;
5478
    HS_Hashes* tmpHashes;
5479
    byte acceptConfirmation[ECH_ACCEPT_CONFIRMATION_SZ];
5480
5481
    XMEMSET(acceptConfirmation, 0, sizeof(acceptConfirmation));
5482
5483
#ifdef WOLFSSL_DTLS13
5484
    headerSz = ssl->options.dtls ? DTLS13_HANDSHAKE_HEADER_SZ :
5485
                                   HANDSHAKE_HEADER_SZ;
5486
#else
5487
    headerSz = HANDSHAKE_HEADER_SZ;
5488
#endif
5489
5490
    ret = EchCalcAcceptance(ssl, label, labelSz, input, acceptOffset, helloSz,
5491
            msgType == hello_retry_request, acceptConfirmation);
5492
5493
    if (ret == 0) {
5494
        tmpHashes = ssl->hsHashes;
5495
        ssl->hsHashes = ssl->hsHashesEch;
5496
5497
        /* last 8 bytes must match the expand output */
5498
        ret = ConstantCompare(acceptConfirmation, input + acceptOffset,
5499
            ECH_ACCEPT_CONFIRMATION_SZ);
5500
5501
        if (ret == 0) {
5502
            WOLFSSL_MSG("ECH accepted");
5503
            ssl->options.echAccepted = 1;
5504
5505
            /* after HRR, hsHashesEch must contain:
5506
             * message_hash(ClientHelloInner1) || HRR (actual, not zeros) */
5507
            if (msgType == hello_retry_request) {
5508
                ret = HashRaw(ssl, input, helloSz + headerSz);
5509
            }
5510
            /* normal TLS code will calculate transcript of ServerHello */
5511
            else {
5512
                ssl->hsHashes = tmpHashes;
5513
                FreeHandshakeHashes(ssl);
5514
                tmpHashes = ssl->hsHashesEch;
5515
                ssl->hsHashesEch = NULL;
5516
            }
5517
        }
5518
        else {
5519
            if (msgType != hello_retry_request && ssl->options.echAccepted) {
5520
                /* the SH has rejected ECH after the HRR has accepted it
5521
                 * RFC 9849, section 6.1.5 */
5522
                WOLFSSL_MSG("ECH rejected, but it was previously accepted...");
5523
                ret = INVALID_PARAMETER;
5524
            }
5525
            else {
5526
                WOLFSSL_MSG("ECH rejected");
5527
                ret = 0;
5528
            }
5529
            ssl->options.echAccepted = 0;
5530
5531
            /* ECH rejected, continue with outer transcript */
5532
            FreeHandshakeHashes(ssl);
5533
            ssl->hsHashesEch = NULL;
5534
        }
5535
5536
        ssl->hsHashes = tmpHashes;
5537
    }
5538
5539
    /* Skip only when the HRR signals ECH acceptance
5540
     * -> CH2 still needs ech->extensions for inner/outer extension swap
5541
     *    during write */
5542
    if (ret == 0 &&
5543
            (msgType != hello_retry_request || !ssl->options.echAccepted))
5544
        ret = TLSX_EchReplaceExtensions(ssl, ssl->options.echAccepted);
5545
5546
    return ret;
5547
}
5548
#endif /* HAVE_ECH */
5549
5550
/* handle processing of TLS 1.3 server_hello (2) and hello_retry_request (6) */
5551
/* Handle the ServerHello message from the server.
5552
 * Only a client will receive this message.
5553
 *
5554
 * ssl       The SSL/TLS object.
5555
 * input     The message buffer.
5556
 * inOutIdx  On entry, the index into the message buffer of ServerHello.
5557
 *           On exit, the index of byte after the ServerHello message.
5558
 * helloSz   The length of the current handshake message.
5559
 * returns 0 on success and otherwise failure.
5560
 */
5561
5562
typedef struct Dsh13Args {
5563
    ProtocolVersion pv;
5564
    word32          idx;
5565
    word32          begin;
5566
    const byte*     sessId;
5567
    word16          totalExtSz;
5568
    byte            sessIdSz;
5569
    byte            extMsgType;
5570
#if defined(HAVE_ECH)
5571
    TLSX* echX;
5572
    byte* acceptLabel;
5573
    word32 acceptOffset;
5574
    word16 acceptLabelSz;
5575
#endif
5576
} Dsh13Args;
5577
5578
/* sessIdSz below bounds both the copy into arrays->sessionID and the comparison
5579
 * against arrays->clientRandom, so one check only covers both while these
5580
 * match. */
5581
wc_static_assert(ID_LEN == RAN_LEN);
5582
5583
int DoTls13ServerHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
5584
                       word32 helloSz, byte* extMsgType)
5585
0
{
5586
0
    int ret;
5587
0
    byte suite[2];
5588
0
    byte tls12minor;
5589
#ifdef WOLFSSL_ASYNC_CRYPT
5590
    Dsh13Args* args = NULL;
5591
#else
5592
0
    Dsh13Args  args[1];
5593
0
#endif
5594
#ifdef WOLFSSL_ASYNC_CRYPT
5595
    WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
5596
#endif
5597
5598
0
    WOLFSSL_START(WC_FUNC_SERVER_HELLO_DO);
5599
0
    WOLFSSL_ENTER("DoTls13ServerHello");
5600
5601
0
    if (ssl == NULL || ssl->arrays == NULL)
5602
0
        return BAD_FUNC_ARG;
5603
5604
0
    tls12minor = TLSv1_2_MINOR;
5605
5606
#ifdef WOLFSSL_DTLS13
5607
    if (ssl->options.dtls)
5608
        tls12minor = DTLSv1_2_MINOR;
5609
#endif /*  WOLFSSL_DTLS13 */
5610
5611
#ifdef WOLFSSL_ASYNC_CRYPT
5612
    if (ssl->async == NULL) {
5613
        ssl->async = (struct WOLFSSL_ASYNC*)
5614
                XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
5615
                        DYNAMIC_TYPE_ASYNC);
5616
        if (ssl->async == NULL)
5617
            return MEMORY_E;
5618
        ssl->async->freeArgs = NULL;
5619
    }
5620
    args = (Dsh13Args*)ssl->async->args;
5621
5622
    ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
5623
    if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) {
5624
        /* Check for error */
5625
        if (ret < 0) {
5626
            if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
5627
                /* Mark message as not received so it can process again */
5628
                ssl->msgsReceived.got_server_hello = 0;
5629
            }
5630
            return ret;
5631
        }
5632
    }
5633
    else
5634
#endif
5635
0
    {
5636
        /* Reset state */
5637
0
        ssl->options.asyncState = TLS_ASYNC_BEGIN;
5638
0
        XMEMSET(args, 0, sizeof(Dsh13Args));
5639
0
    }
5640
5641
0
    switch (ssl->options.asyncState) {
5642
0
    case TLS_ASYNC_BEGIN:
5643
0
    {
5644
0
    byte b;
5645
#if defined(WOLFSSL_DTLS13) && defined(WOLFSSL_DTLS_CID)
5646
    ssl->options.haveSupportedVersions = 0;
5647
#endif
5648
#ifdef WOLFSSL_CALLBACKS
5649
    if (ssl->hsInfoOn) AddPacketName(ssl, "ServerHello");
5650
    if (ssl->toInfoOn) AddLateName("ServerHello", &ssl->timeoutInfo);
5651
#endif
5652
5653
    /* Protocol version length check. */
5654
0
    if (helloSz < OPAQUE16_LEN)
5655
0
        return BUFFER_ERROR;
5656
5657
0
    args->idx = *inOutIdx;
5658
0
    args->begin = args->idx;
5659
5660
    /* Protocol version */
5661
0
    XMEMCPY(&args->pv, input + args->idx, OPAQUE16_LEN);
5662
0
    args->idx += OPAQUE16_LEN;
5663
5664
#ifdef WOLFSSL_DTLS
5665
    if (ssl->options.dtls &&
5666
        (args->pv.major != DTLS_MAJOR || args->pv.minor == DTLS_BOGUS_MINOR))
5667
        return VERSION_ERROR;
5668
#endif /* WOLFSSL_DTLS */
5669
5670
0
#ifndef WOLFSSL_NO_TLS12
5671
0
    {
5672
0
        byte wantDowngrade;
5673
5674
0
        wantDowngrade = args->pv.major == ssl->version.major &&
5675
0
            args->pv.minor < TLSv1_2_MINOR;
5676
5677
#ifdef WOLFSSL_DTLS13
5678
        if (ssl->options.dtls)
5679
            wantDowngrade = args->pv.major == ssl->version.major &&
5680
                args->pv.minor > DTLSv1_2_MINOR;
5681
#endif /* WOLFSSL_DTLS13 */
5682
5683
0
        if (wantDowngrade && ssl->options.downgrade) {
5684
            /* Force client hello version 1.2 to work for static RSA. */
5685
0
            ssl->chVersion.minor = TLSv1_2_MINOR;
5686
0
            ssl->version.minor = TLSv1_2_MINOR;
5687
0
            ssl->options.tls1_3 = 0;
5688
5689
#ifdef WOLFSSL_DTLS13
5690
            if (ssl->options.dtls) {
5691
                ssl->chVersion.minor = DTLSv1_2_MINOR;
5692
                ssl->version.minor = DTLSv1_2_MINOR;
5693
                ret = Dtls13ClientDoDowngrade(ssl);
5694
                if (ret != 0)
5695
                    return ret;
5696
            }
5697
#endif /* WOLFSSL_DTLS13 */
5698
5699
0
            return DoServerHello(ssl, input, inOutIdx, helloSz);
5700
0
        }
5701
0
    }
5702
0
#endif
5703
5704
0
    if (args->pv.major != ssl->version.major ||
5705
0
        args->pv.minor != tls12minor) {
5706
0
        WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
5707
0
        return VERSION_ERROR;
5708
0
    }
5709
5710
    /* Random and session id length check */
5711
0
    if ((args->idx - args->begin) + RAN_LEN + ENUM_LEN > helloSz)
5712
0
        return BUFFER_ERROR;
5713
5714
    /* Check if hello retry request */
5715
0
    if (XMEMCMP(input + args->idx, helloRetryRequestRandom, RAN_LEN) == 0) {
5716
0
        WOLFSSL_MSG("HelloRetryRequest format");
5717
0
        *extMsgType = hello_retry_request;
5718
5719
0
        if (ssl->msgsReceived.got_hello_verify_request) {
5720
0
            WOLFSSL_MSG("Received HelloRetryRequest after a "
5721
0
                        "HelloVerifyRequest");
5722
0
            WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
5723
0
            return VERSION_ERROR;
5724
0
        }
5725
5726
        /* A HelloRetryRequest comes in as an ServerHello for MiddleBox compat.
5727
         * Found message to be a HelloRetryRequest.
5728
         * Don't allow more than one HelloRetryRequest or ServerHello.
5729
         */
5730
0
        if (ssl->msgsReceived.got_hello_retry_request) {
5731
0
            WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
5732
0
            return DUPLICATE_MSG_E;
5733
0
        }
5734
0
    }
5735
0
    args->extMsgType = *extMsgType;
5736
5737
    /* Server random - keep for debugging. */
5738
0
    XMEMCPY(ssl->arrays->serverRandom, input + args->idx, RAN_LEN);
5739
#if defined(HAVE_ECH)
5740
    /* last 8 bytes of server random */
5741
    args->acceptOffset = args->idx + RAN_LEN - ECH_ACCEPT_CONFIRMATION_SZ;
5742
#endif
5743
0
    args->idx += RAN_LEN;
5744
5745
    /* Session id */
5746
0
    args->sessIdSz = input[args->idx++];
5747
0
    if (args->sessIdSz > ID_LEN ||
5748
0
        ((args->idx - args->begin) + args->sessIdSz > helloSz))
5749
0
        return BUFFER_ERROR;
5750
0
    args->sessId = input + args->idx;
5751
0
    args->idx += args->sessIdSz;
5752
5753
0
    ssl->options.haveSessionId = 1;
5754
5755
    /* Ciphersuite and compression check */
5756
0
    if ((args->idx - args->begin) + OPAQUE16_LEN + OPAQUE8_LEN > helloSz)
5757
0
        return BUFFER_ERROR;
5758
5759
    /* Set the cipher suite from the message. */
5760
0
    ssl->options.cipherSuite0 = input[args->idx++];
5761
0
    ssl->options.cipherSuite  = input[args->idx++];
5762
0
    if (*extMsgType == hello_retry_request) {
5763
0
        ssl->options.hrrCipherSuite0 = ssl->options.cipherSuite0;
5764
0
        ssl->options.hrrCipherSuite  = ssl->options.cipherSuite;
5765
0
    }
5766
0
    else if (ssl->msgsReceived.got_hello_retry_request &&
5767
0
             (ssl->options.hrrCipherSuite0 != ssl->options.cipherSuite0 ||
5768
0
                     ssl->options.hrrCipherSuite != ssl->options.cipherSuite)) {
5769
0
        WOLFSSL_MSG("Received ServerHello with different cipher suite than "
5770
0
                    "HelloRetryRequest");
5771
0
        WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
5772
0
        return INVALID_PARAMETER;
5773
0
    }
5774
#ifdef WOLFSSL_DEBUG_TLS
5775
    WOLFSSL_MSG("Chosen cipher suite:");
5776
    WOLFSSL_MSG(GetCipherNameInternal(ssl->options.cipherSuite0,
5777
                                      ssl->options.cipherSuite));
5778
#endif
5779
5780
    /* Compression */
5781
0
    b = input[args->idx++];
5782
0
    if (b != 0) {
5783
0
        WOLFSSL_MSG("Must be no compression types in list");
5784
0
        WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
5785
0
        return INVALID_PARAMETER;
5786
0
    }
5787
5788
0
    if ((args->idx - args->begin) + OPAQUE16_LEN > helloSz) {
5789
        /* Fewer than OPAQUE16_LEN bytes remain after the compression method, so
5790
         * there is no complete extensions length field. */
5791
0
        if ((args->idx - args->begin) < helloSz) {
5792
            /* A partial extensions length field is genuinely malformed: report
5793
             * it as a decode error regardless of message type. */
5794
0
            WOLFSSL_MSG("Truncated extensions length in ServerHello");
5795
0
            return BUFFER_ERROR;
5796
0
        }
5797
5798
        /* No extensions field at all. */
5799
0
        if (args->extMsgType == hello_retry_request) {
5800
            /* The sentinel Random (RFC 8446 4.1.3) identifies this as a TLS 1.3
5801
             * HelloRetryRequest, which MUST carry supported_versions
5802
             * (4.2.1/9.2). Its complete absence is a missing mandatory
5803
             * extension, so - consistently with the extensions-present case
5804
             * handled later - report it as missing_extension (via
5805
             * INCOMPLETE_DATA), regardless of whether a downgrade would
5806
             * otherwise be allowed. Reject here before DoServerHello would
5807
             * reinterpret the sentinel as a plain TLS 1.2 ServerHello.Random. */
5808
0
            WOLFSSL_MSG("HelloRetryRequest with no supported_versions");
5809
0
            WOLFSSL_ERROR_VERBOSE(INCOMPLETE_DATA);
5810
0
            return INCOMPLETE_DATA;
5811
0
        }
5812
5813
0
        if (!ssl->options.downgrade) {
5814
            /* A plain ServerHello with no extensions is not offering TLS 1.3
5815
             * (no supported_versions extension - see RFC 8446 4.2.1) but TLS
5816
             * 1.2 or below. This is a well-formed message, so a TLS 1.3-only
5817
             * client (downgrade disabled) must reject it as a version mismatch,
5818
             * not as a malformed message. Returning VERSION_ERROR makes the
5819
             * caller send a protocol_version alert (RFC 8446 6.2) rather than
5820
             * decode_error. */
5821
0
            WOLFSSL_MSG("Server offered TLS 1.2 (no supported_versions ext) "
5822
0
                        "but downgrade not allowed");
5823
0
            WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
5824
0
            return VERSION_ERROR;
5825
0
        }
5826
0
#ifndef WOLFSSL_NO_TLS12
5827
        /* Force client hello version 1.2 to work for static RSA. */
5828
0
        ssl->chVersion.minor = TLSv1_2_MINOR;
5829
0
        ssl->version.minor = TLSv1_2_MINOR;
5830
5831
#ifdef WOLFSSL_DTLS13
5832
        if (ssl->options.dtls) {
5833
            ssl->chVersion.minor = DTLSv1_2_MINOR;
5834
            ssl->version.minor = DTLSv1_2_MINOR;
5835
            ssl->options.tls1_3 = 0;
5836
            ret = Dtls13ClientDoDowngrade(ssl);
5837
            if (ret != 0)
5838
                return ret;
5839
        }
5840
#endif /* WOLFSSL_DTLS13 */
5841
5842
0
#endif
5843
0
        ssl->options.haveEMS = 0;
5844
0
        if (args->pv.minor < ssl->options.minDowngrade) {
5845
0
            WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
5846
0
            return VERSION_ERROR;
5847
0
        }
5848
0
#ifndef WOLFSSL_NO_TLS12
5849
0
        ssl->options.tls1_3 = 0;
5850
0
        return DoServerHello(ssl, input, inOutIdx, helloSz);
5851
#else
5852
        WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
5853
        return VERSION_ERROR;
5854
#endif
5855
0
    }
5856
5857
0
    if ((args->idx - args->begin) < helloSz) {
5858
0
        int foundVersion;
5859
5860
        /* Get extension length and length check. */
5861
0
        if ((args->idx - args->begin) + OPAQUE16_LEN > helloSz)
5862
0
            return BUFFER_ERROR;
5863
0
        ato16(&input[args->idx], &args->totalExtSz);
5864
0
        args->idx += OPAQUE16_LEN;
5865
0
        if ((args->idx - args->begin) + args->totalExtSz > helloSz)
5866
0
            return BUFFER_ERROR;
5867
5868
        /* Need to negotiate version first. */
5869
0
        if ((ret = TLSX_ParseVersion(ssl, input + args->idx,
5870
0
            args->totalExtSz, *extMsgType, &foundVersion))) {
5871
0
            return ret;
5872
0
        }
5873
0
        if (!foundVersion) {
5874
            /* RFC 8446 4.1.4: "The server's extensions MUST contain
5875
             * 'supported_versions'." (also 9.2: "supported_versions" is
5876
             * REQUIRED for all ... HelloRetryRequest messages). The HRR random
5877
             * unambiguously identifies a TLS 1.3 server, so its absence is not
5878
             * a downgrade attempt but a missing mandatory extension, which per
5879
             * the "missing_extension" alert definition must be reported as
5880
             * such. Return INCOMPLETE_DATA (which maps to a missing_extension
5881
             * alert) and let the caller emit the alert via
5882
             * TranslateErrorToAlert(). */
5883
0
            if (*extMsgType == hello_retry_request) {
5884
0
                WOLFSSL_MSG("HelloRetryRequest missing supported_versions "
5885
0
                            "extension");
5886
0
                WOLFSSL_ERROR_VERBOSE(INCOMPLETE_DATA);
5887
0
                return INCOMPLETE_DATA;
5888
0
            }
5889
0
            if (!ssl->options.downgrade) {
5890
0
                WOLFSSL_MSG("Server trying to downgrade to version less than "
5891
0
                            "TLS v1.3");
5892
0
                WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
5893
0
                return VERSION_ERROR;
5894
0
            }
5895
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
5896
    defined(WOLFSSL_WPAS_SMALL)
5897
            /* Check if client has disabled TLS 1.2 */
5898
            if (args->pv.minor == TLSv1_2_MINOR &&
5899
                (ssl->options.mask & WOLFSSL_OP_NO_TLSv1_2)
5900
                == WOLFSSL_OP_NO_TLSv1_2)
5901
            {
5902
                WOLFSSL_MSG("\tOption set to not allow TLSv1.2");
5903
                WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
5904
                return VERSION_ERROR;
5905
            }
5906
#endif
5907
5908
0
            if (!ssl->options.dtls &&
5909
0
                args->pv.minor < ssl->options.minDowngrade) {
5910
0
                WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
5911
0
                return VERSION_ERROR;
5912
0
            }
5913
5914
0
            if (ssl->options.dtls &&
5915
0
                args->pv.minor > ssl->options.minDowngrade) {
5916
0
                WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
5917
0
                return VERSION_ERROR;
5918
0
            }
5919
5920
0
            ssl->version.minor = args->pv.minor;
5921
0
            ssl->options.tls1_3 = 0;
5922
5923
#ifdef WOLFSSL_DTLS13
5924
            if (ssl->options.dtls) {
5925
                ret = Dtls13ClientDoDowngrade(ssl);
5926
                if (ret != 0)
5927
                    return ret;
5928
            }
5929
#endif /* WOLFSSL_DTLS13 */
5930
0
        }
5931
0
    }
5932
5933
#ifdef WOLFSSL_DTLS13
5934
    /* we are sure that version is >= v1.3 now, we can get rid of buffered
5935
     * ClientHello that was buffered to re-compute the hash in case of
5936
     * downgrade */
5937
    if (ssl->options.dtls && ssl->dtls13ClientHello != NULL) {
5938
        XFREE(ssl->dtls13ClientHello, ssl->heap, DYNAMIC_TYPE_DTLS_MSG);
5939
        ssl->dtls13ClientHello = NULL;
5940
        ssl->dtls13ClientHelloSz = 0;
5941
    }
5942
#endif /* WOLFSSL_DTLS13 */
5943
5944
    /* Advance state and proceed */
5945
0
    ssl->options.asyncState = TLS_ASYNC_BUILD;
5946
0
    } /* case TLS_ASYNC_BEGIN */
5947
0
    FALL_THROUGH;
5948
5949
0
    case TLS_ASYNC_BUILD:
5950
0
    case TLS_ASYNC_DO:
5951
0
    {
5952
    /* restore message type */
5953
0
    *extMsgType = args->extMsgType;
5954
5955
    /* Parse and handle extensions, unless lower than TLS1.3. In that case,
5956
     * extensions will be parsed in DoServerHello. */
5957
0
    if (args->totalExtSz > 0 && IsAtLeastTLSv1_3(ssl->version)) {
5958
0
        ret = TLSX_Parse(ssl, input + args->idx, args->totalExtSz,
5959
0
            *extMsgType, NULL);
5960
0
        if (ret != 0) {
5961
        #ifdef WOLFSSL_ASYNC_CRYPT
5962
            /* Handle async operation */
5963
            if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
5964
                /* Mark message as not received so it can process again */
5965
                ssl->msgsReceived.got_server_hello = 0;
5966
            }
5967
        #endif
5968
0
            return ret;
5969
0
        }
5970
5971
0
        if (*extMsgType == hello_retry_request) {
5972
            /* Update counts to reflect change of message type. */
5973
0
            ssl->msgsReceived.got_hello_retry_request = 1;
5974
0
            ssl->msgsReceived.got_server_hello = 0;
5975
0
        }
5976
0
    }
5977
5978
0
    if (args->totalExtSz > 0) {
5979
0
        args->idx += args->totalExtSz;
5980
0
    }
5981
5982
#ifdef WOLFSSL_DTLS_CID
5983
    if (ssl->options.useDtlsCID && *extMsgType == server_hello)
5984
        DtlsCIDOnExtensionsParsed(ssl);
5985
#endif /* WOLFSSL_DTLS_CID */
5986
5987
0
    if (IsAtLeastTLSv1_3(ssl->version)) {
5988
0
        *inOutIdx = args->idx;
5989
0
    }
5990
5991
0
    ssl->options.serverState = SERVER_HELLO_COMPLETE;
5992
5993
#ifdef HAVE_SECRET_CALLBACK
5994
    if (ssl->sessionSecretCb != NULL
5995
#ifdef HAVE_SESSION_TICKET
5996
            && ssl->session->ticketLen > 0
5997
#endif
5998
            ) {
5999
        int secretSz = SECRET_LEN;
6000
        ret = ssl->sessionSecretCb(ssl, ssl->session->masterSecret,
6001
                                   &secretSz, ssl->sessionSecretCtx);
6002
        if (ret != 0 || secretSz != SECRET_LEN) {
6003
            WOLFSSL_ERROR_VERBOSE(SESSION_SECRET_CB_E);
6004
            return SESSION_SECRET_CB_E;
6005
        }
6006
    }
6007
#endif /* HAVE_SECRET_CALLBACK */
6008
6009
    /* Version only negotiated in extensions for TLS v1.3.
6010
     * Only now do we know how to deal with session id.
6011
     */
6012
0
    if (!IsAtLeastTLSv1_3(ssl->version)) {
6013
0
#ifndef WOLFSSL_NO_TLS12
6014
0
        ssl->arrays->sessionIDSz = args->sessIdSz;
6015
6016
0
        if (ssl->arrays->sessionIDSz > ID_LEN) {
6017
0
            WOLFSSL_MSG("Invalid session ID size");
6018
0
            ssl->arrays->sessionIDSz = 0;
6019
0
            return BUFFER_ERROR;
6020
0
        }
6021
0
        else if (ssl->arrays->sessionIDSz) {
6022
0
            XMEMCPY(ssl->arrays->sessionID, args->sessId,
6023
0
                ssl->arrays->sessionIDSz);
6024
0
            ssl->options.haveSessionId = 1;
6025
0
        }
6026
6027
        /* Force client hello version 1.2 to work for static RSA. */
6028
0
        if (ssl->options.dtls)
6029
0
            ssl->chVersion.minor = DTLSv1_2_MINOR;
6030
0
        else
6031
0
            ssl->chVersion.minor = TLSv1_2_MINOR;
6032
        /* Complete TLS v1.2 processing of ServerHello. */
6033
0
        ret = DoServerHello(ssl, input, inOutIdx, helloSz);
6034
#else
6035
        WOLFSSL_MSG("Client using higher version, fatal error");
6036
        WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
6037
        ret = VERSION_ERROR;
6038
#endif
6039
6040
0
        WOLFSSL_LEAVE("DoTls13ServerHello", ret);
6041
6042
0
        return ret;
6043
0
    }
6044
6045
    /* Advance state and proceed */
6046
0
    ssl->options.asyncState = TLS_ASYNC_FINALIZE;
6047
0
    } /* case TLS_ASYNC_BUILD || TLS_ASYNC_DO */
6048
0
    FALL_THROUGH;
6049
6050
0
    case TLS_ASYNC_FINALIZE:
6051
0
    {
6052
#ifdef WOLFSSL_TLS13_MIDDLEBOX_COMPAT
6053
    if (ssl->options.tls13MiddleBoxCompat) {
6054
        if (args->sessIdSz == 0) {
6055
            WOLFSSL_MSG("args->sessIdSz == 0");
6056
            WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
6057
            return INVALID_PARAMETER;
6058
        }
6059
        if (ssl->session->sessionIDSz != 0) {
6060
            if (ssl->session->sessionIDSz != args->sessIdSz ||
6061
                XMEMCMP(ssl->session->sessionID, args->sessId,
6062
                    args->sessIdSz) != 0) {
6063
                WOLFSSL_MSG("session id doesn't match");
6064
                WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
6065
                return INVALID_PARAMETER;
6066
            }
6067
        }
6068
        else if (XMEMCMP(ssl->arrays->clientRandom, args->sessId,
6069
                args->sessIdSz) != 0) {
6070
            WOLFSSL_MSG("session id doesn't match client random");
6071
            WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
6072
            return INVALID_PARAMETER;
6073
        }
6074
    }
6075
    else
6076
#endif /* WOLFSSL_TLS13_MIDDLEBOX_COMPAT */
6077
#if defined(WOLFSSL_QUIC) || defined(WOLFSSL_DTLS13)
6078
    if (0
6079
#ifdef WOLFSSL_QUIC
6080
        || WOLFSSL_IS_QUIC(ssl)
6081
#endif
6082
#ifdef WOLFSSL_DTLS13
6083
        || ssl->options.dtls
6084
#endif
6085
    ) {
6086
        /* RFC 9147 Section 5 / RFC 9001 Section 8.4: DTLS 1.3 and QUIC
6087
         * ServerHello must have empty legacy_session_id_echo. */
6088
        int requireEmptyEcho = 1;
6089
#ifdef WOLFSSL_DTLS13_ECHO_LEGACY_SESSION_ID
6090
        /* Compat: a wolfSSL <= 5.9.0 DTLS 1.3 server echoes the client's
6091
         * legacy_session_id back instead of omitting it. */
6092
        if (ssl->options.dtls)
6093
            requireEmptyEcho = 0;
6094
#endif
6095
        if (requireEmptyEcho && args->sessIdSz != 0) {
6096
            WOLFSSL_MSG("args->sessIdSz != 0");
6097
            WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
6098
            return INVALID_PARAMETER;
6099
        }
6100
#ifdef WOLFSSL_DTLS13_ECHO_LEGACY_SESSION_ID
6101
        /* An echoing wolfSSL <= 5.9.0 server must still send back what was
6102
         * sent (RFC 8446 Section 4.1.3), so don't accept an arbitrary value.
6103
         * An empty echo is the compliant server case and stays acceptable. */
6104
        if (!requireEmptyEcho && args->sessIdSz != 0 &&
6105
                (args->sessIdSz != ssl->session->sessionIDSz ||
6106
                 XMEMCMP(ssl->session->sessionID, args->sessId,
6107
                         args->sessIdSz) != 0)) {
6108
            WOLFSSL_MSG("Server sent different session id");
6109
            WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
6110
            return INVALID_PARAMETER;
6111
        }
6112
#endif
6113
    }
6114
    else
6115
#endif /* WOLFSSL_QUIC || WOLFSSL_DTLS13 */
6116
0
    if (args->sessIdSz != ssl->session->sessionIDSz || (args->sessIdSz > 0 &&
6117
0
        XMEMCMP(ssl->session->sessionID, args->sessId, args->sessIdSz) != 0))
6118
0
    {
6119
0
        WOLFSSL_MSG("Server sent different session id");
6120
0
        WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
6121
0
        return INVALID_PARAMETER;
6122
0
    }
6123
6124
0
    ret = SetCipherSpecs(ssl);
6125
0
    if (ret != 0)
6126
0
        return ret;
6127
6128
#ifdef HAVE_NULL_CIPHER
6129
    if (ssl->options.cipherSuite0 == ECC_BYTE &&
6130
                              (ssl->options.cipherSuite == TLS_SHA256_SHA256 ||
6131
                               ssl->options.cipherSuite == TLS_SHA384_SHA384)) {
6132
        ;
6133
    }
6134
    else
6135
#endif
6136
#if defined(WOLFSSL_SM4_GCM) && defined(WOLFSSL_SM3)
6137
    if (ssl->options.cipherSuite0 == CIPHER_BYTE &&
6138
            ssl->options.cipherSuite == TLS_SM4_GCM_SM3) {
6139
        ; /* Do nothing. */
6140
    }
6141
    else
6142
#endif
6143
#if defined(WOLFSSL_SM4_CCM) && defined(WOLFSSL_SM3)
6144
    if (ssl->options.cipherSuite0 == CIPHER_BYTE &&
6145
            ssl->options.cipherSuite == TLS_SM4_CCM_SM3) {
6146
        ; /* Do nothing. */
6147
    }
6148
    else
6149
#endif
6150
    /* Check that the negotiated ciphersuite matches protocol version. */
6151
0
    if (ssl->options.cipherSuite0 != TLS13_BYTE) {
6152
0
        WOLFSSL_MSG("Server sent non-TLS13 cipher suite in TLS 1.3 packet");
6153
0
        WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
6154
0
        return INVALID_PARAMETER;
6155
0
    }
6156
6157
0
    suite[0] = ssl->options.cipherSuite0;
6158
0
    suite[1] = ssl->options.cipherSuite;
6159
0
    if (!FindSuiteSSL(ssl, suite)) {
6160
0
        WOLFSSL_MSG("Cipher suite not supported on client");
6161
0
        WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
6162
0
        return INVALID_PARAMETER;
6163
0
    }
6164
6165
#if defined(HAVE_ECH)
6166
    /* check for acceptConfirmation */
6167
    if (ssl->echConfigs != NULL && !ssl->options.disableECH &&
6168
            ssl->hsHashesEch != NULL) {
6169
        args->echX = TLSX_Find(ssl->extensions, TLSX_ECH);
6170
        if (args->echX == NULL || args->echX->data == NULL)
6171
            return WOLFSSL_FATAL_ERROR;
6172
6173
        if (args->extMsgType == hello_retry_request &&
6174
                ((WOLFSSL_ECH*)args->echX->data)->confBuf == NULL) {
6175
            /* server rejected ECH, fall back to outer */
6176
            Free_HS_Hashes(ssl->hsHashesEch, ssl->heap);
6177
            ssl->hsHashesEch = NULL;
6178
            /* EchCheckAcceptance is bypassed, so replace extensions now */
6179
            ret = TLSX_EchReplaceExtensions(ssl, 0);
6180
            if (ret != 0)
6181
                return ret;
6182
        }
6183
        else {
6184
            /* account for hrr extension instead of server random */
6185
            if (args->extMsgType == hello_retry_request) {
6186
                args->acceptOffset =
6187
                    (word32)(((WOLFSSL_ECH*)args->echX->data)->confBuf - input);
6188
                args->acceptLabel = (byte*)echHrrAcceptConfirmationLabel;
6189
                args->acceptLabelSz = ECH_HRR_ACCEPT_CONFIRMATION_LABEL_SZ;
6190
            }
6191
            else {
6192
                args->acceptLabel = (byte*)echAcceptConfirmationLabel;
6193
                args->acceptLabelSz = ECH_ACCEPT_CONFIRMATION_LABEL_SZ;
6194
            }
6195
            /* check acceptance */
6196
            if (ret == 0) {
6197
                ret = EchCheckAcceptance(ssl, args->acceptLabel,
6198
                    args->acceptLabelSz, input, args->acceptOffset, helloSz,
6199
                    args->extMsgType);
6200
            }
6201
            if (ret != 0)
6202
                return ret;
6203
            /* use the inner random for client random */
6204
            if (args->extMsgType != hello_retry_request &&
6205
                    ssl->options.echAccepted) {
6206
                XMEMCPY(ssl->arrays->clientRandom,
6207
                    ssl->arrays->clientRandomInner, RAN_LEN);
6208
            }
6209
        }
6210
    }
6211
#endif /* HAVE_ECH */
6212
6213
0
    if (*extMsgType == server_hello) {
6214
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
6215
        PreSharedKey* psk = NULL;
6216
        TLSX* ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
6217
        if (ext != NULL)
6218
            psk = (PreSharedKey*)ext->data;
6219
        while (psk != NULL && !psk->chosen)
6220
            psk = psk->next;
6221
        if (psk == NULL) {
6222
            /* A mandatory PSK is satisfied by any PSK the server chose,
6223
             * including a resumption PSK - this matches the server-side
6224
             * failNoPSK semantics, where a negotiated PSK (external or
6225
             * resumption) is accepted. The error only fires when no PSK was
6226
             * chosen at all. havePSK is only set by an external-PSK callback,
6227
             * so a peer relying solely on session-ticket resumption is
6228
             * unaffected. */
6229
            if (ssl->options.havePSK && ssl->options.failNoPSK) {
6230
                WOLFSSL_MSG("Server did not negotiate a mandatory PSK");
6231
                WOLFSSL_ERROR_VERBOSE(PSK_MISSING_ERROR);
6232
                return PSK_MISSING_ERROR;
6233
            }
6234
            ssl->options.resuming = 0;
6235
            ssl->arrays->psk_keySz = 0;
6236
            XMEMSET(ssl->arrays->psk_key, 0, MAX_PSK_KEY_LEN);
6237
        }
6238
        else {
6239
#if defined(HAVE_ECH)
6240
            /* do not resume when outerHandshake will be negotiated */
6241
            if (ssl->echConfigs != NULL && !ssl->options.disableECH &&
6242
                    !ssl->options.echAccepted) {
6243
                WOLFSSL_MSG("ECH rejected but server negotiated PSK");
6244
                return INVALID_PARAMETER;
6245
            }
6246
#endif
6247
#ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
6248
            if (ssl->options.certWithExternPsk && psk->resumption) {
6249
                /* RFC 9973 mode requires external PSK, not ticket resumption. */
6250
                WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
6251
                return PSK_KEY_ERROR;
6252
            }
6253
            if (ssl->options.certWithExternPsk && ssl->options.shSentKeyShare == 0) {
6254
                /* RFC 9973 Sect. 3: cert_with_extern_psk requires psk_dhe_ke;
6255
                 * a ServerHello without a key_share confirms only psk_ke. */
6256
                WOLFSSL_MSG("cert_with_extern_psk: ServerHello missing key_share");
6257
                WOLFSSL_ERROR_VERBOSE(EXT_MISSING);
6258
                return EXT_MISSING;
6259
            }
6260
#endif
6261
            if ((ret = SetupPskKey(ssl, psk, 0)) != 0)
6262
                return ret;
6263
            ssl->options.pskNegotiated = 1;
6264
        }
6265
#else
6266
        /* no resumption possible */
6267
0
        ssl->options.resuming = 0;
6268
0
#endif
6269
6270
        /* sanity check on PSK / KSE */
6271
0
        if (
6272
    #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
6273
            ssl->options.pskNegotiated == 0 &&
6274
    #endif
6275
0
            (ssl->session->namedGroup == 0 ||
6276
0
             ssl->options.shSentKeyShare == 0)) {
6277
0
            return EXT_MISSING;
6278
0
        }
6279
6280
0
        ssl->keys.encryptionOn = 1;
6281
0
        ssl->options.serverState = SERVER_HELLO_COMPLETE;
6282
6283
0
    }
6284
0
    else {
6285
        /* https://datatracker.ietf.org/doc/html/rfc8446#section-4.1.4
6286
         * Clients MUST abort the handshake with an
6287
         * "illegal_parameter" alert if the HelloRetryRequest would not result
6288
         * in any change in the ClientHello.
6289
         */
6290
        /* Check if the HRR contained a cookie or a keyshare */
6291
0
        if (!ssl->options.hrrSentKeyShare
6292
0
#ifdef WOLFSSL_TLS13_COOKIE
6293
0
                && !ssl->options.hrrSentCookie
6294
0
#endif
6295
0
                ) {
6296
0
            SendAlert(ssl, alert_fatal, illegal_parameter);
6297
0
            return EXT_MISSING;
6298
0
        }
6299
6300
0
        ssl->options.tls1_3 = 1;
6301
0
        ssl->options.serverState = SERVER_HELLO_RETRY_REQUEST_COMPLETE;
6302
6303
0
        ret = RestartHandshakeHash(ssl);
6304
0
    }
6305
6306
0
    break;
6307
0
    } /* case TLS_ASYNC_FINALIZE */
6308
0
    default:
6309
0
        ret = INPUT_CASE_ERROR;
6310
0
    } /* switch (ssl->options.asyncState) */
6311
6312
#ifdef WOLFSSL_ASYNC_CRYPT
6313
    if (ret == 0) {
6314
        FreeAsyncCtx(ssl, 0);
6315
        /* Replays skip the sanity check that re-sets got_server_hello;
6316
         * restore on completion (not for HRR, which re-counts it). */
6317
        if (*extMsgType == server_hello &&
6318
                ssl->msgsReceived.got_server_hello == 0) {
6319
            ssl->msgsReceived.got_server_hello = 1;
6320
        }
6321
    }
6322
#endif
6323
6324
0
    WOLFSSL_LEAVE("DoTls13ServerHello", ret);
6325
0
    WOLFSSL_END(WC_FUNC_SERVER_HELLO_DO);
6326
6327
0
    return ret;
6328
0
}
6329
6330
/* handle processing TLS 1.3 encrypted_extensions (8) */
6331
/* Parse and handle an EncryptedExtensions message.
6332
 * Only a client will receive this message.
6333
 *
6334
 * ssl       The SSL/TLS object.
6335
 * input     The message buffer.
6336
 * inOutIdx  On entry, the index into the message buffer of
6337
 *           EncryptedExtensions.
6338
 *           On exit, the index of byte after the EncryptedExtensions
6339
 *           message.
6340
 * totalSz   The length of the current handshake message.
6341
 * returns 0 on success and otherwise failure.
6342
 */
6343
static int DoTls13EncryptedExtensions(WOLFSSL* ssl, const byte* input,
6344
                                      word32* inOutIdx, word32 totalSz)
6345
0
{
6346
0
    int    ret;
6347
0
    word32 begin = *inOutIdx;
6348
0
    word32 i = begin;
6349
0
    word16 totalExtSz;
6350
6351
0
    WOLFSSL_START(WC_FUNC_ENCRYPTED_EXTENSIONS_DO);
6352
0
    WOLFSSL_ENTER("DoTls13EncryptedExtensions");
6353
6354
#ifdef WOLFSSL_CALLBACKS
6355
    if (ssl->hsInfoOn) AddPacketName(ssl, "EncryptedExtensions");
6356
    if (ssl->toInfoOn) AddLateName("EncryptedExtensions", &ssl->timeoutInfo);
6357
#endif
6358
6359
    /* Length field of extension data. */
6360
0
    if (totalSz < OPAQUE16_LEN)
6361
0
        return BUFFER_ERROR;
6362
0
    ato16(&input[i], &totalExtSz);
6363
0
    i += OPAQUE16_LEN;
6364
6365
    /* Extension data. */
6366
0
    if (i - begin + totalExtSz != totalSz)
6367
0
        return BUFFER_ERROR;
6368
0
    if ((ret = TLSX_Parse(ssl, input + i, totalExtSz, encrypted_extensions,
6369
0
                                                                       NULL))) {
6370
0
        return ret;
6371
0
    }
6372
6373
    /* Move index to byte after message. */
6374
0
    *inOutIdx = i + totalExtSz;
6375
6376
#ifdef WOLFSSL_EARLY_DATA
6377
    if (ssl->earlyData != no_early_data) {
6378
        TLSX* ext = TLSX_Find(ssl->extensions, TLSX_EARLY_DATA);
6379
        if (ext == NULL || !ext->val) {
6380
            WOLFSSL_MSG("Early data rejected by server (no early_data "
6381
                        "EncryptedExtensions response)");
6382
            ssl->earlyData = no_early_data;
6383
        }
6384
    }
6385
6386
    if (ssl->earlyData == no_early_data) {
6387
        ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY);
6388
        if (ret != 0)
6389
            return ret;
6390
    }
6391
#endif /* WOLFSSL_EARLY_DATA */
6392
6393
0
    ssl->options.serverState = SERVER_ENCRYPTED_EXTENSIONS_COMPLETE;
6394
6395
0
    WOLFSSL_LEAVE("DoTls13EncryptedExtensions", ret);
6396
0
    WOLFSSL_END(WC_FUNC_ENCRYPTED_EXTENSIONS_DO);
6397
6398
0
    return ret;
6399
0
}
6400
6401
#ifndef NO_CERTS
6402
/* handle processing TLS v1.3 certificate_request (13) */
6403
/* Handle a TLS v1.3 CertificateRequest message.
6404
 * This message is always encrypted.
6405
 * Only a client will receive this message.
6406
 *
6407
 * ssl       The SSL/TLS object.
6408
 * input     The message buffer.
6409
 * inOutIdx  On entry, the index into the message buffer of CertificateRequest.
6410
 *           On exit, the index of byte after the CertificateRequest message.
6411
 * size      The length of the current handshake message.
6412
 * returns 0 on success and otherwise failure.
6413
 */
6414
static int DoTls13CertificateRequest(WOLFSSL* ssl, const byte* input,
6415
                                     word32* inOutIdx, word32 size)
6416
0
{
6417
0
    word16      len;
6418
0
    word32      begin = *inOutIdx;
6419
0
    int         ret = 0;
6420
0
    Suites      peerSuites;
6421
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
6422
    word16      reqCtxLen;
6423
    const byte* reqCtxData;
6424
#endif
6425
6426
0
    WOLFSSL_START(WC_FUNC_CERTIFICATE_REQUEST_DO);
6427
0
    WOLFSSL_ENTER("DoTls13CertificateRequest");
6428
6429
0
    XMEMSET(&peerSuites, 0, sizeof(Suites));
6430
0
#if !defined(WOLFSSL_NO_SIGALG)
6431
    /* Post-handshake auth can deliver several requests; each one's cert
6432
     * signature algorithms replace the last rather than adding to them. */
6433
0
    ssl->certHashSigAlgoSz = 0;
6434
0
#endif
6435
6436
#ifdef WOLFSSL_CALLBACKS
6437
    if (ssl->hsInfoOn) AddPacketName(ssl, "CertificateRequest");
6438
    if (ssl->toInfoOn) AddLateName("CertificateRequest", &ssl->timeoutInfo);
6439
#endif
6440
6441
0
    if (OPAQUE8_LEN > size)
6442
0
        return BUFFER_ERROR;
6443
6444
    /* Length of the request context. */
6445
0
    len = input[(*inOutIdx)++];
6446
0
    if ((*inOutIdx - begin) + len > size)
6447
0
        return BUFFER_ERROR;
6448
    /* INVALID_PARAMETER does not map to illegal_parameter in the central
6449
     * alert path, so emit the alert explicitly before returning. */
6450
0
    if (ssl->options.connectState < FINISHED_DONE) {
6451
        /* RFC 8446 Section 4.3.2: in the handshake the context is zero
6452
         * length. */
6453
0
        if (len > 0) {
6454
0
            SendAlert(ssl, alert_fatal, illegal_parameter);
6455
0
            WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
6456
0
            return INVALID_PARAMETER;
6457
0
        }
6458
0
    }
6459
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
6460
#ifdef WOLFSSL_QUIC
6461
    else if (WOLFSSL_IS_QUIC(ssl)) {
6462
        WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
6463
        return OUT_OF_ORDER_E;
6464
    }
6465
#endif
6466
    else if (len == 0) {
6467
        /* RFC 8446 Section 4.3.2: a post-handshake CertificateRequest context
6468
         * MUST be non-empty and unique for the connection. */
6469
        SendAlert(ssl, alert_fatal, illegal_parameter);
6470
        WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
6471
        return INVALID_PARAMETER;
6472
    }
6473
#endif
6474
6475
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
6476
    /* Remember the request context bytes; the CertReqCtx allocation and
6477
     * linking into ssl->certReqCtx is deferred until after the rest of the
6478
     * message has been validated.
6479
     */
6480
    reqCtxLen = len;
6481
    reqCtxData = input + *inOutIdx;
6482
    /* Reject a context that duplicates one still pending on the connection. */
6483
    if (ssl->options.connectState >= FINISHED_DONE) {
6484
        CertReqCtx* dup;
6485
        for (dup = ssl->certReqCtx; dup != NULL; dup = dup->next) {
6486
            if (dup->len == reqCtxLen &&
6487
                    XMEMCMP(&dup->ctx, reqCtxData, reqCtxLen) == 0) {
6488
                SendAlert(ssl, alert_fatal, illegal_parameter);
6489
                WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
6490
                return INVALID_PARAMETER;
6491
            }
6492
        }
6493
    }
6494
#endif
6495
0
    *inOutIdx += len;
6496
6497
    /* TODO: Add support for more extensions:
6498
     *   signed_certificate_timestamp, certificate_authorities, oid_filters.
6499
     */
6500
    /* Certificate extensions */
6501
0
    if ((*inOutIdx - begin) + OPAQUE16_LEN > size)
6502
0
        return BUFFER_ERROR;
6503
0
    ato16(input + *inOutIdx, &len);
6504
0
    *inOutIdx += OPAQUE16_LEN;
6505
0
    if ((*inOutIdx - begin) + len > size)
6506
0
        return BUFFER_ERROR;
6507
    /* RFC 9846 Section 4.4.2: CertificateRequest.extensions has a lower bound of
6508
     * 0, so an empty extensions block is parsed rather than rejected here. A
6509
     * request missing the mandatory signature_algorithms extension is caught by
6510
     * the check below. */
6511
0
    if ((ret = TLSX_Parse(ssl, input + *inOutIdx, len, certificate_request,
6512
0
                                                                &peerSuites))) {
6513
0
        return ret;
6514
0
    }
6515
0
    *inOutIdx += len;
6516
6517
    /* No trailing bytes allowed (RFC 8446 4.3.2). */
6518
0
    if ((*inOutIdx - begin) != size)
6519
0
        return BUFFER_ERROR;
6520
6521
    /* RFC 8446 Section 4.3.2: the signature_algorithms extension MUST be
6522
     * present in a CertificateRequest. */
6523
0
    if (peerSuites.hashSigAlgoSz == 0) {
6524
0
        SendAlert(ssl, alert_fatal, missing_extension);
6525
0
        WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
6526
0
        return INVALID_PARAMETER;
6527
0
    }
6528
6529
0
#if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
6530
0
    SetPeerSha1CertOk(ssl, &peerSuites);
6531
0
#endif
6532
6533
#ifdef WOLFSSL_CERT_SETUP_CB
6534
    if ((ret = CertSetupCbWrapper(ssl)) != 0)
6535
        return ret;
6536
#endif
6537
6538
#if defined(HAVE_ECH)
6539
    /* RFC 9849 s6.1.7: ECH was offered but rejected by the server...
6540
     * the client MUST respond with an empty Certificate message. */
6541
    if (ssl->echConfigs != NULL && !ssl->options.disableECH &&
6542
            !ssl->options.echAccepted) {
6543
        ssl->options.sendVerify = SEND_BLANK_CERT;
6544
    }
6545
    else
6546
#endif
6547
0
    if ((ssl->buffers.certificate && ssl->buffers.certificate->buffer &&
6548
0
        ((ssl->buffers.key && ssl->buffers.key->buffer)
6549
        #ifdef HAVE_PK_CALLBACKS
6550
            || wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)
6551
        #endif
6552
0
    ))
6553
        #ifdef OPENSSL_EXTRA
6554
            || ssl->ctx->certSetupCb != NULL
6555
        #endif
6556
0
            ) {
6557
0
        if (PickHashSigAlgo(ssl, peerSuites.hashSigAlgo,
6558
0
                            peerSuites.hashSigAlgoSz, 0) != 0) {
6559
0
            WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
6560
0
            return INVALID_PARAMETER;
6561
0
        }
6562
0
        ssl->options.sendVerify = SEND_CERT;
6563
0
    }
6564
0
    else {
6565
0
#ifndef WOLFSSL_NO_CLIENT_CERT_ERROR
6566
0
        ssl->options.sendVerify = SEND_BLANK_CERT;
6567
#else
6568
        WOLFSSL_MSG("Certificate required but none set on client");
6569
        /* RFC 8446 Section 4.4.2.4: send certificate_required when a
6570
         * peer (here, the client) cannot provide a certificate that the
6571
         * other peer required. */
6572
        SendAlert(ssl, alert_fatal, certificate_required);
6573
        WOLFSSL_ERROR_VERBOSE(NO_CERT_ERROR);
6574
        return NO_CERT_ERROR;
6575
#endif
6576
0
    }
6577
6578
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
6579
    {
6580
        /* CertReqCtx has one byte at end for context value.
6581
        * Increase size to handle other implementations sending more than one byte.
6582
        * That is, allocate extra space, over one byte, to hold the context value.
6583
        */
6584
        CertReqCtx* certReqCtx = (CertReqCtx*)XMALLOC(
6585
            sizeof(CertReqCtx) + (reqCtxLen == 0 ? 0 : reqCtxLen - 1),
6586
            ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
6587
        if (certReqCtx == NULL)
6588
            return MEMORY_E;
6589
        certReqCtx->next = ssl->certReqCtx;
6590
        certReqCtx->len = reqCtxLen;
6591
        XMEMCPY(&certReqCtx->ctx, reqCtxData, reqCtxLen);
6592
        ssl->certReqCtx = certReqCtx;
6593
    }
6594
#endif
6595
6596
0
    WOLFSSL_LEAVE("DoTls13CertificateRequest", ret);
6597
0
    WOLFSSL_END(WC_FUNC_CERTIFICATE_REQUEST_DO);
6598
6599
0
    return ret;
6600
0
}
6601
#endif /* !NO_CERTS */
6602
#endif /* !NO_WOLFSSL_CLIENT */
6603
6604
#ifndef NO_WOLFSSL_SERVER
6605
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
6606
#ifndef NO_PSK
6607
int FindPskSuite(const WOLFSSL* ssl, PreSharedKey* psk, byte* psk_key,
6608
        word32* psk_keySz, const byte* suite, int* found, byte* foundSuite)
6609
{
6610
    const char* cipherName = NULL;
6611
    byte        cipherSuite0 = TLS13_BYTE;
6612
    byte        cipherSuite  = WOLFSSL_DEF_PSK_CIPHER;
6613
    int         ret = 0;
6614
6615
    *found = 0;
6616
    (void)suite;
6617
6618
    if (ssl->options.server_psk_tls13_cb != NULL) {
6619
         *psk_keySz = ssl->options.server_psk_tls13_cb((WOLFSSL*)ssl,
6620
             (char*)psk->identity, psk_key, MAX_PSK_KEY_LEN, &cipherName);
6621
         if (*psk_keySz != 0) {
6622
             int cipherSuiteFlags = WOLFSSL_CIPHER_SUITE_FLAG_NONE;
6623
             *found = (GetCipherSuiteFromName(cipherName, &cipherSuite0,
6624
                 &cipherSuite, NULL, NULL, &cipherSuiteFlags) == 0);
6625
             (void)cipherSuiteFlags;
6626
         }
6627
    }
6628
    if (*found == 0 && (ssl->options.server_psk_cb != NULL)) {
6629
         *psk_keySz = ssl->options.server_psk_cb((WOLFSSL*)ssl,
6630
                             (char*)psk->identity, psk_key,
6631
                             MAX_PSK_KEY_LEN);
6632
         *found = (*psk_keySz != 0);
6633
    }
6634
    if (*found) {
6635
        if (*psk_keySz > MAX_PSK_KEY_LEN &&
6636
            (int)*psk_keySz != WC_NO_ERR_TRACE(USE_HW_PSK)) {
6637
            WOLFSSL_MSG("Key len too long in FindPsk()");
6638
            ret = PSK_KEY_ERROR;
6639
            WOLFSSL_ERROR_VERBOSE(ret);
6640
            *found = 0;
6641
        }
6642
        if (ret == 0) {
6643
        #if !defined(WOLFSSL_PSK_ONE_ID) && !defined(WOLFSSL_PRIORITIZE_PSK)
6644
            /* Check whether PSK ciphersuite is in SSL. */
6645
            *found = (suite[0] == cipherSuite0) && (suite[1] == cipherSuite);
6646
        #else
6647
            (void)suite;
6648
            /* Check whether PSK ciphersuite is in SSL. */
6649
            {
6650
                byte s[2] = {
6651
                    cipherSuite0,
6652
                    cipherSuite,
6653
                };
6654
                *found = FindSuiteSSL(ssl, s);
6655
            }
6656
        #endif
6657
        }
6658
    }
6659
    if (*found && foundSuite != NULL) {
6660
        foundSuite[0] = cipherSuite0;
6661
        foundSuite[1] = cipherSuite;
6662
    }
6663
6664
    return ret;
6665
}
6666
6667
/* Attempt to find the PSK (not session ticket) that matches.
6668
 *
6669
 * @param [in, out] ssl    The SSL/TLS object.
6670
 * @param [in]      psk    A pre-shared key from the extension.
6671
 * @param [out]     suite  Cipher suite to use with PSK.
6672
 * @param [out]     err    Error code.
6673
 *                         PSK_KEY_ERROR when key is too big,
6674
 *                         UNSUPPORTED_SUITE on invalid suite.
6675
 *                         Other error when attempting to derive early secret.
6676
 * @return  1 when a match found - but check error code.
6677
 * @return  0 when no match found.
6678
 */
6679
static int FindPsk(WOLFSSL* ssl, PreSharedKey* psk, const byte* suite, int* err)
6680
{
6681
    int         ret = 0;
6682
    int         found = 0;
6683
    byte        foundSuite[SUITE_LEN];
6684
6685
    WOLFSSL_ENTER("FindPsk");
6686
6687
    XMEMSET(foundSuite, 0, sizeof(foundSuite));
6688
6689
    ret = FindPskSuite(ssl, psk, ssl->arrays->psk_key, &ssl->arrays->psk_keySz,
6690
                       suite, &found, foundSuite);
6691
    if (ret == 0 && found) {
6692
        /* This identity matched via external PSK callback, not ticket resume. */
6693
        psk->resumption = 0;
6694
        /* Default to ciphersuite if cb doesn't specify. */
6695
        ssl->options.resuming = 0;
6696
        /* Don't send certificate request when using PSK. */
6697
#ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
6698
        if (!ssl->options.certWithExternPsk)
6699
#endif
6700
            ssl->options.verifyPeer = 0;
6701
6702
        /* obfuscated_ticket_age is not checked: RFC 8446 Section 4.2.11
6703
         * requires servers to ignore it for an external identity. */
6704
        /* Set PSK ciphersuite into SSL. */
6705
        ssl->options.cipherSuite0 = foundSuite[0];
6706
        ssl->options.cipherSuite  = foundSuite[1];
6707
        ret = SetCipherSpecs(ssl);
6708
        if (ret == 0) {
6709
            /* Derive the early secret using the PSK. */
6710
            ret = DeriveEarlySecret(ssl);
6711
        }
6712
        if (ret == 0) {
6713
            /* PSK negotiation has succeeded */
6714
            ssl->options.isPSK = 1;
6715
#ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
6716
            if (!ssl->options.certWithExternPsk)
6717
#endif
6718
            {
6719
                /* SERVER: using PSK for peer authentication. */
6720
                ssl->options.peerAuthGood = 1;
6721
            }
6722
        }
6723
    }
6724
6725
    *err = ret;
6726
    WOLFSSL_LEAVE("FindPsk", found);
6727
    WOLFSSL_LEAVE("FindPsk", ret);
6728
    return found;
6729
}
6730
#endif /* !NO_PSK */
6731
6732
/* Handle any Pre-Shared Key (PSK) extension.
6733
 * Find a PSK that supports the cipher suite passed in.
6734
 *
6735
 * ssl         SSL/TLS object.
6736
 * suite       Cipher suite to find PSK for.
6737
 * usingPSK    1=Indicates handshake is using Pre-Shared Keys (2=Ephemeral)
6738
 * first       Set to 1 if first in extension
6739
 * returns 0 on success and otherwise failure.
6740
 */
6741
static int DoPreSharedKeys(WOLFSSL* ssl, const byte* input, word32 inputSz,
6742
    const byte* suite, int* usingPSK, int* first)
6743
{
6744
    int           ret = 0;
6745
    TLSX*         ext;
6746
    PreSharedKey* current;
6747
    byte          binderKey[WC_MAX_DIGEST_SIZE];
6748
    byte          binder[WC_MAX_DIGEST_SIZE];
6749
    word32        binderLen;
6750
#if defined(WOLFSSL_CERT_WITH_EXTERN_PSK) && defined(HAVE_SESSION_TICKET)
6751
    int           certWithExternOffered = 0;
6752
#endif
6753
6754
    #ifdef NO_PSK
6755
        (void) suite; /* to avoid unused var warning when not used */
6756
    #endif
6757
6758
    WOLFSSL_ENTER("DoPreSharedKeys");
6759
6760
    (void)suite;
6761
6762
#ifdef WOLFSSL_CHECK_MEM_ZERO
6763
    /* Poison and register binderKey up front; every exit below (including the
6764
     * error paths) funnels through the cleanup label which zeroes it. */
6765
    XMEMSET(binderKey, 0xff, sizeof(binderKey));
6766
    wc_MemZero_Add("DoPreSharedKeys binderKey", binderKey, sizeof(binderKey));
6767
#endif
6768
6769
#if defined(HAVE_SESSION_TICKET) && defined(WOLFSSL_EARLY_DATA)
6770
    ssl->options.ticketPredatesCtx = 0;
6771
#endif
6772
6773
    ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
6774
    if (ext == NULL) {
6775
        WOLFSSL_MSG("No pre shared extension keys found");
6776
        ret = BAD_FUNC_ARG;
6777
        goto cleanup;
6778
    }
6779
#if defined(WOLFSSL_CERT_WITH_EXTERN_PSK) && defined(HAVE_SESSION_TICKET)
6780
    certWithExternOffered =
6781
        TLSX_Find(ssl->extensions, TLSX_CERT_WITH_EXTERN_PSK) != NULL;
6782
#endif
6783
6784
    /* Look through all client's pre-shared keys for a match. */
6785
    for (current = (PreSharedKey*)ext->data; current != NULL;
6786
            current = current->next) {
6787
    #ifndef NO_PSK
6788
        if (current->identityLen > MAX_PSK_ID_LEN) {
6789
            ret = BUFFER_ERROR;
6790
            goto cleanup;
6791
        }
6792
        XMEMCPY(ssl->arrays->client_identity, current->identity,
6793
                current->identityLen);
6794
        ssl->arrays->client_identity[current->identityLen] = '\0';
6795
    #endif
6796
6797
    #ifdef HAVE_SESSION_TICKET
6798
        /* Decode the identity. */
6799
        switch (current->decryptRet) {
6800
            case PSK_DECRYPT_NONE:
6801
                ret = DoClientTicket_ex(ssl, current, 1);
6802
                /* psk->sess may be set. Need to clean up later. */
6803
                break;
6804
            case PSK_DECRYPT_OK:
6805
                ret = WOLFSSL_TICKET_RET_OK;
6806
                break;
6807
            case PSK_DECRYPT_CREATE:
6808
                ret = WOLFSSL_TICKET_RET_CREATE;
6809
                break;
6810
            case PSK_DECRYPT_FAIL:
6811
                ret = WOLFSSL_TICKET_RET_REJECT;
6812
                break;
6813
        }
6814
6815
        #ifdef WOLFSSL_ASYNC_CRYPT
6816
        if (ret == WC_NO_ERR_TRACE(WC_PENDING_E))
6817
            goto cleanup;
6818
        #endif
6819
6820
        if (ret != WOLFSSL_TICKET_RET_OK && current->sess_free_cb != NULL) {
6821
            current->sess_free_cb(ssl, current->sess,
6822
                    &current->sess_free_cb_ctx);
6823
            current->sess = NULL;
6824
            current->sess_free_cb = NULL;
6825
            XMEMSET(&current->sess_free_cb_ctx, 0,
6826
                    sizeof(psk_sess_free_cb_ctx));
6827
        }
6828
        if (ret == WOLFSSL_TICKET_RET_OK) {
6829
#if defined(WOLFSSL_CERT_WITH_EXTERN_PSK) && defined(HAVE_SESSION_TICKET)
6830
            /* RFC 9973 Sect. 5.1: all PSKs listed alongside
6831
             * tls_cert_with_extern_psk MUST be external PSKs.  A successfully
6832
             * decrypted session ticket identity is a resumption PSK, so the
6833
             * server MUST abort with illegal_parameter regardless of whether
6834
             * the ticket would otherwise be acceptable.  Check here, before
6835
             * DoClientTicketFinalize, to avoid polluting ssl->session with
6836
             * ticket state that will not be used. */
6837
            if (certWithExternOffered) {
6838
                if (current->sess_free_cb != NULL) {
6839
                    current->sess_free_cb(ssl, current->sess,
6840
                            &current->sess_free_cb_ctx);
6841
                    current->sess = NULL;
6842
                    current->sess_free_cb = NULL;
6843
                    XMEMSET(&current->sess_free_cb_ctx, 0,
6844
                            sizeof(psk_sess_free_cb_ctx));
6845
                }
6846
                ret = PSK_KEY_ERROR;
6847
                WOLFSSL_ERROR_VERBOSE(ret);
6848
                goto cleanup;
6849
            }
6850
#endif
6851
            ret = DoClientTicketCheck(ssl, current, ssl->timeout, suite);
6852
        #if defined(HAVE_SNI) || defined(HAVE_ALPN)
6853
            if (ret == 0) {
6854
                /* Decline this PSK if the SNI/ALPN bound to the ticket
6855
                 * does not match the current connection. RFC 6066 Sect.
6856
                 * 3 mandates this for SNI; wolfSSL applies the same
6857
                 * policy to ALPN as defense in depth. Skipping the PSK
6858
                 * (rather than aborting) lets the server try the next
6859
                 * candidate or fall back to a full handshake naturally
6860
                 * without unwinding committed PSK state. ALPN_Select
6861
                 * has already run earlier in DoTls13ClientHello so the
6862
                 * negotiated ALPN is available to TicketAlpnHash. */
6863
                byte curHash[TICKET_BINDING_HASH_SZ];
6864
            #ifdef HAVE_SNI
6865
                if (TicketSniHash(ssl, curHash) != 0 ||
6866
                        XMEMCMP(curHash, current->it->sniHash,
6867
                                TICKET_BINDING_HASH_SZ) != 0) {
6868
                    WOLFSSL_MSG("Ticket SNI mismatch, skipping PSK");
6869
                    ret = WOLFSSL_FATAL_ERROR;
6870
                }
6871
            #endif
6872
            #ifdef HAVE_ALPN
6873
                if (ret == 0 &&
6874
                        (TicketAlpnHash(ssl, curHash) != 0 ||
6875
                         XMEMCMP(curHash, current->it->alpnHash,
6876
                                 TICKET_BINDING_HASH_SZ) != 0)) {
6877
                    WOLFSSL_MSG("Ticket ALPN mismatch, skipping PSK");
6878
                    ret = WOLFSSL_FATAL_ERROR;
6879
                }
6880
            #endif
6881
            }
6882
        #endif
6883
            if (ret == 0)
6884
                DoClientTicketFinalize(ssl, current->it, current->sess);
6885
            if (current->sess_free_cb != NULL) {
6886
                current->sess_free_cb(ssl, current->sess,
6887
                        &current->sess_free_cb_ctx);
6888
                current->sess = NULL;
6889
                current->sess_free_cb = NULL;
6890
                XMEMSET(&current->sess_free_cb_ctx, 0,
6891
                        sizeof(psk_sess_free_cb_ctx));
6892
            }
6893
            if (ret != 0)
6894
                continue;
6895
6896
            /* SERVER: using secret in session ticket for peer auth. */
6897
            ssl->options.peerAuthGood = 1;
6898
6899
        #ifdef WOLFSSL_EARLY_DATA
6900
            ssl->options.maxEarlyDataSz = ssl->session->maxEarlyDataSz;
6901
            /* RFC 8446 Section 8.2: fresh servers should reject 0-RTT.
6902
             * Flag tickets minted before this ctx was created. */
6903
            if (!ssl->ctx->noFreshStartCheck) {
6904
        #ifdef WOLFSSL_32BIT_MILLI_TIME
6905
                /* A 32 bit ms clock wraps every ~49.7 days, so the ctx age is
6906
                 * only exact while it stays below the max ticket age. Past
6907
                 * that point DoClientTicketCheck has already rejected
6908
                 * anything old enough to predate the ctx, so the check can be
6909
                 * skipped.
6910
                 *
6911
                 * ctxAge is unsigned, so a clock reading before the ctx start
6912
                 * time (a backward step) wraps to just under 2^32. Letting
6913
                 * that count as an old ctx would silently disable the check
6914
                 * and admit 0-RTT for tickets minted before a restart, so the
6915
                 * near-wrap band stays in the checked range.
6916
                 *
6917
                 * The two cases are indistinguishable on a wrapping 32 bit
6918
                 * clock, so a ctx aged between (2^32 - max ticket age) and
6919
                 * 2^32 ms also lands in the band and refuses 0-RTT until it
6920
                 * wraps out. Refusing 0-RTT only costs the early data round
6921
                 * trip, so the ambiguity is resolved that way. */
6922
                word32 maxAge = (word32)TLS13_MAX_TICKET_AGE * 1000;
6923
                word32 now = TimeNowInMilliseconds();
6924
                word32 ctxAge = now - ssl->ctx->ticketStartTime;
6925
                word32 delta = ssl->ctx->ticketStartTime -
6926
                               ssl->session->ticketSeen;
6927
                ssl->options.ticketPredatesCtx =
6928
                    (now != 0 &&
6929
                     (ctxAge <= maxAge || ctxAge >= (word32)0u - maxAge) &&
6930
                     delta != 0 &&
6931
                     delta <= maxAge);
6932
        #else
6933
                ssl->options.ticketPredatesCtx =
6934
                    (ssl->session->ticketSeen < ssl->ctx->ticketStartTime);
6935
        #endif
6936
            }
6937
        #endif
6938
            /* Use the same cipher suite as before and set up for use. */
6939
            ssl->options.cipherSuite0   = ssl->session->cipherSuite0;
6940
            ssl->options.cipherSuite    = ssl->session->cipherSuite;
6941
            ret = SetCipherSpecs(ssl);
6942
            if (ret != 0)
6943
                goto cleanup;
6944
6945
            /* Resumption PSK is resumption master secret. */
6946
            ssl->arrays->psk_keySz = ssl->specs.hash_size;
6947
            if ((ret = DeriveResumptionPSK(ssl, ssl->session->ticketNonce.data,
6948
                ssl->session->ticketNonce.len, ssl->arrays->psk_key)) != 0) {
6949
                goto cleanup;
6950
            }
6951
6952
            /* Derive the early secret using the PSK. */
6953
            ret = DeriveEarlySecret(ssl);
6954
            if (ret != 0)
6955
                goto cleanup;
6956
6957
            /* Hash data up to binders for deriving binders in PSK extension.
6958
             * A pended binder derive below re-enters DoTls13ClientHello at
6959
             * TLS_ASYNC_BEGIN, so the hash is guarded to run only once. */
6960
        #ifdef WOLFSSL_ASYNC_CRYPT
6961
            if (!ssl->options.chHashInput)
6962
        #endif
6963
            {
6964
                ret = HashInput(ssl, input, (int)inputSz);
6965
                if (ret < 0)
6966
                    goto cleanup;
6967
            }
6968
        #ifdef WOLFSSL_ASYNC_CRYPT
6969
            ssl->options.chHashInput = 1;
6970
        #endif
6971
6972
            /* Derive the binder key to use with HMAC. */
6973
            ret = DeriveBinderKeyResume(ssl, binderKey);
6974
            if (ret != 0)
6975
                goto cleanup;
6976
        }
6977
        else
6978
    #endif /* HAVE_SESSION_TICKET */
6979
    #ifndef NO_PSK
6980
        if (FindPsk(ssl, current, suite, &ret)) {
6981
            if (ret != 0)
6982
                goto cleanup;
6983
6984
        #ifdef WOLFSSL_ASYNC_CRYPT
6985
            if (!ssl->options.chHashInput)
6986
        #endif
6987
            {
6988
                ret = HashInput(ssl, input, (int)inputSz);
6989
                if (ret < 0)
6990
                    goto cleanup;
6991
            }
6992
        #ifdef WOLFSSL_ASYNC_CRYPT
6993
            ssl->options.chHashInput = 1;
6994
        #endif
6995
6996
            /* Derive the binder key to use with HMAC. */
6997
            ret = DeriveBinderKey(ssl, binderKey);
6998
            if (ret != 0)
6999
                goto cleanup;
7000
        }
7001
        else
7002
    #endif
7003
        {
7004
            continue;
7005
        }
7006
7007
        ssl->options.sendVerify = 0;
7008
7009
        /* Derive the Finished message secret. */
7010
        ret = DeriveFinishedSecret(ssl, binderKey,
7011
                                   ssl->keys.client_write_MAC_secret,
7012
                                   0 /* neither end */);
7013
        if (ret != 0)
7014
            goto cleanup;
7015
7016
        /* Derive the binder and compare with the one in the extension. */
7017
        ret = BuildTls13HandshakeHmac(ssl,
7018
                         ssl->keys.client_write_MAC_secret, binder, &binderLen);
7019
        if (ret != 0)
7020
            goto cleanup;
7021
        if (binderLen != current->binderLen ||
7022
                             ConstantCompare(binder, current->binder,
7023
                                binderLen) != 0) {
7024
            WOLFSSL_ERROR_VERBOSE(BAD_BINDER);
7025
            ret = BAD_BINDER;
7026
            goto cleanup;
7027
        }
7028
7029
        /* This PSK works, no need to try any more. */
7030
        current->chosen = 1;
7031
        ext->resp = 1;
7032
        break;
7033
    }
7034
7035
    if (current == NULL) {
7036
        ret = 0;
7037
        goto cleanup;
7038
    }
7039
7040
    *first = (current == ext->data);
7041
    *usingPSK = 1;
7042
7043
cleanup:
7044
    ForceZero(binderKey, sizeof(binderKey));
7045
    ForceZero(binder, sizeof(binder));
7046
#ifdef WOLFSSL_CHECK_MEM_ZERO
7047
    wc_MemZero_Check(binderKey, sizeof(binderKey));
7048
#endif
7049
    WOLFSSL_LEAVE("DoPreSharedKeys", ret);
7050
7051
    return ret;
7052
}
7053
7054
/* Check whether a PSK may be used given the key exchange modes the client
7055
 * advertised and the modes this server is configured to allow.
7056
 *
7057
 * RFC 9846 Section 4.3.9 forbids selecting a mode the client did not list.
7058
 * Section 4.3.11 says a server that finds no acceptable PSK should perform a
7059
 * non-PSK handshake instead of aborting. Deciding before a PSK is selected
7060
 * leaves nothing to unwind: no ticket is decrypted, no binder is verified, no
7061
 * secret is derived and no early data is accepted.
7062
 *
7063
 * The configured policy is read, not ssl->options.noPskDheKe, which also
7064
 * carries negotiated state and is cleared by every certificate handshake.
7065
 *
7066
 * ssl         SSL/TLS object.
7067
 * clSuites    Client's cipher suite list.
7068
 * returns 1 when PSK selection may proceed and 0 when the PSK must be ignored.
7069
 */
7070
static int PskModesUsable(const WOLFSSL* ssl, const Suites* clSuites)
7071
{
7072
#ifdef HAVE_SUPPORTED_CURVES
7073
    TLSX*  ext;
7074
    word32 modes;
7075
7076
    /* Offering pre_shared_key without psk_key_exchange_modes is a MUST-level
7077
     * abort (Section 4.3.9). Leave it to CheckPreSharedKeys. */
7078
    ext = TLSX_Find(ssl->extensions, TLSX_PSK_KEY_EXCHANGE_MODES);
7079
    if (ext == NULL)
7080
        return 1;
7081
    modes = ext->val;
7082
7083
#ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
7084
    /* RFC 9973 requires psk_dhe_ke and overrides the no-(EC)DHE policy, so a
7085
     * mismatch must abort rather than fall back. */
7086
    if (TLSX_Find(ssl->extensions, TLSX_CERT_WITH_EXTERN_PSK) != NULL)
7087
        return 1;
7088
#endif
7089
7090
    /* Only decline when a certificate handshake can actually run instead.
7091
     * These are the same two things DoTls13ClientHello() requires of a
7092
     * ClientHello that negotiates no PSK. */
7093
    if (TLSX_Find(ssl->extensions, TLSX_KEY_SHARE) == NULL)
7094
        return 1;
7095
    if (clSuites == NULL || clSuites->hashSigAlgoSz == 0)
7096
        return 1;
7097
7098
    if ((modes & (1 << PSK_DHE_KE)) != 0 && !ssl->options.noPskDheKePolicy)
7099
        return 1;
7100
    if (ssl->options.onlyPskDheKe)
7101
        return 0;
7102
    return (modes & (1 << PSK_KE)) != 0;
7103
#else
7104
    /* Without (EC)DHE there is no certificate handshake to fall back to. */
7105
    (void)ssl;
7106
    (void)clSuites;
7107
    return 1;
7108
#endif
7109
}
7110
7111
/* Handle any Pre-Shared Key (PSK) extension.
7112
 * Must do this in ClientHello as it requires a hash of the truncated message.
7113
 * Don't know size of binders until Pre-Shared Key extension has been parsed.
7114
 *
7115
 * ssl         SSL/TLS object.
7116
 * input       ClientHello message.
7117
 * helloSz     Size of the ClientHello message (including binders if present).
7118
 * clSuites    Client's cipher suite list.
7119
 * usingPSK    Indicates handshake is using Pre-Shared Keys.
7120
 */
7121
static int CheckPreSharedKeys(WOLFSSL* ssl, const byte* input, word32 helloSz,
7122
                              Suites* clSuites, int* usingPSK)
7123
{
7124
    int    ret;
7125
    TLSX*  ext;
7126
    word16 bindersLen;
7127
    int    first = 0;
7128
    int    usePsk;
7129
#ifndef WOLFSSL_PSK_ONE_ID
7130
    int    i;
7131
    const Suites* suites;
7132
#else
7133
    byte   suite[2];
7134
#endif
7135
7136
    WOLFSSL_ENTER("CheckPreSharedKeys");
7137
7138
    ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
7139
    if (ext == NULL) {
7140
#ifdef WOLFSSL_EARLY_DATA
7141
        ssl->earlyData = no_early_data;
7142
#endif
7143
        if (usingPSK)
7144
            *usingPSK = 0;
7145
7146
        /* No PSK extension at all: if a mandatory external PSK is configured,
7147
         * refuse the connection rather than continue without one. havePSK is
7148
         * only set by an external-PSK callback, so a peer relying solely on
7149
         * session-ticket resumption is unaffected. */
7150
        if (ssl->options.havePSK && ssl->options.failNoPSK) {
7151
            WOLFSSL_ERROR_VERBOSE(PSK_MISSING_ERROR);
7152
            return PSK_MISSING_ERROR;
7153
        }
7154
7155
        /* Hash data up to binders for deriving binders in PSK extension. */
7156
        ret = HashInput(ssl, input,  (int)helloSz);
7157
        return ret;
7158
    }
7159
7160
    /* Wire-order check that PSK was the last extension in ClientHello is
7161
     * performed in DoTls13ClientHello immediately after TLSX_Parse, since
7162
     * post-parse code (e.g. ALPN_Select via TLSX_SetALPN) may legitimately
7163
     * prepend new entries to ssl->extensions before this point and would
7164
     * otherwise trip a head-of-list check here. */
7165
7166
    /* Assume we are going to resume with a pre-shared key. */
7167
    ssl->options.resuming = 1;
7168
7169
    /* Find the pre-shared key extension and calculate hash of truncated
7170
     * ClientHello for binders.
7171
     */
7172
    ret = TLSX_PreSharedKey_GetSizeBinders((PreSharedKey*)ext->data,
7173
                                                     client_hello, &bindersLen);
7174
    if (ret < 0)
7175
        return ret;
7176
    if (bindersLen > helloSz)
7177
        return BUFFER_ERROR;
7178
7179
    /* Refine list for PSK processing. */
7180
    sslRefineSuites(ssl, clSuites);
7181
7182
    usePsk = PskModesUsable(ssl, clSuites);
7183
    if (!usePsk) {
7184
        WOLFSSL_MSG("No usable psk_key_exchange_modes, ignoring PSK");
7185
    }
7186
7187
#ifndef WOLFSSL_PSK_ONE_ID
7188
    if (usingPSK == NULL)
7189
        return BAD_FUNC_ARG;
7190
7191
    /* set after refineSuites, to avoid taking a stale ptr to ctx->Suites */
7192
    suites = WOLFSSL_SUITES(ssl);
7193
    /* Server list has only common suites from refining in server or client
7194
     * order. */
7195
    for (i = 0; usePsk && !(*usingPSK) && i < suites->suiteSz; i += 2) {
7196
        ret = DoPreSharedKeys(ssl, input, helloSz - bindersLen,
7197
                suites->suites + i, usingPSK, &first);
7198
        if (ret != 0) {
7199
#ifdef HAVE_SESSION_TICKET
7200
#ifdef WOLFSSL_ASYNC_CRYPT
7201
            if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
7202
#endif
7203
                CleanupClientTickets((PreSharedKey*)ext->data);
7204
#endif
7205
            WOLFSSL_MSG_EX("DoPreSharedKeys: %d", ret);
7206
            return ret;
7207
        }
7208
    }
7209
#ifdef HAVE_SESSION_TICKET
7210
    CleanupClientTickets((PreSharedKey*)ext->data);
7211
#endif
7212
#else
7213
    if (usePsk) {
7214
        ret = DoPreSharedKeys(ssl, input, helloSz - bindersLen, suite, usingPSK,
7215
            &first);
7216
        if (ret != 0) {
7217
            WOLFSSL_MSG_EX("DoPreSharedKeys: %d", ret);
7218
            return ret;
7219
        }
7220
    }
7221
#endif
7222
7223
    if (!*usingPSK) {
7224
        /* No suitable PSK was negotiated. When a mandatory external PSK is
7225
         * configured, fail with a dedicated error instead of falling back to a
7226
         * certificate handshake. This must run before the no-certificate
7227
         * BAD_BINDER check below so a PSK-only server (no cert) still reports
7228
         * PSK_MISSING_ERROR. havePSK is only set by an external-PSK callback, so
7229
         * a peer relying solely on session-ticket resumption is unaffected. */
7230
        if (ssl->options.havePSK && ssl->options.failNoPSK) {
7231
            WOLFSSL_ERROR_VERBOSE(PSK_MISSING_ERROR);
7232
            return PSK_MISSING_ERROR;
7233
        }
7234
    #ifndef NO_CERTS
7235
        if (ssl->buffers.certificate == NULL
7236
        #ifdef WOLFSSL_CERT_SETUP_CB
7237
                && ssl->ctx->certSetupCb == NULL
7238
        #endif
7239
                )
7240
    #endif
7241
        {
7242
            /* Reused for identity protection: an unknown identity must look
7243
             * like a bad binder, so keep the error code shared. */
7244
            WOLFSSL_ERROR_VERBOSE(BAD_BINDER);
7245
            return BAD_BINDER;
7246
        }
7247
    }
7248
7249
    if (*usingPSK) {
7250
        /* While verifying the selected PSK, we updated the
7251
         * handshake hash up to the binder bytes in the PSK extensions.
7252
         * Continuing, we need the rest of the ClientHello hashed as well.
7253
         */
7254
        ret = HashRaw(ssl, input + helloSz - bindersLen, bindersLen);
7255
    }
7256
    else {
7257
        /* No suitable PSK found, Hash the complete ClientHello,
7258
         * as caller expect it after we return */
7259
        ret = HashInput(ssl, input,  (int)helloSz);
7260
    }
7261
    if (ret != 0)
7262
        return ret;
7263
7264
    if (*usingPSK != 0) {
7265
        word32 modes;
7266
#ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
7267
        int usingCertWithExternPsk = 0;
7268
        TLSX* certExt = NULL;
7269
        TLSX* pskExt = NULL;
7270
        PreSharedKey* chosenPsk = NULL;
7271
#endif
7272
    #ifdef WOLFSSL_EARLY_DATA
7273
        TLSX*  extEarlyData;
7274
    #ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
7275
        int hasCertWithExternPsk = (TLSX_Find(ssl->extensions,
7276
                                    TLSX_CERT_WITH_EXTERN_PSK) != NULL);
7277
    #endif
7278
7279
        extEarlyData = TLSX_Find(ssl->extensions, TLSX_EARLY_DATA);
7280
        if (extEarlyData != NULL) {
7281
            /* Check if accepting early data and first PSK.
7282
             * RFC 9973: early_data is not compatible with
7283
             * cert_with_extern_psk, so skip key derivation in that case. */
7284
            if (ssl->earlyData != no_early_data && first
7285
                && ssl->options.maxEarlyDataSz > 0
7286
    #ifdef HAVE_SESSION_TICKET
7287
                /* RFC 8446 section 8.2: freshly started servers should
7288
                 * reject 0-RTT. Tickets minted before this ctx was created
7289
                 * belong to a previous instance. */
7290
                && !ssl->options.ticketPredatesCtx
7291
    #endif
7292
    #ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
7293
                && !hasCertWithExternPsk
7294
    #endif
7295
    #if defined(HAVE_SESSION_TICKET) && !defined(NO_SESSION_CACHE)
7296
                /* RFC 8446 section 8: evict the session from the cache.
7297
                 * Accept 0-RTT only when the eviction found the entry
7298
                 * (single-use). */
7299
                && wolfSSL_SSL_CTX_remove_session(ssl->ctx, ssl->session)
7300
                    == 1
7301
    #endif
7302
            ) {
7303
                extEarlyData->resp = 1;
7304
7305
                /* Derive early data decryption key. */
7306
                ret = DeriveTls13Keys(ssl, early_data_key, DECRYPT_SIDE_ONLY,
7307
                                                                             1);
7308
                if (ret != 0)
7309
                    return ret;
7310
                if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0)
7311
                    return ret;
7312
7313
                ssl->keys.encryptionOn = 1;
7314
                ssl->earlyData = process_early_data;
7315
            }
7316
            else
7317
                extEarlyData->resp = 0;
7318
        }
7319
    #endif
7320
7321
        /* Get the PSK key exchange modes the client wants to negotiate. */
7322
        ext = TLSX_Find(ssl->extensions, TLSX_PSK_KEY_EXCHANGE_MODES);
7323
        if (ext == NULL) {
7324
            WOLFSSL_ERROR_VERBOSE(MISSING_HANDSHAKE_DATA);
7325
            return MISSING_HANDSHAKE_DATA;
7326
        }
7327
        modes = ext->val;
7328
7329
    #ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
7330
        certExt = TLSX_Find(ssl->extensions, TLSX_CERT_WITH_EXTERN_PSK);
7331
        if (certExt != NULL) {
7332
            pskExt = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
7333
            if (pskExt != NULL)
7334
                chosenPsk = (PreSharedKey*)pskExt->data;
7335
            while (chosenPsk != NULL && !chosenPsk->chosen)
7336
                chosenPsk = chosenPsk->next;
7337
            if (chosenPsk == NULL || chosenPsk->resumption) {
7338
                WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
7339
                return PSK_KEY_ERROR;
7340
            }
7341
            if ((modes & (1 << PSK_DHE_KE)) == 0) {
7342
                WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
7343
                return PSK_KEY_ERROR;
7344
            }
7345
            usingCertWithExternPsk = 1;
7346
            ssl->options.certWithExternPsk = 1;
7347
            if (clSuites->hashSigAlgoSz == 0) {
7348
                WOLFSSL_ERROR_VERBOSE(MISSING_HANDSHAKE_DATA);
7349
                return MISSING_HANDSHAKE_DATA;
7350
            }
7351
            ret = PickHashSigAlgo(ssl, clSuites->hashSigAlgo,
7352
                                  clSuites->hashSigAlgoSz, 1);
7353
            if (ret != 0)
7354
                return ret;
7355
            ssl->options.sendVerify = SEND_CERT;
7356
            certExt->resp = 1;
7357
        #ifdef WOLFSSL_EARLY_DATA
7358
            /* RFC 9973: early_data is not compatible with
7359
             * cert_with_extern_psk.  TLSX_Parse already rejects the
7360
             * combination in the ClientHello, but clear the response flag
7361
             * here as a defense-in-depth measure. */
7362
            if (extEarlyData != NULL) {
7363
                WOLFSSL_MSG("Rejecting early data: "
7364
                            "cert_with_extern_psk is not 0-RTT compatible");
7365
                extEarlyData->resp = 0;
7366
                ssl->earlyData = no_early_data;
7367
            }
7368
        #endif
7369
        }
7370
        else {
7371
            ssl->options.certWithExternPsk = 0;
7372
        }
7373
    #endif
7374
7375
#ifndef HAVE_SUPPORTED_CURVES
7376
    #ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
7377
        if (usingCertWithExternPsk) {
7378
            WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
7379
            return PSK_KEY_ERROR;
7380
        }
7381
    #endif
7382
#endif
7383
    #ifdef HAVE_SUPPORTED_CURVES
7384
        ext = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
7385
        /* Use (EC)DHE for forward-security if possible. */
7386
        if (((modes & (1 << PSK_DHE_KE)) != 0 &&
7387
             !ssl->options.noPskDheKePolicy && ext != NULL)
7388
#ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
7389
             || usingCertWithExternPsk
7390
#endif
7391
        ) {
7392
            if (ext == NULL) {
7393
                WOLFSSL_ERROR_VERBOSE(EXT_MISSING);
7394
                return EXT_MISSING;
7395
            }
7396
            /* Resumption path uses previous session group. */
7397
#ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
7398
            if (!usingCertWithExternPsk)
7399
#endif
7400
                ssl->namedGroup = ssl->session->namedGroup;
7401
            *usingPSK = 2; /* generate new ephemeral key */
7402
        }
7403
        else if (ssl->options.onlyPskDheKe ||
7404
                 (ssl->options.failNoPSK && !ssl->options.resuming)) {
7405
            /* A mandatory external PSK (failNoPSK) must be combined with
7406
             * (EC)DHE for forward secrecy, so reject a pure psk_ke
7407
             * negotiation. Session-ticket resumption is exempt.
7408
             * onlyPskDheKe only reaches here when PskModesUsable() could not
7409
             * decline, i.e. there is no certificate handshake to fall back
7410
             * to. */
7411
            WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
7412
            return PSK_KEY_ERROR;
7413
        }
7414
        else
7415
    #endif
7416
        {
7417
            if ((modes & (1 << PSK_KE)) == 0) {
7418
                WOLFSSL_MSG("psk_ke mode does not allow key share");
7419
                WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
7420
                return PSK_KEY_ERROR;
7421
            }
7422
            ssl->options.noPskDheKe = 1;
7423
            ssl->arrays->preMasterSz = 0;
7424
7425
            *usingPSK = 1;
7426
        }
7427
    }
7428
    else {
7429
#ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
7430
        /* If no PSK is found, we remove the extension to make sure it
7431
         * is not sent back to the client */
7432
        TLSX_Remove(&ssl->extensions, TLSX_CERT_WITH_EXTERN_PSK, ssl->heap);
7433
        ssl->options.certWithExternPsk = 0;
7434
#endif
7435
        /* No PSK negotiated; the check above already aborted when there is no
7436
         * certificate. Fall through so the trace is emitted here too. */
7437
    }
7438
7439
    WOLFSSL_LEAVE("CheckPreSharedKeys", ret);
7440
7441
    return 0;
7442
}
7443
#endif /* HAVE_SESSION_TICKET || !NO_PSK */
7444
7445
#if defined(WOLFSSL_SEND_HRR_COOKIE)
7446
/* Compute the cookie integrity HMAC over the cookie data (and, for DTLS, the
7447
 * peer address) using the given secret and compare it in constant time against
7448
 * the MAC trailing the cookie.
7449
 *
7450
 * ssl        SSL/TLS object.
7451
 * cookie     The cookie data - hash and MAC.
7452
 * dataSz     Length of the cookie data preceding the trailing MAC.
7453
 * secret     Secret to key the HMAC with.
7454
 * secretSz   Length of the secret in bytes.
7455
 * cookieType Digest type to use for the HMAC.
7456
 * macSz      Length of the MAC in bytes.
7457
 * returns 0 on match, HRR_COOKIE_ERROR on mismatch, otherwise a negative error.
7458
 */
7459
static int TlsCheckCookieMac(const WOLFSSL* ssl, const byte* cookie,
7460
    word16 dataSz, const byte* secret, word32 secretSz, byte cookieType,
7461
    byte macSz)
7462
{
7463
    int  ret;
7464
    byte mac[WC_MAX_DIGEST_SIZE] = {0};
7465
    WC_DECLARE_VAR(cookieHmac, Hmac, 1, ssl->heap);
7466
7467
    WC_ALLOC_VAR_EX(cookieHmac, Hmac, 1, ssl->heap, DYNAMIC_TYPE_HMAC,
7468
                    return MEMORY_E);
7469
7470
    ret = wc_HmacInit(cookieHmac, ssl->heap, ssl->devId);
7471
    if (ret == 0)
7472
        ret = wc_HmacSetKey(cookieHmac, cookieType, secret, secretSz);
7473
    if (ret == 0)
7474
        ret = wc_HmacUpdate(cookieHmac, cookie, dataSz);
7475
#ifdef WOLFSSL_DTLS13
7476
    /* Tie cookie to peer address */
7477
    if (ret == 0) {
7478
        /* peerLock not necessary. Still in handshake phase. */
7479
        if (ssl->options.dtls && ssl->buffers.dtlsCtx.peer.sz > 0) {
7480
            ret = wc_HmacUpdate(cookieHmac,
7481
                (byte*)ssl->buffers.dtlsCtx.peer.sa,
7482
                ssl->buffers.dtlsCtx.peer.sz);
7483
        }
7484
    }
7485
#endif
7486
    if (ret == 0)
7487
        ret = wc_HmacFinal(cookieHmac, mac);
7488
7489
    wc_HmacFree(cookieHmac);
7490
    WC_FREE_VAR_EX(cookieHmac, ssl->heap, DYNAMIC_TYPE_HMAC);
7491
    if (ret != 0)
7492
        return ret;
7493
7494
    if (ConstantCompare(cookie + dataSz, mac, macSz) != 0)
7495
        return HRR_COOKIE_ERROR;
7496
7497
    return 0;
7498
}
7499
7500
/* Check that the Cookie data's integrity.
7501
 *
7502
 * ssl       SSL/TLS object.
7503
 * cookie    The cookie data - hash and MAC.
7504
 * cookieSz  The length of the cookie data in bytes.
7505
 * returns Length of the hash on success, otherwise failure.
7506
 */
7507
int TlsCheckCookie(const WOLFSSL* ssl, const byte* cookie, word16 cookieSz)
7508
{
7509
    int  ret;
7510
    byte cookieType = 0;
7511
    byte macSz = 0;
7512
7513
#ifndef NO_SHA256
7514
    cookieType = WC_SHA256;
7515
    macSz = WC_SHA256_DIGEST_SIZE;
7516
#elif defined(WOLFSSL_SHA384)
7517
    cookieType = WC_SHA384;
7518
    macSz = WC_SHA384_DIGEST_SIZE;
7519
#elif defined(WOLFSSL_TLS13_SHA512)
7520
    cookieType = WC_SHA512;
7521
    macSz = WC_SHA512_DIGEST_SIZE;
7522
#elif defined(WOLFSSL_SM3)
7523
    cookieType = WC_SM3;
7524
    macSz = WC_SM3_DIGEST_SIZE;
7525
#else
7526
    #error "No digest to available to use with HMAC for cookies."
7527
#endif /* NO_SHA */
7528
7529
    if ((ssl->buffers.tls13CookieSecret.buffer == NULL ||
7530
            ssl->buffers.tls13CookieSecret.length == 0)
7531
#ifdef WOLFSSL_DTLS13
7532
        && (ssl->buffers.tls13CookieSecretSecondary.buffer == NULL ||
7533
            ssl->buffers.tls13CookieSecretSecondary.length == 0)
7534
#endif
7535
        ) {
7536
        WOLFSSL_MSG("Missing DTLS 1.3 cookie secret");
7537
        return COOKIE_ERROR;
7538
    }
7539
7540
    if (cookieSz < ssl->specs.hash_size + macSz)
7541
        return HRR_COOKIE_ERROR;
7542
    cookieSz -= macSz;
7543
7544
    /* Verify against the primary secret first.  If that fails and a secondary
7545
     * (verify-only) secret is configured, try that too.  This lets a stateless
7546
     * DTLS 1.3 server keep accepting cookies issued under the secret it held
7547
     * before an application-driven secret rotation.  The secondary secret is
7548
     * DTLS 1.3 only, so its verify path is compiled in only for WOLFSSL_DTLS13. */
7549
    ret = WC_NO_ERR_TRACE(HRR_COOKIE_ERROR);
7550
    if (ssl->buffers.tls13CookieSecret.buffer != NULL &&
7551
            ssl->buffers.tls13CookieSecret.length > 0) {
7552
        ret = TlsCheckCookieMac(ssl, cookie, cookieSz,
7553
            ssl->buffers.tls13CookieSecret.buffer,
7554
            ssl->buffers.tls13CookieSecret.length, cookieType, macSz);
7555
        if (ret != 0 && ret != WC_NO_ERR_TRACE(HRR_COOKIE_ERROR))
7556
            return ret;
7557
    }
7558
#ifdef WOLFSSL_DTLS13
7559
    if (ret == WC_NO_ERR_TRACE(HRR_COOKIE_ERROR) &&
7560
            ssl->buffers.tls13CookieSecretSecondary.buffer != NULL &&
7561
            ssl->buffers.tls13CookieSecretSecondary.length > 0) {
7562
        ret = TlsCheckCookieMac(ssl, cookie, cookieSz,
7563
            ssl->buffers.tls13CookieSecretSecondary.buffer,
7564
            ssl->buffers.tls13CookieSecretSecondary.length, cookieType, macSz);
7565
        if (ret != 0 && ret != WC_NO_ERR_TRACE(HRR_COOKIE_ERROR))
7566
            return ret;
7567
    }
7568
#endif
7569
7570
    if (ret != 0) {
7571
        WOLFSSL_ERROR_VERBOSE(HRR_COOKIE_ERROR);
7572
        return HRR_COOKIE_ERROR;
7573
    }
7574
7575
    return cookieSz;
7576
}
7577
7578
/* Length of the KeyShare Extension */
7579
#define HRR_KEY_SHARE_SZ   (OPAQUE16_LEN + OPAQUE16_LEN + OPAQUE16_LEN)
7580
/* Length of the Supported Versions Extension */
7581
#define HRR_VERSIONS_SZ    (OPAQUE16_LEN + OPAQUE16_LEN + OPAQUE16_LEN)
7582
/* Length of the Cookie Extension excluding cookie data */
7583
#define HRR_COOKIE_HDR_SZ  (OPAQUE16_LEN + OPAQUE16_LEN + OPAQUE16_LEN)
7584
/* PV | Random | Session Id | CipherSuite | Compression | Ext Len */
7585
#define HRR_BODY_SZ        (VERSION_SZ + RAN_LEN + ENUM_LEN + ID_LEN + \
7586
                            SUITE_LEN + COMP_LEN + OPAQUE16_LEN)
7587
/* HH | PV | CipherSuite | Ext Len | Key Share | Supported Version | Cookie */
7588
#define MAX_HRR_SZ   (HRR_MAX_HS_HEADER_SZ   + \
7589
                        HRR_BODY_SZ         + \
7590
                          HRR_KEY_SHARE_SZ  + \
7591
                          HRR_VERSIONS_SZ   + \
7592
                          HRR_COOKIE_HDR_SZ)
7593
7594
7595
/* Restart the handshake hash from the cookie value.
7596
 *
7597
 * ssl     SSL/TLS object.
7598
 * cookie  Cookie data from client.
7599
 * returns 0 on success, otherwise failure.
7600
 */
7601
static int RestartHandshakeHashWithCookie(WOLFSSL* ssl, Cookie* cookie)
7602
{
7603
    byte   header[HANDSHAKE_HEADER_SZ] = {0};
7604
    byte   hrr[MAX_HRR_SZ] = {0};
7605
    int    hrrIdx;
7606
    word32 idx;
7607
    byte   hashSz;
7608
    byte*  cookieData;
7609
    word16 cookieDataSz;
7610
    word16 length;
7611
    int    keyShareExt = 0;
7612
    int    ret;
7613
    byte   sessIdSz;
7614
7615
    ret = TlsCheckCookie(ssl, cookie->data, cookie->len);
7616
    if (ret < 0)
7617
        return ret;
7618
    cookieDataSz = (word16)ret;
7619
    hashSz = cookie->data[0];
7620
    cookieData = cookie->data;
7621
    idx = OPAQUE8_LEN;
7622
7623
    /* Restart handshake hash with synthetic message hash. */
7624
    AddTls13HandShakeHeader(header, hashSz, 0, 0, message_hash, ssl);
7625
7626
    if ((ret = InitHandshakeHashes(ssl)) != 0)
7627
        return ret;
7628
    if ((ret = HashRaw(ssl, header, sizeof(header))) != 0)
7629
        return ret;
7630
#ifdef WOLFSSL_DEBUG_TLS
7631
    WOLFSSL_MSG("Restart Hash from Cookie");
7632
    WOLFSSL_BUFFER(cookieData + idx, hashSz);
7633
#endif
7634
    if ((ret = HashRaw(ssl, cookieData + idx, hashSz)) != 0)
7635
        return ret;
7636
7637
    /* Reconstruct the HelloRetryMessage for handshake hash. */
7638
    sessIdSz = ssl->session->sessionIDSz;
7639
#if defined(WOLFSSL_DTLS13) && !defined(WOLFSSL_DTLS13_ECHO_LEGACY_SESSION_ID)
7640
    /* RFC 9147 Section 5: a DTLS 1.3 server does not echo the session ID, so
7641
     * the reconstructed transcript must not carry one either. */
7642
    if (ssl->options.dtls)
7643
        sessIdSz = 0;
7644
#endif
7645
    length = HRR_BODY_SZ - ID_LEN + sessIdSz +
7646
             HRR_COOKIE_HDR_SZ + cookie->len;
7647
    length += HRR_VERSIONS_SZ;
7648
    /* HashSz (1 byte) + Hash (HashSz bytes) + CipherSuite (2 bytes) */
7649
    if (cookieDataSz > OPAQUE8_LEN + hashSz + OPAQUE16_LEN) {
7650
        keyShareExt = 1;
7651
        length += HRR_KEY_SHARE_SZ;
7652
    }
7653
7654
    AddTls13HandShakeHeader(hrr, length, 0, 0, server_hello, ssl);
7655
7656
    idx += hashSz;
7657
    hrrIdx = HANDSHAKE_HEADER_SZ;
7658
7659
#ifdef WOLFSSL_DTLS13
7660
    if (ssl->options.dtls)
7661
        hrrIdx += DTLS_HANDSHAKE_EXTRA;
7662
#endif /* WOLFSSL_DTLS13 */
7663
7664
    /* The negotiated protocol version. */
7665
    hrr[hrrIdx++] = ssl->version.major;
7666
    hrr[hrrIdx++] = ssl->options.dtls ? DTLSv1_2_MINOR : TLSv1_2_MINOR;
7667
7668
    /* HelloRetryRequest message has fixed value for random. */
7669
    XMEMCPY(hrr + hrrIdx, helloRetryRequestRandom, RAN_LEN);
7670
    hrrIdx += RAN_LEN;
7671
7672
    hrr[hrrIdx++] = sessIdSz;
7673
    if (sessIdSz > 0) {
7674
        XMEMCPY(hrr + hrrIdx, ssl->session->sessionID, sessIdSz);
7675
        hrrIdx += sessIdSz;
7676
    }
7677
7678
    /* Restore the cipher suite from the cookie. */
7679
    ssl->options.hrrCipherSuite0 = cookieData[idx];
7680
    hrr[hrrIdx++] = cookieData[idx++];
7681
    ssl->options.hrrCipherSuite  = cookieData[idx];
7682
    hrr[hrrIdx++] = cookieData[idx++];
7683
7684
    /* Compression not supported in TLS v1.3. */
7685
    hrr[hrrIdx++] = 0;
7686
7687
    /* Extensions' length */
7688
    length -= HRR_BODY_SZ - ID_LEN + sessIdSz;
7689
    c16toa(length, hrr + hrrIdx);
7690
    hrrIdx += 2;
7691
7692
    /* Optional KeyShare Extension */
7693
    if (keyShareExt) {
7694
        c16toa(TLSX_KEY_SHARE, hrr + hrrIdx);
7695
        hrrIdx += 2;
7696
        c16toa(OPAQUE16_LEN, hrr + hrrIdx);
7697
        hrrIdx += 2;
7698
        /* Restore the HRR key share group from the cookie. */
7699
        ato16(cookieData + idx, &ssl->hrr_keyshare_group);
7700
        hrr[hrrIdx++] = cookieData[idx++];
7701
        hrr[hrrIdx++] = cookieData[idx++];
7702
    }
7703
    c16toa(TLSX_SUPPORTED_VERSIONS, hrr + hrrIdx);
7704
    hrrIdx += 2;
7705
    c16toa(OPAQUE16_LEN, hrr + hrrIdx);
7706
    hrrIdx += 2;
7707
    #ifdef WOLFSSL_TLS13_DRAFT
7708
        hrr[hrrIdx++] = TLS_DRAFT_MAJOR;
7709
        hrr[hrrIdx++] = TLS_DRAFT_MINOR;
7710
    #else
7711
        hrr[hrrIdx++] = ssl->version.major;
7712
        hrr[hrrIdx++] = ssl->version.minor;
7713
    #endif
7714
7715
    /* Mandatory Cookie Extension */
7716
    c16toa(TLSX_COOKIE, hrr + hrrIdx);
7717
    hrrIdx += 2;
7718
    c16toa(cookie->len + OPAQUE16_LEN, hrr + hrrIdx);
7719
    hrrIdx += 2;
7720
    c16toa(cookie->len, hrr + hrrIdx);
7721
    hrrIdx += 2;
7722
7723
#ifdef WOLFSSL_DEBUG_TLS
7724
    WOLFSSL_MSG("Reconstructed HelloRetryRequest");
7725
    WOLFSSL_BUFFER(hrr, hrrIdx);
7726
    WOLFSSL_MSG("Cookie");
7727
    WOLFSSL_BUFFER(cookieData, cookie->len);
7728
#endif
7729
7730
#ifdef WOLFSSL_DTLS13
7731
    if (ssl->options.dtls) {
7732
        ret = Dtls13HashHandshake(ssl, hrr, (word16)hrrIdx);
7733
    }
7734
    else
7735
#endif /* WOLFSSL_DTLS13 */
7736
        {
7737
            ret = HashRaw(ssl, hrr, hrrIdx);
7738
        }
7739
7740
    if (ret != 0)
7741
        return ret;
7742
7743
    return HashRaw(ssl, cookieData, cookie->len);
7744
}
7745
#endif
7746
7747
/* Do SupportedVersion extension for TLS v1.3+ otherwise it is not.
7748
 *
7749
 * ssl       The SSL/TLS object.
7750
 * input     The message buffer.
7751
 * i         The index into the message buffer of ClientHello.
7752
 * helloSz   The length of the current handshake message.
7753
 * returns 0 on success and otherwise failure.
7754
 */
7755
static int DoTls13SupportedVersions(WOLFSSL* ssl, const byte* input, word32 i,
7756
                                    word32 helloSz, int* wantDowngrade)
7757
0
{
7758
0
    int    ret;
7759
0
    byte   b;
7760
0
    word16 suiteSz;
7761
0
    word16 totalExtSz;
7762
0
    int    foundVersion = 0;
7763
7764
    /* Client random */
7765
0
    i += RAN_LEN;
7766
7767
0
    if (i > helloSz)
7768
0
        return BUFFER_ERROR;
7769
    /* Session id - not used in TLS v1.3 */
7770
0
    if (helloSz - i < OPAQUE8_LEN) {
7771
0
        return BUFFER_ERROR;
7772
0
    }
7773
0
    b = input[i++];
7774
0
    if (b > helloSz - i) {
7775
0
        return BUFFER_ERROR;
7776
0
    }
7777
0
    i += b;
7778
#ifdef WOLFSSL_DTLS13
7779
    if (ssl->options.dtls) {
7780
        /* legacy_cookie - not used in DTLS v1.3 */
7781
        if (helloSz - i < OPAQUE8_LEN) {
7782
            return BUFFER_ERROR;
7783
        }
7784
        b = input[i++];
7785
        if (b > helloSz - i) {
7786
            return BUFFER_ERROR;
7787
        }
7788
        i += b;
7789
    }
7790
#endif /* WOLFSSL_DTLS13 */
7791
    /* Cipher suites */
7792
0
    if (helloSz - i < OPAQUE16_LEN)
7793
0
        return BUFFER_ERROR;
7794
0
    ato16(input + i, &suiteSz);
7795
0
    i += OPAQUE16_LEN;
7796
0
    if ((word32)suiteSz + OPAQUE8_LEN > helloSz - i)
7797
0
        return BUFFER_ERROR;
7798
0
    i += suiteSz;
7799
    /* Compression */
7800
0
    b = input[i++];
7801
0
    if (b > helloSz - i)
7802
0
        return BUFFER_ERROR;
7803
0
    i += b;
7804
7805
    /* TLS 1.3 must have extensions */
7806
0
    if (i < helloSz) {
7807
0
        if (helloSz - i < OPAQUE16_LEN)
7808
0
            return BUFFER_ERROR;
7809
0
        ato16(&input[i], &totalExtSz);
7810
0
        i += OPAQUE16_LEN;
7811
0
        if (totalExtSz != helloSz - i)
7812
0
            return BUFFER_ERROR;
7813
7814
        /* Need to negotiate version first. */
7815
0
        if ((ret = TLSX_ParseVersion(ssl, input + i, totalExtSz, client_hello,
7816
0
                                                              &foundVersion))) {
7817
0
            return ret;
7818
0
        }
7819
0
    }
7820
0
    *wantDowngrade = !foundVersion || !IsAtLeastTLSv1_3(ssl->version);
7821
7822
0
    return 0;
7823
0
}
7824
7825
#ifdef HAVE_ECH
7826
/* Calculate and write the 8 ECH confirmation bytes.
7827
 * Output into confirmation field on HRR and into ServerRandom on ServerHello.
7828
 *
7829
 * ssl          SSL/TLS object.
7830
 * label        Ascii string describing ECH acceptance or rejection.
7831
 * labelSz      Length of label excluding NULL character.
7832
 * output       The buffer to calculate/write confirmation from/to.
7833
 * acceptOffset Where the 8 ECH confirmation bytes should be placed.
7834
 * helloSz      Size of hello message.
7835
 * msgType      Type of message being written.
7836
 * returns 0 on success and otherwise failure.
7837
 */
7838
static int EchWriteAcceptance(WOLFSSL* ssl, byte* label, word16 labelSz,
7839
    byte* output, int acceptOffset, int helloSz, byte msgType)
7840
{
7841
    int ret = 0;
7842
    int headerSz;
7843
    HS_Hashes* tmpHashes;
7844
7845
#ifdef WOLFSSL_DTLS13
7846
    headerSz = ssl->options.dtls ? DTLS13_HANDSHAKE_HEADER_SZ :
7847
                                   HANDSHAKE_HEADER_SZ;
7848
#else
7849
    headerSz = HANDSHAKE_HEADER_SZ;
7850
#endif
7851
7852
    ret = EchCalcAcceptance(ssl, label, labelSz, output, acceptOffset,
7853
            helloSz - headerSz, msgType == hello_retry_request,
7854
            output + acceptOffset);
7855
7856
    if (ret == 0) {
7857
        tmpHashes = ssl->hsHashes;
7858
        ssl->hsHashes = ssl->hsHashesEch;
7859
7860
        /* after HRR, hsHashesEch must contain:
7861
         * message_hash(ClientHelloInner1) || HRR (actual, not zeros) */
7862
        if (msgType == hello_retry_request) {
7863
            ret = HashRaw(ssl, output, helloSz);
7864
        }
7865
        /* normal TLS code will calculate transcript of ServerHello */
7866
        else {
7867
            ssl->hsHashes = tmpHashes;
7868
            FreeHandshakeHashes(ssl);
7869
            tmpHashes = ssl->hsHashesEch;
7870
            ssl->hsHashesEch = NULL;
7871
        }
7872
7873
        ssl->hsHashes = tmpHashes;
7874
    }
7875
7876
    return ret;
7877
}
7878
#endif
7879
7880
/* Handle a ClientHello handshake message.
7881
 * If the protocol version in the message is not TLS v1.3 or higher, use
7882
 * DoClientHello()
7883
 * Only a server will receive this message.
7884
 *
7885
 * ssl       The SSL/TLS object.
7886
 * input     The message buffer.
7887
 * inOutIdx  On entry, the index into the message buffer of ClientHello.
7888
 *           On exit, the index of byte after the ClientHello message and
7889
 *           padding.
7890
 * helloSz   The length of the current handshake message.
7891
 * returns 0 on success and otherwise failure.
7892
 */
7893
7894
typedef struct Dch13Args {
7895
    ProtocolVersion pv;
7896
    word32          idx;
7897
    word32          begin;
7898
    int             usingPSK;
7899
} Dch13Args;
7900
7901
static void FreeDch13Args(WOLFSSL* ssl, void* pArgs)
7902
0
{
7903
    /* openssl compat builds hang on to the client suites until WOLFSSL object
7904
     * is destroyed */
7905
0
#ifndef OPENSSL_EXTRA
7906
0
    if (ssl->clSuites) {
7907
0
        XFREE(ssl->clSuites, ssl->heap, DYNAMIC_TYPE_SUITES);
7908
0
        ssl->clSuites = NULL;
7909
0
    }
7910
0
#endif
7911
0
    (void)ssl;
7912
0
    (void)pArgs;
7913
7914
0
}
7915
7916
int DoTls13ClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
7917
                       word32 helloSz)
7918
0
{
7919
0
    int ret;
7920
#ifdef WOLFSSL_ASYNC_CRYPT
7921
    Dch13Args* args = NULL;
7922
    WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
7923
#else
7924
0
    Dch13Args  args[1];
7925
0
#endif
7926
#if defined(HAVE_ECH)
7927
    TLSX* echX = NULL;
7928
#endif
7929
7930
0
    WOLFSSL_START(WC_FUNC_CLIENT_HELLO_DO);
7931
0
    WOLFSSL_ENTER("DoTls13ClientHello");
7932
7933
#ifdef WOLFSSL_ASYNC_CRYPT
7934
    if (ssl->async == NULL) {
7935
        ssl->async = (struct WOLFSSL_ASYNC*)
7936
                XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
7937
                        DYNAMIC_TYPE_ASYNC);
7938
        if (ssl->async == NULL)
7939
            ERROR_OUT(MEMORY_E, exit_dch);
7940
        /* Zeroed so the mid-flight resume test below can never route into
7941
         * uninitialised args. */
7942
        XMEMSET(ssl->async, 0, sizeof(struct WOLFSSL_ASYNC));
7943
    }
7944
    args = (Dch13Args*)ssl->async->args;
7945
7946
    ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
7947
    if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) {
7948
        /* Check for error */
7949
        if (ret < 0) {
7950
            goto exit_dch;
7951
        }
7952
    }
7953
    else if (ssl->options.asyncState > TLS_ASYNC_BEGIN &&
7954
             ssl->options.asyncState < TLS_ASYNC_END) {
7955
        /* Mid-flight replay: the event may already be retired but
7956
         * asyncState/args are intact, so resume; resetting would hash the
7957
         * message twice. Fresh ClientHellos arrive at TLS_ASYNC_BEGIN. */
7958
        ret = 0;
7959
    }
7960
    else
7961
#endif
7962
0
    {
7963
        /* Reset state */
7964
0
        ret = WC_NO_ERR_TRACE(VERSION_ERROR);
7965
0
        ssl->options.asyncState = TLS_ASYNC_BEGIN;
7966
0
        XMEMSET(args, 0, sizeof(Dch13Args));
7967
    #ifdef WOLFSSL_ASYNC_CRYPT
7968
        ssl->async->freeArgs = FreeDch13Args;
7969
    #endif
7970
0
    }
7971
7972
0
    switch (ssl->options.asyncState) {
7973
0
    case TLS_ASYNC_BEGIN:
7974
0
    {
7975
0
    byte b;
7976
0
    byte sessIdSz;
7977
0
    int wantDowngrade = 0;
7978
0
    word16 totalExtSz = 0;
7979
7980
#if defined(WOLFSSL_DTLS13) && defined(WOLFSSL_DTLS_CID)
7981
    /* Reset for each ClientHello, including retries and legacy fallbacks. */
7982
    ssl->options.haveSupportedVersions = 0;
7983
#endif
7984
#ifdef WOLFSSL_CALLBACKS
7985
    if (ssl->hsInfoOn) AddPacketName(ssl, "ClientHello");
7986
    if (ssl->toInfoOn) AddLateName("ClientHello", &ssl->timeoutInfo);
7987
#endif
7988
7989
    /* do not change state in the SSL object before the next region of code
7990
     * to be able to statelessly compute a DTLS cookie */
7991
#if defined(WOLFSSL_DTLS13) && defined(WOLFSSL_SEND_HRR_COOKIE)
7992
    /* Update the ssl->options.dtlsStateful setting `if` statement in
7993
     * wolfSSL_accept_TLSv13 when changing this one. */
7994
    if (IsDtlsNotSctpMode(ssl) && ssl->options.sendCookie &&
7995
            !ssl->options.dtlsStateful) {
7996
        DtlsSetSeqNumForReply(ssl);
7997
        ret = DoClientHelloStateless(ssl, input + *inOutIdx, helloSz, 0, NULL);
7998
        if (ret != 0 || !ssl->options.dtlsStateful) {
7999
            *inOutIdx += helloSz;
8000
            goto exit_dch;
8001
        }
8002
        if (ssl->chGoodCb != NULL) {
8003
            int cbret = ssl->chGoodCb(ssl, ssl->chGoodCtx);
8004
            if (cbret < 0) {
8005
                ssl->error = cbret;
8006
                WOLFSSL_MSG("ClientHello Good Cb don't continue error");
8007
                return WOLFSSL_FATAL_ERROR;
8008
            }
8009
        }
8010
    }
8011
    ssl->options.dtlsStateful = 1;
8012
#endif /* WOLFSSL_DTLS */
8013
8014
0
    args->idx = *inOutIdx;
8015
0
    args->begin = args->idx;
8016
8017
    /* protocol version, random and session id length check */
8018
0
    if (OPAQUE16_LEN + RAN_LEN + OPAQUE8_LEN > helloSz) {
8019
0
        ERROR_OUT(BUFFER_ERROR, exit_dch);
8020
0
    }
8021
8022
    /* Protocol version */
8023
0
    XMEMCPY(&args->pv, input + args->idx, OPAQUE16_LEN);
8024
0
    ssl->chVersion = args->pv;   /* store */
8025
0
    args->idx += OPAQUE16_LEN;
8026
8027
8028
    /* this check pass for DTLS Major (0xff) */
8029
0
    if (args->pv.major < SSLv3_MAJOR) {
8030
0
        WOLFSSL_MSG("Legacy version field contains unsupported value");
8031
0
        ERROR_OUT(VERSION_ERROR, exit_dch);
8032
0
    }
8033
8034
#ifdef WOLFSSL_DTLS13
8035
    if (ssl->options.dtls &&
8036
        args->pv.major == DTLS_MAJOR && args->pv.minor > DTLSv1_2_MINOR) {
8037
        wantDowngrade = 1;
8038
        ssl->version.minor = args->pv.minor;
8039
    }
8040
#endif /* WOLFSSL_DTLS13 */
8041
8042
0
    if (!ssl->options.dtls) {
8043
0
#ifndef WOLFSSL_ALLOW_BAD_TLS_LEGACY_VERSION
8044
        /* Check for TLS 1.3 version (0x0304) in legacy version field. RFC 8446
8045
         * Section 4.2.1 allows this action:
8046
         *
8047
         * "Servers MAY abort the handshake upon receiving a ClientHello with
8048
         * legacy_version 0x0304 or later."
8049
         *
8050
         * Note that if WOLFSSL_ALLOW_BAD_TLS_LEGACY_VERSION is defined then the
8051
         * semantics of RFC 5246 Appendix E will be followed. A ServerHello with
8052
         * version 1.2 will be sent. The same is true if TLS 1.3 is not enabled.
8053
         */
8054
0
        if (args->pv.major == SSLv3_MAJOR && args->pv.minor >= TLSv1_3_MINOR) {
8055
0
            WOLFSSL_MSG("Legacy version field is TLS 1.3 or later. Aborting.");
8056
0
            ERROR_OUT(VERSION_ERROR, exit_dch);
8057
0
        }
8058
0
#endif /* WOLFSSL_ALLOW_BAD_TLS_LEGACY_VERSION */
8059
8060
        /* Legacy protocol version cannot negotiate TLS 1.3 or higher. */
8061
0
        if (args->pv.major > SSLv3_MAJOR || (args->pv.major == SSLv3_MAJOR &&
8062
0
                                             args->pv.minor >= TLSv1_3_MINOR)) {
8063
0
            args->pv.major = SSLv3_MAJOR;
8064
0
            args->pv.minor = TLSv1_2_MINOR;
8065
0
            wantDowngrade = 1;
8066
0
            ssl->version.minor = args->pv.minor;
8067
0
        }
8068
        /* Legacy version must be [ SSLv3_MAJOR, TLSv1_2_MINOR ] for TLS v1.3 */
8069
0
        else if (args->pv.major == SSLv3_MAJOR &&
8070
0
                 args->pv.minor < TLSv1_2_MINOR) {
8071
0
            wantDowngrade = 1;
8072
0
            ssl->version.minor = args->pv.minor;
8073
0
        }
8074
0
    }
8075
8076
0
    if (!wantDowngrade) {
8077
0
        ret = DoTls13SupportedVersions(ssl, input + args->begin,
8078
0
            args->idx - args->begin, helloSz, &wantDowngrade);
8079
0
        if (ret < 0)
8080
0
            goto exit_dch;
8081
0
    }
8082
8083
0
    if (wantDowngrade) {
8084
0
#ifndef WOLFSSL_NO_TLS12
8085
0
        byte realMinor;
8086
0
#endif
8087
#if defined(HAVE_ECH)
8088
        if (ssl->options.echProcessingInner) {
8089
            WOLFSSL_MSG("ECH: inner client hello does not support version "
8090
                        "less than TLS v1.3");
8091
            ERROR_OUT(INVALID_PARAMETER, exit_dch);
8092
        }
8093
#endif
8094
0
#ifndef WOLFSSL_NO_TLS12
8095
0
        if (!ssl->options.downgrade) {
8096
0
            WOLFSSL_MSG("Client trying to connect with lesser version than "
8097
0
                        "TLS v1.3");
8098
0
            ERROR_OUT(VERSION_ERROR, exit_dch);
8099
0
        }
8100
8101
0
        if ((!ssl->options.dtls
8102
0
                 && args->pv.minor < ssl->options.minDowngrade) ||
8103
0
            (ssl->options.dtls && args->pv.minor > ssl->options.minDowngrade)) {
8104
0
            WOLFSSL_MSG("\tversion below minimum allowed, fatal error");
8105
0
            ERROR_OUT(VERSION_ERROR, exit_dch);
8106
0
        }
8107
8108
0
        realMinor = ssl->version.minor;
8109
0
        ssl->version.minor = args->pv.minor;
8110
0
        ret = HashInput(ssl, input + args->begin, (int)helloSz);
8111
0
        ssl->version.minor = realMinor;
8112
0
        if (ret == 0) {
8113
0
            ret = DoClientHello(ssl, input, inOutIdx, helloSz);
8114
0
        }
8115
0
        goto exit_dch;
8116
#else
8117
        WOLFSSL_MSG("Client trying to connect with lesser version than "
8118
                    "TLS v1.3");
8119
        ERROR_OUT(VERSION_ERROR, exit_dch);
8120
#endif
8121
0
    }
8122
8123
    /* From here on we are a TLS 1.3 ClientHello. */
8124
8125
    /* Client random
8126
     * ECH Accepted -> This will fill with the innerClientRandom */
8127
0
    XMEMCPY(ssl->arrays->clientRandom, input + args->idx, RAN_LEN);
8128
0
    args->idx += RAN_LEN;
8129
8130
#ifdef WOLFSSL_DEBUG_TLS
8131
    WOLFSSL_MSG("client random");
8132
    WOLFSSL_BUFFER(ssl->arrays->clientRandom, RAN_LEN);
8133
#endif
8134
8135
0
    sessIdSz = input[args->idx++];
8136
0
    if (sessIdSz > ID_LEN)
8137
0
    {
8138
0
        ERROR_OUT(INVALID_PARAMETER, exit_dch);
8139
0
    }
8140
8141
0
    if (sessIdSz + args->idx > helloSz)
8142
0
        ERROR_OUT(BUFFER_ERROR, exit_dch);
8143
8144
#if defined(WOLFSSL_DTLS13) && !defined(WOLFSSL_DTLS13_ECHO_LEGACY_SESSION_ID)
8145
    /* RFC 9147 Section 5: "DTLS servers MUST NOT echo the legacy_session_id
8146
     * value from the client." Don't store it so SendTls13ServerHello can't
8147
     * echo it. */
8148
    if (ssl->options.dtls) {
8149
        ssl->session->sessionIDSz = 0;
8150
    }
8151
    else
8152
#endif
8153
0
    {
8154
0
        ssl->session->sessionIDSz = sessIdSz;
8155
0
        if (sessIdSz > 0)
8156
0
            XMEMCPY(ssl->session->sessionID, input + args->idx, sessIdSz);
8157
0
    }
8158
0
    args->idx += sessIdSz;
8159
8160
    /* RFC 8446 Appendix D.4: server MUST only send CCS if the client's
8161
     * ClientHello contains a non-empty legacy_session_id. An ECH inner hello
8162
     * is rebuilt with the outer session id, so it decides either way. */
8163
0
    if (sessIdSz == 0) {
8164
0
        ssl->options.tls13MiddleBoxCompat = 0;
8165
0
    }
8166
#ifdef WOLFSSL_QUIC
8167
    /* RFC 9001 Section 8.4: QUIC has no compatibility mode to be had. */
8168
    if (WOLFSSL_IS_QUIC(ssl)) {
8169
        ssl->options.tls13MiddleBoxCompat = 0;
8170
    }
8171
#endif
8172
8173
#ifdef WOLFSSL_DTLS13
8174
    /* legacy_cookie */
8175
    if (ssl->options.dtls) {
8176
        word32 rel = args->idx - args->begin;
8177
        byte cookieLen;
8178
        if (rel > helloSz || helloSz - rel < OPAQUE8_LEN)
8179
            ERROR_OUT(BUFFER_ERROR, exit_dch);
8180
        /* https://www.rfc-editor.org/rfc/rfc9147.html#section-5.3 */
8181
        cookieLen = input[args->idx++];
8182
        if (cookieLen != 0) {
8183
            ERROR_OUT(INVALID_PARAMETER, exit_dch);
8184
        }
8185
    }
8186
#endif /* WOLFSSL_DTLS13 */
8187
8188
0
    XFREE(ssl->clSuites, ssl->heap, DYNAMIC_TYPE_SUITES);
8189
0
    ssl->clSuites = (Suites*)XMALLOC(sizeof(Suites), ssl->heap,
8190
0
        DYNAMIC_TYPE_SUITES);
8191
0
    if (ssl->clSuites == NULL) {
8192
0
        ERROR_OUT(MEMORY_E, exit_dch);
8193
0
    }
8194
8195
    /* Cipher suites */
8196
0
    if ((args->idx - args->begin) + OPAQUE16_LEN > helloSz)
8197
0
        ERROR_OUT(BUFFER_ERROR, exit_dch);
8198
0
    ato16(&input[args->idx], &ssl->clSuites->suiteSz);
8199
0
    args->idx += OPAQUE16_LEN;
8200
0
    if ((ssl->clSuites->suiteSz % 2) != 0) {
8201
0
        ERROR_OUT(INVALID_PARAMETER, exit_dch);
8202
0
    }
8203
    /* suites and compression length check */
8204
0
    if ((args->idx - args->begin) + ssl->clSuites->suiteSz + OPAQUE8_LEN >
8205
0
            helloSz) {
8206
0
        ERROR_OUT(BUFFER_ERROR, exit_dch);
8207
0
    }
8208
0
    if (ssl->clSuites->suiteSz > WOLFSSL_MAX_SUITE_SZ)
8209
0
        ERROR_OUT(BUFFER_ERROR, exit_dch);
8210
0
    XMEMCPY(ssl->clSuites->suites, input + args->idx, ssl->clSuites->suiteSz);
8211
0
    args->idx += ssl->clSuites->suiteSz;
8212
0
    ssl->clSuites->hashSigAlgoSz = 0;
8213
0
#if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
8214
    /* Discard any list kept from a previous ClientHello on this object; a
8215
     * second hello that drops signature_algorithms_cert must not inherit it. */
8216
0
    ssl->certHashSigAlgoSz = 0;
8217
0
#endif
8218
8219
    /* Compression */
8220
0
    b = input[args->idx++];
8221
0
    if ((args->idx - args->begin) + b > helloSz)
8222
0
        ERROR_OUT(BUFFER_ERROR, exit_dch);
8223
0
    if (b != COMP_LEN) {
8224
0
        WOLFSSL_MSG("Must be one compression type in list");
8225
0
        ERROR_OUT(INVALID_PARAMETER, exit_dch);
8226
0
    }
8227
0
    b = input[args->idx++];
8228
0
    if (b != NO_COMPRESSION) {
8229
0
        WOLFSSL_MSG("Must be no compression type in list");
8230
0
        ERROR_OUT(INVALID_PARAMETER, exit_dch);
8231
0
    }
8232
8233
    /* Extensions */
8234
0
    if ((args->idx - args->begin) == helloSz)
8235
0
        ERROR_OUT(BUFFER_ERROR, exit_dch);
8236
0
    if ((args->idx - args->begin) + OPAQUE16_LEN > helloSz)
8237
0
        ERROR_OUT(BUFFER_ERROR, exit_dch);
8238
8239
0
    ato16(&input[args->idx], &totalExtSz);
8240
0
    args->idx += OPAQUE16_LEN;
8241
0
    if ((args->idx - args->begin) + totalExtSz > helloSz)
8242
0
        ERROR_OUT(BUFFER_ERROR, exit_dch);
8243
8244
    /* Auto populate extensions supported unless user defined. */
8245
0
    if ((ret = TLSX_PopulateExtensions(ssl, 1)) != 0)
8246
0
        goto exit_dch;
8247
8248
#if defined(HAVE_ECH)
8249
    if (ssl->ctx->echConfigs != NULL && !ssl->options.disableECH) {
8250
        /* save the start of the buffer so we can use it when parsing ech */
8251
        echX = TLSX_Find(ssl->extensions, TLSX_ECH);
8252
8253
        if (echX == NULL)
8254
            ERROR_OUT(WOLFSSL_FATAL_ERROR, exit_dch);
8255
8256
        ((WOLFSSL_ECH*)echX->data)->aad = input + args->begin;
8257
        ((WOLFSSL_ECH*)echX->data)->aadLen = helloSz;
8258
    }
8259
#endif
8260
8261
    /* Parse extensions */
8262
0
    if ((ret = TLSX_Parse(ssl, input + args->idx, totalExtSz, client_hello,
8263
0
                                                            ssl->clSuites))) {
8264
0
        goto exit_dch;
8265
0
    }
8266
8267
0
#if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
8268
0
    SetPeerSha1CertOk(ssl, ssl->clSuites);
8269
0
#endif
8270
8271
#if (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)) && \
8272
    defined(HAVE_TLS_EXTENSIONS)
8273
    /* RFC 8446 Section 4.2.11: the pre_shared_key extension MUST be the
8274
     * last extension in the ClientHello. wolfSSL stores extensions in
8275
     * reverse wire order (TLSX_Push prepends), so a well-formed
8276
     * ClientHello with PSK leaves PSK at the head of ssl->extensions
8277
     * here, before any post-parse code (e.g. ALPN_Select) modifies the
8278
     * list. */
8279
    {
8280
        TLSX* pskExt = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
8281
        if (pskExt != NULL && ssl->extensions != pskExt) {
8282
            WOLFSSL_MSG("pre_shared_key extension was not last in "
8283
                        "ClientHello");
8284
            WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
8285
            ERROR_OUT(PSK_KEY_ERROR, exit_dch);
8286
        }
8287
    }
8288
#endif
8289
8290
#if defined(HAVE_ECH)
8291
    /* ECH accept/reject reconciliation is done at the end of TLSX_Parse. On
8292
     * acceptance the inner hello was decrypted, so jump to exit and let the
8293
     * caller re-invoke with the inner hello. */
8294
    if (!ssl->options.echProcessingInner && echX != NULL &&
8295
            ((WOLFSSL_ECH*)echX->data)->state == ECH_WRITE_NONE &&
8296
            ((WOLFSSL_ECH*)echX->data)->innerClientHello != NULL) {
8297
        goto exit_dch;
8298
    }
8299
#endif
8300
8301
0
#ifdef HAVE_SNI
8302
0
        if ((ret = SNI_Callback(ssl)) != 0)
8303
0
            goto exit_dch;
8304
0
        ssl->options.side = WOLFSSL_SERVER_END;
8305
0
#endif
8306
8307
0
    args->idx += totalExtSz;
8308
0
    ssl->options.haveSessionId = 1;
8309
0
    ssl->options.sendVerify = SEND_CERT;
8310
8311
#if defined(WOLFSSL_SEND_HRR_COOKIE)
8312
    ssl->options.cookieGood = 0;
8313
    if (ssl->options.sendCookie &&
8314
            (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST_COMPLETE
8315
#ifdef WOLFSSL_DTLS13
8316
                    /* Always check for a valid cookie since we may have already
8317
                     * sent a HRR but we reset the state. */
8318
                    || ssl->options.dtls
8319
#endif
8320
                    )) {
8321
        TLSX* ext = TLSX_Find(ssl->extensions, TLSX_COOKIE);
8322
8323
        if (ext != NULL) {
8324
            /* Ensure the cookie came from client and isn't the one in the
8325
            * response - HelloRetryRequest.
8326
            */
8327
            if (ext->resp == 0) {
8328
                ret = RestartHandshakeHashWithCookie(ssl, (Cookie*)ext->data);
8329
                if (ret != 0)
8330
                    goto exit_dch;
8331
                /* Don't change state here as we may want to enter
8332
                 * DoTls13ClientHello again. */
8333
                ssl->options.cookieGood = 1;
8334
            }
8335
            else {
8336
                ERROR_OUT(HRR_COOKIE_ERROR, exit_dch);
8337
            }
8338
        }
8339
        else {
8340
#if defined(WOLFSSL_DTLS13) && defined(WOLFSSL_DTLS13_NO_HRR_ON_RESUME)
8341
            /* Don't error out as we may be resuming. We confirm this later. */
8342
            if (!ssl->options.dtls)
8343
#endif
8344
                ERROR_OUT(HRR_COOKIE_ERROR, exit_dch);
8345
        }
8346
    }
8347
#endif
8348
8349
0
#ifdef HAVE_SUPPORTED_CURVES
8350
0
    if (ssl->hrr_keyshare_group != 0) {
8351
        /*
8352
         * https://datatracker.ietf.org/doc/html/rfc8446#section-4.2.8
8353
         *   when sending the new ClientHello, the client MUST
8354
         *   replace the original "key_share" extension with one containing only
8355
         *   a new KeyShareEntry for the group indicated in the selected_group
8356
         *   field of the triggering HelloRetryRequest.
8357
         */
8358
0
        TLSX* extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
8359
0
        if (extension != NULL) {
8360
0
            KeyShareEntry* kse = (KeyShareEntry*)extension->data;
8361
            /* Exactly one KeyShareEntry with the HRR group must be present. */
8362
0
            if (kse == NULL || kse->next != NULL ||
8363
0
                                        kse->group != ssl->hrr_keyshare_group) {
8364
0
                ERROR_OUT(BAD_KEY_SHARE_DATA, exit_dch);
8365
0
            }
8366
0
        }
8367
0
        else
8368
0
            ERROR_OUT(BAD_KEY_SHARE_DATA, exit_dch);
8369
0
    }
8370
0
#endif
8371
8372
#if defined(HAVE_ECH)
8373
    /* hash clientHelloInner to hsHashesEch */
8374
    if (echX != NULL && ssl->ctx->echConfigs != NULL &&
8375
            !ssl->options.disableECH &&
8376
            ((WOLFSSL_ECH*)echX->data)->innerClientHello != NULL) {
8377
        ret = EchHashHelloInner(ssl, (WOLFSSL_ECH*)echX->data);
8378
        if (ret != 0)
8379
            goto exit_dch;
8380
        ((WOLFSSL_ECH*)echX->data)->innerCount = 1;
8381
    }
8382
#endif
8383
8384
#ifdef HAVE_ALPN
8385
    /* Select the ALPN protocol before PSK selection so that the
8386
     * selected value is available to the per-PSK SNI/ALPN binding check
8387
     * inside CheckPreSharedKeys/DoPreSharedKeys. ALPN_Select itself
8388
     * only inspects ssl->extensions and the app callback; it does not
8389
     * depend on any state set during PSK validation. */
8390
    if ((ret = ALPN_Select(ssl)) != 0)
8391
        goto exit_dch;
8392
#endif
8393
#if (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)) && \
8394
                                                    defined(HAVE_TLS_EXTENSIONS)
8395
    ret = CheckPreSharedKeys(ssl, input + args->begin, helloSz, ssl->clSuites,
8396
        &args->usingPSK);
8397
    if (ret != 0)
8398
        goto exit_dch;
8399
#else
8400
0
    if ((ret = HashInput(ssl, input + args->begin, (int)helloSz)) != 0)
8401
0
        goto exit_dch;
8402
0
#endif
8403
8404
#if (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)) && \
8405
                                                    defined(HAVE_TLS_EXTENSIONS)
8406
    if (!args->usingPSK
8407
#ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
8408
        || ssl->options.certWithExternPsk
8409
#endif
8410
    )
8411
#endif
8412
0
    {
8413
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
8414
        /* Not using PSK so don't require no KE. */
8415
        ssl->options.noPskDheKe = 0;
8416
#endif
8417
8418
0
#ifndef NO_CERTS
8419
0
        if (TLSX_Find(ssl->extensions, TLSX_KEY_SHARE) == NULL) {
8420
0
            WOLFSSL_MSG("Client did not send a KeyShare extension");
8421
0
            ERROR_OUT(INCOMPLETE_DATA, exit_dch);
8422
0
        }
8423
        /* Can't check ssl->extensions here as SigAlgs are unconditionally
8424
           set by TLSX_PopulateExtensions */
8425
0
        if (ssl->clSuites->hashSigAlgoSz == 0) {
8426
0
            WOLFSSL_MSG("Client did not send a SignatureAlgorithms extension");
8427
0
            ERROR_OUT(INCOMPLETE_DATA, exit_dch);
8428
0
        }
8429
#else
8430
        ERROR_OUT(INVALID_PARAMETER, exit_dch);
8431
#endif
8432
0
    }
8433
8434
0
    } /* case TLS_ASYNC_BEGIN */
8435
0
    FALL_THROUGH;
8436
8437
0
    case TLS_ASYNC_BUILD:
8438
    /* Advance state and proceed */
8439
0
    ssl->options.asyncState = TLS_ASYNC_DO;
8440
0
    FALL_THROUGH;
8441
8442
0
    case TLS_ASYNC_DO:
8443
0
    {
8444
#ifdef WOLFSSL_CERT_SETUP_CB
8445
    if ((ret = CertSetupCbWrapper(ssl)) != 0)
8446
        goto exit_dch;
8447
#endif
8448
0
#ifndef NO_CERTS
8449
0
    if (!args->usingPSK) {
8450
0
        if ((ret = MatchSuite(ssl, ssl->clSuites)) < 0) {
8451
        #ifdef WOLFSSL_ASYNC_CRYPT
8452
            if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
8453
        #endif
8454
0
                WOLFSSL_MSG("Unsupported cipher suite, ClientHello 1.3");
8455
0
            goto exit_dch;
8456
0
        }
8457
0
    }
8458
0
#endif
8459
0
#ifdef HAVE_SUPPORTED_CURVES
8460
0
    if (args->usingPSK == 2) {
8461
        /* Pick key share and Generate a new key if not present. */
8462
0
        int doHelloRetry = 0;
8463
0
        ret = TLSX_KeyShare_Establish(ssl, &doHelloRetry);
8464
0
        if (doHelloRetry) {
8465
            /* Make sure we don't send HRR twice */
8466
0
            if (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST_COMPLETE)
8467
0
                ERROR_OUT(INVALID_PARAMETER, exit_dch);
8468
0
            ssl->options.serverState = SERVER_HELLO_RETRY_REQUEST_COMPLETE;
8469
0
            if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
8470
0
                ret = 0; /* for hello_retry return 0 */
8471
0
        }
8472
0
        if (ret != 0)
8473
0
            goto exit_dch;
8474
0
    }
8475
0
#endif
8476
8477
    /* Verify the cipher suite is the same as what was chosen in HRR.
8478
     * got_client_hello == 2 covers the stateful path.
8479
     * cookieGood covers the stateless DTLS path. */
8480
0
    if ((ssl->msgsReceived.got_client_hello == 2
8481
#ifdef WOLFSSL_SEND_HRR_COOKIE
8482
            || ssl->options.cookieGood
8483
#endif
8484
0
        ) &&
8485
0
            (ssl->options.cipherSuite0 != ssl->options.hrrCipherSuite0 ||
8486
0
             ssl->options.cipherSuite  != ssl->options.hrrCipherSuite)) {
8487
0
        WOLFSSL_MSG("Cipher suite in second ClientHello does not match "
8488
0
                    "HelloRetryRequest");
8489
0
        ERROR_OUT(INVALID_PARAMETER, exit_dch);
8490
0
    }
8491
8492
    /* Advance state and proceed */
8493
0
    ssl->options.asyncState = TLS_ASYNC_VERIFY;
8494
0
    } /* case TLS_ASYNC_BUILD || TLS_ASYNC_DO */
8495
0
    FALL_THROUGH;
8496
8497
0
    case TLS_ASYNC_VERIFY:
8498
0
    {
8499
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(HAVE_SUPPORTED_CURVES)
8500
    /* Check if the KeyShare calculations from the previous state are complete.
8501
     * wolfSSL_AsyncPop advances ssl->options.asyncState so we may end up here
8502
     * with a pending calculation. */
8503
    TLSX* extension = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
8504
    if (extension != NULL && extension->resp == 1) {
8505
        KeyShareEntry* serverKSE = (KeyShareEntry*)extension->data;
8506
        if (serverKSE != NULL &&
8507
            serverKSE->lastRet == WC_NO_ERR_TRACE(WC_PENDING_E)) {
8508
    #if defined(WOLFSSL_HAVE_MLKEM)
8509
            if (WOLFSSL_NAMED_GROUP_IS_PQC_HYBRID(serverKSE->group)) {
8510
                ret = TLSX_KeyShare_HandlePqcHybridKeyServer(ssl, serverKSE,
8511
                        serverKSE->ke, serverKSE->keLen);
8512
            }
8513
            else
8514
    #endif
8515
            {
8516
                ret = TLSX_KeyShare_GenKey(ssl, serverKSE);
8517
            }
8518
            if (ret != 0)
8519
                goto exit_dch;
8520
        }
8521
    }
8522
#endif
8523
    /* Advance state and proceed */
8524
0
    ssl->options.asyncState = TLS_ASYNC_FINALIZE;
8525
0
    }
8526
0
    FALL_THROUGH;
8527
8528
0
    case TLS_ASYNC_FINALIZE:
8529
0
    {
8530
0
    *inOutIdx = args->idx;
8531
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
8532
    ssl->options.pskNegotiated = (args->usingPSK != 0);
8533
#endif
8534
8535
0
    if (!args->usingPSK) {
8536
0
#ifndef NO_CERTS
8537
        /* Check that the negotiated ciphersuite matches protocol version. */
8538
    #ifdef HAVE_NULL_CIPHER
8539
        if (ssl->options.cipherSuite0 == ECC_BYTE &&
8540
                              (ssl->options.cipherSuite == TLS_SHA256_SHA256 ||
8541
                               ssl->options.cipherSuite == TLS_SHA384_SHA384)) {
8542
            ;
8543
        }
8544
        else
8545
    #endif
8546
    #if defined(WOLFSSL_SM4_GCM) && defined(WOLFSSL_SM3)
8547
        if (ssl->options.cipherSuite0 == CIPHER_BYTE &&
8548
                ssl->options.cipherSuite == TLS_SM4_GCM_SM3) {
8549
            ; /* Do nothing. */
8550
        }
8551
        else
8552
    #endif
8553
    #if defined(WOLFSSL_SM4_CCM) && defined(WOLFSSL_SM3)
8554
        if (ssl->options.cipherSuite0 == CIPHER_BYTE &&
8555
                ssl->options.cipherSuite == TLS_SM4_CCM_SM3) {
8556
            ; /* Do nothing. */
8557
        }
8558
        else
8559
    #endif
8560
0
        if (ssl->options.cipherSuite0 != TLS13_BYTE) {
8561
0
            WOLFSSL_MSG("Negotiated ciphersuite from lesser version than "
8562
0
                        "TLS v1.3");
8563
0
            ERROR_OUT(MATCH_SUITE_ERROR, exit_dch);
8564
0
        }
8565
8566
    #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
8567
        if (ssl->options.resuming) {
8568
            ssl->options.resuming = 0;
8569
            ssl->arrays->psk_keySz = 0;
8570
            XMEMSET(ssl->arrays->psk_key, 0, ssl->specs.hash_size);
8571
        }
8572
    #endif
8573
8574
        /* Derive early secret for handshake secret. */
8575
0
        if ((ret = DeriveEarlySecret(ssl)) != 0)
8576
0
            goto exit_dch;
8577
0
#endif /* !NO_CERTS */
8578
0
    }
8579
8580
    /* Advanced only after the derive: earlier would let the accept loop
8581
     * proceed on an unfinished early secret. */
8582
0
    ssl->options.clientState = CLIENT_HELLO_COMPLETE;
8583
0
    break;
8584
0
    } /* case TLS_ASYNC_FINALIZE */
8585
0
    default:
8586
0
        ret = INPUT_CASE_ERROR;
8587
0
    } /* switch (ssl->options.asyncState) */
8588
8589
#ifdef WOLFSSL_SEND_HRR_COOKIE
8590
    if (ret == 0 && ssl->options.sendCookie) {
8591
        if (ssl->options.cookieGood &&
8592
                ssl->options.acceptState == TLS13_ACCEPT_FIRST_REPLY_DONE) {
8593
            /* Processing second ClientHello. Clear HRR state. */
8594
            ssl->options.serverState = NULL_STATE;
8595
        }
8596
8597
        if (ssl->options.cookieGood &&
8598
            ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
8599
            /* If we already verified the peer with a cookie then we can't
8600
             * do another HRR for cipher negotiation. Send alert and restart
8601
             * the entire handshake. */
8602
            ERROR_OUT(INVALID_PARAMETER, exit_dch);
8603
        }
8604
#ifdef WOLFSSL_DTLS13
8605
        if (ssl->options.dtls &&
8606
            ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
8607
            /* Cookie and key share negotiation should be handled in
8608
             * DoClientHelloStateless. If we enter here then something went
8609
             * wrong in our logic. */
8610
            ERROR_OUT(BAD_HELLO, exit_dch);
8611
        }
8612
#endif
8613
        /* Send a cookie */
8614
        if (!ssl->options.cookieGood &&
8615
            ssl->options.serverState != SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
8616
#ifdef WOLFSSL_DTLS13
8617
            if (ssl->options.dtls) {
8618
#ifdef WOLFSSL_DTLS13_NO_HRR_ON_RESUME
8619
                /* We can skip cookie on resumption */
8620
                if (!ssl->options.dtls || !ssl->options.dtls13NoHrrOnResume ||
8621
                        !args->usingPSK)
8622
#endif
8623
                    ERROR_OUT(BAD_HELLO, exit_dch);
8624
            }
8625
            else
8626
#endif
8627
            {
8628
                /* Need to remove the keyshare ext if we found a common group
8629
                 * and are not doing curve negotiation. */
8630
                TLSX_Remove(&ssl->extensions, TLSX_KEY_SHARE, ssl->heap);
8631
                ssl->options.serverState = SERVER_HELLO_RETRY_REQUEST_COMPLETE;
8632
            }
8633
8634
        }
8635
    }
8636
#endif /* WOLFSSL_DTLS13 */
8637
8638
#ifdef WOLFSSL_DTLS_CID
8639
    /* do not modify CID state if we are sending an HRR  */
8640
    if (ret == 0 && ssl->options.dtls && ssl->options.useDtlsCID &&
8641
            ssl->options.serverState != SERVER_HELLO_RETRY_REQUEST_COMPLETE)
8642
        DtlsCIDOnExtensionsParsed(ssl);
8643
#endif /* WOLFSSL_DTLS_CID */
8644
8645
8646
8647
0
exit_dch:
8648
8649
0
    WOLFSSL_LEAVE("DoTls13ClientHello", ret);
8650
8651
#ifdef WOLFSSL_ASYNC_CRYPT
8652
    if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
8653
        ssl->msgsReceived.got_client_hello = 0;
8654
        return ret;
8655
    }
8656
#endif
8657
8658
0
    FreeDch13Args(ssl, args);
8659
#ifdef WOLFSSL_ASYNC_CRYPT
8660
    FreeAsyncCtx(ssl, 0);
8661
    /* Back to BEGIN so a later ClientHello (HRR, duplicate) can never be
8662
     * mistaken for a replay and resume into freed args. */
8663
    ssl->options.asyncState = TLS_ASYNC_BEGIN;
8664
    /* This ClientHello is done; a later one (HRR CH2, duplicate) must hash
8665
     * itself afresh. */
8666
    ssl->options.chHashInput = 0;
8667
    /* Replays skip the sanity check that re-sets got_client_hello; restore
8668
     * on completion (only from 0: an HRR second ClientHello counts to 2). */
8669
    if (ret == 0 && ssl->msgsReceived.got_client_hello == 0) {
8670
        ssl->msgsReceived.got_client_hello = 1;
8671
    }
8672
#endif
8673
0
    WOLFSSL_END(WC_FUNC_CLIENT_HELLO_DO);
8674
8675
0
    if (ret != 0) {
8676
0
        WOLFSSL_ERROR_VERBOSE(ret);
8677
0
    }
8678
8679
#if defined(HAVE_ECH)
8680
    if (ret == 0 && echX != NULL &&
8681
        ((WOLFSSL_ECH*)echX->data)->state == ECH_WRITE_NONE &&
8682
        ((WOLFSSL_ECH*)echX->data)->innerClientHello != NULL) {
8683
8684
        /* add the header to the inner hello */
8685
        AddTls13HandShakeHeader(((WOLFSSL_ECH*)echX->data)->innerClientHello,
8686
            ((WOLFSSL_ECH*)echX->data)->innerClientHelloLen, 0, 0,
8687
            client_hello, ssl);
8688
    }
8689
#endif
8690
8691
0
    return ret;
8692
0
}
8693
8694
/* Send TLS v1.3 ServerHello message to client.
8695
 * Only a server will send this message.
8696
 *
8697
 * ssl  The SSL/TLS object.
8698
 * returns 0 on success, otherwise failure.
8699
 */
8700
/* handle generation of TLS 1.3 server_hello (2) */
8701
int SendTls13ServerHello(WOLFSSL* ssl, byte extMsgType)
8702
0
{
8703
0
    int    ret;
8704
0
    byte*  output;
8705
0
    word16 length;
8706
0
    word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
8707
0
    int    sendSz;
8708
#if defined(HAVE_ECH)
8709
    TLSX* echX = NULL;
8710
    byte* acceptLabel = (byte*)echAcceptConfirmationLabel;
8711
    word32 acceptOffset;
8712
    word16 acceptLabelSz = ECH_ACCEPT_CONFIRMATION_LABEL_SZ;
8713
#endif
8714
8715
0
    WOLFSSL_START(WC_FUNC_SERVER_HELLO_SEND);
8716
0
    WOLFSSL_ENTER("SendTls13ServerHello");
8717
8718
    /* When ssl->options.dtlsStateful is not set then cookie is calculated in
8719
     * dtls.c */
8720
0
    if (extMsgType == hello_retry_request
8721
#ifdef WOLFSSL_DTLS13
8722
            && (!ssl->options.dtls || ssl->options.dtlsStateful)
8723
#endif
8724
0
            ) {
8725
0
        WOLFSSL_MSG("wolfSSL Sending HelloRetryRequest");
8726
0
        if ((ret = RestartHandshakeHash(ssl)) < 0)
8727
0
            return ret;
8728
0
    }
8729
8730
0
    ssl->options.buildingMsg = 1;
8731
#ifdef WOLFSSL_DTLS13
8732
    if (ssl->options.dtls)
8733
        idx = DTLS_RECORD_HEADER_SZ + DTLS_HANDSHAKE_HEADER_SZ;
8734
#endif /* WOLFSSL_DTLS13 */
8735
8736
    /* Protocol version, server random, session id, cipher suite, compression
8737
     * and extensions.
8738
     */
8739
0
    length = VERSION_SZ + RAN_LEN + ENUM_LEN + ssl->session->sessionIDSz +
8740
0
             SUITE_LEN + COMP_LEN;
8741
0
    ret = TLSX_GetResponseSize(ssl, extMsgType, &length);
8742
0
    if (ret != 0)
8743
0
        return ret;
8744
0
    sendSz = (int)(idx + length);
8745
8746
    /* Check buffers are big enough and grow if needed. */
8747
0
    if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
8748
0
        return ret;
8749
8750
    /* Get position in output buffer to write new message to. */
8751
0
    output = GetOutputBuffer(ssl);
8752
8753
    /* Put the record and handshake headers on. */
8754
0
    AddTls13Headers(output, length, server_hello, ssl);
8755
8756
    /* The protocol version must be TLS v1.2 for middleboxes. */
8757
0
    output[idx++] = ssl->version.major;
8758
0
    output[idx++] = ssl->options.dtls ? DTLSv1_2_MINOR : TLSv1_2_MINOR;
8759
8760
0
    if (extMsgType == server_hello) {
8761
        /* Generate server random. */
8762
0
        if ((ret = wc_RNG_GenerateBlock(ssl->rng, output + idx, RAN_LEN)) != 0)
8763
0
            return ret;
8764
0
    }
8765
0
    else {
8766
        /* HelloRetryRequest message has fixed value for random. */
8767
0
        XMEMCPY(output + idx, helloRetryRequestRandom, RAN_LEN);
8768
0
    }
8769
8770
#if defined(HAVE_ECH)
8771
    /* last 8 bytes of server random */
8772
    acceptOffset = idx + RAN_LEN - ECH_ACCEPT_CONFIRMATION_SZ;
8773
#endif
8774
8775
    /* Store in SSL for debugging. */
8776
0
    XMEMCPY(ssl->arrays->serverRandom, output + idx, RAN_LEN);
8777
0
    idx += RAN_LEN;
8778
8779
#ifdef WOLFSSL_DEBUG_TLS
8780
    WOLFSSL_MSG("Server random");
8781
    WOLFSSL_BUFFER(ssl->arrays->serverRandom, RAN_LEN);
8782
#endif
8783
8784
#if defined(WOLFSSL_DTLS13) && !defined(WOLFSSL_DTLS13_ECHO_LEGACY_SESSION_ID)
8785
    if (ssl->options.dtls) {
8786
        /* RFC 9147 Section 5: "DTLS servers MUST NOT echo the
8787
         * legacy_session_id value from the client." */
8788
        output[idx++] = 0;
8789
    }
8790
    else
8791
#endif
8792
0
    {
8793
0
        output[idx++] = ssl->session->sessionIDSz;
8794
0
        if (ssl->session->sessionIDSz > 0) {
8795
0
            XMEMCPY(output + idx, ssl->session->sessionID,
8796
0
                ssl->session->sessionIDSz);
8797
0
            idx += ssl->session->sessionIDSz;
8798
0
        }
8799
0
    }
8800
8801
    /* Chosen cipher suite */
8802
0
    output[idx++] = ssl->options.cipherSuite0;
8803
0
    output[idx++] = ssl->options.cipherSuite;
8804
#ifdef WOLFSSL_DEBUG_TLS
8805
    WOLFSSL_MSG("Chosen cipher suite:");
8806
    WOLFSSL_MSG(GetCipherNameInternal(ssl->options.cipherSuite0,
8807
                                      ssl->options.cipherSuite));
8808
#endif
8809
8810
    /* Compression not supported in TLS v1.3. */
8811
0
    output[idx++] = 0;
8812
8813
    /* Extensions */
8814
0
    ret = TLSX_WriteResponse(ssl, output + idx, extMsgType, NULL);
8815
0
    if (ret != 0)
8816
0
        return ret;
8817
8818
    /* When we send a HRR, we store the selected key share group to later check
8819
     * that the client uses the same group in the second ClientHello.
8820
     *
8821
     * In case of stateless DTLS, we do not store the group, however, as it is
8822
     * already stored in the cookie that is sent to the client. We later recover
8823
     * the group from the cookie to prevent storing a state in a stateless
8824
     * server.
8825
     *
8826
     * Similar logic holds for the hrrCipherSuite. */
8827
0
    if (extMsgType == hello_retry_request
8828
#if defined(WOLFSSL_DTLS13) && defined(WOLFSSL_SEND_HRR_COOKIE)
8829
        && (!ssl->options.dtls || ssl->options.dtlsStateful)
8830
#endif
8831
0
    ) {
8832
0
        TLSX* ksExt = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
8833
0
        if (ksExt != NULL) {
8834
0
            KeyShareEntry* kse = (KeyShareEntry*)ksExt->data;
8835
0
            if (kse != NULL)
8836
0
                ssl->hrr_keyshare_group = kse->group;
8837
0
        }
8838
8839
0
        ssl->options.hrrCipherSuite0 = ssl->options.cipherSuite0;
8840
0
        ssl->options.hrrCipherSuite  = ssl->options.cipherSuite;
8841
0
    }
8842
8843
#ifdef WOLFSSL_SEND_HRR_COOKIE
8844
    if (ssl->options.sendCookie && extMsgType == hello_retry_request) {
8845
        /* Reset the hashes from here. We will be able to restart the hashes
8846
         * from the cookie in RestartHandshakeHashWithCookie */
8847
#ifdef WOLFSSL_DTLS13
8848
        /* When ssl->options.dtlsStateful is not set then cookie is calculated
8849
         * in dtls.c */
8850
        if (ssl->options.dtls && !ssl->options.dtlsStateful)
8851
            ret = 0;
8852
        else
8853
#endif
8854
            ret = InitHandshakeHashes(ssl);
8855
    }
8856
    else
8857
#endif
8858
0
    {
8859
#ifdef WOLFSSL_DTLS13
8860
        if (ssl->options.dtls) {
8861
            ret = Dtls13HashHandshake(
8862
                ssl,
8863
                output + Dtls13GetRlHeaderLength(ssl, 0) ,
8864
                (word16)sendSz - Dtls13GetRlHeaderLength(ssl, 0));
8865
        }
8866
        else
8867
#endif /* WOLFSSL_DTLS13 */
8868
0
        {
8869
#if defined(HAVE_ECH)
8870
            if (ssl->ctx->echConfigs != NULL && !ssl->options.disableECH) {
8871
                echX = TLSX_Find(ssl->extensions, TLSX_ECH);
8872
                if (echX == NULL)
8873
                    return WOLFSSL_FATAL_ERROR;
8874
                /* use hrr offset */
8875
                if (extMsgType == hello_retry_request) {
8876
                    acceptOffset =
8877
                        (word32)(((WOLFSSL_ECH*)echX->data)->confBuf - output);
8878
                    acceptLabel = (byte*)echHrrAcceptConfirmationLabel;
8879
                    acceptLabelSz = ECH_HRR_ACCEPT_CONFIRMATION_LABEL_SZ;
8880
                }
8881
                /* replace the last 8 bytes of server random with the accept */
8882
                if (((WOLFSSL_ECH*)echX->data)->state == ECH_PARSED_INTERNAL) {
8883
                    if (ret == 0) {
8884
                        ret = EchWriteAcceptance(ssl, acceptLabel,
8885
                            acceptLabelSz, output + RECORD_HEADER_SZ,
8886
                            acceptOffset - RECORD_HEADER_SZ,
8887
                            sendSz - RECORD_HEADER_SZ, extMsgType);
8888
                    }
8889
                    if (extMsgType == hello_retry_request) {
8890
                        /* reset the ech state for round 2 */
8891
                        ((WOLFSSL_ECH*)echX->data)->state = ECH_WRITE_NONE;
8892
                        /* inner hello no longer needed, free it */
8893
                        XFREE(((WOLFSSL_ECH*)echX->data)->innerClientHello,
8894
                              ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
8895
                        ((WOLFSSL_ECH*)echX->data)->innerClientHello = NULL;
8896
                    }
8897
                    else {
8898
                        if (ret == 0) {
8899
                            /* update serverRandom on success */
8900
                            XMEMCPY(ssl->arrays->serverRandom,
8901
                                output + acceptOffset -
8902
                                (RAN_LEN -ECH_ACCEPT_CONFIRMATION_SZ), RAN_LEN);
8903
                        }
8904
                        /* remove ech so we don't keep sending it in write */
8905
                        TLSX_Remove(&ssl->extensions, TLSX_ECH, ssl->heap);
8906
                    }
8907
                }
8908
            }
8909
#endif
8910
0
            if (ret == 0)
8911
0
                ret = HashOutput(ssl, output, sendSz, 0);
8912
0
        }
8913
0
    }
8914
8915
0
    if (ret != 0)
8916
0
        return ret;
8917
8918
#if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
8919
    if (ssl->hsInfoOn)
8920
        AddPacketName(ssl, "ServerHello");
8921
    if (ssl->toInfoOn) {
8922
        ret = AddPacketInfo(ssl, "ServerHello", handshake, output, sendSz,
8923
                      WRITE_PROTO, 0, ssl->heap);
8924
        if (ret != 0)
8925
            return ret;
8926
    }
8927
    #endif
8928
8929
0
    if (extMsgType == server_hello)
8930
0
        ssl->options.serverState = SERVER_HELLO_COMPLETE;
8931
8932
0
    ssl->options.buildingMsg = 0;
8933
#ifdef WOLFSSL_DTLS13
8934
    if (ssl->options.dtls) {
8935
        ret = Dtls13HandshakeSend(ssl, output, (word16)sendSz, (word16)sendSz,
8936
            (enum HandShakeType)extMsgType, 0);
8937
8938
        WOLFSSL_LEAVE("SendTls13ServerHello", ret);
8939
        WOLFSSL_END(WC_FUNC_SERVER_HELLO_SEND);
8940
        return ret;
8941
    }
8942
#endif /* WOLFSSL_DTLS13 */
8943
8944
0
    ssl->buffers.outputBuffer.length += (word32)sendSz;
8945
8946
0
    if (!ssl->options.groupMessages || extMsgType != server_hello)
8947
0
        ret = SendBuffered(ssl);
8948
8949
0
    WOLFSSL_LEAVE("SendTls13ServerHello", ret);
8950
0
    WOLFSSL_END(WC_FUNC_SERVER_HELLO_SEND);
8951
8952
0
    return ret;
8953
0
}
8954
8955
/* handle generation of TLS 1.3 encrypted_extensions (8) */
8956
/* Send the rest of the extensions encrypted under the handshake key.
8957
 * This message is always encrypted in TLS v1.3.
8958
 * Only a server will send this message.
8959
 *
8960
 * ssl  The SSL/TLS object.
8961
 * returns 0 on success, otherwise failure.
8962
 */
8963
static int SendTls13EncryptedExtensions(WOLFSSL* ssl)
8964
0
{
8965
0
    int    ret;
8966
0
    byte*  output;
8967
0
    word16 length = 0;
8968
0
    word32 idx;
8969
0
    int    sendSz;
8970
8971
0
    WOLFSSL_START(WC_FUNC_ENCRYPTED_EXTENSIONS_SEND);
8972
0
    WOLFSSL_ENTER("SendTls13EncryptedExtensions");
8973
8974
0
    ssl->options.buildingMsg = 1;
8975
0
    ssl->keys.encryptionOn = 1;
8976
8977
#ifdef WOLFSSL_DTLS13
8978
    if (ssl->options.dtls) {
8979
        idx = Dtls13GetHeadersLength(ssl, encrypted_extensions);
8980
    }
8981
    else
8982
#endif /* WOLFSSL_DTLS13 */
8983
0
    {
8984
0
        idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
8985
0
    }
8986
8987
#ifdef WOLFSSL_ASYNC_CRYPT
8988
    /* A suspended build already ran the key schedule below; re-running it
8989
     * would extract in place over preMasterSecret a second time. */
8990
    if (ssl->options.buildArgs13Set)
8991
        goto tls13_send_ee_build;
8992
#endif
8993
8994
0
#if defined(HAVE_SUPPORTED_CURVES) && !defined(WOLFSSL_NO_SERVER_GROUPS_EXT)
8995
0
    if ((ret = TLSX_SupportedCurve_CheckPriority(ssl)) != 0)
8996
0
        return ret;
8997
0
#endif
8998
8999
    /* Derive the handshake secret now that we are at first message to be
9000
     * encrypted under the keys.
9001
     */
9002
0
    if (ssl->kdfDeriveStep <= TLS13_SEND_KDF_NONE) {
9003
0
        ret = DeriveHandshakeSecret(ssl);
9004
0
        if (ret != 0) {
9005
0
            if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
9006
0
                ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
9007
0
            return ret;
9008
0
        }
9009
0
        ssl->kdfDeriveStep = TLS13_SEND_KDF_EE_HS_SECRET;
9010
0
    }
9011
0
    if (ssl->kdfDeriveStep <= TLS13_SEND_KDF_EE_HS_SECRET) {
9012
0
        ret = DeriveTls13Keys(ssl, handshake_key, ENCRYPT_AND_DECRYPT_SIDE, 1);
9013
0
        if (ret != 0) {
9014
0
            if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
9015
0
                ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
9016
0
            return ret;
9017
0
        }
9018
0
        ssl->kdfDeriveStep = TLS13_SEND_KDF_EE_HS_KEYS;
9019
0
    }
9020
9021
    /* Setup encrypt/decrypt keys for following messages. */
9022
#ifdef WOLFSSL_EARLY_DATA
9023
    if (ssl->kdfDeriveStep <= TLS13_SEND_KDF_EE_HS_KEYS) {
9024
        ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY);
9025
        if (ret != 0) {
9026
            if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
9027
                ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
9028
            return ret;
9029
        }
9030
        ssl->kdfDeriveStep = TLS13_SEND_KDF_EE_ENC_KEYS_SET;
9031
    }
9032
    if (ssl->earlyData != process_early_data) {
9033
        if (ssl->kdfDeriveStep <= TLS13_SEND_KDF_EE_ENC_KEYS_SET) {
9034
            ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY);
9035
            if (ret != 0) {
9036
                if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
9037
                    ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
9038
                return ret;
9039
            }
9040
            ssl->kdfDeriveStep = TLS13_SEND_KDF_EE_KEYS_SET;
9041
        }
9042
    }
9043
#else
9044
0
    if (ssl->kdfDeriveStep <= TLS13_SEND_KDF_EE_ENC_KEYS_SET) {
9045
0
        ret = SetKeysSide(ssl, ENCRYPT_AND_DECRYPT_SIDE);
9046
0
        if (ret != 0) {
9047
0
            if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
9048
0
                ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
9049
0
            return ret;
9050
0
        }
9051
0
        ssl->kdfDeriveStep = TLS13_SEND_KDF_EE_KEYS_SET;
9052
0
    }
9053
0
#endif
9054
#ifdef WOLFSSL_QUIC
9055
    if (IsAtLeastTLSv1_3(ssl->version) && WOLFSSL_IS_QUIC(ssl)) {
9056
        ret = wolfSSL_quic_add_transport_extensions(ssl, encrypted_extensions);
9057
        if (ret != 0)
9058
            return ret;
9059
    }
9060
#endif
9061
9062
#ifdef WOLFSSL_DTLS13
9063
    if (ssl->options.dtls) {
9064
        w64wrapper epochHandshake = w64From32(0, DTLS13_EPOCH_HANDSHAKE);
9065
        ssl->dtls13Epoch = epochHandshake;
9066
9067
        if (ssl->kdfDeriveStep <= TLS13_SEND_KDF_EE_KEYS_SET) {
9068
            ret = Dtls13SetEpochKeys(ssl, epochHandshake,
9069
                                     ENCRYPT_AND_DECRYPT_SIDE);
9070
            if (ret != 0) {
9071
                if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
9072
                    ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
9073
                return ret;
9074
            }
9075
            ssl->kdfDeriveStep = TLS13_SEND_KDF_EE_DTLS_EPOCH;
9076
        }
9077
    }
9078
#endif /* WOLFSSL_DTLS13 */
9079
0
    ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
9080
9081
#ifdef WOLFSSL_ASYNC_CRYPT
9082
tls13_send_ee_build:
9083
#endif
9084
9085
0
    ret = TLSX_GetResponseSize(ssl, encrypted_extensions, &length);
9086
0
    if (ret != 0)
9087
0
        return ret;
9088
9089
0
    sendSz = (int)(idx + length);
9090
    /* Encryption always on. */
9091
0
    sendSz += MAX_MSG_EXTRA;
9092
9093
    /* Check buffers are big enough and grow if needed. */
9094
0
    ret = CheckAvailableSize(ssl, sendSz);
9095
0
    if (ret != 0)
9096
0
        return ret;
9097
9098
    /* Get position in output buffer to write new message to. */
9099
0
    output = GetOutputBuffer(ssl);
9100
9101
#ifdef WOLFSSL_ASYNC_CRYPT
9102
    /* Skip on a resume: BuildTls13Message already replaced the record
9103
     * header; rewriting the plaintext headers would corrupt it. */
9104
    if (!ssl->options.buildArgs13Set)
9105
#endif
9106
0
    {
9107
        /* Put the record and handshake headers on. */
9108
0
        AddTls13Headers(output, length, encrypted_extensions, ssl);
9109
9110
0
        ret = TLSX_WriteResponse(ssl, output + idx, encrypted_extensions, NULL);
9111
0
        if (ret != 0)
9112
0
            return ret;
9113
0
    }
9114
0
    idx += length;
9115
9116
#if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
9117
    if (ssl->hsInfoOn)
9118
        AddPacketName(ssl, "EncryptedExtensions");
9119
    if (ssl->toInfoOn) {
9120
        ret = AddPacketInfo(ssl, "EncryptedExtensions", handshake, output,
9121
                      sendSz, WRITE_PROTO, 0, ssl->heap);
9122
        if (ret != 0)
9123
            return ret;
9124
    }
9125
#endif
9126
9127
#ifdef WOLFSSL_DTLS13
9128
    if (ssl->options.dtls) {
9129
        ssl->options.buildingMsg = 0;
9130
        ret = Dtls13HandshakeSend(ssl, output, (word16)sendSz, (word16)idx,
9131
                                  encrypted_extensions, 1);
9132
9133
        if (ret == 0)
9134
            ssl->options.serverState = SERVER_ENCRYPTED_EXTENSIONS_COMPLETE;
9135
9136
        WOLFSSL_LEAVE("SendTls13EncryptedExtensions", ret);
9137
        WOLFSSL_END(WC_FUNC_ENCRYPTED_EXTENSIONS_SEND);
9138
9139
        return ret;
9140
    }
9141
#endif /* WOLFSSL_DTLS13 */
9142
9143
    /* This handshake message is always encrypted. */
9144
0
    sendSz = BuildTls13Message(ssl, output, sendSz, output + RECORD_HEADER_SZ,
9145
0
                               (int)(idx - RECORD_HEADER_SZ),
9146
0
                               handshake, 1, 0, TLS13_HS_ASYNC_OKAY);
9147
0
    if (sendSz < 0)
9148
0
        return sendSz;
9149
9150
0
    ssl->buffers.outputBuffer.length += (word32)sendSz;
9151
0
    ssl->options.buildingMsg = 0;
9152
0
    ssl->options.serverState = SERVER_ENCRYPTED_EXTENSIONS_COMPLETE;
9153
9154
0
    if (!ssl->options.groupMessages)
9155
0
        ret = SendBuffered(ssl);
9156
9157
9158
0
    WOLFSSL_LEAVE("SendTls13EncryptedExtensions", ret);
9159
0
    WOLFSSL_END(WC_FUNC_ENCRYPTED_EXTENSIONS_SEND);
9160
9161
0
    return ret;
9162
0
}
9163
9164
#ifndef NO_CERTS
9165
/* handle generation TLS v1.3 certificate_request (13) */
9166
/* Send the TLS v1.3 CertificateRequest message.
9167
 * This message is always encrypted in TLS v1.3.
9168
 * Only a server will send this message.
9169
 *
9170
 * ssl        SSL/TLS object.
9171
 * reqCtx     Request context.
9172
 * reqCtxLen  Length of context. 0 when sending as part of handshake.
9173
 * returns 0 on success, otherwise failure.
9174
 */
9175
static int SendTls13CertificateRequest(WOLFSSL* ssl, byte* reqCtx,
9176
                                       word32 reqCtxLen)
9177
0
{
9178
0
    byte*   output;
9179
0
    int    ret;
9180
0
    int    sendSz;
9181
0
    word32 i;
9182
0
    word32 reqSz;
9183
0
    SignatureAlgorithms* sa;
9184
9185
0
    WOLFSSL_START(WC_FUNC_CERTIFICATE_REQUEST_SEND);
9186
0
    WOLFSSL_ENTER("SendTls13CertificateRequest");
9187
9188
0
    ssl->options.buildingMsg = 1;
9189
9190
0
    if (ssl->options.side != WOLFSSL_SERVER_END)
9191
0
        return SIDE_ERROR;
9192
9193
    /* Use ssl->suites->hashSigAlgo so wolfSSL_set1_sigalgs_list() is honored.
9194
     * hashSigAlgoSz=0 makes GetSize/Write fall back to WOLFSSL_SUITES(ssl). */
9195
0
    sa = TLSX_SignatureAlgorithms_New(ssl, 0, ssl->heap);
9196
0
    if (sa == NULL)
9197
0
        return MEMORY_ERROR;
9198
0
    ret = TLSX_Push(&ssl->extensions, TLSX_SIGNATURE_ALGORITHMS, sa, ssl->heap);
9199
0
    if (ret != 0) {
9200
0
        TLSX_SignatureAlgorithms_FreeAll(sa, ssl->heap);
9201
0
        return ret;
9202
0
    }
9203
9204
0
    i = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
9205
#ifdef WOLFSSL_DTLS13
9206
    if (ssl->options.dtls)
9207
        i = Dtls13GetRlHeaderLength(ssl, 1) + DTLS_HANDSHAKE_HEADER_SZ;
9208
#endif /* WOLFSSL_DTLS13 */
9209
9210
0
    reqSz = (word16)(OPAQUE8_LEN + reqCtxLen);
9211
0
    ret = TLSX_GetRequestSize(ssl, certificate_request, &reqSz);
9212
0
    if (ret != 0)
9213
0
        return ret;
9214
9215
0
    sendSz = (int)(i + reqSz);
9216
    /* Always encrypted and make room for padding. */
9217
0
    sendSz += MAX_MSG_EXTRA;
9218
9219
    /* Check buffers are big enough and grow if needed. */
9220
0
    if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
9221
0
        return ret;
9222
9223
    /* Get position in output buffer to write new message to. */
9224
0
    output = GetOutputBuffer(ssl);
9225
9226
    /* Put the record and handshake headers on. */
9227
0
    AddTls13Headers(output, reqSz, certificate_request, ssl);
9228
9229
    /* Certificate request context. */
9230
0
    output[i++] = (byte)reqCtxLen;
9231
0
    if (reqCtxLen != 0) {
9232
0
        XMEMCPY(output + i, reqCtx, reqCtxLen);
9233
0
        i += reqCtxLen;
9234
0
    }
9235
9236
    /* Certificate extensions. */
9237
0
    reqSz = 0;
9238
0
    ret = TLSX_WriteRequest(ssl, output + i, certificate_request, &reqSz);
9239
0
    if (ret != 0)
9240
0
        return ret;
9241
0
    i += reqSz;
9242
9243
#ifdef WOLFSSL_DTLS13
9244
    if (ssl->options.dtls) {
9245
        ssl->options.buildingMsg = 0;
9246
        ret =
9247
            Dtls13HandshakeSend(ssl, output, (word16)sendSz, (word16)i,
9248
                                certificate_request, 1);
9249
9250
        WOLFSSL_LEAVE("SendTls13CertificateRequest", ret);
9251
        WOLFSSL_END(WC_FUNC_CERTIFICATE_REQUEST_SEND);
9252
9253
        return ret;
9254
9255
    }
9256
#endif /* WOLFSSL_DTLS13 */
9257
9258
    /* Always encrypted. */
9259
0
    sendSz = BuildTls13Message(ssl, output, sendSz, output + RECORD_HEADER_SZ,
9260
0
                               (int)(i - RECORD_HEADER_SZ), handshake, 1, 0, 0);
9261
0
    if (sendSz < 0)
9262
0
        return sendSz;
9263
9264
    #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
9265
        if (ssl->hsInfoOn)
9266
            AddPacketName(ssl, "CertificateRequest");
9267
        if (ssl->toInfoOn) {
9268
            ret = AddPacketInfo(ssl, "CertificateRequest", handshake, output,
9269
                          sendSz, WRITE_PROTO, 0, ssl->heap);
9270
            if (ret != 0)
9271
                return ret;
9272
        }
9273
    #endif
9274
9275
0
    ssl->buffers.outputBuffer.length += (word32)sendSz;
9276
0
    ssl->options.buildingMsg = 0;
9277
0
    if (!ssl->options.groupMessages)
9278
0
        ret = SendBuffered(ssl);
9279
9280
0
    WOLFSSL_LEAVE("SendTls13CertificateRequest", ret);
9281
0
    WOLFSSL_END(WC_FUNC_CERTIFICATE_REQUEST_SEND);
9282
9283
0
    return ret;
9284
0
}
9285
#endif /* NO_CERTS */
9286
#endif /* NO_WOLFSSL_SERVER */
9287
9288
#ifndef NO_CERTS
9289
#if (!defined(NO_WOLFSSL_SERVER) || !defined(WOLFSSL_NO_CLIENT_AUTH)) && \
9290
    (!defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
9291
     defined(HAVE_ED448) || defined(HAVE_FALCON) || defined(WOLFSSL_HAVE_MLDSA) || \
9292
     defined(WOLFSSL_HAVE_SLHDSA))
9293
/* Encode the signature algorithm into buffer.
9294
 *
9295
 * hashalgo  The hash algorithm.
9296
 * hsType   The signature type.
9297
 * output    The buffer to encode into.
9298
 */
9299
static WC_INLINE void EncodeSigAlg(const WOLFSSL * ssl, byte hashAlgo,
9300
    byte hsType, byte* output)
9301
0
{
9302
0
    (void)ssl;
9303
0
    (void)hashAlgo;
9304
0
    switch (hsType) {
9305
0
#ifdef HAVE_ECC
9306
0
        case ecc_dsa_sa_algo:
9307
0
            if (ssl->pkCurveOID == ECC_BRAINPOOLP256R1_OID) {
9308
0
                output[0] = NEW_SA_MAJOR;
9309
0
                output[1] = ECDSA_BRAINPOOLP256R1TLS13_SHA256_MINOR;
9310
0
            }
9311
0
            else if (ssl->pkCurveOID == ECC_BRAINPOOLP384R1_OID) {
9312
0
                output[0] = NEW_SA_MAJOR;
9313
0
                output[1] = ECDSA_BRAINPOOLP384R1TLS13_SHA384_MINOR;
9314
0
            }
9315
0
            else if (ssl->pkCurveOID == ECC_BRAINPOOLP512R1_OID) {
9316
0
                output[0] = NEW_SA_MAJOR;
9317
0
                output[1] = ECDSA_BRAINPOOLP512R1TLS13_SHA512_MINOR;
9318
0
            }
9319
0
            else {
9320
0
                output[0] = hashAlgo;
9321
0
                output[1] = ecc_dsa_sa_algo;
9322
0
            }
9323
0
            break;
9324
0
#endif
9325
#if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
9326
        case sm2_sa_algo:
9327
            output[0] = SM2_SA_MAJOR;
9328
            output[1] = SM2_SA_MINOR;
9329
            break;
9330
#endif
9331
#ifdef HAVE_ED25519
9332
        /* ED25519: 0x0807 */
9333
        case ed25519_sa_algo:
9334
            output[0] = ED25519_SA_MAJOR;
9335
            output[1] = ED25519_SA_MINOR;
9336
            break;
9337
#endif
9338
#ifdef HAVE_ED448
9339
        /* ED448: 0x0808 */
9340
        case ed448_sa_algo:
9341
            output[0] = ED448_SA_MAJOR;
9342
            output[1] = ED448_SA_MINOR;
9343
            break;
9344
#endif
9345
0
#ifndef NO_RSA
9346
        /* PSS signatures: 0x080[4-6] or 0x080[9-B] */
9347
0
        case rsa_pss_sa_algo:
9348
0
            output[0] = rsa_pss_sa_algo;
9349
0
#ifdef WC_RSA_PSS
9350
            /* If the private key uses the RSA-PSS OID, and the peer supports
9351
             * the rsa_pss_pss_* signature algorithm in use, then report
9352
             * rsa_pss_pss_* rather than rsa_pss_rsae_*. */
9353
0
            if (ssl->useRsaPss &&
9354
0
                ((ssl->pssAlgo & (1U << hashAlgo)) != 0U) &&
9355
0
                (sha256_mac <= hashAlgo) && (hashAlgo <= sha512_mac))
9356
0
            {
9357
0
                output[1] = PSS_RSAE_TO_PSS_PSS(hashAlgo);
9358
0
            }
9359
0
            else
9360
0
#endif
9361
0
            {
9362
0
                output[1] = hashAlgo;
9363
0
            }
9364
0
            break;
9365
0
#endif
9366
#ifdef HAVE_FALCON
9367
        case falcon_level1_sa_algo:
9368
            output[0] = FALCON_LEVEL1_SA_MAJOR;
9369
            output[1] = FALCON_LEVEL1_SA_MINOR;
9370
            break;
9371
        case falcon_level5_sa_algo:
9372
            output[0] = FALCON_LEVEL5_SA_MAJOR;
9373
            output[1] = FALCON_LEVEL5_SA_MINOR;
9374
            break;
9375
#endif
9376
#ifdef WOLFSSL_HAVE_MLDSA
9377
        case mldsa_44_sa_algo:
9378
            output[0] = MLDSA_44_SA_MAJOR;
9379
            output[1] = MLDSA_44_SA_MINOR;
9380
            break;
9381
        case mldsa_65_sa_algo:
9382
            output[0] = MLDSA_65_SA_MAJOR;
9383
            output[1] = MLDSA_65_SA_MINOR;
9384
            break;
9385
        case mldsa_87_sa_algo:
9386
            output[0] = MLDSA_87_SA_MAJOR;
9387
            output[1] = MLDSA_87_SA_MINOR;
9388
            break;
9389
#endif
9390
#ifdef WOLFSSL_HAVE_SLHDSA
9391
    #if defined(WOLFSSL_SLHDSA_SHA2) && defined(WOLFSSL_SLHDSA_PARAM_SHA2_128S)
9392
        case slhdsa_sha2_128s_sa_algo:
9393
            output[0] = SLHDSA_SA_MAJOR;
9394
            output[1] = SLHDSA_SHA2_128S_SA_MINOR;
9395
            break;
9396
    #endif
9397
    #if defined(WOLFSSL_SLHDSA_SHA2) && defined(WOLFSSL_SLHDSA_PARAM_SHA2_128F)
9398
        case slhdsa_sha2_128f_sa_algo:
9399
            output[0] = SLHDSA_SA_MAJOR;
9400
            output[1] = SLHDSA_SHA2_128F_SA_MINOR;
9401
            break;
9402
    #endif
9403
    #if defined(WOLFSSL_SLHDSA_SHA2) && defined(WOLFSSL_SLHDSA_PARAM_SHA2_192S)
9404
        case slhdsa_sha2_192s_sa_algo:
9405
            output[0] = SLHDSA_SA_MAJOR;
9406
            output[1] = SLHDSA_SHA2_192S_SA_MINOR;
9407
            break;
9408
    #endif
9409
    #if defined(WOLFSSL_SLHDSA_SHA2) && defined(WOLFSSL_SLHDSA_PARAM_SHA2_192F)
9410
        case slhdsa_sha2_192f_sa_algo:
9411
            output[0] = SLHDSA_SA_MAJOR;
9412
            output[1] = SLHDSA_SHA2_192F_SA_MINOR;
9413
            break;
9414
    #endif
9415
    #if defined(WOLFSSL_SLHDSA_SHA2) && defined(WOLFSSL_SLHDSA_PARAM_SHA2_256S)
9416
        case slhdsa_sha2_256s_sa_algo:
9417
            output[0] = SLHDSA_SA_MAJOR;
9418
            output[1] = SLHDSA_SHA2_256S_SA_MINOR;
9419
            break;
9420
    #endif
9421
    #if defined(WOLFSSL_SLHDSA_SHA2) && defined(WOLFSSL_SLHDSA_PARAM_SHA2_256F)
9422
        case slhdsa_sha2_256f_sa_algo:
9423
            output[0] = SLHDSA_SA_MAJOR;
9424
            output[1] = SLHDSA_SHA2_256F_SA_MINOR;
9425
            break;
9426
    #endif
9427
    #ifdef WOLFSSL_SLHDSA_PARAM_128S
9428
        case slhdsa_shake_128s_sa_algo:
9429
            output[0] = SLHDSA_SA_MAJOR;
9430
            output[1] = SLHDSA_SHAKE_128S_SA_MINOR;
9431
            break;
9432
    #endif
9433
    #ifdef WOLFSSL_SLHDSA_PARAM_128F
9434
        case slhdsa_shake_128f_sa_algo:
9435
            output[0] = SLHDSA_SA_MAJOR;
9436
            output[1] = SLHDSA_SHAKE_128F_SA_MINOR;
9437
            break;
9438
    #endif
9439
    #ifdef WOLFSSL_SLHDSA_PARAM_192S
9440
        case slhdsa_shake_192s_sa_algo:
9441
            output[0] = SLHDSA_SA_MAJOR;
9442
            output[1] = SLHDSA_SHAKE_192S_SA_MINOR;
9443
            break;
9444
    #endif
9445
    #ifdef WOLFSSL_SLHDSA_PARAM_192F
9446
        case slhdsa_shake_192f_sa_algo:
9447
            output[0] = SLHDSA_SA_MAJOR;
9448
            output[1] = SLHDSA_SHAKE_192F_SA_MINOR;
9449
            break;
9450
    #endif
9451
    #ifdef WOLFSSL_SLHDSA_PARAM_256S
9452
        case slhdsa_shake_256s_sa_algo:
9453
            output[0] = SLHDSA_SA_MAJOR;
9454
            output[1] = SLHDSA_SHAKE_256S_SA_MINOR;
9455
            break;
9456
    #endif
9457
    #ifdef WOLFSSL_SLHDSA_PARAM_256F
9458
        case slhdsa_shake_256f_sa_algo:
9459
            output[0] = SLHDSA_SA_MAJOR;
9460
            output[1] = SLHDSA_SHAKE_256F_SA_MINOR;
9461
            break;
9462
    #endif
9463
#endif /* WOLFSSL_HAVE_SLHDSA */
9464
0
        default:
9465
0
            break;
9466
0
    }
9467
0
}
9468
#endif
9469
9470
#if !defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
9471
    defined(HAVE_ED448) || defined(HAVE_FALCON) || defined(WOLFSSL_HAVE_MLDSA) || \
9472
    defined(WOLFSSL_HAVE_SLHDSA)
9473
#ifdef WOLFSSL_DUAL_ALG_CERTS
9474
/* These match up with what the OQS team has defined. */
9475
#define HYBRID_SA_MAJOR 0xFE
9476
#define HYBRID_P256_MLDSA_44_SA_MINOR            0xA1
9477
#define HYBRID_RSA3072_MLDSA_44_SA_MINOR         0xA2
9478
#define HYBRID_P384_MLDSA_65_SA_MINOR            0xA4
9479
#define HYBRID_P521_MLDSA_87_SA_MINOR            0xA6
9480
/* Falcon hybrid codepoints aligned with oqs-provider. */
9481
#define HYBRID_P256_FALCON_LEVEL1_SA_MINOR       0xD8
9482
#define HYBRID_RSA3072_FALCON_LEVEL1_SA_MINOR    0xD9
9483
#define HYBRID_P521_FALCON_LEVEL5_SA_MINOR       0xDB
9484
9485
/* Custom defined ones for PQC first */
9486
#define HYBRID_MLDSA_44_P256_SA_MINOR            0xD1
9487
#define HYBRID_MLDSA_44_RSA3072_SA_MINOR         0xD2
9488
#define HYBRID_MLDSA_65_P384_SA_MINOR            0xD3
9489
#define HYBRID_MLDSA_87_P521_SA_MINOR            0xD4
9490
#define HYBRID_FALCON_LEVEL1_P256_SA_MINOR       0xD5
9491
#define HYBRID_FALCON_LEVEL1_RSA3072_SA_MINOR    0xD6
9492
#define HYBRID_FALCON_LEVEL5_P521_SA_MINOR       0xD7
9493
9494
9495
static void EncodeDualSigAlg(byte sigAlg, byte altSigAlg, byte* output)
9496
{
9497
    /* Initialize output to error indicator. */
9498
    output[0] = 0x0;
9499
    output[1] = 0x0;
9500
9501
    if (sigAlg == ecc_dsa_sa_algo && altSigAlg == mldsa_44_sa_algo) {
9502
        output[1] = HYBRID_P256_MLDSA_44_SA_MINOR;
9503
    }
9504
    else if (sigAlg == rsa_pss_sa_algo &&
9505
             altSigAlg == mldsa_44_sa_algo) {
9506
        output[1] = HYBRID_RSA3072_MLDSA_44_SA_MINOR;
9507
    }
9508
    else if (sigAlg == ecc_dsa_sa_algo &&
9509
             altSigAlg == mldsa_65_sa_algo) {
9510
        output[1] = HYBRID_P384_MLDSA_65_SA_MINOR;
9511
    }
9512
    else if (sigAlg == ecc_dsa_sa_algo &&
9513
             altSigAlg == mldsa_87_sa_algo) {
9514
        output[1] = HYBRID_P521_MLDSA_87_SA_MINOR;
9515
    }
9516
    else if (sigAlg == ecc_dsa_sa_algo &&
9517
             altSigAlg == falcon_level1_sa_algo) {
9518
        output[1] = HYBRID_P256_FALCON_LEVEL1_SA_MINOR;
9519
    }
9520
    else if (sigAlg == rsa_pss_sa_algo &&
9521
             altSigAlg == falcon_level1_sa_algo) {
9522
        output[1] = HYBRID_RSA3072_FALCON_LEVEL1_SA_MINOR;
9523
    }
9524
    else if (sigAlg == ecc_dsa_sa_algo &&
9525
             altSigAlg == falcon_level5_sa_algo) {
9526
        output[1] = HYBRID_P521_FALCON_LEVEL5_SA_MINOR;
9527
    }
9528
    else if (sigAlg == mldsa_44_sa_algo &&
9529
             altSigAlg == ecc_dsa_sa_algo) {
9530
        output[1] = HYBRID_MLDSA_44_P256_SA_MINOR;
9531
    }
9532
    else if (sigAlg == mldsa_44_sa_algo &&
9533
             altSigAlg == rsa_pss_sa_algo) {
9534
        output[1] = HYBRID_MLDSA_44_RSA3072_SA_MINOR;
9535
    }
9536
    else if (sigAlg == mldsa_65_sa_algo &&
9537
             altSigAlg == ecc_dsa_sa_algo) {
9538
        output[1] = HYBRID_MLDSA_65_P384_SA_MINOR;
9539
    }
9540
    else if (sigAlg == mldsa_87_sa_algo &&
9541
             altSigAlg == ecc_dsa_sa_algo) {
9542
        output[1] = HYBRID_MLDSA_87_P521_SA_MINOR;
9543
    }
9544
    else if (sigAlg == falcon_level1_sa_algo &&
9545
             altSigAlg == ecc_dsa_sa_algo) {
9546
        output[1] = HYBRID_FALCON_LEVEL1_P256_SA_MINOR;
9547
    }
9548
    else if (sigAlg == falcon_level1_sa_algo &&
9549
             altSigAlg == rsa_pss_sa_algo) {
9550
        output[1] = HYBRID_FALCON_LEVEL1_RSA3072_SA_MINOR;
9551
    }
9552
    else if (sigAlg == falcon_level5_sa_algo &&
9553
             altSigAlg == ecc_dsa_sa_algo) {
9554
        output[1] = HYBRID_FALCON_LEVEL5_P521_SA_MINOR;
9555
    }
9556
9557
    if (output[1] != 0x0) {
9558
        output[0] = HYBRID_SA_MAJOR;
9559
    }
9560
}
9561
#endif /* WOLFSSL_DUAL_ALG_CERTS */
9562
9563
static enum wc_MACAlgorithm GetNewSAHashAlgo(int typeIn)
9564
0
{
9565
0
    switch (typeIn) {
9566
0
        case RSA_PSS_RSAE_SHA256_MINOR:
9567
0
        case RSA_PSS_PSS_SHA256_MINOR:
9568
0
        case ECDSA_BRAINPOOLP256R1TLS13_SHA256_MINOR:
9569
0
            return sha256_mac;
9570
9571
0
        case RSA_PSS_RSAE_SHA384_MINOR:
9572
0
        case RSA_PSS_PSS_SHA384_MINOR:
9573
0
        case ECDSA_BRAINPOOLP384R1TLS13_SHA384_MINOR:
9574
0
            return sha384_mac;
9575
9576
0
        case RSA_PSS_RSAE_SHA512_MINOR:
9577
0
        case RSA_PSS_PSS_SHA512_MINOR:
9578
0
        case ED25519_SA_MINOR:
9579
0
        case ED448_SA_MINOR:
9580
0
        case ECDSA_BRAINPOOLP512R1TLS13_SHA512_MINOR:
9581
0
            return sha512_mac;
9582
0
        default:
9583
0
            return no_mac;
9584
0
    }
9585
0
}
9586
9587
/* Decode the signature algorithm.
9588
 *
9589
 * input     The encoded signature algorithm.
9590
 * hashalgo  The hash algorithm.
9591
 * hsType    The signature type.
9592
 * returns INVALID_PARAMETER if not recognized and 0 otherwise.
9593
 */
9594
static WC_INLINE int DecodeTls13SigAlg(byte* input, byte* hashAlgo,
9595
                                       byte* hsType)
9596
0
{
9597
0
    int ret = 0;
9598
#if defined(WOLFSSL_HAVE_SLHDSA)
9599
    byte slhType;
9600
#endif
9601
9602
0
    switch (input[0]) {
9603
    #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
9604
        case SM2_SA_MAJOR:
9605
            if (input[1] == SM2_SA_MINOR) {
9606
                *hsType = sm2_sa_algo;
9607
                *hashAlgo = sm3_mac;
9608
            }
9609
            else
9610
                ret = INVALID_PARAMETER;
9611
            break;
9612
    #endif
9613
0
        case NEW_SA_MAJOR:
9614
0
        {
9615
0
            enum wc_MACAlgorithm mac = GetNewSAHashAlgo(input[1]);
9616
0
            *hashAlgo = (byte)mac;
9617
0
        }
9618
9619
            /* PSS encryption: 0x080[4-6] */
9620
0
            if (input[1] >= RSA_PSS_RSAE_SHA256_MINOR &&
9621
0
                    input[1] <= RSA_PSS_RSAE_SHA512_MINOR) {
9622
0
                *hsType   = input[0];
9623
0
            }
9624
            /* PSS signature: 0x080[9-B] */
9625
0
            else if (input[1] >= RSA_PSS_PSS_SHA256_MINOR &&
9626
0
                    input[1] <= RSA_PSS_PSS_SHA512_MINOR) {
9627
0
                *hsType   = input[0];
9628
0
            }
9629
    #ifdef HAVE_ED25519
9630
            /* ED25519: 0x0807 */
9631
            else if (input[1] == ED25519_SA_MINOR) {
9632
                *hsType = ed25519_sa_algo;
9633
                /* Hash performed as part of sign/verify operation. */
9634
            }
9635
    #endif
9636
    #ifdef HAVE_ED448
9637
            /* ED448: 0x0808 */
9638
            else if (input[1] == ED448_SA_MINOR) {
9639
                *hsType = ed448_sa_algo;
9640
                /* Hash performed as part of sign/verify operation. */
9641
            }
9642
    #endif
9643
    #ifdef HAVE_ECC_BRAINPOOL
9644
            else if ((input[1] == ECDSA_BRAINPOOLP256R1TLS13_SHA256_MINOR) ||
9645
                     (input[1] == ECDSA_BRAINPOOLP384R1TLS13_SHA384_MINOR) ||
9646
                     (input[1] == ECDSA_BRAINPOOLP512R1TLS13_SHA512_MINOR)) {
9647
                *hsType = ecc_dsa_sa_algo;
9648
            }
9649
    #endif
9650
0
            else
9651
0
                ret = INVALID_PARAMETER;
9652
0
            break;
9653
#if defined(HAVE_FALCON)
9654
        case FALCON_SA_MAJOR:
9655
            if (input[1] == FALCON_LEVEL1_SA_MINOR) {
9656
                *hsType = falcon_level1_sa_algo;
9657
                /* Hash performed as part of sign/verify operation. */
9658
                *hashAlgo = sha512_mac;
9659
            } else if (input[1] == FALCON_LEVEL5_SA_MINOR) {
9660
                *hsType = falcon_level5_sa_algo;
9661
                /* Hash performed as part of sign/verify operation. */
9662
                *hashAlgo = sha512_mac;
9663
            }
9664
            else
9665
                ret = INVALID_PARAMETER;
9666
            break;
9667
#endif /* HAVE_FALCON */
9668
#if defined(WOLFSSL_HAVE_MLDSA) || defined(WOLFSSL_HAVE_SLHDSA)
9669
        /* ML-DSA and SLH-DSA share the same major byte (0x09); their minor
9670
         * bytes are disjoint (ML-DSA 0x04-0x06, SLH-DSA 0x11-0x1C). */
9671
        case MLDSA_SA_MAJOR:
9672
            ret = INVALID_PARAMETER;
9673
    #if defined(WOLFSSL_HAVE_MLDSA)
9674
            if (input[1] == MLDSA_44_SA_MINOR) {
9675
                *hsType = mldsa_44_sa_algo;
9676
                /* Hash performed as part of sign/verify operation. */
9677
                *hashAlgo = sha512_mac;
9678
                ret = 0;
9679
            } else if (input[1] == MLDSA_65_SA_MINOR) {
9680
                *hsType = mldsa_65_sa_algo;
9681
                *hashAlgo = sha512_mac;
9682
                ret = 0;
9683
            } else if (input[1] == MLDSA_87_SA_MINOR) {
9684
                *hsType = mldsa_87_sa_algo;
9685
                *hashAlgo = sha512_mac;
9686
                ret = 0;
9687
            }
9688
    #endif /* WOLFSSL_HAVE_MLDSA */
9689
    #if defined(WOLFSSL_HAVE_SLHDSA)
9690
            if (ret != 0) {
9691
                slhType = SlhDsaSigMinorToType(input[1]);
9692
                if (slhType != (byte)invalid_sa_algo) {
9693
                    *hsType = slhType;
9694
                    /* Hash performed as part of sign/verify operation. */
9695
                    *hashAlgo = sha512_mac;
9696
                    ret = 0;
9697
                }
9698
            }
9699
    #endif /* WOLFSSL_HAVE_SLHDSA */
9700
            break;
9701
#endif /* WOLFSSL_HAVE_MLDSA || WOLFSSL_HAVE_SLHDSA */
9702
0
        default:
9703
0
            *hashAlgo = input[0];
9704
0
            *hsType   = input[1];
9705
0
            break;
9706
0
    }
9707
9708
0
    return ret;
9709
0
}
9710
9711
#ifdef WOLFSSL_DUAL_ALG_CERTS
9712
/* Decode the hybrid signature algorithm.
9713
 *
9714
 * input     The encoded signature algorithm.
9715
 * hashalgo  The hash algorithm.
9716
 * hsType    The signature type.
9717
 * returns INVALID_PARAMETER if not recognized and 0 otherwise.
9718
 */
9719
static WC_INLINE int DecodeTls13HybridSigAlg(byte* input, byte* hashAlg,
9720
                                             byte *sigAlg, byte *altSigAlg)
9721
{
9722
9723
    if (input[0] != HYBRID_SA_MAJOR) {
9724
        return INVALID_PARAMETER;
9725
    }
9726
9727
    if (input[1] == HYBRID_P256_MLDSA_44_SA_MINOR) {
9728
        *sigAlg = ecc_dsa_sa_algo;
9729
        *hashAlg = sha256_mac;
9730
        *altSigAlg = mldsa_44_sa_algo;
9731
    }
9732
    else if (input[1] == HYBRID_RSA3072_MLDSA_44_SA_MINOR) {
9733
        *sigAlg = rsa_pss_sa_algo;
9734
        *hashAlg = sha256_mac;
9735
        *altSigAlg = mldsa_44_sa_algo;
9736
    }
9737
    else if (input[1] == HYBRID_P384_MLDSA_65_SA_MINOR) {
9738
        *sigAlg = ecc_dsa_sa_algo;
9739
        *hashAlg = sha384_mac;
9740
        *altSigAlg = mldsa_65_sa_algo;
9741
    }
9742
    else if (input[1] == HYBRID_P521_MLDSA_87_SA_MINOR) {
9743
        *sigAlg = ecc_dsa_sa_algo;
9744
        *hashAlg = sha512_mac;
9745
        *altSigAlg = mldsa_87_sa_algo;
9746
    }
9747
    else if (input[1] == HYBRID_P256_FALCON_LEVEL1_SA_MINOR) {
9748
        *sigAlg = ecc_dsa_sa_algo;
9749
        *hashAlg = sha256_mac;
9750
        *altSigAlg = falcon_level1_sa_algo;
9751
    }
9752
    else if (input[1] == HYBRID_RSA3072_FALCON_LEVEL1_SA_MINOR) {
9753
        *sigAlg = rsa_pss_sa_algo;
9754
        *hashAlg = sha256_mac;
9755
        *altSigAlg = falcon_level1_sa_algo;
9756
    }
9757
    else if (input[1] == HYBRID_P521_FALCON_LEVEL5_SA_MINOR) {
9758
        *sigAlg = ecc_dsa_sa_algo;
9759
        *hashAlg = sha512_mac;
9760
        *altSigAlg = falcon_level5_sa_algo;
9761
    }
9762
    else if (input[1] == HYBRID_MLDSA_44_P256_SA_MINOR) {
9763
        *sigAlg = mldsa_44_sa_algo;
9764
        *hashAlg = sha256_mac;
9765
        *altSigAlg = ecc_dsa_sa_algo;
9766
    }
9767
    else if (input[1] == HYBRID_MLDSA_44_RSA3072_SA_MINOR) {
9768
        *sigAlg = mldsa_44_sa_algo;
9769
        *hashAlg = sha256_mac;
9770
        *altSigAlg = rsa_pss_sa_algo;
9771
    }
9772
    else if (input[1] == HYBRID_MLDSA_65_P384_SA_MINOR) {
9773
        *sigAlg = mldsa_65_sa_algo;
9774
        *hashAlg = sha384_mac;
9775
        *altSigAlg = ecc_dsa_sa_algo;
9776
    }
9777
    else if (input[1] == HYBRID_MLDSA_87_P521_SA_MINOR) {
9778
        *sigAlg = mldsa_87_sa_algo;
9779
        *hashAlg = sha512_mac;
9780
        *altSigAlg = ecc_dsa_sa_algo;
9781
    }
9782
    else if (input[1] == HYBRID_FALCON_LEVEL1_P256_SA_MINOR) {
9783
        *sigAlg = falcon_level1_sa_algo;
9784
        *hashAlg = sha256_mac;
9785
        *altSigAlg = ecc_dsa_sa_algo;
9786
    }
9787
    else if (input[1] == HYBRID_FALCON_LEVEL1_RSA3072_SA_MINOR) {
9788
        *sigAlg = falcon_level1_sa_algo;
9789
        *hashAlg = sha256_mac;
9790
        *altSigAlg = rsa_pss_sa_algo;
9791
    }
9792
    else if (input[1] == HYBRID_FALCON_LEVEL5_P521_SA_MINOR) {
9793
        *sigAlg = falcon_level5_sa_algo;
9794
        *hashAlg = sha512_mac;
9795
        *altSigAlg = ecc_dsa_sa_algo;
9796
    }
9797
    else {
9798
        return INVALID_PARAMETER;
9799
    }
9800
9801
    return 0;
9802
}
9803
#endif /* WOLFSSL_DUAL_ALG_CERTS */
9804
9805
/* Get the hash of the messages so far.
9806
 *
9807
 * ssl   The SSL/TLS object.
9808
 * hash  The buffer to write the hash to.
9809
 * returns the length of the hash.
9810
 */
9811
static WC_INLINE int GetMsgHash(WOLFSSL* ssl, byte* hash)
9812
0
{
9813
0
    int ret = 0;
9814
0
    switch (ssl->specs.mac_algorithm) {
9815
0
    #ifndef NO_SHA256
9816
0
        case sha256_mac:
9817
0
            ret = wc_Sha256GetHash(&ssl->hsHashes->hashSha256, hash);
9818
0
            if (ret == 0)
9819
0
                ret = WC_SHA256_DIGEST_SIZE;
9820
0
            break;
9821
0
    #endif /* !NO_SHA256 */
9822
0
    #ifdef WOLFSSL_SHA384
9823
0
        case sha384_mac:
9824
0
            ret = wc_Sha384GetHash(&ssl->hsHashes->hashSha384, hash);
9825
0
            if (ret == 0)
9826
0
                ret = WC_SHA384_DIGEST_SIZE;
9827
0
            break;
9828
0
    #endif /* WOLFSSL_SHA384 */
9829
    #ifdef WOLFSSL_TLS13_SHA512
9830
        case sha512_mac:
9831
            ret = wc_Sha512GetHash(&ssl->hsHashes->hashSha512, hash);
9832
            if (ret == 0)
9833
                ret = WC_SHA512_DIGEST_SIZE;
9834
            break;
9835
    #endif /* WOLFSSL_TLS13_SHA512 */
9836
    #ifdef WOLFSSL_SM3
9837
        case sm3_mac:
9838
            ret = wc_Sm3GetHash(&ssl->hsHashes->hashSm3, hash);
9839
            if (ret == 0)
9840
                ret = WC_SM3_DIGEST_SIZE;
9841
            break;
9842
    #endif /* WOLFSSL_SM3 */
9843
0
        default:
9844
0
            break;
9845
0
    }
9846
0
    return ret;
9847
0
}
9848
9849
/* The server certificate verification label. */
9850
static const byte serverCertVfyLabel[CERT_VFY_LABEL_SZ] =
9851
    "TLS 1.3, server CertificateVerify";
9852
/* The client certificate verification label. */
9853
static const byte clientCertVfyLabel[CERT_VFY_LABEL_SZ] =
9854
    "TLS 1.3, client CertificateVerify";
9855
/* The prefix byte in the signature data. */
9856
#define SIGNING_DATA_PREFIX_BYTE   0x20
9857
9858
/* Create the signature data for TLS v1.3 certificate verification.
9859
 *
9860
 * ssl        The SSL/TLS object.
9861
 * sigData    The signature data.
9862
 * sigDataSz  The length of the signature data.
9863
 * check      Indicates this is a check not create.
9864
 */
9865
int CreateSigData(WOLFSSL* ssl, byte* sigData, word16* sigDataSz,
9866
                  int check)
9867
0
{
9868
0
    word16 idx;
9869
0
    int side = ssl->options.side;
9870
0
    int ret;
9871
9872
    /* Signature Data = Prefix | Label | Handshake Hash */
9873
0
    XMEMSET(sigData, SIGNING_DATA_PREFIX_BYTE, SIGNING_DATA_PREFIX_SZ);
9874
0
    idx = SIGNING_DATA_PREFIX_SZ;
9875
9876
0
    if ((side == WOLFSSL_SERVER_END && check) ||
9877
0
        (side == WOLFSSL_CLIENT_END && !check)) {
9878
0
        XMEMCPY(&sigData[idx], clientCertVfyLabel, CERT_VFY_LABEL_SZ);
9879
0
    }
9880
0
    if ((side == WOLFSSL_CLIENT_END && check) ||
9881
0
        (side == WOLFSSL_SERVER_END && !check)) {
9882
0
        XMEMCPY(&sigData[idx], serverCertVfyLabel, CERT_VFY_LABEL_SZ);
9883
0
    }
9884
0
    idx += CERT_VFY_LABEL_SZ;
9885
9886
0
    ret = GetMsgHash(ssl, &sigData[idx]);
9887
0
    if (ret < 0)
9888
0
        return ret;
9889
0
    if (ret == 0)
9890
0
        return HASH_TYPE_E;
9891
9892
0
    *sigDataSz = (word16)(idx + ret);
9893
0
    ret = 0;
9894
9895
0
    return ret;
9896
0
}
9897
9898
#ifndef NO_RSA
9899
/* Encode the PKCS #1.5 RSA signature.
9900
 *
9901
 * sig        The buffer to place the encoded signature into.
9902
 * sigData    The data to be signed.
9903
 * sigDataSz  The size of the data to be signed.
9904
 * hashAlgo   The hash algorithm to use when signing.
9905
 * returns the length of the encoded signature or negative on error.
9906
 */
9907
int CreateRSAEncodedSig(byte* sig, byte* sigData, int sigDataSz,
9908
                        int sigAlgo, int hashAlgo)
9909
0
{
9910
0
    Digest digest;
9911
0
    int    hashSz = 0;
9912
0
    int    ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG);
9913
0
    byte*  hash;
9914
9915
0
    (void)sigAlgo;
9916
9917
0
    hash = sig;
9918
9919
    /* Digest the signature data. */
9920
0
    switch (hashAlgo) {
9921
0
#ifndef NO_SHA256
9922
0
        case sha256_mac:
9923
0
            ret = wc_InitSha256(&digest.sha256);
9924
0
            if (ret == 0) {
9925
0
                ret = wc_Sha256Update(&digest.sha256, sigData, (word32)sigDataSz);
9926
0
                if (ret == 0)
9927
0
                    ret = wc_Sha256Final(&digest.sha256, hash);
9928
0
                wc_Sha256Free(&digest.sha256);
9929
0
            }
9930
0
            hashSz = WC_SHA256_DIGEST_SIZE;
9931
0
            break;
9932
0
#endif
9933
0
#ifdef WOLFSSL_SHA384
9934
0
        case sha384_mac:
9935
0
            ret = wc_InitSha384(&digest.sha384);
9936
0
            if (ret == 0) {
9937
0
                ret = wc_Sha384Update(&digest.sha384, sigData, (word32)sigDataSz);
9938
0
                if (ret == 0)
9939
0
                    ret = wc_Sha384Final(&digest.sha384, hash);
9940
0
                wc_Sha384Free(&digest.sha384);
9941
0
            }
9942
0
            hashSz = WC_SHA384_DIGEST_SIZE;
9943
0
            break;
9944
0
#endif
9945
0
#ifdef WOLFSSL_SHA512
9946
0
        case sha512_mac:
9947
0
            ret = wc_InitSha512(&digest.sha512);
9948
0
            if (ret == 0) {
9949
0
                ret = wc_Sha512Update(&digest.sha512, sigData, (word32)sigDataSz);
9950
0
                if (ret == 0)
9951
0
                    ret = wc_Sha512Final(&digest.sha512, hash);
9952
0
                wc_Sha512Free(&digest.sha512);
9953
0
            }
9954
0
            hashSz = WC_SHA512_DIGEST_SIZE;
9955
0
            break;
9956
0
#endif
9957
0
       default:
9958
0
            ret = BAD_FUNC_ARG;
9959
0
            break;
9960
9961
0
    }
9962
9963
0
    if (ret != 0)
9964
0
        return ret;
9965
9966
0
    return hashSz;
9967
0
}
9968
#endif /* !NO_RSA */
9969
9970
#ifdef HAVE_ECC
9971
/* Encode the ECC signature.
9972
 *
9973
 * sigData    The data to be signed.
9974
 * sigDataSz  The size of the data to be signed.
9975
 * hashAlgo   The hash algorithm to use when signing.
9976
 * returns the length of the encoded signature or negative on error.
9977
 */
9978
static int CreateECCEncodedSig(byte* sigData, int sigDataSz, int hashAlgo)
9979
0
{
9980
0
    Digest digest;
9981
0
    int    hashSz = 0;
9982
0
    int    ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG);
9983
9984
    /* Digest the signature data. */
9985
0
    switch (hashAlgo) {
9986
0
#ifndef NO_SHA256
9987
0
        case sha256_mac:
9988
0
            ret = wc_InitSha256(&digest.sha256);
9989
0
            if (ret == 0) {
9990
0
                ret = wc_Sha256Update(&digest.sha256, sigData, (word32)sigDataSz);
9991
0
                if (ret == 0)
9992
0
                    ret = wc_Sha256Final(&digest.sha256, sigData);
9993
0
                wc_Sha256Free(&digest.sha256);
9994
0
            }
9995
0
            hashSz = WC_SHA256_DIGEST_SIZE;
9996
0
            break;
9997
0
#endif
9998
0
#ifdef WOLFSSL_SHA384
9999
0
        case sha384_mac:
10000
0
            ret = wc_InitSha384(&digest.sha384);
10001
0
            if (ret == 0) {
10002
0
                ret = wc_Sha384Update(&digest.sha384, sigData, (word32)sigDataSz);
10003
0
                if (ret == 0)
10004
0
                    ret = wc_Sha384Final(&digest.sha384, sigData);
10005
0
                wc_Sha384Free(&digest.sha384);
10006
0
            }
10007
0
            hashSz = WC_SHA384_DIGEST_SIZE;
10008
0
            break;
10009
0
#endif
10010
0
#ifdef WOLFSSL_SHA512
10011
0
        case sha512_mac:
10012
0
            ret = wc_InitSha512(&digest.sha512);
10013
0
            if (ret == 0) {
10014
0
                ret = wc_Sha512Update(&digest.sha512, sigData, (word32)sigDataSz);
10015
0
                if (ret == 0)
10016
0
                    ret = wc_Sha512Final(&digest.sha512, sigData);
10017
0
                wc_Sha512Free(&digest.sha512);
10018
0
            }
10019
0
            hashSz = WC_SHA512_DIGEST_SIZE;
10020
0
            break;
10021
0
#endif
10022
0
        default:
10023
0
            ret = BAD_FUNC_ARG;
10024
0
            break;
10025
0
    }
10026
10027
0
    if (ret != 0)
10028
0
        return ret;
10029
10030
0
    return hashSz;
10031
0
}
10032
#endif /* HAVE_ECC */
10033
10034
#if !defined(NO_RSA) && defined(WC_RSA_PSS)
10035
/* Check that the decrypted signature matches the encoded signature
10036
 * based on the digest of the signature data.
10037
 *
10038
 * ssl       The SSL/TLS object.
10039
 * sigAlgo   The signature algorithm used to generate signature.
10040
 * hashAlgo  The hash algorithm used to generate signature.
10041
 * decSig    The decrypted signature.
10042
 * decSigSz  The size of the decrypted signature.
10043
 * returns 0 on success, otherwise failure.
10044
 */
10045
static int CheckRSASignature(WOLFSSL* ssl, int sigAlgo, int hashAlgo,
10046
                             byte* decSig, word32 decSigSz)
10047
0
{
10048
0
    int    ret = 0;
10049
0
    byte   sigData[MAX_SIG_DATA_SZ];
10050
0
    word16 sigDataSz;
10051
10052
0
    ret = CreateSigData(ssl, sigData, &sigDataSz, 1);
10053
0
    if (ret != 0)
10054
0
        return ret;
10055
10056
0
    if (sigAlgo == rsa_pss_sa_algo) {
10057
0
        enum wc_HashType hashType = WC_HASH_TYPE_NONE;
10058
0
        word32 sigSz;
10059
10060
0
        ret = ConvertHashPss(hashAlgo, &hashType, NULL);
10061
0
        if (ret < 0)
10062
0
            return ret;
10063
10064
        /* PSS signature can be done in-place */
10065
0
        ret = CreateRSAEncodedSig(sigData, sigData, sigDataSz,
10066
0
                                  sigAlgo, hashAlgo);
10067
0
        if (ret < 0)
10068
0
            return ret;
10069
0
        sigSz = (word32)ret;
10070
10071
0
        ret = wc_RsaPSS_CheckPadding(sigData, sigSz, decSig, decSigSz,
10072
0
                                     hashType);
10073
0
    }
10074
10075
0
    return ret;
10076
0
}
10077
#endif /* !NO_RSA && WC_RSA_PSS */
10078
#endif /* !NO_RSA || HAVE_ECC */
10079
10080
#if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER)
10081
/* Get the next certificate from the list for writing into the TLS v1.3
10082
 * Certificate message.
10083
 *
10084
 * data    The certificate list.
10085
 * length  The length of the certificate data in the list.
10086
 * idx     The index of the next certificate.
10087
 * returns the length of the certificate data. 0 indicates no more certificates
10088
 * in the list.
10089
 */
10090
static word32 NextCert(byte* data, word32 length, word32* idx)
10091
0
{
10092
0
    word32 len;
10093
10094
    /* Would index read past end of list? */
10095
0
    if (*idx + 3 > length)
10096
0
        return 0;
10097
10098
    /* Length of the current ASN.1 encoded certificate. */
10099
0
    c24to32(data + *idx, &len);
10100
    /* Include the length field. */
10101
0
    len += 3;
10102
10103
    /* Ensure len does not overrun certificate list */
10104
0
    if (*idx + len > length)
10105
0
        return 0;
10106
10107
    /* Move index to next certificate and return the current certificate's
10108
     * length.
10109
     */
10110
0
    *idx += len;
10111
0
    return len;
10112
0
}
10113
10114
#if defined(HAVE_CERTIFICATE_STATUS_REQUEST) && !defined(NO_WOLFSSL_SERVER)
10115
/* Write certificate status request into certificate to buffer.
10116
 *
10117
 * ssl       SSL/TLS object.
10118
 * certExts  DerBuffer array. buffers written
10119
 * extSz     word32 array.
10120
 *           Length of the certificate status request data for the certificate.
10121
 * extSz_num number of the CSR written
10122
 * extIdx    The index number of certificate status request data
10123
 *           for the certificate.
10124
 * offset    index offset
10125
 * returns   Total number of bytes written on success or negative value on error.
10126
 */
10127
static int WriteCSRToBuffer(WOLFSSL* ssl, DerBuffer** certExts,
10128
                                word16* extSz,  word16 extSz_num)
10129
{
10130
    int    ret = 0;
10131
    TLSX* ext;
10132
    CertificateStatusRequest* csr;
10133
    word32 ex_offset = HELLO_EXT_TYPE_SZ + OPAQUE16_LEN /* extension type */
10134
                    + OPAQUE16_LEN /* extension length */;
10135
    word32 totalSz = 0;
10136
    word32 tmpSz;
10137
    word32 extIdx;
10138
    DerBuffer* der;
10139
10140
    if (extSz_num > MAX_CERT_EXTENSIONS)
10141
        return MAX_CERT_EXTENSIONS_ERR;
10142
10143
    ext = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST);
10144
    csr = ext ? (CertificateStatusRequest*)ext->data : NULL;
10145
10146
    if (csr) {
10147
        for (extIdx = 0; extIdx < (word16)(extSz_num); extIdx++) {
10148
            tmpSz = TLSX_CSR_GetSize_ex(csr, 0, (int)extIdx);
10149
10150
            if (ssl->fragOffset != 0 && certExts[extIdx] != NULL) {
10151
                /* A fragmented send is being resumed and this buffer was
10152
                 * written by the earlier call. extSz starts over on every
10153
                 * call, so recover this entry's size from the length written
10154
                 * into the buffer. */
10155
                ato16(certExts[extIdx]->buffer, &extSz[extIdx]);
10156
                extSz[extIdx] += OPAQUE16_LEN;
10157
            }
10158
            else {
10159
                /* Not a resume, so anything still allocated here is left over
10160
                 * from a completed message and must not be reused. */
10161
                FreeDer(&certExts[extIdx]);
10162
10163
                if (tmpSz > (OPAQUE8_LEN + OPAQUE24_LEN)) {
10164
                    /* csr extension is not zero */
10165
                    if (tmpSz > WOLFSSL_MAX_16BIT)
10166
                        return BUFFER_E;
10167
                    extSz[extIdx] = (word16)tmpSz;
10168
10169
                    ret = AllocDer(&certExts[extIdx], extSz[extIdx] + ex_offset,
10170
                                                        CERT_TYPE, ssl->heap);
10171
                    if (ret < 0)
10172
                        return ret;
10173
                    der = certExts[extIdx];
10174
10175
                    /* write extension type */
10176
                    c16toa(ext->type, der->buffer
10177
                                    + OPAQUE16_LEN);
10178
                    /* writes extension data length. */
10179
                    c16toa(extSz[extIdx], der->buffer
10180
                                + HELLO_EXT_TYPE_SZ + OPAQUE16_LEN);
10181
                    /* write extension data */
10182
                    extSz[extIdx] = (word16)TLSX_CSR_Write_ex(csr,
10183
                            der->buffer + ex_offset, 0, extIdx);
10184
                    /* add extension offset */
10185
                    extSz[extIdx] += (word16)ex_offset;
10186
                    /* extension length */
10187
                    c16toa(extSz[extIdx] - OPAQUE16_LEN,
10188
                                der->buffer);
10189
                }
10190
            }
10191
            totalSz += extSz[extIdx];
10192
        }
10193
    }
10194
    else {
10195
        /* chain cert empty extension size */
10196
        totalSz += OPAQUE16_LEN * extSz_num;
10197
    }
10198
    return (int)totalSz;
10199
}
10200
#endif /* HAVE_CERTIFICATE_STATUS_REQUEST */
10201
/* Add certificate data and empty extension to output up to the fragment size.
10202
 *
10203
 * ssl     SSL/TLS object.
10204
 * cert    The certificate data to write out.
10205
 * len     The length of the certificate data.
10206
 * extSz   Length of the extension data with the certificate.
10207
 * idx     The start of the certificate data to write out.
10208
 * fragSz  The maximum size of this fragment.
10209
 * output  The buffer to write to.
10210
 * extIdx  The index number of the extension data with the certificate
10211
 * returns the number of bytes written.
10212
 */
10213
static word32 AddCertExt(WOLFSSL* ssl, byte* cert, word32 len, word16 extSz,
10214
                         word32 idx, word32 fragSz, byte* output, word16 extIdx)
10215
0
{
10216
0
    word32 i = 0;
10217
0
    word32 copySz = min(len - idx, fragSz);
10218
10219
0
    if (idx < len) {
10220
0
        XMEMCPY(output, cert + idx, copySz);
10221
0
        i = copySz;
10222
0
        if (copySz == fragSz)
10223
0
            return i;
10224
0
    }
10225
0
    copySz = len + extSz - idx - i;
10226
10227
0
    if (extSz == OPAQUE16_LEN) {
10228
0
        if (copySz <= fragSz) {
10229
            /* Empty extension */
10230
0
            output[i++] = 0;
10231
0
            output[i++] = 0;
10232
0
        }
10233
0
    }
10234
0
    else {
10235
0
        byte* certExts = ssl->buffers.certExts[extIdx]->buffer + idx + i - len;
10236
        /* Put out as much of the extensions' data as will fit in fragment. */
10237
0
        if (copySz > fragSz - i)
10238
0
            copySz = fragSz - i;
10239
0
        XMEMCPY(output + i, certExts, copySz);
10240
0
        i += copySz;
10241
0
    }
10242
10243
0
    return i;
10244
0
}
10245
10246
#if defined(HAVE_CERTIFICATE_STATUS_REQUEST) && !defined(NO_WOLFSSL_SERVER)
10247
static int SetupOcspResp(WOLFSSL* ssl)
10248
{
10249
    DecodedCert* cert = NULL;
10250
    CertificateStatusRequest* csr = NULL;
10251
    TLSX* extension = NULL;
10252
    int ret = 0;
10253
    OcspRequest* request = NULL;
10254
    byte ctxOwnsRequest = 0;
10255
10256
    extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST);
10257
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
10258
    /* During post-handshake client authentication the client must staple
10259
     * its own OCSP response, but the status_request extension it offered in
10260
     * the initial ClientHello is no longer present on ssl->extensions.
10261
     * Recreate it here (the request extension still lives on
10262
     * ctx->extensions). Pass ssl so csr->ssl is set, which the response
10263
     * size/write path requires. */
10264
    if (extension == NULL &&
10265
            ssl->options.side == WOLFSSL_CLIENT_END &&
10266
            ssl->options.handShakeDone &&
10267
            TLSX_Find(ssl->ctx->extensions, TLSX_STATUS_REQUEST) != NULL) {
10268
        ret = TLSX_UseCertificateStatusRequest(&ssl->extensions,
10269
                WOLFSSL_CSR_OCSP, 0, ssl, ssl->heap, ssl->devId);
10270
        if (ret != WOLFSSL_SUCCESS)
10271
            return ret;
10272
        extension = TLSX_Find(ssl->extensions, TLSX_STATUS_REQUEST);
10273
    }
10274
#endif
10275
    if (extension == NULL)
10276
        return 0; /* peer didn't signal ocsp support */
10277
    csr = (CertificateStatusRequest*)extension->data;
10278
    if (csr == NULL)
10279
        return MEMORY_ERROR;
10280
10281
    if (SSL_CM(ssl) != NULL &&
10282
            SSL_CM(ssl)->ocsp_stapling != NULL &&
10283
            SSL_CM(ssl)->ocsp_stapling->statusCb != NULL) {
10284
        return TLSX_CSR_SetResponseWithStatusCB(ssl);
10285
    }
10286
10287
    if (ssl->buffers.certificate == NULL) {
10288
        WOLFSSL_MSG("Certificate buffer not set!");
10289
        return BUFFER_ERROR;
10290
    }
10291
    cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), ssl->heap,
10292
                                 DYNAMIC_TYPE_DCERT);
10293
    if (cert == NULL) {
10294
        return MEMORY_E;
10295
    }
10296
    InitDecodedCert(cert, ssl->buffers.certificate->buffer,
10297
                    ssl->buffers.certificate->length, ssl->heap);
10298
    ret = ParseCert(cert, CERT_TYPE, NO_VERIFY, SSL_CM(ssl));
10299
    if (ret != 0) {
10300
        FreeDecodedCert(cert);
10301
        XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
10302
        return ret;
10303
    }
10304
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
10305
    /* On client PHA the same certificate is re-stapled every round; reuse
10306
     * request slot 0 instead of appending, else csr->requests grows until
10307
     * MAX_CERT_EXTENSIONS_ERR. */
10308
    if (ssl->options.side == WOLFSSL_CLIENT_END && ssl->options.handShakeDone) {
10309
        ret = TLSX_CSR_InitRequest_ex(ssl->extensions, cert, ssl->heap, 0);
10310
    }
10311
    else
10312
#endif
10313
    {
10314
        ret = TLSX_CSR_InitRequest(ssl->extensions, cert, ssl->heap);
10315
    }
10316
    FreeDecodedCert(cert);
10317
    XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
10318
    if (ret != 0 )
10319
        return ret;
10320
10321
    /* Free previous OCSP response buffers to avoid leak on PHA reuse */
10322
    {
10323
        int j;
10324
        for (j = 0; j < MAX_CERT_EXTENSIONS; j++) {
10325
            XFREE(csr->responses[j].buffer, ssl->heap,
10326
                DYNAMIC_TYPE_TMP_BUFFER);
10327
            csr->responses[j].buffer = NULL;
10328
            csr->responses[j].length = 0;
10329
        }
10330
    }
10331
    request = &csr->request.ocsp[0];
10332
    ret = CreateOcspResponse(ssl, &request, &csr->responses[0],
10333
                             &ctxOwnsRequest);
10334
    /* Only a successful call replaces "request", and only a request the CTX did
10335
     * not take ownership of is ours to free. Both are checked, matching the
10336
     * SendCertificateStatus() callers. */
10337
    if (ret == 0 && request != &csr->request.ocsp[0] && !ctxOwnsRequest) {
10338
        /* request was allocated in CreateOcspResponse() */
10339
        FreeOcspRequest(request);
10340
        XFREE(request, ssl->heap, DYNAMIC_TYPE_OCSP_REQUEST);
10341
    }
10342
    if (ret != 0)
10343
        return ret;
10344
10345
    if (csr->responses[0].buffer)
10346
        extension->resp = 1;
10347
#if defined(WOLFSSL_TLS_OCSP_MULTI)
10348
    /* process OCSP request in certificate chain */
10349
    if ((ret = ProcessChainOCSPRequest(ssl)) != 0) {
10350
        WOLFSSL_MSG("Process Cert Chain OCSP request failed");
10351
        WOLFSSL_ERROR_VERBOSE(ret);
10352
        return ret;
10353
    }
10354
#endif
10355
    return ret;
10356
}
10357
#endif
10358
10359
#if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
10360
/* Certificate is signed with the deprecated SHA-1 hash. An unrecognized or
10361
 * unparsable algorithm is not SHA-1; the peer still verifies the chain.
10362
 *
10363
 * der    Buffer holding the DER encoded certificate.
10364
 * derSz  Length of the DER encoded certificate.
10365
 * returns 1 when SHA-1 signed, 0 otherwise.
10366
 */
10367
static int IsSha1SignedCert(const byte* der, word32 derSz)
10368
0
{
10369
0
    word32 idx = 0;
10370
0
    word32 oid = 0;
10371
0
    word32 algoIdEnd = 0;
10372
0
    int    len = 0;
10373
0
    int    isSha1 = 0;
10374
0
    int    ret;
10375
0
#if defined(WC_RSA_PSS) && !defined(NO_RSA)
10376
0
    enum wc_HashType hash = WC_HASH_TYPE_NONE;
10377
0
    int    mgf = 0;
10378
0
    int    saltLen = 0;
10379
0
#endif
10380
10381
    /* Certificate ::= SEQUENCE { tbsCertificate, signatureAlgorithm, ... }.
10382
     * GetSequence() checks each length against the maximum index passed in, so
10383
     * idx and idx + len stay inside the buffer. */
10384
0
    ret = GetSequence(der, &idx, &len, derSz);
10385
0
    if (ret >= 0)
10386
0
        ret = GetSequence(der, &idx, &len, derSz);
10387
0
    if (ret >= 0) {
10388
        /* signatureAlgorithm immediately follows the tbsCertificate. Decode
10389
         * the AlgorithmIdentifier here rather than with GetAlgoId() so the
10390
         * RSASSA-PSS parameters, which hold the digest, stay reachable. */
10391
0
        idx += (word32)len;
10392
0
        ret = GetSequence(der, &idx, &len, derSz);
10393
0
    }
10394
0
    if (ret >= 0) {
10395
0
        algoIdEnd = idx + (word32)len;
10396
0
        ret = GetObjectId(der, &idx, &oid, oidSigType, algoIdEnd);
10397
0
    }
10398
0
    if (ret >= 0) {
10399
0
        if ((oid == CTC_SHAwRSA) || (oid == CTC_SHAwECDSA) ||
10400
0
                (oid == CTC_SHAwDSA)) {
10401
0
            isSha1 = 1;
10402
0
        }
10403
0
    #if defined(WC_RSA_PSS) && !defined(NO_RSA)
10404
        /* RSASSA-PSS uses one signature OID for every digest and names the
10405
         * digest in the algorithm parameters instead. Absent parameters are
10406
         * passed through as a zero length buffer rather than skipped: RFC 4055
10407
         * makes them mean all defaults, which is SHA-1, and
10408
         * wc_DecodeRsaPssParams() reports that. */
10409
0
        else if ((oid == RSAPSSk) && (idx <= algoIdEnd) &&
10410
0
                (wc_DecodeRsaPssParams(der + idx, algoIdEnd - idx, &hash, &mgf,
10411
0
                                       &saltLen) == 0)) {
10412
0
            isSha1 = (hash == WC_HASH_TYPE_SHA);
10413
0
        }
10414
0
    #endif
10415
0
    }
10416
10417
0
    return isSha1;
10418
0
}
10419
10420
/* Certificate is self signed. RFC 8446 Section 4.4.2.2: "Certificates that are
10421
 * self-signed or certificates that are expected to be trust anchors are not
10422
 * validated as part of the chain and therefore MAY be signed with any
10423
 * algorithm."
10424
 *
10425
 * DecodedCert.selfSigned is an issuer/subject name hash compare rather than a
10426
 * verified self-signature, which is enough here: the chain is the one this end
10427
 * was configured with, not one an attacker supplies.
10428
 *
10429
 * The certificate is parsed as CA_TYPE rather than CERT_TYPE so a trust anchor
10430
 * carrying serial number 0 still decodes. ParseCertRelative() rejects a zero
10431
 * serial for CERT_TYPE, and legacy roots, the certificates most likely to be
10432
 * SHA-1 signed, are the ones that use it. With NO_VERIFY and no certificate
10433
 * manager the serial exemption is all the type changes, and that exemption
10434
 * still requires a self signed CA, so a leaf carrying serial 0 is reported as
10435
 * not self signed and stays subject to the SHA-1 rule.
10436
 *
10437
 * ssl           The SSL/TLS object.
10438
 * der           Buffer holding the DER encoded certificate.
10439
 * derSz         Length of the DER encoded certificate.
10440
 * isSelfSigned  On success, 1 when self signed, 0 otherwise. A certificate
10441
 *               that will not parse is reported as not self signed so the
10442
 *               SHA-1 rule still applies to it.
10443
 * returns 0 on success, MEMORY_E when the decoder cannot be allocated.
10444
 */
10445
static int IsSelfSignedCert(WOLFSSL* ssl, const byte* der, word32 derSz,
10446
                            int* isSelfSigned)
10447
0
{
10448
0
    DecodedCert* cert;
10449
10450
0
    *isSelfSigned = 0;
10451
10452
0
    cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), ssl->heap,
10453
0
                                 DYNAMIC_TYPE_DCERT);
10454
0
    if (cert == NULL)
10455
0
        return MEMORY_E;
10456
10457
0
    InitDecodedCert(cert, der, derSz, ssl->heap);
10458
0
    if (ParseCertRelative(cert, CA_TYPE, NO_VERIFY, NULL, NULL) == 0)
10459
0
        *isSelfSigned = (cert->selfSigned != 0);
10460
0
    else
10461
0
        WOLFSSL_MSG("Cannot decode certificate, not treating as self signed");
10462
0
    FreeDecodedCert(cert);
10463
0
    XFREE(cert, ssl->heap, DYNAMIC_TYPE_DCERT);
10464
10465
0
    return 0;
10466
0
}
10467
10468
/* Check the chain about to be sent against what the peer advertised.
10469
 *
10470
 * RFC 8446 Section 4.4.2.2 permits a fallback chain the peer did not advertise
10471
 * support for, but the chain "MUST NOT" use SHA-1 unless the peer's
10472
 * advertisement permits it. Section 4.4.2.3 requires client certificates to be
10473
 * signed with an acceptable algorithm "as described in Section 4.4.2.2", so the
10474
 * same rule covers both sides. How a failure is resolved differs by side and is
10475
 * left to the caller.
10476
 *
10477
 * ssl  The SSL/TLS object.
10478
 * returns 0 when the chain may be sent, MATCH_SUITE_ERROR when it may not and
10479
 * MEMORY_E when a certificate could not be examined.
10480
 */
10481
static int CheckCertChainSigAlgo(WOLFSSL* ssl)
10482
0
{
10483
0
    byte*  chain;
10484
0
    byte*  cur;
10485
0
    word32 chainSz;
10486
0
    word32 len;
10487
0
    word32 idx = 0;
10488
0
    int    selfSigned = 0;
10489
0
    int    ret = 0;
10490
10491
0
    if (ssl->options.peerSha1CertOk)
10492
0
        return 0;
10493
10494
0
    if (ssl->buffers.certificate == NULL ||
10495
0
            ssl->buffers.certificate->buffer == NULL) {
10496
0
        return 0;
10497
0
    }
10498
10499
0
    if (IsSha1SignedCert(ssl->buffers.certificate->buffer,
10500
0
                         ssl->buffers.certificate->length)) {
10501
0
        ret = IsSelfSignedCert(ssl, ssl->buffers.certificate->buffer,
10502
0
                               ssl->buffers.certificate->length, &selfSigned);
10503
0
        if (ret != 0)
10504
0
            return ret;
10505
0
        if (!selfSigned)
10506
0
            ret = MATCH_SUITE_ERROR;
10507
0
    }
10508
10509
0
    if (ret == 0 && ssl->buffers.certChain != NULL &&
10510
0
            ssl->buffers.certChain->buffer != NULL &&
10511
0
            ssl->buffers.certChainCnt > 0) {
10512
0
        chain = ssl->buffers.certChain->buffer;
10513
0
        chainSz = ssl->buffers.certChain->length;
10514
10515
0
        while (ret == 0) {
10516
0
            cur = chain + idx;
10517
            /* NextCert() length includes the CERT_HEADER_SZ byte prefix and
10518
             * is 0 at the end of the list. Keep this terminator matching the
10519
             * send loop so both walk the same certificates. */
10520
0
            len = NextCert(chain, chainSz, &idx);
10521
0
            if (len == 0)
10522
0
                break;
10523
0
            if (len <= CERT_HEADER_SZ)
10524
0
                continue;
10525
0
            cur += CERT_HEADER_SZ;
10526
0
            len -= CERT_HEADER_SZ;
10527
10528
0
            if (IsSha1SignedCert(cur, len)) {
10529
0
                ret = IsSelfSignedCert(ssl, cur, len, &selfSigned);
10530
0
                if (ret != 0)
10531
0
                    return ret;
10532
0
                if (!selfSigned)
10533
0
                    ret = MATCH_SUITE_ERROR;
10534
0
            }
10535
0
        }
10536
0
    }
10537
10538
0
    if (ret == WC_NO_ERR_TRACE(MATCH_SUITE_ERROR))
10539
0
        WOLFSSL_MSG("Chain is SHA-1 signed but peer did not advertise SHA-1");
10540
10541
0
    return ret;
10542
0
}
10543
#endif /* !NO_CERTS && !WOLFSSL_NO_SIGALG */
10544
10545
/* handle generation TLS v1.3 certificate (11) */
10546
/* Send the certificate for this end and any CAs that help with validation.
10547
 * This message is always encrypted in TLS v1.3.
10548
 *
10549
 * ssl  The SSL/TLS object.
10550
 * returns 0 on success, otherwise failure.
10551
 */
10552
static int SendTls13Certificate(WOLFSSL* ssl)
10553
0
{
10554
0
    int    ret = 0;
10555
0
    word32 certSz, certChainSz, headerSz, listSz, payloadSz;
10556
0
    word16 extSz[MAX_CERT_EXTENSIONS];
10557
0
    word16 extIdx = 0;
10558
0
    word32 maxFragment;
10559
0
    word32 totalextSz = 0;
10560
0
    word32 len = 0;
10561
0
    word32 idx = 0;
10562
0
    word32 offset = 0;
10563
0
    word32 entrySz = 0;
10564
0
    byte*  p = NULL;
10565
0
    byte   certReqCtxLen = 0;
10566
0
    sword32 length;
10567
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
10568
    byte*  certReqCtx = NULL;
10569
#endif
10570
0
#ifndef WOLFSSL_NO_SIGALG
10571
0
    int    chainRet;
10572
0
#endif
10573
10574
#ifdef OPENSSL_EXTRA
10575
    WOLFSSL_X509* x509 = NULL;
10576
    WOLFSSL_EVP_PKEY* pkey = NULL;
10577
#endif
10578
10579
0
    WOLFSSL_START(WC_FUNC_CERTIFICATE_SEND);
10580
0
    WOLFSSL_ENTER("SendTls13Certificate");
10581
10582
0
    XMEMSET(extSz, 0, sizeof(extSz));
10583
10584
0
    ssl->options.buildingMsg = 1;
10585
10586
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
10587
    if (ssl->options.side == WOLFSSL_CLIENT_END && ssl->certReqCtx != NULL) {
10588
        certReqCtxLen = ssl->certReqCtx->len;
10589
        certReqCtx = &ssl->certReqCtx->ctx;
10590
    }
10591
#endif
10592
10593
#if defined(OPENSSL_EXTRA) && defined(WOLFSSL_CERT_SETUP_CB)
10594
    /* call client cert callback if no cert has been loaded */
10595
    if ((ssl->ctx->CBClientCert != NULL) &&
10596
        (!ssl->buffers.certificate || !ssl->buffers.certificate->buffer)) {
10597
        ret = ssl->ctx->CBClientCert(ssl, &x509, &pkey);
10598
        if (ret == 1) {
10599
            if ((wolfSSL_CTX_use_certificate(ssl->ctx, x509) == WOLFSSL_SUCCESS) &&
10600
                (wolfSSL_CTX_use_PrivateKey(ssl->ctx, pkey) == WOLFSSL_SUCCESS)) {
10601
                ssl->options.sendVerify = SEND_CERT;
10602
            }
10603
            wolfSSL_X509_free(x509);
10604
            x509 = NULL;
10605
            wolfSSL_EVP_PKEY_free(pkey);
10606
        }
10607
    }
10608
#endif
10609
10610
0
#ifndef WOLFSSL_NO_SIGALG
10611
    /* Run before the blank certificate branch below so a client with nothing
10612
     * acceptable can fall into it. Only on first entry: fragOffset is reset to
10613
     * 0 before this message is built and is non-zero only while resuming a
10614
     * fragmented send, whose chain was checked on the first pass. The result is
10615
     * kept out of ret so a pending value there is left alone. */
10616
0
    if (ssl->options.sendVerify != SEND_BLANK_CERT && ssl->fragOffset == 0) {
10617
0
        chainRet = CheckCertChainSigAlgo(ssl);
10618
0
        if ((chainRet != 0) &&
10619
0
                (chainRet != WC_NO_ERR_TRACE(MATCH_SUITE_ERROR))) {
10620
0
            return chainRet;
10621
0
        }
10622
0
        if (chainRet == WC_NO_ERR_TRACE(MATCH_SUITE_ERROR)) {
10623
0
            if (ssl->options.side == WOLFSSL_SERVER_END) {
10624
0
                SendAlert(ssl, alert_fatal, handshake_failure);
10625
0
                WOLFSSL_ERROR_VERBOSE(MATCH_SUITE_ERROR);
10626
0
                return MATCH_SUITE_ERROR;
10627
0
            }
10628
0
        #ifndef WOLFSSL_NO_CLIENT_CERT_ERROR
10629
            /* RFC 8446 Section 4.4.2: a client with no acceptable certificate
10630
             * sends an empty certificate_list rather than failing. */
10631
0
            WOLFSSL_MSG("Client chain not acceptable, sending blank cert");
10632
0
            ssl->options.sendVerify = SEND_BLANK_CERT;
10633
        #else
10634
            /* RFC 8446 Section 4.4.2.2: an endpoint that cannot produce an
10635
             * acceptable chain aborts with a certificate related alert,
10636
             * unsupported_certificate by default. */
10637
            WOLFSSL_MSG("Client chain not acceptable and blank cert not "
10638
                        "allowed");
10639
            SendAlert(ssl, alert_fatal, unsupported_certificate);
10640
            WOLFSSL_ERROR_VERBOSE(NO_CERT_ERROR);
10641
            return NO_CERT_ERROR;
10642
        #endif
10643
0
        }
10644
0
    }
10645
0
#endif
10646
10647
0
    if (ssl->options.sendVerify == SEND_BLANK_CERT) {
10648
0
        certSz = 0;
10649
0
        certChainSz = 0;
10650
0
        headerSz = OPAQUE8_LEN + certReqCtxLen + CERT_HEADER_SZ;
10651
0
        length = (sword32)headerSz;
10652
0
        listSz = 0;
10653
0
    }
10654
0
    else {
10655
0
        if (!ssl->buffers.certificate || !ssl->buffers.certificate->buffer) {
10656
0
            WOLFSSL_MSG("Send Cert missing certificate buffer");
10657
0
            return NO_CERT_ERROR;
10658
0
        }
10659
        /* Certificate Data */
10660
0
        certSz = ssl->buffers.certificate->length;
10661
0
        if (ssl->buffers.certChainCnt > MAX_CHAIN_DEPTH) {
10662
0
            WOLFSSL_MSG("Certificate chain count exceeds maximum depth");
10663
0
            return MAX_CHAIN_ERROR;
10664
0
        }
10665
        /* Cert Req Ctx Len | Cert Req Ctx | Cert List Len | Cert Data Len */
10666
0
        headerSz = OPAQUE8_LEN + certReqCtxLen + CERT_HEADER_SZ +
10667
0
                   CERT_HEADER_SZ;
10668
        /* set empty extension as default */
10669
0
        for (extIdx = 0; extIdx < (word16)XELEM_CNT(extSz); extIdx++)
10670
0
            extSz[extIdx] = OPAQUE16_LEN;
10671
10672
    #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) && !defined(NO_WOLFSSL_SERVER)
10673
        /* Staple our own OCSP response with the Certificate. Normally only the
10674
         * server staples; the client's CSR holds the server's response, so
10675
         * echoing it back is wrong. The exception is post-handshake auth (PHA),
10676
         * where the client sends its own Certificate and staples for it. */
10677
        if (ssl->options.side == WOLFSSL_SERVER_END
10678
        #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
10679
            || (ssl->options.side == WOLFSSL_CLIENT_END
10680
                && ssl->options.handShakeDone)
10681
        #endif
10682
        ) {
10683
            /* Build the responses once. A resumed send reuses them: looking
10684
             * them up again appends another set of requests to the extension
10685
             * until it overflows with MAX_CERT_EXTENSIONS_ERR. */
10686
            if (ssl->fragOffset == 0) {
10687
                ret = SetupOcspResp(ssl);
10688
                if (ret != 0)
10689
                    return ret;
10690
            }
10691
10692
            if ((1 + ssl->buffers.certChainCnt) > MAX_CERT_EXTENSIONS)
10693
                ret = MAX_CERT_EXTENSIONS_ERR;
10694
            if (ret == 0)
10695
                ret = WriteCSRToBuffer(ssl, &ssl->buffers.certExts[0], &extSz[0],
10696
                        1 /* +1 for leaf */ + (word16)ssl->buffers.certChainCnt);
10697
            if (ret < 0)
10698
                return ret;
10699
            totalextSz += ret;
10700
            ret = 0; /* Clear to signal no error */
10701
        }
10702
        else
10703
    #endif
10704
0
        {
10705
            /* Leaf cert empty extension size */
10706
0
            totalextSz += OPAQUE16_LEN;
10707
            /* chain cert empty extension size */
10708
0
            totalextSz += OPAQUE16_LEN * ssl->buffers.certChainCnt;
10709
0
        }
10710
10711
        /* Length of message data with one certificate and extensions. */
10712
0
        length = (sword32)(headerSz + certSz + totalextSz);
10713
        /* Length of list data with one certificate and extensions. */
10714
0
        listSz = CERT_HEADER_SZ + certSz + totalextSz;
10715
10716
        /* Send rest of chain if sending cert (chain has leading size/s). */
10717
0
        if (certSz > 0 && ssl->buffers.certChainCnt > 0) {
10718
0
            p = ssl->buffers.certChain->buffer;
10719
            /* Chain length including extensions. */
10720
0
            certChainSz = ssl->buffers.certChain->length;
10721
10722
0
            length += certChainSz;
10723
0
            listSz += certChainSz;
10724
0
        }
10725
0
        else
10726
0
            certChainSz = 0;
10727
0
    }
10728
10729
0
    payloadSz = (word32)length;
10730
10731
0
    if (ssl->fragOffset != 0)
10732
0
        length -= (ssl->fragOffset + headerSz);
10733
10734
0
    maxFragment = (word32)wolfssl_local_GetMaxPlaintextSize(ssl);
10735
10736
0
    extIdx = 0;
10737
10738
    /* Only ssl->fragOffset survives a WANT_WRITE, so a resume inside the chain
10739
     * has to rebuild the walk cursor from it. */
10740
0
    if (certChainSz > 0 && ssl->fragOffset >= certSz + extSz[0]) {
10741
0
        word32 chainPos = ssl->fragOffset - (certSz + extSz[0]);
10742
10743
    #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) && !defined(NO_WOLFSSL_SERVER)
10744
        /* The leaf is behind us and its buffer was rebuilt above. */
10745
        FreeDer(&ssl->buffers.certExts[0]);
10746
    #endif
10747
10748
0
        while (chainPos > 0) {
10749
0
            word32 prevIdx = idx;
10750
10751
0
            len = NextCert(ssl->buffers.certChain->buffer,
10752
0
                           ssl->buffers.certChain->length, &idx);
10753
0
            if (len == 0)
10754
0
                break;
10755
        #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) && \
10756
                !defined(NO_WOLFSSL_SERVER)
10757
            if (extIdx + 1 < MAX_CERT_EXTENSIONS)
10758
                extIdx++;
10759
        #endif
10760
0
            entrySz = len + extSz[extIdx];
10761
10762
0
            if (chainPos < entrySz) {
10763
                /* Resume part way through this entry. */
10764
0
                p = ssl->buffers.certChain->buffer + prevIdx;
10765
0
                offset = chainPos;
10766
0
                chainPos = 0;
10767
0
            }
10768
0
            else {
10769
                /* Entry already sent in full; stay primed for the next one. */
10770
            #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) && \
10771
                    !defined(NO_WOLFSSL_SERVER)
10772
                /* Its buffer was rebuilt above and nothing writes it again. */
10773
                FreeDer(&ssl->buffers.certExts[extIdx]);
10774
            #endif
10775
0
                chainPos -= entrySz;
10776
0
                offset = 0;
10777
0
                entrySz = 0;
10778
0
            }
10779
0
        }
10780
0
    }
10781
10782
0
    while (length > 0 && ret == 0) {
10783
0
        byte*  output = NULL;
10784
0
        word32 fragSz = 0;
10785
0
        word32 i = RECORD_HEADER_SZ;
10786
0
        int    sendSz = RECORD_HEADER_SZ;
10787
10788
#ifdef WOLFSSL_DTLS13
10789
        if (ssl->options.dtls) {
10790
            i = Dtls13GetRlHeaderLength(ssl, 1);
10791
            sendSz = (int)i;
10792
        }
10793
#endif /* WOLFSSL_DTLS13 */
10794
10795
0
        if (ssl->fragOffset == 0) {
10796
0
            if (headerSz + certSz + totalextSz + certChainSz <=
10797
0
                                            maxFragment - HANDSHAKE_HEADER_SZ) {
10798
0
                fragSz = headerSz + certSz + totalextSz + certChainSz;
10799
0
            }
10800
#ifdef WOLFSSL_DTLS13
10801
            else if (ssl->options.dtls){
10802
                /* short-circuit the fragmentation logic here. DTLS
10803
                   fragmentation will be done in dtls13HandshakeSend() */
10804
                fragSz = headerSz + certSz + totalextSz + certChainSz;
10805
            }
10806
#endif /* WOLFSSL_DTLS13 */
10807
0
            else {
10808
0
                fragSz = maxFragment - HANDSHAKE_HEADER_SZ;
10809
0
            }
10810
10811
0
            sendSz += fragSz + HANDSHAKE_HEADER_SZ;
10812
0
            i += HANDSHAKE_HEADER_SZ;
10813
#ifdef WOLFSSL_DTLS13
10814
            if (ssl->options.dtls) {
10815
                sendSz += DTLS_HANDSHAKE_EXTRA;
10816
                i += DTLS_HANDSHAKE_EXTRA;
10817
            }
10818
#endif /* WOLFSSL_DTLS13 */
10819
0
        }
10820
0
        else {
10821
0
            fragSz = min((word32)length, maxFragment);
10822
0
            sendSz += fragSz;
10823
0
        }
10824
10825
0
        sendSz += MAX_MSG_EXTRA;
10826
10827
        /* Check buffers are big enough and grow if needed. */
10828
0
        if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
10829
0
            return ret;
10830
10831
        /* Get position in output buffer to write new message to. */
10832
0
        output = GetOutputBuffer(ssl);
10833
10834
0
        if (ssl->fragOffset == 0) {
10835
0
            AddTls13FragHeaders(output, fragSz, 0, payloadSz, certificate, ssl);
10836
10837
            /* Request context. */
10838
0
            output[i++] = certReqCtxLen;
10839
        #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
10840
            if (certReqCtxLen > 0) {
10841
                XMEMCPY(output + i, certReqCtx, certReqCtxLen);
10842
                i += certReqCtxLen;
10843
            }
10844
        #endif
10845
0
            length -= OPAQUE8_LEN + certReqCtxLen;
10846
0
            fragSz -= OPAQUE8_LEN + certReqCtxLen;
10847
            /* Certificate list length. */
10848
0
            c32to24(listSz, output + i);
10849
0
            i += CERT_HEADER_SZ;
10850
0
            length -= CERT_HEADER_SZ;
10851
0
            fragSz -= CERT_HEADER_SZ;
10852
            /* Leaf certificate data length. */
10853
0
            if (certSz > 0) {
10854
0
                c32to24(certSz, output + i);
10855
0
                i += CERT_HEADER_SZ;
10856
0
                length -= CERT_HEADER_SZ;
10857
0
                fragSz -= CERT_HEADER_SZ;
10858
0
            }
10859
0
        }
10860
0
        else
10861
0
            AddTls13RecordHeader(output, fragSz, handshake, ssl);
10862
10863
0
        if (extIdx == 0) {
10864
0
            if (certSz > 0 && ssl->fragOffset < certSz + extSz[0]) {
10865
                /* Put in the leaf certificate with extensions. */
10866
0
                word32 copySz = AddCertExt(ssl, ssl->buffers.certificate->buffer,
10867
0
                                certSz, extSz[0], ssl->fragOffset, fragSz,
10868
0
                                output + i, 0);
10869
0
                i += copySz;
10870
0
                ssl->fragOffset += copySz;
10871
0
                length -= copySz;
10872
0
                fragSz -= copySz;
10873
0
                if (ssl->fragOffset == certSz + extSz[0])
10874
0
                    FreeDer(&ssl->buffers.certExts[0]);
10875
0
            }
10876
0
        }
10877
0
        if (certChainSz > 0 && fragSz > 0) {
10878
             /* Put in the CA certificates with extensions. */
10879
0
             while (fragSz > 0) {
10880
0
                word32 l;
10881
10882
0
                if (offset == entrySz) {
10883
                    /* Find next CA certificate to write out. */
10884
0
                    offset = 0;
10885
                    /* Point to the start of current cert in chain buffer. */
10886
0
                    p = ssl->buffers.certChain->buffer + idx;
10887
0
                    len = NextCert(ssl->buffers.certChain->buffer,
10888
0
                            ssl->buffers.certChain->length, &idx);
10889
0
                    if (len == 0)
10890
0
                        break;
10891
                #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) && \
10892
                        !defined(NO_WOLFSSL_SERVER)
10893
                    if (extIdx + 1 < MAX_CERT_EXTENSIONS)
10894
                        extIdx++;
10895
                #endif
10896
                    /* Certificate and its extensions make up the entry. */
10897
0
                    entrySz = len + extSz[extIdx];
10898
0
                }
10899
                /* Write out certificate and extension. */
10900
0
                l = AddCertExt(ssl, p, len, extSz[extIdx], offset, fragSz,
10901
0
                                                       output + i, extIdx);
10902
0
                i += l;
10903
0
                ssl->fragOffset += l;
10904
0
                length -= l;
10905
0
                fragSz -= l;
10906
0
                offset += l;
10907
10908
0
                if (extIdx != 0 && extIdx < MAX_CERT_EXTENSIONS &&
10909
0
                    ssl->buffers.certExts[extIdx] != NULL &&
10910
0
                                offset == entrySz) {
10911
0
                    FreeDer(&ssl->buffers.certExts[extIdx]);
10912
0
                }
10913
0
            }
10914
0
        }
10915
10916
0
        if ((int)i - RECORD_HEADER_SZ < 0) {
10917
0
            WOLFSSL_MSG("Send Cert bad inputSz");
10918
0
            return BUFFER_E;
10919
0
        }
10920
10921
#ifdef WOLFSSL_DTLS13
10922
        if (ssl->options.dtls) {
10923
            /* DTLS1.3 uses a separate variable and logic for fragments */
10924
            ssl->options.buildingMsg = 0;
10925
            ssl->fragOffset = 0;
10926
            if ((word32)sendSz > WOLFSSL_MAX_16BIT || i > WOLFSSL_MAX_16BIT) {
10927
                WOLFSSL_MSG("Send Cert DTLS size exceeds word16");
10928
                return BUFFER_E;
10929
            }
10930
            ret = Dtls13HandshakeSend(ssl, output, (word16)sendSz, (word16)i,
10931
                                      certificate, 1);
10932
        }
10933
        else
10934
#endif /* WOLFSSL_DTLS13 */
10935
0
        {
10936
            /* This message is always encrypted. */
10937
0
            sendSz = BuildTls13Message(ssl, output, sendSz,
10938
0
                output + RECORD_HEADER_SZ, (int)(i - RECORD_HEADER_SZ),
10939
0
                handshake, 1,
10940
0
                0, 0);
10941
0
            if (sendSz < 0)
10942
0
                return sendSz;
10943
10944
#if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
10945
            if (ssl->hsInfoOn)
10946
                AddPacketName(ssl, "Certificate");
10947
            if (ssl->toInfoOn) {
10948
                ret = AddPacketInfo(ssl, "Certificate", handshake, output,
10949
                              sendSz, WRITE_PROTO, 0, ssl->heap);
10950
                if (ret != 0)
10951
                    return ret;
10952
            }
10953
#endif
10954
10955
0
            ssl->buffers.outputBuffer.length += (word32)sendSz;
10956
0
            ssl->options.buildingMsg = 0;
10957
0
            if (!ssl->options.groupMessages)
10958
0
                ret = SendBuffered(ssl);
10959
0
        }
10960
0
    }
10961
10962
0
    if (ret != WC_NO_ERR_TRACE(WANT_WRITE)) {
10963
        /* Clean up the fragment offset. */
10964
0
        ssl->options.buildingMsg = 0;
10965
0
        ssl->fragOffset = 0;
10966
0
        if (ssl->options.side == WOLFSSL_SERVER_END)
10967
0
            ssl->options.serverState = SERVER_CERT_COMPLETE;
10968
0
    }
10969
10970
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
10971
    if (ssl->options.side == WOLFSSL_CLIENT_END && ssl->certReqCtx != NULL) {
10972
        CertReqCtx* ctx = ssl->certReqCtx;
10973
        ssl->certReqCtx = ssl->certReqCtx->next;
10974
        XFREE(ctx, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
10975
    }
10976
#endif
10977
10978
0
    WOLFSSL_LEAVE("SendTls13Certificate", ret);
10979
0
    WOLFSSL_END(WC_FUNC_CERTIFICATE_SEND);
10980
10981
0
    return ret;
10982
0
}
10983
10984
#if (!defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
10985
     defined(HAVE_ED448) || defined(HAVE_FALCON) || \
10986
     defined(WOLFSSL_HAVE_MLDSA) || defined(WOLFSSL_HAVE_SLHDSA)) && \
10987
    (!defined(NO_WOLFSSL_SERVER) || !defined(WOLFSSL_NO_CLIENT_AUTH))
10988
/* Members are grouped widest first so the struct carries no interior padding.
10989
 * Under WOLFSSL_ASYNC_CRYPT this must fit ssl->async->args (MAX_ASYNC_ARGS
10990
 * word32s), which the static assert in SendTls13CertificateVerify enforces. */
10991
typedef struct Scv13Args {
10992
    byte*  output; /* not allocated */
10993
    byte*  verify; /* not allocated */
10994
    byte*  sigData;
10995
#ifndef NO_RSA
10996
    byte*  toSign; /* not allocated */
10997
#endif
10998
#ifdef WOLFSSL_DUAL_ALG_CERTS
10999
    byte*  altSigData;
11000
#endif
11001
    /* Fragmented CertificateVerify send cursor, used when the signature does
11002
     * not fit in a single TLS record (SLH-DSA and other oversized signatures).
11003
     * Kept in the async args so a WC_PENDING_E from the record AEAD under
11004
     * WOLFSSL_ASYNC_CRYPT resumes on the same fragment instead of re-emitting
11005
     * the records already committed to the output buffer. */
11006
    byte*  frag;         /* body copy, freed by FreeScv13Args; NULL when idle */
11007
11008
    word32 idx;
11009
    word32 sigLen;
11010
    int    sendSz;
11011
    word32 length;
11012
#ifndef NO_RSA
11013
    word32 toSignSz;
11014
#endif
11015
#ifdef WOLFSSL_DUAL_ALG_CERTS
11016
    word32 altSigLen;    /* Only used in the case of both native and alt. */
11017
#endif
11018
    word32 outputSz;     /* reserved capacity of the output record buffer */
11019
    word32 fragOffset;   /* body bytes already committed to records */
11020
11021
    word16 sigDataSz;
11022
#ifdef WOLFSSL_DUAL_ALG_CERTS
11023
    word16 altSigDataSz;
11024
#endif
11025
11026
    byte   sigAlgo;
11027
#ifdef WOLFSSL_DUAL_ALG_CERTS
11028
    byte   altSigAlgo;
11029
#endif
11030
    byte   fragActive;   /* current fragment laid out, record build may pend */
11031
} Scv13Args;
11032
11033
static void FreeScv13Args(WOLFSSL* ssl, void* pArgs)
11034
0
{
11035
0
    Scv13Args* args = (Scv13Args*)pArgs;
11036
11037
0
    (void)ssl;
11038
11039
0
    if (args && args->sigData) {
11040
0
        XFREE(args->sigData, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
11041
0
        args->sigData = NULL;
11042
0
    }
11043
#ifdef WOLFSSL_DUAL_ALG_CERTS
11044
    if (args && args->altSigData != NULL) {
11045
        XFREE(args->altSigData, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
11046
        args->altSigData = NULL;
11047
    }
11048
#endif
11049
0
    if (args != NULL && args->frag != NULL) {
11050
0
        XFREE(args->frag, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
11051
0
        args->frag = NULL;
11052
0
    }
11053
0
}
11054
11055
/* handle generation TLS v1.3 certificate_verify (15) */
11056
/* Send the TLS v1.3 CertificateVerify message.
11057
 * A hash of all the message so far is used.
11058
 * The signed data is:
11059
 *     0x20 * 64 | context string | 0x00 | hash of messages
11060
 * This message is always encrypted in TLS v1.3.
11061
 *
11062
 * ssl  The SSL/TLS object.
11063
 * returns 0 on success, otherwise failure.
11064
 */
11065
static int SendTls13CertificateVerify(WOLFSSL* ssl)
11066
0
{
11067
0
    int ret = 0;
11068
0
#ifndef NO_RSA
11069
    /* Use this as a temporary buffer for RSA signature verification. */
11070
0
    buffer* rsaSigBuf = &ssl->buffers.sig;
11071
0
#endif
11072
#ifdef WOLFSSL_ASYNC_CRYPT
11073
    Scv13Args* args = NULL;
11074
    WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
11075
#else
11076
0
    Scv13Args  args[1];
11077
0
#endif
11078
11079
#ifdef WOLFSSL_DTLS13
11080
    int recordLayerHdrExtra;
11081
#endif /* WOLFSSL_DTLS13 */
11082
11083
0
    WOLFSSL_START(WC_FUNC_CERTIFICATE_VERIFY_SEND);
11084
0
    WOLFSSL_ENTER("SendTls13CertificateVerify");
11085
11086
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
11087
    wolfssl_priv_der_blind_toggle(ssl->buffers.key, ssl->buffers.keyMask);
11088
#endif
11089
11090
0
    ssl->options.buildingMsg = 1;
11091
11092
#if defined(WOLFSSL_RENESAS_TSIP_TLS)
11093
    ret = tsip_Tls13SendCertVerify(ssl);
11094
    if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
11095
        goto exit_scv;
11096
    }
11097
    ret = 0;
11098
#endif /* WOLFSSL_RENESAS_TSIP_TLS */
11099
11100
#ifdef WOLFSSL_DTLS13
11101
    /* can be negative */
11102
    if (ssl->options.dtls)
11103
        recordLayerHdrExtra = Dtls13GetRlHeaderLength(ssl, 1) - RECORD_HEADER_SZ;
11104
    else
11105
        recordLayerHdrExtra = 0;
11106
11107
#endif /* WOLFSSL_DTLS13 */
11108
11109
#ifdef WOLFSSL_ASYNC_CRYPT
11110
    if (ssl->async == NULL) {
11111
        ssl->async = (struct WOLFSSL_ASYNC*)
11112
                XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
11113
                        DYNAMIC_TYPE_ASYNC);
11114
        if (ssl->async == NULL)
11115
            ERROR_OUT(MEMORY_E, exit_scv);
11116
    }
11117
    args = (Scv13Args*)ssl->async->args;
11118
11119
    ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
11120
    if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) {
11121
        /* Check for error */
11122
        if (ret < 0)
11123
            goto exit_scv;
11124
    }
11125
    else
11126
#endif
11127
0
    {
11128
        /* Reset state */
11129
0
        ret = 0;
11130
0
        ssl->options.asyncState = TLS_ASYNC_BEGIN;
11131
0
        XMEMSET(args, 0, sizeof(Scv13Args));
11132
    #ifdef WOLFSSL_ASYNC_CRYPT
11133
        ssl->async->freeArgs = FreeScv13Args;
11134
    #endif
11135
0
    }
11136
11137
#ifdef WOLFSSL_TLS13_STREAM_CERT_VERIFY
11138
    /* Resuming a partially-sent streamed CertificateVerify (e.g. after a
11139
     * non-blocking WANT_WRITE): the signature is already assembled in
11140
     * ssl->buffers.certVerifyMsg and ssl->fragOffset marks how much has been
11141
     * committed to records, so skip re-signing and continue sending. */
11142
    if (ssl->buffers.certVerifyMsg.buffer != NULL && ssl->fragOffset != 0) {
11143
        ssl->options.asyncState = TLS_ASYNC_END;
11144
    }
11145
#endif
11146
11147
0
    switch(ssl->options.asyncState)
11148
0
    {
11149
0
        case TLS_ASYNC_BEGIN:
11150
0
        {
11151
0
            if (ssl->options.sendVerify == SEND_BLANK_CERT) {
11152
            #ifdef WOLFSSL_BLIND_PRIVATE_KEY
11153
                wolfssl_priv_der_blind_toggle(ssl->buffers.key,
11154
                    ssl->buffers.keyMask);
11155
            #endif
11156
0
                return 0;  /* sent blank cert, can't verify */
11157
0
            }
11158
11159
            /* The output buffer is reserved in TLS_ASYNC_BUILD, once the
11160
             * private key has been decoded and the actual signature size is
11161
             * known. This avoids reserving the worst-case WC_MAX_CERT_VERIFY_SZ
11162
             * (very large when SLH-DSA is enabled) for every algorithm. */
11163
11164
            /* Advance state and proceed */
11165
0
            ssl->options.asyncState = TLS_ASYNC_BUILD;
11166
0
        } /* case TLS_ASYNC_BEGIN */
11167
0
        FALL_THROUGH;
11168
11169
0
        case TLS_ASYNC_BUILD:
11170
0
        {
11171
0
            int rem;
11172
#ifdef WOLFSSL_TLS13_STREAM_CERT_VERIFY
11173
            word32 bodySz;
11174
            word32 maxFrag;
11175
#endif
11176
0
            int doStream = 0;
11177
11178
            /* Decode the private key first so the output buffer can be sized
11179
             * to the actual signature length rather than the worst-case
11180
             * WC_MAX_CERT_VERIFY_SZ (very large when SLH-DSA is enabled). */
11181
0
            if (ssl->buffers.key == NULL) {
11182
            #ifdef HAVE_PK_CALLBACKS
11183
                if (wolfSSL_CTX_IsPrivatePkSet(ssl->ctx))
11184
                    args->sigLen = (word32)GetPrivateKeySigSize(ssl);
11185
                else
11186
            #endif
11187
0
                    ERROR_OUT(NO_PRIVATE_KEY, exit_scv);
11188
0
            }
11189
0
            else {
11190
#ifdef WOLFSSL_DUAL_ALG_CERTS
11191
                if (ssl->sigSpec != NULL &&
11192
                    *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_ALTERNATIVE) {
11193
                    /* In the case of alternative, we swap in the alt. */
11194
                    if (ssl->buffers.altKey == NULL) {
11195
                        ERROR_OUT(NO_PRIVATE_KEY, exit_scv);
11196
                    }
11197
                    ssl->buffers.keyType = ssl->buffers.altKeyType;
11198
                    ssl->buffers.keySz = ssl->buffers.altKeySz;
11199
                    /* If we own it, free key before overriding it. */
11200
                    if (ssl->buffers.weOwnKey) {
11201
                        FreeDer(&ssl->buffers.key);
11202
                    #ifdef WOLFSSL_BLIND_PRIVATE_KEY
11203
                        FreeDer(&ssl->buffers.keyMask);
11204
                    #endif
11205
                    }
11206
11207
                    /* Swap keys */
11208
                    ssl->buffers.key     = ssl->buffers.altKey;
11209
                    ssl->buffers.weOwnKey = ssl->buffers.weOwnAltKey;
11210
                    /* buffers.key is the only owner of the alt key now. */
11211
                    ssl->buffers.weOwnAltKey = 0;
11212
11213
                #ifdef WOLFSSL_BLIND_PRIVATE_KEY
11214
                    ssl->buffers.keyMask = ssl->buffers.altKeyMask;
11215
                    /* Unblind the alternative key before decoding */
11216
                    wolfssl_priv_der_blind_toggle(ssl->buffers.key, ssl->buffers.keyMask);
11217
                #endif
11218
                }
11219
#endif /* WOLFSSL_DUAL_ALG_CERTS */
11220
0
                ret = DecodePrivateKey(ssl, &args->sigLen);
11221
0
                if (ret != 0)
11222
0
                    goto exit_scv;
11223
0
            }
11224
11225
0
            if (args->sigLen == 0) {
11226
0
                ERROR_OUT(NO_PRIVATE_KEY, exit_scv);
11227
0
            }
11228
11229
#ifdef WOLFSSL_DUAL_ALG_CERTS
11230
            if (ssl->peerSigSpec == NULL) {
11231
                /* The peer did not respond. We didn't send CKS or they don't
11232
                 * support it. Either way, we do not need to handle dual
11233
                 * key/sig case. */
11234
                ssl->sigSpec = NULL;
11235
                ssl->sigSpecSz = 0;
11236
            }
11237
11238
            if (ssl->sigSpec != NULL &&
11239
                *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) {
11240
                /* The native was already decoded. Decode the alternative now
11241
                 * too so its signature length is included when the output
11242
                 * buffer is sized below. */
11243
                if (ssl->buffers.altKey == NULL) {
11244
                    ERROR_OUT(NO_PRIVATE_KEY, exit_scv);
11245
                }
11246
11247
                /* After this call, args->altSigLen has the length we need for
11248
                 * the alternative signature. */
11249
                ret = DecodeAltPrivateKey(ssl, &args->altSigLen);
11250
                if (ret != 0)
11251
                    goto exit_scv;
11252
11253
                if (ssl->buffers.altKeyType == ecc_dsa_sa_algo ||
11254
                    ssl->buffers.altKeyType == falcon_level1_sa_algo ||
11255
                    ssl->buffers.altKeyType == falcon_level5_sa_algo ||
11256
                    ssl->buffers.altKeyType == mldsa_44_sa_algo ||
11257
                    ssl->buffers.altKeyType == mldsa_65_sa_algo ||
11258
                    ssl->buffers.altKeyType == mldsa_87_sa_algo) {
11259
                    args->altSigAlgo = ssl->buffers.altKeyType;
11260
                }
11261
                else if (ssl->buffers.altKeyType == rsa_sa_algo &&
11262
                         ssl->hsAltType == DYNAMIC_TYPE_RSA) {
11263
                    args->altSigAlgo = rsa_pss_sa_algo;
11264
                }
11265
                else {
11266
                    ERROR_OUT(ALGO_ID_E, exit_scv);
11267
                }
11268
            }
11269
#endif /* WOLFSSL_DUAL_ALG_CERTS */
11270
11271
            /* Decide how the CertificateVerify body will be emitted. When it
11272
             * exceeds a single record (e.g. a large SLH-DSA/ML-DSA signature,
11273
             * or any signature under a small max_fragment_length) on TLS 1.3,
11274
             * use the streaming path: generate the signature into a
11275
             * connection-level body buffer and send it one record at a time in
11276
             * TLS_ASYNC_END, so the shared output buffer never has to hold the
11277
             * whole signature. Otherwise reserve the output buffer for the
11278
             * whole message and build it in place. */
11279
#ifdef WOLFSSL_TLS13_STREAM_CERT_VERIFY
11280
            bodySz = HASH_SIG_SIZE + VERIFY_HEADER + (word32)args->sigLen;
11281
        #ifdef WOLFSSL_DUAL_ALG_CERTS
11282
            /* A dual (BOTH) body carries a second length-prefixed signature.
11283
             * args->sigLen/altSigLen are upper bounds here for variable-length
11284
             * schemes (ECDSA, Falcon), so this may over-size the body buffer by
11285
             * a few bytes; the body is assembled contiguously with the actual
11286
             * lengths, the exact length is recorded in TLS_ASYNC_FINALIZE, and
11287
             * the trailing slack is never sent. */
11288
            if (ssl->sigSpec != NULL &&
11289
                    *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) {
11290
                bodySz += (word32)args->altSigLen + OPAQUE16_LEN + OPAQUE16_LEN;
11291
            }
11292
        #endif
11293
            maxFrag = (word32)wolfssl_local_GetMaxPlaintextSize(ssl);
11294
            if (!ssl->options.dtls &&
11295
                    (word32)HANDSHAKE_HEADER_SZ + bodySz > maxFrag) {
11296
                doStream = 1;
11297
            }
11298
#endif /* WOLFSSL_TLS13_STREAM_CERT_VERIFY */
11299
11300
0
            if (doStream) {
11301
#ifdef WOLFSSL_TLS13_STREAM_CERT_VERIFY
11302
                /* Generate the body directly into the connection-level buffer.
11303
                 * bodySz is exact here (a single fixed-or-max-length
11304
                 * signature); the final length is recorded in
11305
                 * TLS_ASYNC_FINALIZE. args->output stays NULL to mark the
11306
                 * streaming path; the send loop reserves one record at a
11307
                 * time. */
11308
                XFREE(ssl->buffers.certVerifyMsg.buffer, ssl->heap,
11309
                      DYNAMIC_TYPE_TMP_BUFFER);
11310
                ssl->buffers.certVerifyMsg.buffer =
11311
                    (byte*)XMALLOC(bodySz, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
11312
                if (ssl->buffers.certVerifyMsg.buffer == NULL) {
11313
                    ssl->buffers.certVerifyMsg.length = 0;
11314
                    ERROR_OUT(MEMORY_E, exit_scv);
11315
                }
11316
                ssl->buffers.certVerifyMsg.length = bodySz;
11317
                ssl->fragOffset = 0;
11318
                args->verify = ssl->buffers.certVerifyMsg.buffer;
11319
                args->idx = 0;
11320
                args->sendSz = (int)bodySz;
11321
                args->output = NULL;
11322
                args->outputSz = 0;
11323
#endif /* WOLFSSL_TLS13_STREAM_CERT_VERIFY */
11324
0
            }
11325
0
            else {
11326
                /* Reserve the output buffer, sized from the actual signature
11327
                 * length(s) plus record/handshake framing and encryption
11328
                 * slack. */
11329
0
                args->sendSz = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ +
11330
0
                               HASH_SIG_SIZE + VERIFY_HEADER + (int)args->sigLen;
11331
            #ifdef WOLFSSL_DUAL_ALG_CERTS
11332
                /* A dual (BOTH) body carries a second signature behind its own
11333
                 * length prefix, plus the combined length prefix. Matches the
11334
                 * streaming bodySz above. */
11335
                if (ssl->sigSpec != NULL &&
11336
                        *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) {
11337
                    args->sendSz += (int)args->altSigLen + OPAQUE16_LEN +
11338
                                    OPAQUE16_LEN;
11339
                }
11340
                else {
11341
                    args->sendSz += (int)args->altSigLen;
11342
                }
11343
            #endif
11344
            #ifdef WOLFSSL_DTLS13
11345
                if (ssl->options.dtls)
11346
                    args->sendSz += recordLayerHdrExtra + DTLS_HANDSHAKE_EXTRA;
11347
            #endif /* WOLFSSL_DTLS13 */
11348
                /* Framing and always-on encryption expansion. */
11349
0
                args->sendSz += MAX_MSG_EXTRA;
11350
11351
                /* check for available size */
11352
0
                if ((ret = CheckAvailableSize(ssl, args->sendSz)) != 0) {
11353
0
                    goto exit_scv;
11354
0
                }
11355
11356
                /* get output buffer */
11357
0
                args->output = GetOutputBuffer(ssl);
11358
                /* Remember the reserved capacity for BuildTls13Message /
11359
                 * Dtls13HandshakeSend in TLS_ASYNC_END. */
11360
0
                args->outputSz = (word32)args->sendSz;
11361
11362
0
                rem = (int)(ssl->buffers.outputBuffer.bufferSize
11363
0
                                - ssl->buffers.outputBuffer.length
11364
0
                                - RECORD_HEADER_SZ - HANDSHAKE_HEADER_SZ);
11365
11366
                /* idx is used to track verify pointer offset to output */
11367
0
                args->idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
11368
0
                args->verify =
11369
0
                          &args->output[RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ];
11370
11371
            #ifdef WOLFSSL_DTLS13
11372
                if (ssl->options.dtls) {
11373
                    rem -= recordLayerHdrExtra + DTLS_HANDSHAKE_EXTRA;
11374
                    args->idx += recordLayerHdrExtra + DTLS_HANDSHAKE_EXTRA;
11375
                    args->verify += recordLayerHdrExtra + DTLS_HANDSHAKE_EXTRA;
11376
                }
11377
            #endif /* WOLFSSL_DTLS13 */
11378
11379
0
                if (rem < 0 || (int)args->sigLen > rem) {
11380
0
                    ERROR_OUT(BUFFER_E, exit_scv);
11381
0
                }
11382
0
            }
11383
11384
            /* Add signature algorithm. */
11385
0
            if (ssl->hsType == DYNAMIC_TYPE_RSA)
11386
0
                args->sigAlgo = rsa_pss_sa_algo;
11387
0
        #ifdef HAVE_ECC
11388
0
            else if (ssl->hsType == DYNAMIC_TYPE_ECC) {
11389
        #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
11390
                if (ssl->buffers.keyType == sm2_sa_algo) {
11391
                    args->sigAlgo = sm2_sa_algo;
11392
                }
11393
                else
11394
        #endif
11395
0
                {
11396
0
                    args->sigAlgo = ecc_dsa_sa_algo;
11397
0
                }
11398
0
            }
11399
0
        #endif
11400
        #ifdef HAVE_ED25519
11401
            else if (ssl->hsType == DYNAMIC_TYPE_ED25519)
11402
                args->sigAlgo = ed25519_sa_algo;
11403
        #endif
11404
        #ifdef HAVE_ED448
11405
            else if (ssl->hsType == DYNAMIC_TYPE_ED448)
11406
                args->sigAlgo = ed448_sa_algo;
11407
        #endif
11408
        #if defined(HAVE_FALCON)
11409
            else if (ssl->hsType == DYNAMIC_TYPE_FALCON) {
11410
                args->sigAlgo = ssl->buffers.keyType;
11411
            }
11412
        #endif /* HAVE_FALCON */
11413
        #if defined(WOLFSSL_HAVE_MLDSA)
11414
            else if (ssl->hsType == DYNAMIC_TYPE_MLDSA) {
11415
                args->sigAlgo = ssl->buffers.keyType;
11416
            }
11417
        #endif /* WOLFSSL_HAVE_MLDSA */
11418
        #if defined(WOLFSSL_HAVE_SLHDSA)
11419
            else if (ssl->hsType == DYNAMIC_TYPE_SLHDSA) {
11420
                args->sigAlgo = ssl->buffers.keyType;
11421
            }
11422
        #endif /* WOLFSSL_HAVE_SLHDSA */
11423
0
            else {
11424
0
                ERROR_OUT(ALGO_ID_E, exit_scv);
11425
0
            }
11426
11427
        #ifdef WOLFSSL_DUAL_ALG_CERTS
11428
            if (ssl->sigSpec != NULL &&
11429
                *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) {
11430
                /* The alternative key was already decoded and its sig-alg
11431
                 * determined above (when sizing the output buffer). Encode the
11432
                 * dual (native + alternative) signature algorithm pair. */
11433
                EncodeDualSigAlg(args->sigAlgo, args->altSigAlgo, args->verify);
11434
                if (args->verify[0] == 0) {
11435
                    ERROR_OUT(ALGO_ID_E, exit_scv);
11436
                }
11437
            }
11438
            else
11439
        #endif /* WOLFSSL_DUAL_ALG_CERTS */
11440
0
                EncodeSigAlg(ssl, ssl->options.hashAlgo, args->sigAlgo,
11441
0
                             args->verify);
11442
11443
0
            if (args->sigData == NULL) {
11444
0
                word32 sigLen = MAX_SIG_DATA_SZ;
11445
0
                if ((ssl->hsType == DYNAMIC_TYPE_RSA) &&
11446
0
                    (args->sigLen > MAX_SIG_DATA_SZ)) {
11447
                    /* We store the RSA signature in the sigData buffer
11448
                     * temporarily, hence its size must be fitting. */
11449
0
                    sigLen = args->sigLen;
11450
0
                }
11451
0
                args->sigData = (byte*)XMALLOC(sigLen, ssl->heap,
11452
0
                                                    DYNAMIC_TYPE_SIGNATURE);
11453
0
                if (args->sigData == NULL) {
11454
0
                    ERROR_OUT(MEMORY_E, exit_scv);
11455
0
                }
11456
0
            }
11457
11458
        #ifdef WOLFSSL_DUAL_ALG_CERTS
11459
            if ((ssl->sigSpec != NULL) &&
11460
                (*ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) &&
11461
                (args->altSigData == NULL)) {
11462
                word32 sigLen = MAX_SIG_DATA_SZ;
11463
                if (ssl->hsAltType == DYNAMIC_TYPE_RSA &&
11464
                    args->altSigLen > MAX_SIG_DATA_SZ) {
11465
                    /* We store the RSA signature in the sigData buffer
11466
                     * temporarily, hence its size must be fitting. */
11467
                    sigLen = args->altSigLen;
11468
                }
11469
                args->altSigData = (byte*)XMALLOC(sigLen, ssl->heap,
11470
                                                    DYNAMIC_TYPE_SIGNATURE);
11471
                if (args->altSigData == NULL) {
11472
                    ERROR_OUT(MEMORY_E, exit_scv);
11473
                }
11474
            }
11475
        #endif /* WOLFSSL_DUAL_ALG_CERTS */
11476
11477
            /* Create the data to be signed. */
11478
0
            ret = CreateSigData(ssl, args->sigData, &args->sigDataSz, 0);
11479
0
            if (ret != 0)
11480
0
                goto exit_scv;
11481
11482
        #ifdef WOLFSSL_DUAL_ALG_CERTS
11483
            if ((ssl->sigSpec != NULL) &&
11484
                (*ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH)) {
11485
                XMEMCPY(args->altSigData, args->sigData, args->sigDataSz);
11486
                args->altSigDataSz = args->sigDataSz;
11487
            }
11488
        #endif /* WOLFSSL_DUAL_ALG_CERTS */
11489
11490
0
        #ifndef NO_RSA
11491
0
            if (ssl->hsType == DYNAMIC_TYPE_RSA) {
11492
                /* build encoded signature buffer */
11493
0
                rsaSigBuf->length = WC_MAX_DIGEST_SIZE;
11494
0
                rsaSigBuf->buffer = (byte*)XMALLOC(rsaSigBuf->length, ssl->heap,
11495
0
                                                   DYNAMIC_TYPE_SIGNATURE);
11496
0
                if (rsaSigBuf->buffer == NULL) {
11497
0
                    ERROR_OUT(MEMORY_E, exit_scv);
11498
0
                }
11499
11500
0
                ret = CreateRSAEncodedSig(rsaSigBuf->buffer, args->sigData,
11501
0
                    args->sigDataSz, args->sigAlgo, ssl->options.hashAlgo);
11502
0
                if (ret < 0)
11503
0
                    goto exit_scv;
11504
0
                rsaSigBuf->length = (unsigned int)ret;
11505
0
                ret = 0;
11506
0
            }
11507
0
        #endif /* !NO_RSA */
11508
0
        #ifdef HAVE_ECC
11509
0
            if (ssl->hsType == DYNAMIC_TYPE_ECC) {
11510
0
                args->sigLen = (word32)args->sendSz - args->idx -
11511
0
                               HASH_SIG_SIZE -
11512
0
                               VERIFY_HEADER;
11513
            #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
11514
                if (ssl->buffers.keyType != sm2_sa_algo)
11515
            #endif
11516
0
                {
11517
0
                    ret = CreateECCEncodedSig(args->sigData,
11518
0
                        args->sigDataSz, ssl->options.hashAlgo);
11519
0
                    if (ret < 0)
11520
0
                        goto exit_scv;
11521
0
                    args->sigDataSz = (word16)ret;
11522
0
                    ret = 0;
11523
0
                }
11524
0
            }
11525
0
        #endif /* HAVE_ECC */
11526
        #ifdef HAVE_ED25519
11527
            if (ssl->hsType == DYNAMIC_TYPE_ED25519) {
11528
                ret = Ed25519CheckPubKey(ssl);
11529
                if (ret < 0) {
11530
                    ERROR_OUT(ret, exit_scv);
11531
                }
11532
                args->sigLen = ED25519_SIG_SIZE;
11533
            }
11534
        #endif /* HAVE_ED25519 */
11535
        #ifdef HAVE_ED448
11536
            if (ssl->hsType == DYNAMIC_TYPE_ED448) {
11537
                ret = Ed448CheckPubKey(ssl);
11538
                if (ret < 0) {
11539
                    ERROR_OUT(ret, exit_scv);
11540
                }
11541
                args->sigLen = ED448_SIG_SIZE;
11542
            }
11543
11544
        #endif /* HAVE_ED448 */
11545
        #if defined(HAVE_FALCON)
11546
            if (ssl->hsType == DYNAMIC_TYPE_FALCON) {
11547
                /* Per-key, not the family maximum: this is handed to the
11548
                 * signer as the output capacity and the buffer above was
11549
                 * reserved from this key's signature length. */
11550
                int fSigSz = wc_falcon_sig_size((falcon_key*)ssl->hsKey);
11551
                if (fSigSz <= 0) {
11552
                    ERROR_OUT(ALGO_ID_E, exit_scv);
11553
                }
11554
                args->sigLen = (word32)fSigSz;
11555
            }
11556
        #endif /* HAVE_FALCON */
11557
        #if defined(WOLFSSL_HAVE_MLDSA) && !defined(WOLFSSL_MLDSA_NO_SIGN)
11558
            if (ssl->hsType == DYNAMIC_TYPE_MLDSA) {
11559
                int mSigSz = wc_MlDsaKey_SigSize((wc_MlDsaKey*)ssl->hsKey);
11560
                if (mSigSz <= 0) {
11561
                    ERROR_OUT(ALGO_ID_E, exit_scv);
11562
                }
11563
                args->sigLen = (word32)mSigSz;
11564
            }
11565
        #endif /* WOLFSSL_HAVE_MLDSA && !WOLFSSL_MLDSA_NO_SIGN */
11566
        #if defined(WOLFSSL_HAVE_SLHDSA)
11567
            if (ssl->hsType == DYNAMIC_TYPE_SLHDSA) {
11568
                int slhSigSz = wc_SlhDsaKey_SigSize((SlhDsaKey*)ssl->hsKey);
11569
                if (slhSigSz <= 0) {
11570
                    ERROR_OUT(ALGO_ID_E, exit_scv);
11571
                }
11572
                args->sigLen = (word32)slhSigSz;
11573
            }
11574
        #endif /* WOLFSSL_HAVE_SLHDSA */
11575
11576
        #ifdef WOLFSSL_DUAL_ALG_CERTS
11577
            if (ssl->sigSpec != NULL &&
11578
                *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) {
11579
11580
            #ifndef NO_RSA
11581
                if (ssl->hsAltType == DYNAMIC_TYPE_RSA) {
11582
                    /* build encoded signature buffer */
11583
                    XFREE(rsaSigBuf->buffer, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
11584
                    rsaSigBuf->length = WC_MAX_DIGEST_SIZE;
11585
                    rsaSigBuf->buffer = (byte*)XMALLOC(rsaSigBuf->length,
11586
                                                       ssl->heap,
11587
                                                       DYNAMIC_TYPE_SIGNATURE);
11588
                    if (rsaSigBuf->buffer == NULL) {
11589
                        ERROR_OUT(MEMORY_E, exit_scv);
11590
                    }
11591
11592
                    ret = CreateRSAEncodedSig(rsaSigBuf->buffer,
11593
                                    args->altSigData, args->altSigDataSz,
11594
                                    args->altSigAlgo, ssl->options.hashAlgo);
11595
                    if (ret < 0)
11596
                        goto exit_scv;
11597
                    rsaSigBuf->length = ret;
11598
                    ret = 0;
11599
                }
11600
            #endif /* !NO_RSA */
11601
            #ifdef HAVE_ECC
11602
                if (ssl->hsAltType == DYNAMIC_TYPE_ECC) {
11603
                    ret = CreateECCEncodedSig(args->altSigData,
11604
                            args->altSigDataSz, ssl->options.hashAlgo);
11605
                    if (ret < 0)
11606
                        goto exit_scv;
11607
                    args->altSigDataSz = (word16)ret;
11608
                    ret = 0;
11609
                }
11610
            #endif /* HAVE_ECC */
11611
            }
11612
        #endif /* WOLFSSL_DUAL_ALG_CERTS */
11613
11614
            /* Advance state and proceed */
11615
0
            ssl->options.asyncState = TLS_ASYNC_DO;
11616
0
        } /* case TLS_ASYNC_BUILD */
11617
0
        FALL_THROUGH;
11618
11619
0
        case TLS_ASYNC_DO:
11620
0
        {
11621
0
            byte* sigOut = args->verify + HASH_SIG_SIZE + VERIFY_HEADER;
11622
        #ifdef WOLFSSL_DUAL_ALG_CERTS
11623
            if (ssl->sigSpec != NULL &&
11624
                *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) {
11625
                /* As we have two signatures in the message, we store
11626
                 * the length of each before the actual signature. This
11627
                 * is necessary, as we could have two algorithms with
11628
                 * variable length signatures. */
11629
                sigOut += OPAQUE16_LEN;
11630
            }
11631
        #endif
11632
            /* Only the per-algorithm signing branches below consume this. */
11633
0
            (void)sigOut;
11634
0
        #ifdef HAVE_ECC
11635
0
            if (ssl->hsType == DYNAMIC_TYPE_ECC) {
11636
            #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
11637
                if (ssl->buffers.keyType == sm2_sa_algo) {
11638
                    ret = Sm2wSm3Sign(ssl, TLS13_SM2_SIG_ID,
11639
                        TLS13_SM2_SIG_ID_SZ, args->sigData, args->sigDataSz,
11640
                        sigOut, &args->sigLen, (ecc_key*)ssl->hsKey, NULL);
11641
                }
11642
                else
11643
            #endif
11644
0
                {
11645
0
                    ret = EccSign(ssl, args->sigData, args->sigDataSz,
11646
0
                        sigOut, &args->sigLen, (ecc_key*)ssl->hsKey,
11647
                #ifdef HAVE_PK_CALLBACKS
11648
                        ssl->buffers.key
11649
                #else
11650
0
                        NULL
11651
0
                #endif
11652
0
                    );
11653
0
                }
11654
0
                args->length = args->sigLen;
11655
0
            }
11656
0
        #endif /* HAVE_ECC */
11657
        #ifdef HAVE_ED25519
11658
            if (ssl->hsType == DYNAMIC_TYPE_ED25519) {
11659
                ret = Ed25519Sign(ssl, args->sigData, args->sigDataSz,
11660
                    sigOut, &args->sigLen, (ed25519_key*)ssl->hsKey,
11661
            #ifdef HAVE_PK_CALLBACKS
11662
                    ssl->buffers.key
11663
            #else
11664
                    NULL
11665
            #endif
11666
                );
11667
                args->length = args->sigLen;
11668
            }
11669
        #endif
11670
        #ifdef HAVE_ED448
11671
            if (ssl->hsType == DYNAMIC_TYPE_ED448) {
11672
                ret = Ed448Sign(ssl, args->sigData, args->sigDataSz,
11673
                    sigOut, &args->sigLen, (ed448_key*)ssl->hsKey,
11674
            #ifdef HAVE_PK_CALLBACKS
11675
                    ssl->buffers.key
11676
            #else
11677
                    NULL
11678
            #endif
11679
                );
11680
                args->length = args->sigLen;
11681
            }
11682
        #endif
11683
        #if defined(HAVE_FALCON)
11684
            if (ssl->hsType == DYNAMIC_TYPE_FALCON) {
11685
                ret = wc_falcon_sign_msg(args->sigData, args->sigDataSz,
11686
                                         sigOut, &args->sigLen,
11687
                                         (falcon_key*)ssl->hsKey, ssl->rng);
11688
                args->length = args->sigLen;
11689
            }
11690
        #endif /* HAVE_FALCON */
11691
        #if defined(WOLFSSL_HAVE_MLDSA) && !defined(WOLFSSL_MLDSA_NO_SIGN)
11692
            if (ssl->hsType == DYNAMIC_TYPE_MLDSA) {
11693
                ret = wc_MlDsaKey_SignCtx((wc_MlDsaKey*)ssl->hsKey, NULL, 0,
11694
                                          sigOut, &args->sigLen,
11695
                                          args->sigData, args->sigDataSz,
11696
                                          ssl->rng);
11697
                args->length = args->sigLen;
11698
            }
11699
        #endif /* WOLFSSL_HAVE_MLDSA */
11700
        #if defined(WOLFSSL_HAVE_SLHDSA) && !defined(WOLFSSL_SLHDSA_VERIFY_ONLY)
11701
            if (ssl->hsType == DYNAMIC_TYPE_SLHDSA) {
11702
                /* The FIPS wrapper for wc_SlhDsaKey_Sign gates on the per-thread
11703
                 * privateKeyReadEnable flag (unlike ML-DSA sign), returning
11704
                 * FIPS_PRIVATE_KEY_LOCKED_E when the key is locked. Bracket the
11705
                 * sign so it can read the SLH-DSA private key. */
11706
                PRIVATE_KEY_UNLOCK();
11707
                ret = wc_SlhDsaKey_Sign((SlhDsaKey*)ssl->hsKey, NULL, 0,
11708
                                        args->sigData, args->sigDataSz,
11709
                                        sigOut, &args->sigLen, ssl->rng);
11710
                PRIVATE_KEY_LOCK();
11711
                args->length = args->sigLen;
11712
            }
11713
        #endif /* WOLFSSL_HAVE_SLHDSA */
11714
0
        #if !defined(NO_RSA) && !defined(WOLFSSL_RSA_PUBLIC_ONLY) && \
11715
0
            !defined(WOLFSSL_RSA_VERIFY_ONLY)
11716
0
            if (ssl->hsType == DYNAMIC_TYPE_RSA) {
11717
0
                args->toSign = rsaSigBuf->buffer;
11718
0
                args->toSignSz = (word32)rsaSigBuf->length;
11719
            #if defined(HAVE_PK_CALLBACKS) && \
11720
                defined(TLS13_RSA_PSS_SIGN_CB_NO_PREHASH)
11721
                /* Pass full data to sign (args->sigData), not hash of */
11722
                if (ssl->ctx->RsaPssSignCb) {
11723
                    args->toSign = args->sigData;
11724
                    args->toSignSz = args->sigDataSz;
11725
                }
11726
            #endif
11727
0
                ret = RsaSign(ssl, (const byte*)args->toSign, args->toSignSz,
11728
0
                              sigOut, &args->sigLen, args->sigAlgo,
11729
0
                              ssl->options.hashAlgo, (RsaKey*)ssl->hsKey,
11730
0
                              ssl->buffers.key);
11731
0
                if (ret == 0) {
11732
0
                    args->length = args->sigLen;
11733
0
                    XMEMCPY(args->sigData, sigOut, args->sigLen);
11734
0
                }
11735
0
            }
11736
0
        #endif /* !NO_RSA && !WOLFSSL_RSA_PUBLIC_ONLY && !WOLFSSL_RSA_VERIFY_ONLY */
11737
11738
            /* Check for error */
11739
0
            if (ret != 0) {
11740
0
                goto exit_scv;
11741
0
            }
11742
11743
        #ifdef WOLFSSL_DUAL_ALG_CERTS
11744
            if (ssl->sigSpec != NULL &&
11745
                *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) {
11746
                /* Add signature length for the first signature. */
11747
                c16toa((word16)args->sigLen, sigOut - OPAQUE16_LEN);
11748
                args->length += OPAQUE16_LEN;
11749
11750
                /* Advance our pointer to where we store the alt signature.
11751
                 * We also add additional space for the length field of the
11752
                 * second signature. */
11753
                sigOut += args->sigLen + OPAQUE16_LEN;
11754
11755
                /* Generate the alternative signature */
11756
            #ifdef HAVE_ECC
11757
                if (ssl->hsAltType == DYNAMIC_TYPE_ECC) {
11758
                    ret = EccSign(ssl, args->altSigData, args->altSigDataSz,
11759
                                  sigOut, &args->altSigLen,
11760
                                  (ecc_key*)ssl->hsAltKey,
11761
                    #ifdef HAVE_PK_CALLBACKS
11762
                                  ssl->buffers.altKey
11763
                    #else
11764
                                  NULL
11765
                    #endif
11766
                                  );
11767
                }
11768
            #endif /* HAVE_ECC */
11769
            #if !defined(NO_RSA) && !defined(WOLFSSL_RSA_PUBLIC_ONLY) && \
11770
                !defined(WOLFSSL_RSA_VERIFY_ONLY)
11771
                if (ssl->hsAltType == DYNAMIC_TYPE_RSA) {
11772
                    args->toSign = rsaSigBuf->buffer;
11773
                    args->toSignSz = (word32)rsaSigBuf->length;
11774
                #if defined(HAVE_PK_CALLBACKS) && \
11775
                    defined(TLS13_RSA_PSS_SIGN_CB_NO_PREHASH)
11776
                    /* Pass full data to sign (args->altSigData), not hash of */
11777
                    if (ssl->ctx->RsaPssSignCb) {
11778
                        args->toSign = args->altSigData;
11779
                        args->toSignSz = (word32)args->altSigDataSz;
11780
                    }
11781
                #endif
11782
                    ret = RsaSign(ssl, (const byte*)args->toSign,
11783
                                  args->toSignSz, sigOut, &args->altSigLen,
11784
                                  args->altSigAlgo, ssl->options.hashAlgo,
11785
                                  (RsaKey*)ssl->hsAltKey,
11786
                                  ssl->buffers.altKey);
11787
11788
                    if (ret == 0) {
11789
                        XMEMCPY(args->altSigData, sigOut, args->altSigLen);
11790
                    }
11791
                }
11792
            #endif /* !NO_RSA && !WOLFSSL_RSA_PUBLIC_ONLY && !WOLFSSL_RSA_VERIFY_ONLY */
11793
            #if defined(HAVE_FALCON)
11794
                if (ssl->hsAltType == DYNAMIC_TYPE_FALCON) {
11795
                    ret = wc_falcon_sign_msg(args->altSigData,
11796
                                             args->altSigDataSz, sigOut,
11797
                                             &args->altSigLen,
11798
                                             (falcon_key*)ssl->hsAltKey,
11799
                                             ssl->rng);
11800
                }
11801
            #endif /* HAVE_FALCON */
11802
            #if defined(WOLFSSL_HAVE_MLDSA) && !defined(WOLFSSL_MLDSA_NO_SIGN)
11803
                if (ssl->hsAltType == DYNAMIC_TYPE_MLDSA) {
11804
                    ret = wc_MlDsaKey_SignCtx((wc_MlDsaKey*)ssl->hsAltKey,
11805
                                NULL, 0, sigOut, &args->altSigLen,
11806
                                args->altSigData, args->altSigDataSz, ssl->rng);
11807
                }
11808
            #endif /* WOLFSSL_HAVE_MLDSA */
11809
11810
                /* Check for error */
11811
                if (ret != 0) {
11812
                    goto exit_scv;
11813
                }
11814
11815
                /* Add signature length for the alternative signature. */
11816
                c16toa((word16)args->altSigLen, sigOut - OPAQUE16_LEN);
11817
11818
                /* Add length of the alt sig to the total length */
11819
                args->length += args->altSigLen + OPAQUE16_LEN;
11820
            }
11821
        #endif /* WOLFSSL_DUAL_ALG_CERTS */
11822
11823
            /* The TLS 1.3 CertificateVerify signature is length-prefixed with a
11824
             * 2-byte field (opaque signature<0..2^16-1>), so the body - a single
11825
             * signature, or the combined native + alternative signature with
11826
             * WOLFSSL_DUAL_ALG_CERTS - cannot exceed 65535 bytes. Reject rather
11827
             * than let c16toa truncate it into a malformed message. args->length
11828
             * is word32 so the dual-alg accumulation above cannot wrap before
11829
             * this check. */
11830
0
            if (args->length > WOLFSSL_MAX_16BIT) {
11831
0
                ERROR_OUT(BUFFER_E, exit_scv);
11832
0
            }
11833
11834
            /* Add signature length. */
11835
0
            c16toa((word16)args->length, args->verify + HASH_SIG_SIZE);
11836
11837
            /* Advance state and proceed */
11838
0
            ssl->options.asyncState = TLS_ASYNC_VERIFY;
11839
0
        } /* case TLS_ASYNC_DO */
11840
0
        FALL_THROUGH;
11841
11842
0
        case TLS_ASYNC_VERIFY:
11843
0
        {
11844
0
        #ifndef NO_RSA
11845
0
            if (ssl->hsType == DYNAMIC_TYPE_RSA) {
11846
                /* check for signature faults */
11847
0
                ret = VerifyRsaSign(ssl, args->sigData, args->sigLen,
11848
0
                    rsaSigBuf->buffer, (word32)rsaSigBuf->length, args->sigAlgo,
11849
0
                    ssl->options.hashAlgo, (RsaKey*)ssl->hsKey,
11850
0
                    ssl->buffers.key);
11851
0
            }
11852
        #ifdef WOLFSSL_DUAL_ALG_CERTS
11853
            if (ssl->sigSpec != NULL &&
11854
                *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH &&
11855
                ssl->hsAltType == DYNAMIC_TYPE_RSA) {
11856
                /* check for signature faults */
11857
                ret = VerifyRsaSign(ssl, args->altSigData, args->altSigLen,
11858
                        rsaSigBuf->buffer, (word32)rsaSigBuf->length,
11859
                        args->altSigAlgo, ssl->options.hashAlgo,
11860
                        (RsaKey*)ssl->hsAltKey, ssl->buffers.altKey);
11861
            }
11862
        #endif /* WOLFSSL_DUAL_ALG_CERTS */
11863
0
        #endif /* !NO_RSA */
11864
        #if defined(HAVE_ECC) && defined(WOLFSSL_CHECK_SIG_FAULTS)
11865
            if (ssl->hsType == DYNAMIC_TYPE_ECC) {
11866
                byte* sigOut = args->verify + HASH_SIG_SIZE + VERIFY_HEADER;
11867
            #ifdef WOLFSSL_DUAL_ALG_CERTS
11868
                if (ssl->sigSpec != NULL &&
11869
                    *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) {
11870
                    /* Add our length offset. */
11871
                    sigOut += OPAQUE16_LEN;
11872
                }
11873
            #endif
11874
            #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
11875
                if (ssl->buffers.keyType == sm2_sa_algo) {
11876
                    ret = Sm2wSm3Verify(ssl, TLS13_SM2_SIG_ID,
11877
                        TLS13_SM2_SIG_ID_SZ,
11878
                        sigOut, args->sigLen, args->sigData, args->sigDataSz,
11879
                        (ecc_key*)ssl->hsKey, NULL);
11880
                }
11881
                else
11882
            #endif
11883
                {
11884
                #ifdef HAVE_PK_CALLBACKS
11885
                    buffer tmp;
11886
11887
                    /* Private key may be held by the PK callback. */
11888
                    tmp.length = ssl->buffers.key ?
11889
                        ssl->buffers.key->length : 0;
11890
                    tmp.buffer = ssl->buffers.key ?
11891
                        ssl->buffers.key->buffer : NULL;
11892
                #endif
11893
                    ret = EccVerify(ssl, sigOut, args->sigLen,
11894
                            args->sigData, args->sigDataSz,
11895
                            (ecc_key*)ssl->hsKey,
11896
                #ifdef HAVE_PK_CALLBACKS
11897
                            &tmp
11898
                #else
11899
                            NULL
11900
                #endif
11901
                            );
11902
                }
11903
            }
11904
        #ifdef WOLFSSL_DUAL_ALG_CERTS
11905
            if (ssl->sigSpec != NULL &&
11906
                *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH &&
11907
                ssl->hsAltType == DYNAMIC_TYPE_ECC) {
11908
                /* check for signature faults */
11909
                byte* sigOut = args->verify + HASH_SIG_SIZE + VERIFY_HEADER +
11910
                                args->sigLen + OPAQUE16_LEN + OPAQUE16_LEN;
11911
            #ifdef HAVE_PK_CALLBACKS
11912
                buffer tmp;
11913
11914
                /* Private key may be held by the PK callback. */
11915
                tmp.length = ssl->buffers.altKey ?
11916
                    ssl->buffers.altKey->length : 0;
11917
                tmp.buffer = ssl->buffers.altKey ?
11918
                    ssl->buffers.altKey->buffer : NULL;
11919
            #endif
11920
                ret = EccVerify(ssl, sigOut, args->altSigLen,
11921
                        args->altSigData, args->altSigDataSz,
11922
                        (ecc_key*)ssl->hsAltKey,
11923
            #ifdef HAVE_PK_CALLBACKS
11924
                        &tmp
11925
            #else
11926
                        NULL
11927
            #endif
11928
                        );
11929
            }
11930
        #endif /* WOLFSSL_DUAL_ALG_CERTS */
11931
        #endif /* HAVE_ECC && WOLFSSL_CHECK_SIG_FAULTS */
11932
11933
            /* Check for error */
11934
0
            if (ret != 0) {
11935
0
                goto exit_scv;
11936
0
            }
11937
11938
            /* Advance state and proceed */
11939
0
            ssl->options.asyncState = TLS_ASYNC_FINALIZE;
11940
0
        } /* case TLS_ASYNC_VERIFY */
11941
0
        FALL_THROUGH;
11942
11943
0
        case TLS_ASYNC_FINALIZE:
11944
0
        {
11945
#ifdef WOLFSSL_TLS13_STREAM_CERT_VERIFY
11946
            if (ssl->buffers.certVerifyMsg.buffer != NULL) {
11947
                /* Streaming path: the assembled body sits in certVerifyMsg;
11948
                 * record its final length (exact even for variable-length
11949
                 * signatures). Per-fragment record/handshake headers are added
11950
                 * in TLS_ASYNC_END. */
11951
                ssl->buffers.certVerifyMsg.length =
11952
                    (word32)args->length + HASH_SIG_SIZE + VERIFY_HEADER;
11953
            }
11954
#endif /* WOLFSSL_TLS13_STREAM_CERT_VERIFY */
11955
            /* In-place path: put the record and handshake headers on now.
11956
             * args->output is NULL only on the streaming path. */
11957
0
            if (args->output != NULL) {
11958
0
                AddTls13Headers(args->output, args->length + HASH_SIG_SIZE +
11959
0
                                VERIFY_HEADER, certificate_verify, ssl);
11960
11961
0
                args->sendSz = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ +
11962
0
                                args->length + HASH_SIG_SIZE + VERIFY_HEADER;
11963
            #ifdef WOLFSSL_DTLS13
11964
                if (ssl->options.dtls)
11965
                    args->sendSz += recordLayerHdrExtra + DTLS_HANDSHAKE_EXTRA;
11966
            #endif /* WOLFSSL_DTLS13 */
11967
0
            }
11968
            /* Advance state and proceed */
11969
0
            ssl->options.asyncState = TLS_ASYNC_END;
11970
0
        } /* case TLS_ASYNC_FINALIZE */
11971
0
        FALL_THROUGH;
11972
11973
0
        case TLS_ASYNC_END:
11974
0
        {
11975
            /* Body of the handshake message: [sigAlg(2) | sigLen(2) | sig]. In
11976
             * the in-place path it sits at args->verify in the output buffer;
11977
             * in the streaming path it sits in ssl->buffers.certVerifyMsg. */
11978
0
            word32 msgSz;
11979
0
            word32 maxFrag = (word32)wolfssl_local_GetMaxPlaintextSize(ssl);
11980
0
            byte*  output;
11981
0
            word32 fragSz;
11982
0
            word32 i;
11983
0
            int    recSz;
11984
0
            int    thisSendSz;
11985
11986
#ifdef WOLFSSL_TLS13_STREAM_CERT_VERIFY
11987
            if (ssl->buffers.certVerifyMsg.buffer != NULL) {
11988
                /* Streamed send: the assembled body lives in
11989
                 * ssl->buffers.certVerifyMsg and the send cursor in
11990
                 * ssl->fragOffset - both connection-level - so a non-blocking
11991
                 * WANT_WRITE resumes here (via TLS_ASYNC_END) without
11992
                 * recomputing the signature. Emit one encrypted record per
11993
                 * iteration and flush it, so the output buffer never holds more
11994
                 * than a single fragment. Only the first record carries the
11995
                 * handshake header; BuildTls13Message hashes each fragment's
11996
                 * plaintext in order, keeping the transcript hash correct. The
11997
                 * cursor is advanced before the flush because the record is
11998
                 * already committed to the output buffer; the cursor tracks
11999
                 * message-body -> record progress, not bytes on the wire, so a
12000
                 * WANT_WRITE resumes on the next fragment. Advancing after the
12001
                 * flush would rebuild and double-send the fragment on resume.
12002
                 * This is not merely a convention: the accept/connect loop
12003
                 * flushes pending output and returns WANT_WRITE without
12004
                 * re-entering this function until the output buffer drains, so
12005
                 * the committed record is never skipped or overwritten.
12006
                 * certVerifyMsg is released on completion or error at exit_scv;
12007
                 * it is kept across WANT_WRITE for resume. */
12008
                msgSz = ssl->buffers.certVerifyMsg.length;
12009
                if (maxFrag <= HANDSHAKE_HEADER_SZ) {
12010
                    ERROR_OUT(BUFFER_E, exit_scv);
12011
                }
12012
                while (ssl->fragOffset < msgSz && ret == 0) {
12013
                    if (ssl->fragOffset == 0) {
12014
                        fragSz = maxFrag - HANDSHAKE_HEADER_SZ;
12015
                        if (fragSz > msgSz)
12016
                            fragSz = msgSz;
12017
                        i = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
12018
                        thisSendSz = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ +
12019
                                     (int)fragSz + MAX_MSG_EXTRA;
12020
                    }
12021
                    else {
12022
                        fragSz = msgSz - ssl->fragOffset;
12023
                        if (fragSz > maxFrag)
12024
                            fragSz = maxFrag;
12025
                        i = RECORD_HEADER_SZ;
12026
                        thisSendSz = RECORD_HEADER_SZ + (int)fragSz +
12027
                                     MAX_MSG_EXTRA;
12028
                    }
12029
12030
                    if ((ret = CheckAvailableSize(ssl, thisSendSz)) != 0) {
12031
                        goto exit_scv;
12032
                    }
12033
                    output = GetOutputBuffer(ssl);
12034
12035
                    if (ssl->fragOffset == 0) {
12036
                        AddTls13FragHeaders(output, fragSz, 0, msgSz,
12037
                                            certificate_verify, ssl);
12038
                    }
12039
                    else {
12040
                        AddTls13RecordHeader(output, fragSz, handshake, ssl);
12041
                    }
12042
                    XMEMCPY(output + i,
12043
                            ssl->buffers.certVerifyMsg.buffer + ssl->fragOffset,
12044
                            fragSz);
12045
12046
                    /* This message is always encrypted. */
12047
                    recSz = BuildTls13Message(ssl, output, thisSendSz,
12048
                                output + RECORD_HEADER_SZ,
12049
                                (int)(i - RECORD_HEADER_SZ + fragSz), handshake,
12050
                                1, 0, 0);
12051
                    if (recSz < 0) {
12052
                        ret = recSz;
12053
                        goto exit_scv;
12054
                    }
12055
12056
                #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
12057
                    /* Trace the logical CertificateVerify once (first fragment),
12058
                     * matching the single-record path. */
12059
                    if (ssl->fragOffset == 0) {
12060
                        if (ssl->hsInfoOn)
12061
                            AddPacketName(ssl, "CertificateVerify");
12062
                        if (ssl->toInfoOn) {
12063
                            ret = AddPacketInfo(ssl, "CertificateVerify",
12064
                                        handshake, output, recSz, WRITE_PROTO, 0,
12065
                                        ssl->heap);
12066
                            if (ret != 0)
12067
                                goto exit_scv;
12068
                        }
12069
                    }
12070
                #endif
12071
12072
                    ssl->buffers.outputBuffer.length += (word32)recSz;
12073
                    ssl->fragOffset += fragSz;
12074
                    /* Flush every fragment unconditionally - unlike the
12075
                     * in-place path this cannot honor ssl->options.groupMessages
12076
                     * (batch with later handshake messages), because streaming
12077
                     * exists precisely to keep the output buffer bounded to a
12078
                     * single fragment. */
12079
                    ret = SendBuffered(ssl);
12080
                }
12081
12082
                ssl->options.buildingMsg = 0;
12083
                break;
12084
            }
12085
#endif /* WOLFSSL_TLS13_STREAM_CERT_VERIFY */
12086
12087
            /* In-place path: the whole message is in args->output. */
12088
0
            msgSz = (word32)args->length + HASH_SIG_SIZE + VERIFY_HEADER;
12089
12090
#ifdef WOLFSSL_DTLS13
12091
            if (ssl->options.dtls) {
12092
                ssl->options.buildingMsg = 0;
12093
12094
                /* Dtls13HandshakeSend takes word16 output/send sizes, so the
12095
                 * whole assembled CertificateVerify (signature plus framing)
12096
                 * must fit in 16 bits. Every current SLH-DSA parameter set
12097
                 * stays well under this (256f, the largest, is ~50KB), but
12098
                 * guard the casts explicitly - mirroring the args->length check
12099
                 * on the TLS path - so a future larger signature fails loudly
12100
                 * instead of being silently truncated into a malformed record.
12101
                 * outputSz is the reserved capacity and is >= sendSz, so it
12102
                 * bounds both casts. */
12103
                if (args->outputSz > WOLFSSL_MAX_16BIT) {
12104
                    ERROR_OUT(BUFFER_E, exit_scv);
12105
                }
12106
12107
                ret = Dtls13HandshakeSend(ssl, args->output,
12108
                    (word16)args->outputSz,
12109
                    (word16)args->sendSz, certificate_verify, 1);
12110
                if (ret != 0)
12111
                    goto exit_scv;
12112
12113
                break;
12114
            }
12115
#endif /* WOLFSSL_DTLS13 */
12116
12117
0
            if (HANDSHAKE_HEADER_SZ + msgSz <= maxFrag) {
12118
                /* Fits in a single record: the common path used by RSA, ECC,
12119
                 * EdDSA and ML-DSA is left byte-for-byte unchanged. */
12120
12121
                /* Always encrypted. A record AEAD pend propagates through
12122
                 * exit_scv (args kept) and the retry resumes the build. */
12123
0
                ret = BuildTls13Message(ssl, args->output,
12124
0
                                        (int)args->outputSz,
12125
0
                                        args->output + RECORD_HEADER_SZ,
12126
0
                                        args->sendSz - RECORD_HEADER_SZ,
12127
0
                                        handshake, 1, 0,
12128
0
                                        TLS13_HS_ASYNC_OKAY);
12129
12130
0
                if (ret < 0) {
12131
0
                    goto exit_scv;
12132
0
                }
12133
0
                else {
12134
0
                    args->sendSz = ret;
12135
0
                    ret = 0;
12136
0
                }
12137
12138
            #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
12139
                if (ssl->hsInfoOn)
12140
                    AddPacketName(ssl, "CertificateVerify");
12141
                if (ssl->toInfoOn) {
12142
                    ret = AddPacketInfo(ssl, "CertificateVerify", handshake,
12143
                                args->output, args->sendSz, WRITE_PROTO, 0,
12144
                                ssl->heap);
12145
                    if (ret != 0)
12146
                        goto exit_scv;
12147
                }
12148
            #endif
12149
12150
0
                ssl->buffers.outputBuffer.length += (word32)args->sendSz;
12151
0
            }
12152
0
            else {
12153
                /* Signature does not fit in a single TLS record (e.g. SLH-DSA,
12154
                 * whose signatures range up to ~50KB). Fragment the handshake
12155
                 * message across multiple encrypted records. Only the first
12156
                 * fragment carries the 4-byte handshake header; the transcript
12157
                 * hash is maintained correctly because BuildTls13Message hashes
12158
                 * each fragment's plaintext in order.
12159
                 *
12160
                 * The fragmentation cursor lives in args (frag/fragOffset/
12161
                 * fragActive) so that a WC_PENDING_E from the record AEAD under
12162
                 * WOLFSSL_ASYNC_CRYPT resumes on the same fragment rather than
12163
                 * restarting at offset 0 and re-emitting committed records. */
12164
0
                if (maxFrag <= HANDSHAKE_HEADER_SZ) {
12165
0
                    ERROR_OUT(BUFFER_E, exit_scv);
12166
0
                }
12167
12168
                /* Copy the assembled body out of the output buffer once, before
12169
                 * we begin overwriting it with per-record data. args->frag is
12170
                 * preserved across async resumes and freed by FreeScv13Args. */
12171
0
                if (args->frag == NULL) {
12172
0
                    args->frag = (byte*)XMALLOC(msgSz, ssl->heap,
12173
0
                                                DYNAMIC_TYPE_TMP_BUFFER);
12174
0
                    if (args->frag == NULL) {
12175
0
                        ERROR_OUT(MEMORY_E, exit_scv);
12176
0
                    }
12177
0
                    XMEMCPY(args->frag, args->verify, msgSz);
12178
0
                    args->fragOffset = 0;
12179
0
                    args->fragActive = 0;
12180
0
                }
12181
12182
0
                while (args->fragOffset < msgSz && ret == 0) {
12183
0
                    if (args->fragOffset == 0) {
12184
0
                        fragSz = maxFrag - HANDSHAKE_HEADER_SZ;
12185
0
                        if (fragSz > msgSz)
12186
0
                            fragSz = msgSz;
12187
0
                        thisSendSz = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ +
12188
0
                                     (int)fragSz + MAX_MSG_EXTRA;
12189
0
                    }
12190
0
                    else {
12191
0
                        fragSz = msgSz - args->fragOffset;
12192
0
                        if (fragSz > maxFrag)
12193
0
                            fragSz = maxFrag;
12194
0
                        thisSendSz = RECORD_HEADER_SZ + (int)fragSz +
12195
0
                                     MAX_MSG_EXTRA;
12196
0
                    }
12197
12198
0
                    if ((ret = CheckAvailableSize(ssl, thisSendSz)) != 0) {
12199
0
                        goto exit_scv;
12200
0
                    }
12201
0
                    output = GetOutputBuffer(ssl);
12202
12203
0
                    i = RECORD_HEADER_SZ;
12204
0
                    if (args->fragOffset == 0)
12205
0
                        i += HANDSHAKE_HEADER_SZ;
12206
12207
                    /* Lay out this fragment's record header and plaintext once.
12208
                     * On an async resume of a pending fragment they are already
12209
                     * in place (outputBuffer.length was not advanced), so skip
12210
                     * straight to re-driving BuildTls13Message. */
12211
0
                    if (!args->fragActive) {
12212
0
                        if (args->fragOffset == 0) {
12213
0
                            AddTls13FragHeaders(output, fragSz, 0, msgSz,
12214
0
                                                certificate_verify, ssl);
12215
0
                        }
12216
0
                        else {
12217
0
                            AddTls13RecordHeader(output, fragSz, handshake, ssl);
12218
0
                        }
12219
0
                        XMEMCPY(output + i, args->frag + args->fragOffset,
12220
0
                                fragSz);
12221
0
                        args->fragActive = 1;
12222
0
                    }
12223
0
                    i += fragSz;
12224
12225
                    /* This message is always encrypted. */
12226
0
                    recSz = BuildTls13Message(ssl, output, thisSendSz,
12227
0
                                output + RECORD_HEADER_SZ,
12228
0
                                (int)(i - RECORD_HEADER_SZ), handshake, 1, 0, 0);
12229
0
                    if (recSz < 0) {
12230
                        /* WC_PENDING_E leaves frag/fragOffset/fragActive intact
12231
                         * for resume; real errors are cleaned up by
12232
                         * FreeScv13Args at exit_scv. */
12233
0
                        ret = recSz;
12234
0
                        goto exit_scv;
12235
0
                    }
12236
12237
                #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
12238
                    /* Trace the logical CertificateVerify once (on the first
12239
                     * fragment), matching the single-record path rather than
12240
                     * emitting one entry per record. */
12241
                    if (args->fragOffset == 0) {
12242
                        if (ssl->hsInfoOn)
12243
                            AddPacketName(ssl, "CertificateVerify");
12244
                        if (ssl->toInfoOn) {
12245
                            ret = AddPacketInfo(ssl, "CertificateVerify",
12246
                                        handshake, output, recSz, WRITE_PROTO, 0,
12247
                                        ssl->heap);
12248
                            if (ret != 0)
12249
                                goto exit_scv;
12250
                        }
12251
                    }
12252
                #endif
12253
12254
0
                    ssl->buffers.outputBuffer.length += (word32)recSz;
12255
0
                    args->fragOffset += fragSz;
12256
0
                    args->fragActive = 0;
12257
0
                }
12258
0
            }
12259
12260
0
            ssl->options.buildingMsg = 0;
12261
0
            if (!ssl->options.groupMessages)
12262
0
                ret = SendBuffered(ssl);
12263
0
            break;
12264
0
        }
12265
0
        default:
12266
0
            ret = INPUT_CASE_ERROR;
12267
0
    } /* switch(ssl->options.asyncState) */
12268
12269
0
exit_scv:
12270
#ifdef WOLFSSL_TLS13_STREAM_CERT_VERIFY
12271
    /* A streamed CertificateVerify keeps its assembled body across a
12272
     * non-blocking WANT_WRITE so the send resumes without recomputing the
12273
     * signature; release it on completion or on any real error. This path is
12274
     * mutually exclusive with WOLFSSL_ASYNC_CRYPT (see the feature guard in
12275
     * internal.h), so ret is never WC_PENDING_E here and the buffer needs no
12276
     * retention across an async resume. */
12277
    if (ret != WC_NO_ERR_TRACE(WANT_WRITE) &&
12278
            ssl->buffers.certVerifyMsg.buffer != NULL) {
12279
        XFREE(ssl->buffers.certVerifyMsg.buffer, ssl->heap,
12280
              DYNAMIC_TYPE_TMP_BUFFER);
12281
        ssl->buffers.certVerifyMsg.buffer = NULL;
12282
        ssl->buffers.certVerifyMsg.length = 0;
12283
        ssl->fragOffset = 0;
12284
    }
12285
#endif /* WOLFSSL_TLS13_STREAM_CERT_VERIFY */
12286
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
12287
    if (ret == 0) {
12288
        ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.key,
12289
            &ssl->buffers.keyMask);
12290
    }
12291
    else {
12292
        wolfssl_priv_der_blind_toggle(ssl->buffers.key, ssl->buffers.keyMask);
12293
    }
12294
#endif
12295
12296
0
    WOLFSSL_LEAVE("SendTls13CertificateVerify", ret);
12297
0
    WOLFSSL_END(WC_FUNC_CERTIFICATE_VERIFY_SEND);
12298
12299
#ifdef WOLFSSL_ASYNC_CRYPT
12300
    /* Handle async operation */
12301
    if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
12302
        return ret;
12303
    }
12304
#endif /* WOLFSSL_ASYNC_CRYPT */
12305
12306
    /* Final cleanup */
12307
0
    FreeScv13Args(ssl, args);
12308
0
    FreeKeyExchange(ssl);
12309
0
#ifdef WOLFSSL_ASYNC_IO
12310
    /* Cleanup async */
12311
0
    FreeAsyncCtx(ssl, 0);
12312
0
#endif
12313
12314
0
    if (ret != 0) {
12315
0
        WOLFSSL_ERROR_VERBOSE(ret);
12316
0
    }
12317
12318
0
    return ret;
12319
0
}
12320
#endif
12321
#endif /* !NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER */
12322
12323
#if !defined(NO_WOLFSSL_CLIENT) || !defined(WOLFSSL_NO_CLIENT_AUTH)
12324
/* handle processing TLS v1.3 certificate (11) */
12325
/* Parse and handle a TLS v1.3 Certificate message.
12326
 *
12327
 * ssl       The SSL/TLS object.
12328
 * input     The message buffer.
12329
 * inOutIdx  On entry, the index into the message buffer of Certificate.
12330
 *           On exit, the index of byte after the Certificate message.
12331
 * totalSz   The length of the current handshake message.
12332
 * returns 0 on success and otherwise failure.
12333
 */
12334
static int DoTls13Certificate(WOLFSSL* ssl, byte* input, word32* inOutIdx,
12335
                              word32 totalSz)
12336
0
{
12337
0
    int ret = 0;
12338
12339
0
    WOLFSSL_START(WC_FUNC_CERTIFICATE_DO);
12340
0
    WOLFSSL_ENTER("DoTls13Certificate");
12341
12342
#ifdef WOLFSSL_DTLS13
12343
    if (ssl->options.dtls && ssl->options.handShakeDone) {
12344
        /* certificate needs some special care after the handshake */
12345
        ret = Dtls13RtxProcessingCertificate(
12346
            ssl, input + *inOutIdx, totalSz);
12347
    }
12348
#endif /* WOLFSSL_DTLS13 */
12349
12350
0
    if (ret == 0)
12351
0
        ret = ProcessPeerCerts(ssl, input, inOutIdx, totalSz);
12352
0
    if (ret == 0) {
12353
0
#if !defined(NO_WOLFSSL_CLIENT)
12354
0
        if (ssl->options.side == WOLFSSL_CLIENT_END)
12355
0
            ssl->options.serverState = SERVER_CERT_COMPLETE;
12356
0
#endif
12357
#if !defined(NO_WOLFSSL_SERVER) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
12358
        if (ssl->options.side == WOLFSSL_SERVER_END &&
12359
                                ssl->options.handShakeState == HANDSHAKE_DONE) {
12360
            /* reset handshake states */
12361
            ssl->options.serverState = SERVER_FINISHED_COMPLETE;
12362
            ssl->options.acceptState  = TICKET_SENT;
12363
            ssl->options.handShakeState = SERVER_FINISHED_COMPLETE;
12364
        }
12365
#endif
12366
0
    }
12367
12368
0
    WOLFSSL_LEAVE("DoTls13Certificate", ret);
12369
0
    WOLFSSL_END(WC_FUNC_CERTIFICATE_DO);
12370
12371
0
    return ret;
12372
0
}
12373
#endif
12374
12375
#if (!defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
12376
     defined(HAVE_ED448) || defined(HAVE_FALCON) || \
12377
     defined(WOLFSSL_HAVE_MLDSA) || defined(WOLFSSL_HAVE_SLHDSA)) && \
12378
    !defined(NO_CERTS)
12379
12380
typedef struct Dcv13Args {
12381
    byte*  output; /* not allocated */
12382
    word32 sendSz;
12383
    word16 sz;
12384
    word32 sigSz;
12385
    word32 idx;
12386
    word32 begin;
12387
12388
    byte*  sigData;
12389
    word16 sigDataSz;
12390
#ifdef WOLFSSL_DUAL_ALG_CERTS
12391
    byte   altSigAlgo;
12392
    byte*  altSigData;
12393
    word32 altSigDataSz;
12394
    word32 altSignatureSz;
12395
    byte   altPeerAuthGood;
12396
#endif
12397
} Dcv13Args;
12398
12399
static void FreeDcv13Args(WOLFSSL* ssl, void* pArgs)
12400
0
{
12401
0
    Dcv13Args* args = (Dcv13Args*)pArgs;
12402
12403
0
    if (args && args->sigData != NULL) {
12404
0
        XFREE(args->sigData, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
12405
0
        args->sigData = NULL;
12406
0
    }
12407
#ifdef WOLFSSL_DUAL_ALG_CERTS
12408
    if (args && args->altSigData != NULL) {
12409
        XFREE(args->altSigData, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
12410
        args->altSigData = NULL;
12411
    }
12412
#endif
12413
0
    (void)ssl;
12414
0
}
12415
12416
#ifdef WOLFSSL_DUAL_ALG_CERTS
12417
#ifndef NO_RSA
12418
/* ssl->peerCert->sapkiDer is the alternative public key. Hopefully it is a
12419
 * RSA public key. Convert it into a usable public key. */
12420
static int decodeRsaKey(WOLFSSL* ssl)
12421
{
12422
    int keyRet;
12423
    word32 tmpIdx = 0;
12424
12425
    if (ssl->peerRsaKeyPresent)
12426
        return INVALID_PARAMETER;
12427
12428
    keyRet = AllocKey(ssl, DYNAMIC_TYPE_RSA, (void**)&ssl->peerRsaKey);
12429
    if (keyRet != 0)
12430
        return PEER_KEY_ERROR;
12431
12432
    ssl->peerRsaKeyPresent = 1;
12433
    keyRet = wc_RsaPublicKeyDecode(ssl->peerCert.sapkiDer, &tmpIdx,
12434
                                   ssl->peerRsaKey,
12435
                                   ssl->peerCert.sapkiLen);
12436
    if (keyRet != 0)
12437
        return PEER_KEY_ERROR;
12438
12439
    return 0;
12440
}
12441
#endif /* !NO_RSA */
12442
12443
#ifdef HAVE_ECC
12444
/* ssl->peerCert->sapkiDer is the alternative public key. Hopefully it is a
12445
 * ECC public key. Convert it into a usable public key. */
12446
static int decodeEccKey(WOLFSSL* ssl)
12447
{
12448
    int keyRet;
12449
    word32 tmpIdx = 0;
12450
12451
    if (ssl->peerEccDsaKeyPresent)
12452
        return INVALID_PARAMETER;
12453
12454
    keyRet = AllocKey(ssl, DYNAMIC_TYPE_ECC, (void**)&ssl->peerEccDsaKey);
12455
    if (keyRet != 0)
12456
        return PEER_KEY_ERROR;
12457
12458
    ssl->peerEccDsaKeyPresent = 1;
12459
    keyRet = wc_EccPublicKeyDecode(ssl->peerCert.sapkiDer, &tmpIdx,
12460
                                   ssl->peerEccDsaKey,
12461
                                   ssl->peerCert.sapkiLen);
12462
    if (keyRet != 0)
12463
        return PEER_KEY_ERROR;
12464
12465
    return 0;
12466
}
12467
#endif /* HAVE_ECC */
12468
12469
#ifdef WOLFSSL_HAVE_MLDSA
12470
/* ssl->peerCert->sapkiDer is the alternative public key. Hopefully it is a
12471
 * ML-DSA public key. Convert it into a usable public key. */
12472
static int decodeMlDsaKey(WOLFSSL* ssl, int level)
12473
{
12474
    int keyRet;
12475
    word32 tmpIdx = 0;
12476
12477
    if (ssl->peerMlDsaKeyPresent)
12478
        return INVALID_PARAMETER;
12479
12480
    keyRet = AllocKey(ssl, DYNAMIC_TYPE_MLDSA,
12481
                      (void**)&ssl->peerMlDsaKey);
12482
    if (keyRet != 0)
12483
        return PEER_KEY_ERROR;
12484
12485
    ssl->peerMlDsaKeyPresent = 1;
12486
    keyRet = wc_MlDsaKey_SetParams(ssl->peerMlDsaKey, level);
12487
    if (keyRet != 0)
12488
        return PEER_KEY_ERROR;
12489
12490
    keyRet = wc_MlDsaKey_PublicKeyDecode(ssl->peerMlDsaKey,
12491
                                         ssl->peerCert.sapkiDer,
12492
                                         ssl->peerCert.sapkiLen, &tmpIdx);
12493
    if (keyRet != 0)
12494
        return PEER_KEY_ERROR;
12495
12496
    return 0;
12497
}
12498
#endif /* WOLFSSL_HAVE_MLDSA */
12499
12500
#ifdef HAVE_FALCON
12501
/* ssl->peerCert->sapkiDer is the alternative public key. Hopefully it is a
12502
 * falcon public key. Convert it into a usable public key. */
12503
static int decodeFalconKey(WOLFSSL* ssl, int level)
12504
{
12505
    int keyRet;
12506
    word32 tmpIdx = 0;
12507
12508
    if (ssl->peerFalconKeyPresent)
12509
        return INVALID_PARAMETER;
12510
12511
    keyRet = AllocKey(ssl, DYNAMIC_TYPE_FALCON, (void**)&ssl->peerFalconKey);
12512
    if (keyRet != 0)
12513
        return PEER_KEY_ERROR;
12514
12515
    ssl->peerFalconKeyPresent = 1;
12516
    keyRet = wc_falcon_set_level(ssl->peerFalconKey, level);
12517
    if (keyRet != 0)
12518
        return PEER_KEY_ERROR;
12519
12520
    keyRet = wc_Falcon_PublicKeyDecode(ssl->peerCert.sapkiDer, &tmpIdx,
12521
                                       ssl->peerFalconKey,
12522
                                       ssl->peerCert.sapkiLen);
12523
    if (keyRet != 0)
12524
        return PEER_KEY_ERROR;
12525
12526
    return 0;
12527
}
12528
#endif /* HAVE_FALCON */
12529
#endif /* WOLFSSL_DUAL_ALG_CERTS */
12530
12531
/* handle processing TLS v1.3 certificate_verify (15) */
12532
/* Parse and handle a TLS v1.3 CertificateVerify message.
12533
 *
12534
 * ssl       The SSL/TLS object.
12535
 * input     The message buffer.
12536
 * inOutIdx  On entry, the index into the message buffer of
12537
 *           CertificateVerify.
12538
 *           On exit, the index of byte after the CertificateVerify message.
12539
 * totalSz   The length of the current handshake message.
12540
 * returns 0 on success and otherwise failure.
12541
 */
12542
static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input,
12543
                                    word32* inOutIdx, word32 totalSz)
12544
0
{
12545
0
    int         ret = 0;
12546
0
    byte*       sig = NULL;
12547
0
#ifndef NO_RSA
12548
    /* Use this as a temporary buffer for RSA signature verification. */
12549
0
    buffer*     rsaSigBuf = &ssl->buffers.sig;
12550
0
#endif
12551
#ifdef WOLFSSL_ASYNC_CRYPT
12552
    Dcv13Args* args = NULL;
12553
    WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
12554
#else
12555
0
    Dcv13Args  args[1];
12556
0
#endif
12557
12558
0
    WOLFSSL_START(WC_FUNC_CERTIFICATE_VERIFY_DO);
12559
0
    WOLFSSL_ENTER("DoTls13CertificateVerify");
12560
12561
#if defined(WOLFSSL_RENESAS_TSIP_TLS)
12562
    ret = tsip_Tls13CertificateVerify(ssl, input, inOutIdx, totalSz);
12563
    if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
12564
        goto exit_dcv;
12565
    }
12566
    ret = 0;
12567
#endif
12568
12569
#ifdef WOLFSSL_ASYNC_CRYPT
12570
    if (ssl->async == NULL) {
12571
        ssl->async = (struct WOLFSSL_ASYNC*)
12572
                XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
12573
                        DYNAMIC_TYPE_ASYNC);
12574
        if (ssl->async == NULL)
12575
            ERROR_OUT(MEMORY_E, exit_dcv);
12576
    }
12577
    args = (Dcv13Args*)ssl->async->args;
12578
12579
    ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
12580
    if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) {
12581
        /* Check for error */
12582
        if (ret < 0)
12583
            goto exit_dcv;
12584
    }
12585
    else
12586
#endif
12587
0
    {
12588
        /* Reset state */
12589
0
        ret = 0;
12590
0
        ssl->options.asyncState = TLS_ASYNC_BEGIN;
12591
0
        XMEMSET(args, 0, sizeof(Dcv13Args));
12592
0
        ssl->options.peerHashAlgo = sha_mac;
12593
0
        ssl->options.peerSigAlgo = anonymous_sa_algo;
12594
0
        args->idx = *inOutIdx;
12595
0
        args->begin = *inOutIdx;
12596
    #ifdef WOLFSSL_ASYNC_CRYPT
12597
        ssl->async->freeArgs = FreeDcv13Args;
12598
    #endif
12599
0
    }
12600
12601
0
    switch(ssl->options.asyncState)
12602
0
    {
12603
0
        case TLS_ASYNC_BEGIN:
12604
0
        {
12605
        #ifdef WOLFSSL_CALLBACKS
12606
            if (ssl->hsInfoOn) AddPacketName(ssl, "CertificateVerify");
12607
            if (ssl->toInfoOn) AddLateName("CertificateVerify",
12608
                                           &ssl->timeoutInfo);
12609
        #endif
12610
12611
            /* Advance state and proceed */
12612
0
            ssl->options.asyncState = TLS_ASYNC_BUILD;
12613
0
        } /* case TLS_ASYNC_BEGIN */
12614
0
        FALL_THROUGH;
12615
12616
0
        case TLS_ASYNC_BUILD:
12617
0
        {
12618
0
            int validSigAlgo;
12619
0
            const Suites* suites = WOLFSSL_SUITES(ssl);
12620
0
            word16 i;
12621
12622
            /* Signature algorithm. */
12623
0
            if ((args->idx - args->begin) + ENUM_LEN + ENUM_LEN > totalSz) {
12624
0
                ERROR_OUT(BUFFER_ERROR, exit_dcv);
12625
0
            }
12626
12627
#ifdef WOLFSSL_DUAL_ALG_CERTS
12628
            if (ssl->peerSigSpec == NULL) {
12629
                /* The peer did not respond. We didn't send CKS or they don't
12630
                 * support it. Either way, we do not need to handle dual
12631
                 * key/sig case. */
12632
                ssl->sigSpec = NULL;
12633
                ssl->sigSpecSz = 0;
12634
            }
12635
12636
            /* If no CKS extension or either native or alternative, then just
12637
             * get a normal sigalgo.  But if BOTH, then get the native and alt
12638
             * sig algos. */
12639
            if (ssl->sigSpec == NULL ||
12640
                *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_NATIVE ||
12641
                *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_ALTERNATIVE) {
12642
#endif /* WOLFSSL_DUAL_ALG_CERTS */
12643
0
                validSigAlgo = 0;
12644
0
                for (i = 0; i < suites->hashSigAlgoSz; i += 2) {
12645
0
                     if ((suites->hashSigAlgo[i + 0] == input[args->idx + 0]) &&
12646
0
                             (suites->hashSigAlgo[i + 1] == input[args->idx + 1])) {
12647
0
                         validSigAlgo = 1;
12648
0
                         break;
12649
0
                     }
12650
0
                }
12651
0
                if (!validSigAlgo) {
12652
0
                    ERROR_OUT(INVALID_PARAMETER, exit_dcv);
12653
0
                }
12654
12655
0
                ret = DecodeTls13SigAlg(input + args->idx,
12656
0
                        &ssl->options.peerHashAlgo, &ssl->options.peerSigAlgo);
12657
#ifdef WOLFSSL_DUAL_ALG_CERTS
12658
            }
12659
            else {
12660
                ret = DecodeTls13HybridSigAlg(input + args->idx,
12661
                                              &ssl->options.peerHashAlgo,
12662
                                              &ssl->options.peerSigAlgo,
12663
                                              &args->altSigAlgo);
12664
            }
12665
#endif /* WOLFSSL_DUAL_ALG_CERTS */
12666
12667
0
            if (ret < 0)
12668
0
                goto exit_dcv;
12669
0
            args->idx += OPAQUE16_LEN;
12670
12671
            /* Signature length. */
12672
0
            if ((args->idx - args->begin) + OPAQUE16_LEN > totalSz) {
12673
0
                ERROR_OUT(BUFFER_ERROR, exit_dcv);
12674
0
            }
12675
0
            ato16(input + args->idx, &args->sz);
12676
0
            args->idx += OPAQUE16_LEN;
12677
12678
            /* Signature data. */
12679
0
            if ((args->idx - args->begin) + args->sz > totalSz) {
12680
0
                ERROR_OUT(BUFFER_ERROR, exit_dcv);
12681
0
            }
12682
12683
#ifdef WOLFSSL_DUAL_ALG_CERTS
12684
            if ((ssl->sigSpec != NULL) &&
12685
                (*ssl->sigSpec != WOLFSSL_CKS_SIGSPEC_NATIVE)) {
12686
12687
                word16 sa;
12688
                if (args->altSigAlgo == 0)
12689
                    sa = ssl->options.peerSigAlgo;
12690
                else
12691
                    sa = args->altSigAlgo;
12692
12693
                switch(sa) {
12694
            #ifndef NO_RSA
12695
                case rsa_pss_sa_algo:
12696
                    ret = decodeRsaKey(ssl);
12697
                    break;
12698
            #endif
12699
            #ifdef HAVE_ECC
12700
                case ecc_dsa_sa_algo:
12701
                    ret = decodeEccKey(ssl);
12702
                    break;
12703
            #endif
12704
            #ifdef WOLFSSL_HAVE_MLDSA
12705
                case mldsa_44_sa_algo:
12706
                    ret = decodeMlDsaKey(ssl, WC_ML_DSA_44);
12707
                    break;
12708
                case mldsa_65_sa_algo:
12709
                    ret = decodeMlDsaKey(ssl, WC_ML_DSA_65);
12710
                    break;
12711
                case mldsa_87_sa_algo:
12712
                    ret = decodeMlDsaKey(ssl, WC_ML_DSA_87);
12713
                    break;
12714
            #endif
12715
            #ifdef WOLFSSL_HAVE_SLHDSA
12716
                case slhdsa_sha2_128s_sa_algo:
12717
                case slhdsa_sha2_128f_sa_algo:
12718
                case slhdsa_sha2_192s_sa_algo:
12719
                case slhdsa_sha2_192f_sa_algo:
12720
                case slhdsa_sha2_256s_sa_algo:
12721
                case slhdsa_sha2_256f_sa_algo:
12722
                case slhdsa_shake_128s_sa_algo:
12723
                case slhdsa_shake_128f_sa_algo:
12724
                case slhdsa_shake_192s_sa_algo:
12725
                case slhdsa_shake_192f_sa_algo:
12726
                case slhdsa_shake_256s_sa_algo:
12727
                case slhdsa_shake_256f_sa_algo:
12728
                    /* SLH-DSA is not supported as an alternative (dual-algorithm
12729
                     * / CKS) key. The alternative-signature verification block
12730
                     * in this function has no SLH-DSA case, so a decoded key
12731
                     * would never be verified and the handshake would always be
12732
                     * rejected at TLS_ASYNC_FINALIZE. Fail fast here instead of
12733
                     * allocating a key that can never authenticate the peer. */
12734
                    ERROR_OUT(ALGO_ID_E, exit_dcv);
12735
            #endif
12736
            #ifdef HAVE_FALCON
12737
                case falcon_level1_sa_algo:
12738
                    ret = decodeFalconKey(ssl, 1);
12739
                    break;
12740
                case falcon_level5_sa_algo:
12741
                    ret = decodeFalconKey(ssl, 5);
12742
                    break;
12743
            #endif
12744
                default:
12745
                    ERROR_OUT(PEER_KEY_ERROR, exit_dcv);
12746
                }
12747
12748
                if (ret != 0)
12749
                    ERROR_OUT(ret, exit_dcv);
12750
12751
                if (*ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_ALTERNATIVE) {
12752
                    /* Now swap in the alternative by removing the native.
12753
                     * sa contains the alternative signature type. */
12754
                #ifndef NO_RSA
12755
                    if (ssl->peerRsaKeyPresent && sa != rsa_pss_sa_algo) {
12756
                        FreeKey(ssl, DYNAMIC_TYPE_RSA,
12757
                                (void**)&ssl->peerRsaKey);
12758
                        ssl->peerRsaKeyPresent = 0;
12759
                    }
12760
                #endif
12761
                #ifdef HAVE_ECC
12762
                    else if (ssl->peerEccDsaKeyPresent &&
12763
                             sa != ecc_dsa_sa_algo) {
12764
                        FreeKey(ssl, DYNAMIC_TYPE_ECC,
12765
                                (void**)&ssl->peerEccDsaKey);
12766
                        ssl->peerEccDsaKeyPresent = 0;
12767
                    }
12768
                #endif
12769
                #ifdef WOLFSSL_HAVE_MLDSA
12770
                    else if (ssl->peerMlDsaKeyPresent &&
12771
                             sa != mldsa_44_sa_algo &&
12772
                             sa != mldsa_65_sa_algo &&
12773
                             sa != mldsa_87_sa_algo) {
12774
                        FreeKey(ssl, DYNAMIC_TYPE_MLDSA,
12775
                                (void**)&ssl->peerMlDsaKey);
12776
                        ssl->peerMlDsaKeyPresent = 0;
12777
                    }
12778
                #endif
12779
                #ifdef WOLFSSL_HAVE_SLHDSA
12780
                    else if (ssl->peerSlhDsaKeyPresent &&
12781
                             !IsSlhDsaSigAlgo(sa)) {
12782
                        FreeKey(ssl, DYNAMIC_TYPE_SLHDSA,
12783
                                (void**)&ssl->peerSlhDsaKey);
12784
                        ssl->peerSlhDsaKeyPresent = 0;
12785
                    }
12786
                #endif
12787
                #ifdef HAVE_FALCON
12788
                    else if (ssl->peerFalconKeyPresent &&
12789
                             sa != falcon_level1_sa_algo &&
12790
                             sa != falcon_level5_sa_algo) {
12791
                        FreeKey(ssl, DYNAMIC_TYPE_FALCON,
12792
                                (void**)&ssl->peerFalconKey);
12793
                        ssl->peerFalconKeyPresent = 0;
12794
                    }
12795
                #endif
12796
                    else {
12797
                        ERROR_OUT(PEER_KEY_ERROR, exit_dcv);
12798
                    }
12799
                }
12800
            }
12801
#endif /* WOLFSSL_DUAL_ALG_CERTS */
12802
12803
            /* Check for public key of required type. */
12804
            /* Assume invalid unless signature algo matches the key provided */
12805
0
            validSigAlgo = 0;
12806
        #ifdef HAVE_ED25519
12807
            if (ssl->options.peerSigAlgo == ed25519_sa_algo) {
12808
                WOLFSSL_MSG("Peer sent ED25519 sig");
12809
                validSigAlgo = (ssl->peerEd25519Key != NULL) &&
12810
                                                     ssl->peerEd25519KeyPresent;
12811
            }
12812
        #endif
12813
        #ifdef HAVE_ED448
12814
            if (ssl->options.peerSigAlgo == ed448_sa_algo) {
12815
                WOLFSSL_MSG("Peer sent ED448 sig");
12816
                validSigAlgo = (ssl->peerEd448Key != NULL) &&
12817
                                                       ssl->peerEd448KeyPresent;
12818
            }
12819
        #endif
12820
0
        #ifdef HAVE_ECC
12821
0
            if (ssl->options.peerSigAlgo == ecc_dsa_sa_algo) {
12822
0
                WOLFSSL_MSG("Peer sent ECC sig");
12823
0
                validSigAlgo = (ssl->peerEccDsaKey != NULL) &&
12824
0
                                                      ssl->peerEccDsaKeyPresent;
12825
0
            }
12826
0
        #endif
12827
        #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
12828
            if (ssl->options.peerSigAlgo == sm2_sa_algo) {
12829
                WOLFSSL_MSG("Peer sent SM2 sig");
12830
                validSigAlgo = (ssl->peerEccDsaKey != NULL) &&
12831
                                                      ssl->peerEccDsaKeyPresent;
12832
            }
12833
        #endif
12834
        #ifdef HAVE_FALCON
12835
            if (ssl->options.peerSigAlgo == falcon_level1_sa_algo) {
12836
                WOLFSSL_MSG("Peer sent Falcon Level 1 sig");
12837
                validSigAlgo = (ssl->peerFalconKey != NULL) &&
12838
                               ssl->peerFalconKeyPresent;
12839
            }
12840
            if (ssl->options.peerSigAlgo == falcon_level5_sa_algo) {
12841
                WOLFSSL_MSG("Peer sent Falcon Level 5 sig");
12842
                validSigAlgo = (ssl->peerFalconKey != NULL) &&
12843
                               ssl->peerFalconKeyPresent;
12844
            }
12845
        #endif
12846
        #ifdef WOLFSSL_HAVE_MLDSA
12847
            if (ssl->options.peerSigAlgo == mldsa_44_sa_algo) {
12848
                WOLFSSL_MSG("Peer sent ML-DSA Level 2 sig");
12849
                validSigAlgo = (ssl->peerMlDsaKey != NULL) &&
12850
                               ssl->peerMlDsaKeyPresent;
12851
            }
12852
            if (ssl->options.peerSigAlgo == mldsa_65_sa_algo) {
12853
                WOLFSSL_MSG("Peer sent ML-DSA Level 3 sig");
12854
                validSigAlgo = (ssl->peerMlDsaKey != NULL) &&
12855
                               ssl->peerMlDsaKeyPresent;
12856
            }
12857
            if (ssl->options.peerSigAlgo == mldsa_87_sa_algo) {
12858
                WOLFSSL_MSG("Peer sent ML-DSA Level 5 sig");
12859
                validSigAlgo = (ssl->peerMlDsaKey != NULL) &&
12860
                               ssl->peerMlDsaKeyPresent;
12861
            }
12862
        #endif
12863
        #ifdef WOLFSSL_HAVE_SLHDSA
12864
            if (IsSlhDsaSigAlgo(ssl->options.peerSigAlgo)) {
12865
                WOLFSSL_MSG("Peer sent SLH-DSA sig");
12866
                validSigAlgo = (ssl->peerSlhDsaKey != NULL) &&
12867
                               ssl->peerSlhDsaKeyPresent;
12868
            }
12869
        #endif
12870
0
        #ifndef NO_RSA
12871
0
            if (ssl->options.peerSigAlgo == rsa_sa_algo) {
12872
0
                WOLFSSL_MSG("Peer sent PKCS#1.5 algo - not valid TLS 1.3");
12873
0
                ERROR_OUT(INVALID_PARAMETER, exit_dcv);
12874
0
            }
12875
0
            if (ssl->options.peerSigAlgo == rsa_pss_sa_algo) {
12876
0
                WOLFSSL_MSG("Peer sent RSA sig");
12877
0
                validSigAlgo = (ssl->peerRsaKey != NULL) &&
12878
0
                                                         ssl->peerRsaKeyPresent;
12879
0
            }
12880
0
        #endif
12881
0
            if (!validSigAlgo) {
12882
0
                WOLFSSL_MSG("Sig algo doesn't correspond to certificate");
12883
0
                ERROR_OUT(SIG_VERIFY_E, exit_dcv);
12884
0
            }
12885
12886
0
            args->sigSz = args->sz;
12887
#ifdef WOLFSSL_DUAL_ALG_CERTS
12888
            if (ssl->sigSpec != NULL &&
12889
                *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) {
12890
                /* In case we received two signatures, both of them are encoded
12891
                 * with their size as 16-bit integeter prior in memory. Hence,
12892
                 * we can decode both lengths here now. */
12893
                word32 tmpIdx = args->idx;
12894
                word16 tmpSz = 0;
12895
                if (args->sz < OPAQUE16_LEN) {
12896
                    ERROR_OUT(BUFFER_ERROR, exit_dcv);
12897
                }
12898
                ato16(input + tmpIdx, &tmpSz);
12899
                args->sigSz = tmpSz;
12900
12901
                tmpIdx += OPAQUE16_LEN + args->sigSz;
12902
                if (tmpIdx - args->idx + OPAQUE16_LEN > args->sz) {
12903
                    ERROR_OUT(BUFFER_ERROR, exit_dcv);
12904
                }
12905
                ato16(input + tmpIdx, &tmpSz);
12906
                args->altSignatureSz = tmpSz;
12907
12908
                if (args->sz != (args->sigSz + args->altSignatureSz +
12909
                                    OPAQUE16_LEN + OPAQUE16_LEN)) {
12910
                    ERROR_OUT(BUFFER_ERROR, exit_dcv);
12911
                }
12912
            }
12913
#endif /* WOLFSSL_DUAL_ALG_CERTS */
12914
12915
0
        #if !defined(NO_RSA) && defined(WC_RSA_PSS)
12916
            /* In case we have to verify an RSA signature, we have to store the
12917
             * signature in the 'rsaSigBuf' structure for further processing.
12918
             */
12919
0
            if (ssl->peerRsaKey != NULL && ssl->peerRsaKeyPresent != 0) {
12920
0
                word32 sigSz = args->sigSz;
12921
0
                sig = input + args->idx;
12922
            #ifdef WOLFSSL_DUAL_ALG_CERTS
12923
                /* Check if our alternative signature was RSA */
12924
                if (ssl->sigSpec != NULL &&
12925
                    *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) {
12926
                    if (ssl->options.peerSigAlgo != rsa_pss_sa_algo) {
12927
                        /* We have to skip the first signature (length field
12928
                         * and signature itself) and the length field of the
12929
                         * alternative signature. */
12930
                        sig += OPAQUE16_LEN + OPAQUE16_LEN + args->sigSz;
12931
                        sigSz = args->altSignatureSz;
12932
                    }
12933
                    else {
12934
                        /* We have to skip the length field */
12935
                        sig += OPAQUE16_LEN;
12936
                    }
12937
                }
12938
            #endif
12939
0
                rsaSigBuf->buffer = (byte*)XMALLOC(sigSz, ssl->heap,
12940
0
                                         DYNAMIC_TYPE_SIGNATURE);
12941
0
                if (rsaSigBuf->buffer == NULL) {
12942
0
                    ERROR_OUT(MEMORY_E, exit_dcv);
12943
0
                }
12944
0
                rsaSigBuf->length = sigSz;
12945
0
                XMEMCPY(rsaSigBuf->buffer, sig, rsaSigBuf->length);
12946
0
            }
12947
0
        #endif /* !NO_RSA && WC_RSA_PSS */
12948
12949
0
            args->sigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap,
12950
0
                                                    DYNAMIC_TYPE_SIGNATURE);
12951
0
            if (args->sigData == NULL) {
12952
0
                ERROR_OUT(MEMORY_E, exit_dcv);
12953
0
            }
12954
12955
0
            ret = CreateSigData(ssl, args->sigData, &args->sigDataSz, 1);
12956
0
            if (ret < 0)
12957
0
                goto exit_dcv;
12958
12959
        #ifdef WOLFSSL_DUAL_ALG_CERTS
12960
            if ((ssl->sigSpec != NULL) &&
12961
                (*ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH)) {
12962
                args->altSigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap,
12963
                                                        DYNAMIC_TYPE_SIGNATURE);
12964
                if (args->altSigData == NULL) {
12965
                    ERROR_OUT(MEMORY_E, exit_dcv);
12966
                }
12967
                XMEMCPY(args->altSigData, args->sigData, args->sigDataSz);
12968
                args->altSigDataSz = args->sigDataSz;
12969
            }
12970
        #endif /* WOLFSSL_DUAL_ALG_CERTS */
12971
12972
0
        #ifdef HAVE_ECC
12973
0
            if ((ssl->options.peerSigAlgo == ecc_dsa_sa_algo) &&
12974
0
                (ssl->peerEccDsaKeyPresent)) {
12975
0
                ret = CreateECCEncodedSig(args->sigData,
12976
0
                    args->sigDataSz, ssl->options.peerHashAlgo);
12977
0
                if (ret < 0)
12978
0
                    goto exit_dcv;
12979
0
                args->sigDataSz = (word16)ret;
12980
0
                ret = 0;
12981
0
            }
12982
12983
        #ifdef WOLFSSL_DUAL_ALG_CERTS
12984
            if ((ssl->sigSpec != NULL) &&
12985
                (*ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) &&
12986
                (args->altSigAlgo == ecc_dsa_sa_algo) &&
12987
                (ssl->peerEccDsaKeyPresent)) {
12988
                ret = CreateECCEncodedSig(args->altSigData,
12989
                        args->altSigDataSz, ssl->options.peerHashAlgo);
12990
                    if (ret < 0)
12991
                        goto exit_dcv;
12992
                    args->altSigDataSz = (word16)ret;
12993
                    ret = 0;
12994
            }
12995
        #endif /* WOLFSSL_DUAL_ALG_CERTS */
12996
0
        #endif /* HAVE_ECC */
12997
12998
            /* Advance state and proceed */
12999
0
            ssl->options.asyncState = TLS_ASYNC_DO;
13000
0
        } /* case TLS_ASYNC_BUILD */
13001
0
        FALL_THROUGH;
13002
13003
0
        case TLS_ASYNC_DO:
13004
0
        {
13005
0
            sig = input + args->idx;
13006
0
            (void)sig;
13007
        #ifdef WOLFSSL_DUAL_ALG_CERTS
13008
            if (ssl->sigSpec != NULL &&
13009
                *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) {
13010
                /* As we have two signatures in the message, we stored
13011
                 * the length of each before the actual signature. This
13012
                 * is necessary, as we could have two algorithms with
13013
                 * variable length signatures. */
13014
                sig += OPAQUE16_LEN;
13015
            }
13016
        #endif
13017
0
        #ifndef NO_RSA
13018
0
            if ((ssl->options.peerSigAlgo == rsa_pss_sa_algo) &&
13019
0
                (ssl->peerRsaKey != NULL) && (ssl->peerRsaKeyPresent != 0)) {
13020
0
                WOLFSSL_MSG("Doing RSA peer cert verify");
13021
0
                ret = RsaVerify(ssl, rsaSigBuf->buffer,
13022
0
                                (word32)rsaSigBuf->length, &args->output,
13023
0
                                ssl->options.peerSigAlgo,
13024
0
                                ssl->options.peerHashAlgo, ssl->peerRsaKey,
13025
                #ifdef HAVE_PK_CALLBACKS
13026
                                &ssl->buffers.peerRsaKey
13027
                #else
13028
0
                                NULL
13029
0
                #endif
13030
0
                                );
13031
0
                if (ret >= 0) {
13032
0
                    args->sendSz = (word32)ret;
13033
0
                    ret = 0;
13034
0
                }
13035
0
            }
13036
0
        #endif /* !NO_RSA */
13037
0
        #ifdef HAVE_ECC
13038
0
            if ((ssl->options.peerSigAlgo == ecc_dsa_sa_algo) &&
13039
0
                    ssl->peerEccDsaKeyPresent) {
13040
0
                WOLFSSL_MSG("Doing ECC peer cert verify");
13041
0
                ret = EccVerify(ssl, sig, args->sigSz,
13042
0
                    args->sigData, args->sigDataSz,
13043
0
                    ssl->peerEccDsaKey,
13044
                #ifdef HAVE_PK_CALLBACKS
13045
                    &ssl->buffers.peerEccDsaKey
13046
                #else
13047
0
                    NULL
13048
0
                #endif
13049
0
                    );
13050
13051
0
                if (ret >= 0) {
13052
                    /* CLIENT/SERVER: data verified with public key from
13053
                     * certificate. */
13054
0
                    ssl->options.peerAuthGood = 1;
13055
13056
0
                    FreeKey(ssl, DYNAMIC_TYPE_ECC, (void**)&ssl->peerEccDsaKey);
13057
0
                    ssl->peerEccDsaKeyPresent = 0;
13058
0
                }
13059
0
            }
13060
0
        #endif /* HAVE_ECC */
13061
        #if defined(HAVE_ECC) && defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
13062
            if ((ssl->options.peerSigAlgo == sm2_sa_algo) &&
13063
                   ssl->peerEccDsaKeyPresent) {
13064
                WOLFSSL_MSG("Doing SM2/SM3 peer cert verify");
13065
                ret = Sm2wSm3Verify(ssl, TLS13_SM2_SIG_ID, TLS13_SM2_SIG_ID_SZ,
13066
                    sig, args->sigSz, args->sigData, args->sigDataSz,
13067
                    ssl->peerEccDsaKey, NULL);
13068
                if (ret >= 0) {
13069
                    /* CLIENT/SERVER: data verified with public key from
13070
                     * certificate. */
13071
                    ssl->options.peerAuthGood = 1;
13072
13073
                    FreeKey(ssl, DYNAMIC_TYPE_ECC, (void**)&ssl->peerEccDsaKey);
13074
                    ssl->peerEccDsaKeyPresent = 0;
13075
                }
13076
            }
13077
        #endif
13078
        #ifdef HAVE_ED25519
13079
            if ((ssl->options.peerSigAlgo == ed25519_sa_algo) &&
13080
                (ssl->peerEd25519KeyPresent)) {
13081
                WOLFSSL_MSG("Doing ED25519 peer cert verify");
13082
                ret = Ed25519Verify(ssl, sig, args->sigSz,
13083
                    args->sigData, args->sigDataSz,
13084
                    ssl->peerEd25519Key,
13085
                #ifdef HAVE_PK_CALLBACKS
13086
                    &ssl->buffers.peerEd25519Key
13087
                #else
13088
                    NULL
13089
                #endif
13090
                    );
13091
13092
                if (ret >= 0) {
13093
                    /* CLIENT/SERVER: data verified with public key from
13094
                     * certificate. */
13095
                    ssl->options.peerAuthGood = 1;
13096
                    FreeKey(ssl, DYNAMIC_TYPE_ED25519,
13097
                                                  (void**)&ssl->peerEd25519Key);
13098
                    ssl->peerEd25519KeyPresent = 0;
13099
                }
13100
            }
13101
        #endif
13102
        #ifdef HAVE_ED448
13103
            if ((ssl->options.peerSigAlgo == ed448_sa_algo) &&
13104
                (ssl->peerEd448KeyPresent)) {
13105
                WOLFSSL_MSG("Doing ED448 peer cert verify");
13106
                ret = Ed448Verify(ssl, sig, args->sigSz,
13107
                    args->sigData, args->sigDataSz,
13108
                    ssl->peerEd448Key,
13109
                #ifdef HAVE_PK_CALLBACKS
13110
                    &ssl->buffers.peerEd448Key
13111
                #else
13112
                    NULL
13113
                #endif
13114
                );
13115
13116
                if (ret >= 0) {
13117
                    /* CLIENT/SERVER: data verified with public key from
13118
                     * certificate. */
13119
                    ssl->options.peerAuthGood = 1;
13120
                    FreeKey(ssl, DYNAMIC_TYPE_ED448,
13121
                                                    (void**)&ssl->peerEd448Key);
13122
                    ssl->peerEd448KeyPresent = 0;
13123
                }
13124
            }
13125
        #endif
13126
        #if defined(HAVE_FALCON)
13127
            if (((ssl->options.peerSigAlgo == falcon_level1_sa_algo) ||
13128
                 (ssl->options.peerSigAlgo == falcon_level5_sa_algo)) &&
13129
                (ssl->peerFalconKeyPresent)) {
13130
                int res = 0;
13131
                WOLFSSL_MSG("Doing Falcon peer cert verify");
13132
                ret = wc_falcon_verify_msg(sig, args->sigSz,
13133
                                           args->sigData, args->sigDataSz,
13134
                                           &res, ssl->peerFalconKey);
13135
13136
                if ((ret >= 0) && (res == 1)) {
13137
                    /* CLIENT/SERVER: data verified with public key from
13138
                     * certificate. */
13139
                    ssl->options.peerAuthGood = 1;
13140
13141
                    FreeKey(ssl, DYNAMIC_TYPE_FALCON,
13142
                                                   (void**)&ssl->peerFalconKey);
13143
                    ssl->peerFalconKeyPresent = 0;
13144
                }
13145
                else if ((ret >= 0) && (res == 0)) {
13146
                    WOLFSSL_MSG("Falcon signature verification failed");
13147
                    ret = SIG_VERIFY_E;
13148
                }
13149
            }
13150
        #endif /* HAVE_FALCON */
13151
        #if defined(WOLFSSL_HAVE_MLDSA) && !defined(WOLFSSL_MLDSA_NO_VERIFY)
13152
            if (((ssl->options.peerSigAlgo == mldsa_44_sa_algo) ||
13153
                 (ssl->options.peerSigAlgo == mldsa_65_sa_algo) ||
13154
                 (ssl->options.peerSigAlgo == mldsa_87_sa_algo)) &&
13155
                (ssl->peerMlDsaKeyPresent)) {
13156
                int res = 0;
13157
                WOLFSSL_MSG("Doing ML-DSA peer cert verify");
13158
                ret = wc_MlDsaKey_VerifyCtx(ssl->peerMlDsaKey, sig, args->sigSz,
13159
                                            NULL, 0, args->sigData,
13160
                                            args->sigDataSz, &res);
13161
13162
                if ((ret >= 0) && (res == 1)) {
13163
                    /* CLIENT/SERVER: data verified with public key from
13164
                     * certificate. */
13165
                    ssl->options.peerAuthGood = 1;
13166
13167
                    FreeKey(ssl, DYNAMIC_TYPE_MLDSA,
13168
                            (void**)&ssl->peerMlDsaKey);
13169
                    ssl->peerMlDsaKeyPresent = 0;
13170
                }
13171
                else if ((ret >= 0) && (res == 0)) {
13172
                    WOLFSSL_MSG("ML-DSA signature verification failed");
13173
                    ret = SIG_VERIFY_E;
13174
                }
13175
            }
13176
        #endif /* WOLFSSL_HAVE_MLDSA */
13177
        #if defined(WOLFSSL_HAVE_SLHDSA)
13178
            if (IsSlhDsaSigAlgo(ssl->options.peerSigAlgo) &&
13179
                (ssl->peerSlhDsaKeyPresent)) {
13180
                WOLFSSL_MSG("Doing SLH-DSA peer cert verify");
13181
13182
                /* The advertised signature scheme must match the parameter set
13183
                 * of the peer's certificate key (RFC 8446 4.4.3). The key
13184
                 * params come from the certificate OID, so a mismatch means the
13185
                 * peer is over-claiming its security level; reject it. */
13186
                if ((ssl->peerSlhDsaKey->params == NULL) ||
13187
                    (SlhDsaParamToType((int)ssl->peerSlhDsaKey->params->param)
13188
                        != ssl->options.peerSigAlgo)) {
13189
                    ERROR_OUT(SIG_VERIFY_E, exit_dcv);
13190
                }
13191
13192
                /* wc_SlhDsaKey_Verify returns 0 for a valid signature. */
13193
                ret = wc_SlhDsaKey_Verify(ssl->peerSlhDsaKey, NULL, 0,
13194
                                          args->sigData, args->sigDataSz,
13195
                                          sig, args->sigSz);
13196
13197
                if (ret == 0) {
13198
                    /* CLIENT/SERVER: data verified with public key from
13199
                     * certificate. */
13200
                    ssl->options.peerAuthGood = 1;
13201
13202
                    FreeKey(ssl, DYNAMIC_TYPE_SLHDSA,
13203
                            (void**)&ssl->peerSlhDsaKey);
13204
                    ssl->peerSlhDsaKeyPresent = 0;
13205
                }
13206
                else {
13207
                    /* wc_SlhDsaKey_Verify already returns SIG_VERIFY_E on a
13208
                     * signature mismatch and propagates real errors verbatim
13209
                     * (WC_PENDING_E on the async crypto-callback path, MEMORY_E,
13210
                     * ...), so leave ret unchanged. Flattening everything to
13211
                     * SIG_VERIFY_E would break async resume and mask
13212
                     * diagnostics; the ML-DSA/Falcon blocks above likewise
13213
                     * preserve non-completion return codes. */
13214
                    WOLFSSL_MSG("SLH-DSA signature verification failed");
13215
                }
13216
            }
13217
        #endif /* WOLFSSL_HAVE_SLHDSA */
13218
13219
            /* Check for error */
13220
0
            if (ret != 0) {
13221
0
                goto exit_dcv;
13222
0
            }
13223
13224
        #ifdef WOLFSSL_DUAL_ALG_CERTS
13225
            if (ssl->sigSpec != NULL &&
13226
                *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) {
13227
                /* Move forward to the alternative signature. */
13228
                sig += args->sigSz + OPAQUE16_LEN;
13229
13230
                /* Verify the alternative signature */
13231
            #ifndef NO_RSA
13232
                if ((args->altSigAlgo == rsa_pss_sa_algo) &&
13233
                    (ssl->peerRsaKey != NULL) &&
13234
                    (ssl->peerRsaKeyPresent != 0)) {
13235
                    WOLFSSL_MSG("Doing RSA peer cert alt verify");
13236
                    ret = RsaVerify(ssl, rsaSigBuf->buffer,
13237
                                    (word32)rsaSigBuf->length,
13238
                                    &args->output, args->altSigAlgo,
13239
                                    ssl->options.peerHashAlgo, ssl->peerRsaKey,
13240
                    #ifdef HAVE_PK_CALLBACKS
13241
                                    &ssl->buffers.peerRsaKey
13242
                    #else
13243
                                    NULL
13244
                    #endif
13245
                                    );
13246
                    if (ret >= 0) {
13247
                        args->sendSz = ret;
13248
                        ret = 0;
13249
                    }
13250
                }
13251
            #endif /* !NO_RSA */
13252
            #ifdef HAVE_ECC
13253
                if ((args->altSigAlgo == ecc_dsa_sa_algo) &&
13254
                    (ssl->peerEccDsaKeyPresent)) {
13255
                    WOLFSSL_MSG("Doing ECC peer cert alt verify");
13256
                    ret = EccVerify(ssl, sig, args->altSignatureSz,
13257
                                args->altSigData, args->altSigDataSz,
13258
                                ssl->peerEccDsaKey,
13259
                    #ifdef HAVE_PK_CALLBACKS
13260
                                &ssl->buffers.peerEccDsaKey
13261
                    #else
13262
                                NULL
13263
                    #endif
13264
                                );
13265
13266
                    if (ret >= 0) {
13267
                        /* CLIENT/SERVER: data verified with public key from
13268
                        * certificate. */
13269
                        args->altPeerAuthGood = 1;
13270
13271
                        FreeKey(ssl, DYNAMIC_TYPE_ECC,
13272
                                                (void**)&ssl->peerEccDsaKey);
13273
                        ssl->peerEccDsaKeyPresent = 0;
13274
                    }
13275
                }
13276
            #endif /* HAVE_ECC */
13277
            #if defined(HAVE_FALCON)
13278
                if (((args->altSigAlgo == falcon_level1_sa_algo) ||
13279
                     (args->altSigAlgo == falcon_level5_sa_algo)) &&
13280
                    (ssl->peerFalconKeyPresent)) {
13281
                    int res = 0;
13282
                    WOLFSSL_MSG("Doing Falcon peer cert alt verify");
13283
                    ret = wc_falcon_verify_msg(sig, args->altSignatureSz,
13284
                                        args->altSigData, args->altSigDataSz,
13285
                                        &res, ssl->peerFalconKey);
13286
13287
                    if ((ret >= 0) && (res == 1)) {
13288
                        /* CLIENT/SERVER: data verified with public key from
13289
                        * certificate. */
13290
                        args->altPeerAuthGood = 1;
13291
13292
                        FreeKey(ssl, DYNAMIC_TYPE_FALCON,
13293
                                                (void**)&ssl->peerFalconKey);
13294
                        ssl->peerFalconKeyPresent = 0;
13295
                    }
13296
                    else if ((ret >= 0) && (res == 0)) {
13297
                        WOLFSSL_MSG("Falcon signature verification failed");
13298
                        ret = SIG_VERIFY_E;
13299
                    }
13300
                }
13301
            #endif /* HAVE_FALCON */
13302
            #if defined(WOLFSSL_HAVE_MLDSA) && !defined(WOLFSSL_MLDSA_NO_VERIFY)
13303
                if (((args->altSigAlgo == mldsa_44_sa_algo) ||
13304
                     (args->altSigAlgo == mldsa_65_sa_algo) ||
13305
                     (args->altSigAlgo == mldsa_87_sa_algo)) &&
13306
                    (ssl->peerMlDsaKeyPresent)) {
13307
                    int res = 0;
13308
                    WOLFSSL_MSG("Doing ML-DSA peer cert alt verify");
13309
                    ret = wc_MlDsaKey_VerifyCtx(ssl->peerMlDsaKey, sig,
13310
                                        args->altSignatureSz, NULL, 0,
13311
                                        args->altSigData,
13312
                                        args->altSigDataSz, &res);
13313
13314
                    if ((ret >= 0) && (res == 1)) {
13315
                        /* CLIENT/SERVER: data verified with public key from
13316
                        * certificate. */
13317
                        args->altPeerAuthGood = 1;
13318
13319
                        FreeKey(ssl, DYNAMIC_TYPE_MLDSA,
13320
                                            (void**)&ssl->peerMlDsaKey);
13321
                        ssl->peerMlDsaKeyPresent = 0;
13322
                    }
13323
                    else if ((ret >= 0) && (res == 0)) {
13324
                        WOLFSSL_MSG("ML-DSA signature verification failed");
13325
                        ret = SIG_VERIFY_E;
13326
                    }
13327
                }
13328
            #endif /* WOLFSSL_HAVE_MLDSA */
13329
13330
                /* Check for error */
13331
                if (ret != 0) {
13332
                    goto exit_dcv;
13333
                }
13334
            }
13335
        #endif /* WOLFSSL_DUAL_ALG_CERTS */
13336
13337
            /* Advance state and proceed */
13338
0
            ssl->options.asyncState = TLS_ASYNC_VERIFY;
13339
0
        } /* case TLS_ASYNC_DO */
13340
0
        FALL_THROUGH;
13341
13342
0
        case TLS_ASYNC_VERIFY:
13343
0
        {
13344
0
        #if !defined(NO_RSA) && defined(WC_RSA_PSS)
13345
0
            if (ssl->peerRsaKey != NULL && ssl->peerRsaKeyPresent != 0) {
13346
0
                int sigAlgo = ssl->options.peerSigAlgo;
13347
            #ifdef WOLFSSL_DUAL_ALG_CERTS
13348
                /* Check if our alternative signature was RSA */
13349
                if (ssl->sigSpec != NULL &&
13350
                    *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH &&
13351
                    ssl->options.peerSigAlgo != rsa_pss_sa_algo) {
13352
                    sigAlgo = args->altSigAlgo;
13353
                }
13354
            #endif
13355
0
                ret = CheckRSASignature(ssl, sigAlgo,
13356
0
                        ssl->options.peerHashAlgo, args->output, args->sendSz);
13357
0
                if (ret != 0)
13358
0
                    goto exit_dcv;
13359
13360
                /* CLIENT/SERVER: data verified with public key from
13361
                 * certificate. */
13362
0
                ssl->peerRsaKeyPresent = 0;
13363
0
                FreeKey(ssl, DYNAMIC_TYPE_RSA, (void**)&ssl->peerRsaKey);
13364
            #ifdef WOLFSSL_DUAL_ALG_CERTS
13365
                /* Check if our alternative signature was RSA */
13366
                if (ssl->sigSpec != NULL &&
13367
                    *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH &&
13368
                    ssl->options.peerSigAlgo != rsa_pss_sa_algo) {
13369
                    args->altPeerAuthGood = 1;
13370
                }
13371
                else
13372
            #endif
13373
0
                    ssl->options.peerAuthGood = 1;
13374
0
            }
13375
0
        #endif /* !NO_RSA && WC_RSA_PSS */
13376
13377
            /* Advance state and proceed */
13378
0
            ssl->options.asyncState = TLS_ASYNC_FINALIZE;
13379
0
        } /* case TLS_ASYNC_VERIFY */
13380
0
        FALL_THROUGH;
13381
13382
0
        case TLS_ASYNC_FINALIZE:
13383
0
        {
13384
#ifdef WOLFSSL_DUAL_ALG_CERTS
13385
            if (ssl->options.peerAuthGood &&
13386
                ssl->sigSpec != NULL &&
13387
                *ssl->sigSpec == WOLFSSL_CKS_SIGSPEC_BOTH) {
13388
                ssl->options.peerAuthGood = args->altPeerAuthGood;
13389
            }
13390
#endif /* WOLFSSL_DUAL_ALG_CERTS */
13391
0
            ssl->options.havePeerVerify = 1;
13392
13393
            /* Set final index */
13394
0
            args->idx += args->sz;
13395
0
            *inOutIdx = args->idx;
13396
13397
            /* Advance state and proceed */
13398
0
            ssl->options.asyncState = TLS_ASYNC_END;
13399
13400
0
        #if !defined(NO_WOLFSSL_CLIENT)
13401
0
            if (ssl->options.side == WOLFSSL_CLIENT_END)
13402
0
                ssl->options.serverState = SERVER_CERT_VERIFY_COMPLETE;
13403
0
        #endif
13404
0
        } /* case TLS_ASYNC_FINALIZE */
13405
0
        FALL_THROUGH;
13406
13407
0
        case TLS_ASYNC_END:
13408
0
        {
13409
0
            break;
13410
0
        }
13411
13412
0
        default:
13413
0
            ret = INPUT_CASE_ERROR;
13414
0
    } /* switch(ssl->options.asyncState) */
13415
13416
0
exit_dcv:
13417
13418
0
    WOLFSSL_LEAVE("DoTls13CertificateVerify", ret);
13419
0
    WOLFSSL_END(WC_FUNC_CERTIFICATE_VERIFY_DO);
13420
13421
#ifdef WOLFSSL_ASYNC_CRYPT
13422
    /* Handle async operation */
13423
    if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
13424
        /* Mark message as not received so it can process again */
13425
        ssl->msgsReceived.got_certificate_verify = 0;
13426
13427
        return ret;
13428
    }
13429
    else
13430
#endif /* WOLFSSL_ASYNC_CRYPT */
13431
0
    if (ret != 0) {
13432
0
        WOLFSSL_ERROR_VERBOSE(ret);
13433
13434
0
        if (ret != WC_NO_ERR_TRACE(INVALID_PARAMETER)) {
13435
0
            SendAlert(ssl, alert_fatal, decrypt_error);
13436
0
        }
13437
0
    }
13438
13439
    /* Final cleanup */
13440
0
    FreeDcv13Args(ssl, args);
13441
0
    FreeKeyExchange(ssl);
13442
0
#ifdef WOLFSSL_ASYNC_IO
13443
    /* Cleanup async */
13444
0
    FreeAsyncCtx(ssl, 0);
13445
0
#endif
13446
#ifdef WOLFSSL_ASYNC_CRYPT
13447
    /* Replays skip the sanity check that re-sets got_certificate_verify;
13448
     * restore on completion or Finished reports out-of-order. */
13449
    if (ret == 0 && ssl->msgsReceived.got_certificate_verify == 0) {
13450
        ssl->msgsReceived.got_certificate_verify = 1;
13451
    }
13452
#endif
13453
13454
0
    return ret;
13455
0
}
13456
#endif /* !NO_RSA || HAVE_ECC || HAVE_ED25519 || HAVE_ED448 ||
13457
        * HAVE_FALCON || WOLFSSL_HAVE_MLDSA || WOLFSSL_HAVE_SLHDSA */
13458
#endif /* !NO_CERTS */
13459
13460
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
13461
/* Message is being processed after the enclosing handshake completed. Whatever
13462
 * resumption, PSK or deferred (post-handshake) verification excused during that
13463
 * handshake, a later post-handshake exchange has to stand on its own. */
13464
#define TLS13_AFTER_HANDSHAKE(ssl)  ((ssl)->options.handShakeDone)
13465
#else
13466
0
#define TLS13_AFTER_HANDSHAKE(ssl)  0
13467
#endif
13468
13469
/* Parse and handle a TLS v1.3 Finished message.
13470
 *
13471
 * ssl       The SSL/TLS object.
13472
 * input     The message buffer.
13473
 * inOutIdx  On entry, the index into the message buffer of Finished.
13474
 *           On exit, the index of byte after the Finished message and padding.
13475
 * size      Length of message data.
13476
 * totalSz   Length of remaining data in the message buffer.
13477
 * sniff     Indicates whether we are sniffing packets.
13478
 * returns 0 on success and otherwise failure.
13479
 */
13480
int DoTls13Finished(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
13481
                           word32 size, word32 totalSz, int sniff)
13482
0
{
13483
0
    int    ret;
13484
0
    word32 finishedSz = 0;
13485
0
    byte*  secret;
13486
0
    byte   mac[WC_MAX_DIGEST_SIZE];
13487
13488
0
    WOLFSSL_START(WC_FUNC_FINISHED_DO);
13489
0
    WOLFSSL_ENTER("DoTls13Finished");
13490
13491
0
#if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CLIENT_AUTH)
13492
    /* verify the client sent certificate if required */
13493
0
    if (ssl->options.side == WOLFSSL_SERVER_END &&
13494
0
            (!ssl->options.resuming || TLS13_AFTER_HANDSHAKE(ssl)) &&
13495
0
            (ssl->options.mutualAuth || ssl->options.failNoCert)) {
13496
#ifdef OPENSSL_COMPATIBLE_DEFAULTS
13497
        if (ssl->options.isPSK && !TLS13_AFTER_HANDSHAKE(ssl)) {
13498
            WOLFSSL_MSG("TLS v1.3 client used PSK but cert required. Allowing "
13499
                        "for OpenSSL compatibility");
13500
        }
13501
        else
13502
#endif
13503
0
        if (
13504
        #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
13505
            /* Exempt only the enclosing handshake; a post-handshake exchange
13506
             * still requires a peer certificate and a valid
13507
             * CertificateVerify. */
13508
            (!ssl->options.verifyPostHandshake || TLS13_AFTER_HANDSHAKE(ssl)) &&
13509
        #endif
13510
0
            (!ssl->options.havePeerCert || !ssl->options.havePeerVerify)) {
13511
0
            ret = NO_PEER_CERT; /* NO_PEER_VERIFY */
13512
0
            WOLFSSL_MSG("TLS v1.3 client did not present peer cert");
13513
0
            DoCertFatalAlert(ssl, ret);
13514
0
            goto cleanup;
13515
0
        }
13516
0
    }
13517
0
#endif
13518
13519
#if !defined(NO_CERTS) && !defined(NO_PSK) && \
13520
    defined(WOLFSSL_CERT_WITH_EXTERN_PSK)
13521
    /* Verify the server sent a certificate if requested */
13522
    if (ssl->options.side == WOLFSSL_CLIENT_END && ssl->options.pskNegotiated &&
13523
            ssl->options.failNoCert) {
13524
        if ((TLSX_Find(ssl->extensions, TLSX_CERT_WITH_EXTERN_PSK) != NULL) &&
13525
                (!ssl->options.havePeerCert || !ssl->options.havePeerVerify)) {
13526
            ret = NO_PEER_CERT;
13527
            WOLFSSL_MSG("TLS v1.3 server did not present peer cert");
13528
            DoCertFatalAlert(ssl, ret);
13529
            goto cleanup;
13530
        }
13531
    }
13532
#endif
13533
13534
    /* check against totalSz */
13535
0
    if (*inOutIdx + size > totalSz) {
13536
0
        ret = BUFFER_E;
13537
0
        goto cleanup;
13538
0
    }
13539
13540
#if defined(WOLFSSL_RENESAS_TSIP_TLS)
13541
    ret = tsip_Tls13HandleFinished(ssl, input, inOutIdx, size, totalSz);
13542
    if (ret == 0) {
13543
        ssl->options.serverState = SERVER_FINISHED_COMPLETE;
13544
        goto cleanup;
13545
    }
13546
    if (ret == WC_NO_ERR_TRACE(VERIFY_FINISHED_ERROR)) {
13547
        SendAlert(ssl, alert_fatal, decrypt_error);
13548
        goto cleanup;
13549
    }
13550
    if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
13551
        /* other errors */
13552
        goto cleanup;
13553
    }
13554
    ret = 0;
13555
#endif /* WOLFSSL_RENESAS_TSIP_TLS */
13556
13557
0
    if (ssl->options.handShakeDone) {
13558
0
        ret = DeriveFinishedSecret(ssl, ssl->clientSecret,
13559
0
                                   ssl->keys.client_write_MAC_secret,
13560
0
                                   WOLFSSL_CLIENT_END);
13561
0
        if (ret != 0)
13562
0
            goto cleanup;
13563
13564
0
        secret = ssl->keys.client_write_MAC_secret;
13565
0
    }
13566
0
    else if (ssl->options.side == WOLFSSL_CLIENT_END) {
13567
        /* All the handshake messages have been received to calculate
13568
         * client and server finished keys.
13569
         */
13570
0
        ret = DeriveFinishedSecret(ssl, ssl->clientSecret,
13571
0
                                   ssl->keys.client_write_MAC_secret,
13572
0
                                   WOLFSSL_CLIENT_END);
13573
0
        if (ret != 0)
13574
0
            goto cleanup;
13575
13576
0
        ret = DeriveFinishedSecret(ssl, ssl->serverSecret,
13577
0
                                   ssl->keys.server_write_MAC_secret,
13578
0
                                   WOLFSSL_SERVER_END);
13579
0
        if (ret != 0)
13580
0
            goto cleanup;
13581
13582
0
        secret = ssl->keys.server_write_MAC_secret;
13583
0
    }
13584
0
    else {
13585
0
        secret = ssl->keys.client_write_MAC_secret;
13586
0
    }
13587
13588
0
    if (sniff == NO_SNIFF) {
13589
13590
0
        ret = BuildTls13HandshakeHmac(ssl, secret, mac, &finishedSz);
13591
    #ifdef WOLFSSL_HAVE_TLS_UNIQUE
13592
        if (finishedSz > TLS_FINISHED_SZ_MAX) {
13593
            ret = BUFFER_ERROR;
13594
            goto cleanup;
13595
        }
13596
        if (ssl->options.side == WOLFSSL_CLIENT_END) {
13597
            XMEMCPY(ssl->serverFinished, mac, finishedSz);
13598
            ssl->serverFinished_len = (byte)finishedSz;
13599
        }
13600
        else {
13601
            XMEMCPY(ssl->clientFinished, mac, finishedSz);
13602
            ssl->clientFinished_len = (byte)finishedSz;
13603
        }
13604
    #endif /* WOLFSSL_HAVE_TLS_UNIQUE */
13605
0
        if (ret != 0)
13606
0
            goto cleanup;
13607
0
        if (size != finishedSz) {
13608
0
            ret = BUFFER_ERROR;
13609
0
            goto cleanup;
13610
0
        }
13611
0
    }
13612
13613
#ifdef WOLFSSL_CALLBACKS
13614
    if (ssl->hsInfoOn) AddPacketName(ssl, "Finished");
13615
    if (ssl->toInfoOn) AddLateName("Finished", &ssl->timeoutInfo);
13616
#endif
13617
13618
0
    if (sniff == NO_SNIFF) {
13619
        /* Actually check verify data. */
13620
0
        if (size > WC_MAX_DIGEST_SIZE ||
13621
0
                ConstantCompare(input + *inOutIdx, mac, size) != 0){
13622
0
            WOLFSSL_MSG("Verify finished error on hashes");
13623
0
            SendAlert(ssl, alert_fatal, decrypt_error);
13624
0
            WOLFSSL_ERROR_VERBOSE(VERIFY_FINISHED_ERROR);
13625
0
            ret = VERIFY_FINISHED_ERROR;
13626
0
            goto cleanup;
13627
0
        }
13628
0
    }
13629
13630
0
    *inOutIdx += size;
13631
13632
0
#ifndef NO_WOLFSSL_SERVER
13633
0
    if (ssl->options.side == WOLFSSL_SERVER_END &&
13634
0
                                                  !ssl->options.handShakeDone) {
13635
#ifdef WOLFSSL_EARLY_DATA
13636
        if (ssl->earlyData != no_early_data) {
13637
            if ((ret = DeriveTls13Keys(ssl, no_key, DECRYPT_SIDE_ONLY, 1)) != 0)
13638
                goto cleanup;
13639
        }
13640
#endif
13641
        /* Setup keys for application data messages from client. */
13642
0
        if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0)
13643
0
            goto cleanup;
13644
0
    }
13645
0
#endif
13646
13647
0
#ifndef NO_WOLFSSL_CLIENT
13648
0
    if (ssl->options.side == WOLFSSL_CLIENT_END)
13649
0
        ssl->options.serverState = SERVER_FINISHED_COMPLETE;
13650
0
#endif
13651
0
#ifndef NO_WOLFSSL_SERVER
13652
0
    if (ssl->options.side == WOLFSSL_SERVER_END) {
13653
0
        ssl->options.clientState = CLIENT_FINISHED_COMPLETE;
13654
0
        ssl->options.handShakeState = HANDSHAKE_DONE;
13655
0
        ssl->options.handShakeDone  = 1;
13656
0
    }
13657
0
#endif
13658
13659
#if defined(WOLFSSL_DTLS13) && defined(WOLFSSL_EARLY_DATA)
13660
    if (ssl->options.dtls && ssl->earlyData > early_data_ext) {
13661
        /* DTLSv1.3 has no EndOfearlydata messages. We stop processing EarlyData
13662
           as soon we receive the client's finished message */
13663
        ssl->earlyData = done_early_data;
13664
    }
13665
#endif /* WOLFSSL_DTLS13 && WOLFSSL_EARLY_DATA */
13666
#if defined(WOLFSSL_QUIC) && defined(WOLFSSL_EARLY_DATA)
13667
    if (WOLFSSL_IS_QUIC(ssl) && ssl->earlyData > early_data_ext) {
13668
        /* QUIC has no EndOfEarlyData messages. We stop processing EarlyData
13669
           as soon we receive the client's finished message */
13670
        ssl->earlyData = done_early_data;
13671
    }
13672
#endif /* WOLFSSL_QUIC && WOLFSSL_EARLY_DATA */
13673
13674
0
    ret = 0;
13675
0
cleanup:
13676
0
    ForceZero(mac, sizeof(mac));
13677
0
    WOLFSSL_LEAVE("DoTls13Finished", ret);
13678
0
    WOLFSSL_END(WC_FUNC_FINISHED_DO);
13679
13680
0
    return ret;
13681
0
}
13682
13683
#if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER)
13684
/* Send the TLS v1.3 Finished message.
13685
 *
13686
 * ssl  The SSL/TLS object.
13687
 * returns 0 on success, otherwise failure.
13688
 */
13689
static int SendTls13Finished(WOLFSSL* ssl)
13690
0
{
13691
0
    byte  finishedSz = ssl->specs.hash_size;
13692
0
    byte* input;
13693
0
    byte* output;
13694
0
    int   ret = 0; /* the resume goto can skip every build-phase assign */
13695
0
    int   headerSz = HANDSHAKE_HEADER_SZ;
13696
0
    int   outputSz;
13697
0
    byte* secret;
13698
13699
#ifdef WOLFSSL_DTLS13
13700
    int dtlsRet = 0, isDtls = 0;
13701
#endif /* WOLFSSL_DTLS13 */
13702
13703
0
    WOLFSSL_START(WC_FUNC_FINISHED_SEND);
13704
0
    WOLFSSL_ENTER("SendTls13Finished");
13705
13706
#ifdef WOLFSSL_DTLS13
13707
    if (ssl->options.dtls) {
13708
        headerSz = DTLS_HANDSHAKE_HEADER_SZ;
13709
        /* using isDtls instead of ssl->options.dtls will abide clang static
13710
           analyzer on using an uninitialized value */
13711
        isDtls = 1;
13712
    }
13713
#endif /* WOLFSSL_DTLS13 */
13714
13715
    /* Post-send key-schedule resume: the Finished record is already
13716
     * queued, so skip the build phase (re-running would queue it twice). */
13717
0
    if (ssl->kdfDeriveStep > 0)
13718
0
        goto tls13_send_finished_derives;
13719
13720
0
    ssl->options.buildingMsg = 1;
13721
13722
0
    outputSz = WC_MAX_DIGEST_SIZE + headerSz + MAX_MSG_EXTRA;
13723
#ifdef WOLFSSL_DTLS13
13724
    /* MAX_MSG_EXTRA reserves RECORD_HEADER_SZ, which is the size of the DTLS
13725
     * 1.3 unified header without the CID, so only the CID is missing. */
13726
    if (isDtls)
13727
        outputSz += DtlsGetCidTxSize(ssl);
13728
#endif /* WOLFSSL_DTLS13 */
13729
    /* Check buffers are big enough and grow if needed. */
13730
0
    if ((ret = CheckAvailableSize(ssl, outputSz)) != 0)
13731
0
        return ret;
13732
13733
    /* get output buffer */
13734
0
    output = GetOutputBuffer(ssl);
13735
0
    input = output + RECORD_HEADER_SZ;
13736
13737
#ifdef WOLFSSL_DTLS13
13738
    if (isDtls)
13739
        input = output + Dtls13GetRlHeaderLength(ssl, 1);
13740
#endif /* WOLFSSL_DTLS13 */
13741
13742
0
    AddTls13HandShakeHeader(input, (word32)finishedSz, 0, (word32)finishedSz,
13743
0
            finished, ssl);
13744
13745
#ifdef WOLFSSL_ASYNC_CRYPT
13746
    /* A suspended build already wrote the verify data and hashed it;
13747
     * recomputing would hash the body twice. */
13748
    if (ssl->options.buildArgs13Set)
13749
        goto tls13_send_finished_encrypt;
13750
#endif
13751
13752
#if defined(WOLFSSL_RENESAS_TSIP_TLS)
13753
    if (ssl->options.side == WOLFSSL_CLIENT_END) {
13754
        ret = tsip_Tls13SendFinished(ssl, output, outputSz, input, 1);
13755
        if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
13756
            return ret;
13757
        }
13758
        ret = 0;
13759
    }
13760
#endif /* WOLFSSL_RENESAS_TSIP_TLS */
13761
13762
    /* make finished hashes */
13763
0
    if (ssl->options.handShakeDone) {
13764
0
        ret = DeriveFinishedSecret(ssl, ssl->clientSecret,
13765
0
                                   ssl->keys.client_write_MAC_secret,
13766
0
                                   WOLFSSL_CLIENT_END);
13767
0
        if (ret != 0)
13768
0
            return ret;
13769
13770
0
        secret = ssl->keys.client_write_MAC_secret;
13771
0
    }
13772
0
    else if (ssl->options.side == WOLFSSL_CLIENT_END)
13773
0
        secret = ssl->keys.client_write_MAC_secret;
13774
0
    else {
13775
        /* All the handshake messages have been done to calculate client and
13776
         * server finished keys.
13777
         */
13778
0
        ret = DeriveFinishedSecret(ssl, ssl->clientSecret,
13779
0
                                   ssl->keys.client_write_MAC_secret,
13780
0
                                   WOLFSSL_CLIENT_END);
13781
0
        if (ret != 0)
13782
0
            return ret;
13783
13784
0
        ret = DeriveFinishedSecret(ssl, ssl->serverSecret,
13785
0
                                   ssl->keys.server_write_MAC_secret,
13786
0
                                   WOLFSSL_SERVER_END);
13787
0
        if (ret != 0)
13788
0
            return ret;
13789
13790
0
        secret = ssl->keys.server_write_MAC_secret;
13791
0
    }
13792
0
    ret = BuildTls13HandshakeHmac(ssl, secret, &input[headerSz], NULL);
13793
0
    if (ret != 0)
13794
0
        return ret;
13795
    #ifdef WOLFSSL_HAVE_TLS_UNIQUE
13796
        if (ssl->options.side == WOLFSSL_CLIENT_END) {
13797
            XMEMCPY(ssl->clientFinished, &input[headerSz], finishedSz);
13798
            ssl->clientFinished_len = finishedSz;
13799
        }
13800
        else {
13801
            XMEMCPY(ssl->serverFinished, &input[headerSz], finishedSz);
13802
            ssl->serverFinished_len = finishedSz;
13803
        }
13804
    #endif /* WOLFSSL_HAVE_TLS_UNIQUE */
13805
13806
#ifdef WOLFSSL_ASYNC_CRYPT
13807
tls13_send_finished_encrypt:
13808
#endif
13809
13810
#ifdef WOLFSSL_DTLS13
13811
    if (isDtls) {
13812
        dtlsRet = Dtls13HandshakeSend(ssl, output, (word16)outputSz,
13813
            (word16)(Dtls13GetRlHeaderLength(ssl, 1) + headerSz + finishedSz), finished,
13814
            1);
13815
        if (dtlsRet != 0 && dtlsRet != WC_NO_ERR_TRACE(WANT_WRITE))
13816
            return dtlsRet;
13817
13818
    } else
13819
#endif /* WOLFSSL_DTLS13 */
13820
0
    {
13821
        /* This message is always encrypted. */
13822
0
        int sendSz = BuildTls13Message(ssl, output, outputSz, input,
13823
0
                                   headerSz + finishedSz, handshake, 1, 0,
13824
0
                                   TLS13_HS_ASYNC_OKAY);
13825
0
        if (sendSz < 0) {
13826
        #ifdef WOLFSSL_ASYNC_CRYPT
13827
            /* Propagate a pending record encryption rather than reporting it
13828
             * as a build failure: the retry resumes the record. */
13829
            if (sendSz == WC_NO_ERR_TRACE(WC_PENDING_E))
13830
                return sendSz;
13831
        #endif
13832
0
            WOLFSSL_ERROR_VERBOSE(BUILD_MSG_ERROR);
13833
0
            return BUILD_MSG_ERROR;
13834
0
        }
13835
13836
        #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
13837
            if (ssl->hsInfoOn) AddPacketName(ssl, "Finished");
13838
            if (ssl->toInfoOn) {
13839
                ret = AddPacketInfo(ssl, "Finished", handshake, output, sendSz,
13840
                              WRITE_PROTO, 0, ssl->heap);
13841
                if (ret != 0)
13842
                    return ret;
13843
            }
13844
        #endif
13845
13846
0
        ssl->buffers.outputBuffer.length += (word32)sendSz;
13847
0
        ssl->options.buildingMsg = 0;
13848
0
    }
13849
13850
    /* Build phase complete; steps below are individually resumable. */
13851
0
    ssl->kdfDeriveStep = TLS13_SEND_KDF_FIN_ENTERED;
13852
0
tls13_send_finished_derives:
13853
13854
0
    if (ssl->options.side == WOLFSSL_SERVER_END) {
13855
#ifdef WOLFSSL_EARLY_DATA
13856
        byte storeTrafficDecKeys = ssl->earlyData == no_early_data;
13857
#endif
13858
        /* Can send application data now. */
13859
0
        if (ssl->kdfDeriveStep <= TLS13_SEND_KDF_FIN_ENTERED) {
13860
0
            ret = DeriveMasterSecret(ssl);
13861
0
            if (ret != 0) {
13862
0
                if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
13863
0
                    ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
13864
0
                return ret;
13865
0
            }
13866
0
            ssl->kdfDeriveStep = TLS13_SEND_KDF_FIN_MASTER_SECRET;
13867
0
        }
13868
        /* Last use of preMasterSecret - zeroize as soon as possible. */
13869
0
        ForceZero(ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz);
13870
#ifdef WOLFSSL_EARLY_DATA
13871
13872
#ifdef WOLFSSL_DTLS13
13873
        /* DTLS13 dynamically change keys and it needs all
13874
           the keys in ssl->keys to save the keying material */
13875
        if (isDtls)
13876
            storeTrafficDecKeys = 1;
13877
#endif /* WOLFSSL_DTLS13 */
13878
13879
        if (ssl->kdfDeriveStep <= TLS13_SEND_KDF_FIN_MASTER_SECRET) {
13880
            ret = DeriveTls13Keys(ssl, traffic_key, ENCRYPT_SIDE_ONLY, 1);
13881
            if (ret != 0) {
13882
                if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
13883
                    ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
13884
                return ret;
13885
            }
13886
            ssl->kdfDeriveStep = TLS13_SEND_KDF_FIN_ENC_TRAFFIC_KEYS;
13887
        }
13888
        if (ssl->kdfDeriveStep <= TLS13_SEND_KDF_FIN_ENC_TRAFFIC_KEYS) {
13889
            ret = DeriveTls13Keys(ssl, traffic_key, DECRYPT_SIDE_ONLY,
13890
                                  storeTrafficDecKeys);
13891
            if (ret != 0) {
13892
                if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
13893
                    ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
13894
                return ret;
13895
            }
13896
            ssl->kdfDeriveStep = TLS13_SEND_KDF_FIN_TRAFFIC_KEYS;
13897
        }
13898
#else
13899
0
        if (ssl->kdfDeriveStep <= TLS13_SEND_KDF_FIN_ENC_TRAFFIC_KEYS) {
13900
0
            ret = DeriveTls13Keys(ssl, traffic_key, ENCRYPT_AND_DECRYPT_SIDE,
13901
0
                                  1);
13902
0
            if (ret != 0) {
13903
0
                if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
13904
0
                    ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
13905
0
                return ret;
13906
0
            }
13907
0
            ssl->kdfDeriveStep = TLS13_SEND_KDF_FIN_TRAFFIC_KEYS;
13908
0
        }
13909
0
#endif
13910
0
        if (ssl->kdfDeriveStep <= TLS13_SEND_KDF_FIN_TRAFFIC_KEYS) {
13911
0
            ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY);
13912
0
            if (ret != 0) {
13913
0
                if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
13914
0
                    ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
13915
0
                return ret;
13916
0
            }
13917
0
            ssl->kdfDeriveStep = TLS13_SEND_KDF_FIN_ENC_KEYS_SET;
13918
0
        }
13919
13920
#ifdef WOLFSSL_DTLS13
13921
        if (isDtls) {
13922
            w64wrapper epochTraffic0;
13923
            epochTraffic0 = w64From32(0, DTLS13_EPOCH_TRAFFIC0);
13924
            ssl->dtls13Epoch = epochTraffic0;
13925
            ssl->dtls13PeerEpoch = epochTraffic0;
13926
13927
            if (ssl->kdfDeriveStep <= TLS13_SEND_KDF_FIN_ENC_KEYS_SET) {
13928
                ret = Dtls13SetEpochKeys(ssl, epochTraffic0,
13929
                                         ENCRYPT_AND_DECRYPT_SIDE);
13930
                if (ret != 0) {
13931
                    if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
13932
                        ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
13933
                    return ret;
13934
                }
13935
                ssl->kdfDeriveStep = TLS13_SEND_KDF_FIN_DTLS_TRAFFIC_EPOCH;
13936
            }
13937
        }
13938
#endif /* WOLFSSL_DTLS13 */
13939
13940
0
    }
13941
13942
0
    if (ssl->options.side == WOLFSSL_CLIENT_END &&
13943
0
                                                  !ssl->options.handShakeDone) {
13944
#ifdef WOLFSSL_EARLY_DATA
13945
        if (ssl->earlyData != no_early_data) {
13946
            if (ssl->kdfDeriveStep <= TLS13_SEND_KDF_FIN_DTLS_TRAFFIC_EPOCH) {
13947
                ret = DeriveTls13Keys(ssl, no_key, ENCRYPT_SIDE_ONLY, 1);
13948
                if (ret != 0) {
13949
                    if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
13950
                        ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
13951
                    return ret;
13952
                }
13953
                ssl->kdfDeriveStep = TLS13_SEND_KDF_FIN_EARLY_ENC_KEYS;
13954
            }
13955
        }
13956
#endif
13957
        /* Setup keys for application data messages. */
13958
0
        if (ssl->kdfDeriveStep <= TLS13_SEND_KDF_FIN_EARLY_ENC_KEYS) {
13959
0
            ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY);
13960
0
            if (ret != 0) {
13961
0
                if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
13962
0
                    ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
13963
0
                return ret;
13964
0
            }
13965
0
            ssl->kdfDeriveStep = TLS13_SEND_KDF_FIN_EARLY_KEYS_SET;
13966
0
        }
13967
13968
#if defined(HAVE_SESSION_TICKET)
13969
        if (ssl->kdfDeriveStep <= TLS13_SEND_KDF_FIN_EARLY_KEYS_SET) {
13970
            ret = DeriveResumptionSecret(ssl, ssl->session->masterSecret);
13971
            if (ret != 0) {
13972
                if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
13973
                    ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
13974
                return ret;
13975
            }
13976
            ssl->kdfDeriveStep = TLS13_SEND_KDF_FIN_RESUMPTION_SECRET;
13977
        }
13978
#endif
13979
13980
#ifdef WOLFSSL_DTLS13
13981
        if (isDtls) {
13982
            w64wrapper epochTraffic0;
13983
            epochTraffic0 = w64From32(0, DTLS13_EPOCH_TRAFFIC0);
13984
            ssl->dtls13Epoch = epochTraffic0;
13985
            ssl->dtls13PeerEpoch = epochTraffic0;
13986
13987
            /* Step-guarded like every other derive in this function, so a
13988
             * pend resumes here and a real error clears the resume state. */
13989
            if (ssl->kdfDeriveStep <= TLS13_SEND_KDF_FIN_RESUMPTION_SECRET) {
13990
                ret = Dtls13SetEpochKeys(
13991
                    ssl, epochTraffic0, ENCRYPT_AND_DECRYPT_SIDE);
13992
                if (ret != 0) {
13993
                    if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
13994
                        ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
13995
                    return ret;
13996
                }
13997
                ssl->kdfDeriveStep = TLS13_SEND_KDF_FIN_DTLS_EPOCH_SET;
13998
            }
13999
        }
14000
#endif /* WOLFSSL_DTLS13 */
14001
0
    }
14002
14003
0
    ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
14004
14005
0
#ifndef NO_WOLFSSL_CLIENT
14006
0
    if (ssl->options.side == WOLFSSL_CLIENT_END) {
14007
0
        ssl->options.clientState = CLIENT_FINISHED_COMPLETE;
14008
0
        ssl->options.handShakeState = HANDSHAKE_DONE;
14009
0
        ssl->options.handShakeDone  = 1;
14010
0
    }
14011
0
#endif
14012
0
#ifndef NO_WOLFSSL_SERVER
14013
0
    if (ssl->options.side == WOLFSSL_SERVER_END) {
14014
0
        ssl->options.serverState = SERVER_FINISHED_COMPLETE;
14015
0
    }
14016
0
#endif
14017
14018
#ifdef WOLFSSL_DTLS13
14019
    if (isDtls) {
14020
        WOLFSSL_LEAVE("SendTls13Finished", ret);
14021
        WOLFSSL_END(WC_FUNC_FINISHED_SEND);
14022
14023
        return dtlsRet;
14024
    }
14025
#endif /* WOLFSSL_DTLS13 */
14026
14027
0
    if ((ret = SendBuffered(ssl)) != 0)
14028
0
        return ret;
14029
14030
0
    WOLFSSL_LEAVE("SendTls13Finished", ret);
14031
0
    WOLFSSL_END(WC_FUNC_FINISHED_SEND);
14032
14033
0
    return ret;
14034
0
}
14035
#endif /* !NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER */
14036
14037
/* RFC 9846 Section 4.7.3: a TLS 1.3 sender MUST NOT allow its number of key
14038
 * updates to exceed 2^48-1. DTLS 1.3 bounds the epoch instead (RFC 9147
14039
 * Section 4.2.1), so this only covers TLS.
14040
 *
14041
 * ssl  The SSL/TLS object.
14042
 * returns 1 when a further KeyUpdate would exceed the limit, 0 otherwise.
14043
 */
14044
int Tls13KeyUpdateLimitReached(WOLFSSL* ssl)
14045
0
{
14046
0
    if (ssl->options.dtls)
14047
0
        return 0;
14048
14049
0
    return w64GTE(ssl->keys.keyUpdateCount,
14050
0
                  w64From32(TLS13_KEY_UPDATE_MAX_HI32,
14051
0
                            TLS13_KEY_UPDATE_MAX_LO32));
14052
0
}
14053
14054
/* handle generation TLS v1.3 key_update (24) */
14055
/* Send the TLS v1.3 KeyUpdate message.
14056
 *
14057
 * ssl  The SSL/TLS object.
14058
 * returns 0 on success, otherwise failure.
14059
 */
14060
int SendTls13KeyUpdate(WOLFSSL* ssl)
14061
0
{
14062
0
    byte*  input;
14063
0
    byte*  output;
14064
0
    int    ret;
14065
0
    int    headerSz = HANDSHAKE_HEADER_SZ;
14066
0
    int    outputSz;
14067
0
    word32 i = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
14068
14069
0
    WOLFSSL_START(WC_FUNC_KEY_UPDATE_SEND);
14070
0
    WOLFSSL_ENTER("SendTls13KeyUpdate");
14071
14072
#ifdef WOLFSSL_DTLS13
14073
    if (ssl->options.dtls) {
14074
        /* RFC 9147 Section 4.2.1: do not send a KeyUpdate that would advance
14075
         * the sending epoch beyond 2^48-1. */
14076
        if (w64GTE(ssl->dtls13Epoch,
14077
                   w64From32(DTLS13_EPOCH_MAX_HI32, DTLS13_EPOCH_MAX_LO32))) {
14078
            WOLFSSL_MSG("DTLS 1.3 sending epoch at maximum; refusing KeyUpdate");
14079
            return BAD_STATE_E;
14080
        }
14081
        i = Dtls13GetRlHeaderLength(ssl, 1) + DTLS_HANDSHAKE_HEADER_SZ;
14082
    }
14083
#endif /* WOLFSSL_DTLS13 */
14084
14085
    /* RFC 9846 Section 4.7.3: a sending implementation MUST NOT allow its
14086
     * number of key updates to exceed 2^48-1. Receivers MUST NOT enforce this
14087
     * on the peer. */
14088
0
    if (Tls13KeyUpdateLimitReached(ssl)) {
14089
0
        WOLFSSL_MSG("TLS 1.3 key update count at maximum; refusing KeyUpdate");
14090
0
        return BAD_STATE_E;
14091
0
    }
14092
14093
    /* i already carries the real record and handshake header lengths.
14094
     * MAX_MSG_EXTRA only budgets RECORD_HEADER_SZ. */
14095
0
    outputSz = (int)i + OPAQUE8_LEN + MAX_MSG_EXTRA;
14096
    /* Check buffers are big enough and grow if needed. */
14097
0
    if ((ret = CheckAvailableSize(ssl, outputSz)) != 0)
14098
0
        return ret;
14099
14100
    /* get output buffer */
14101
0
    output = GetOutputBuffer(ssl);
14102
0
    input = output + RECORD_HEADER_SZ;
14103
14104
#ifdef WOLFSSL_DTLS13
14105
    if (ssl->options.dtls)
14106
        input = output + Dtls13GetRlHeaderLength(ssl, 1);
14107
#endif /* WOLFSSL_DTLS13 */
14108
14109
0
    AddTls13Headers(output, OPAQUE8_LEN, key_update, ssl);
14110
14111
    /* If:
14112
     *   1. I haven't sent a KeyUpdate requesting a response and
14113
     *   2. This isn't responding to peer KeyUpdate requiring a response then,
14114
     * I want a response.
14115
     */
14116
0
    ssl->keys.updateResponseReq = output[i++] =
14117
0
         !ssl->keys.updateResponseReq && !ssl->keys.keyUpdateRespond;
14118
    /* Sent response, no longer need to respond. */
14119
0
    ssl->keys.keyUpdateRespond = 0;
14120
14121
#ifdef WOLFSSL_DTLS13
14122
    if (ssl->options.dtls) {
14123
        ret = Dtls13HandshakeSend(ssl, output, (word16)outputSz,
14124
            OPAQUE8_LEN + Dtls13GetRlHeaderLength(ssl, 1) +
14125
                DTLS_HANDSHAKE_HEADER_SZ,
14126
            key_update, 0);
14127
    }
14128
    else
14129
#endif /* WOLFSSL_DTLS13 */
14130
0
    {
14131
        /* This message is always encrypted. */
14132
0
        int sendSz = BuildTls13Message(ssl, output, outputSz, input,
14133
0
                                   headerSz + OPAQUE8_LEN, handshake, 0, 0, 0);
14134
0
        if (sendSz < 0)
14135
0
            return BUILD_MSG_ERROR;
14136
14137
        #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
14138
            if (ssl->hsInfoOn) AddPacketName(ssl, "KeyUpdate");
14139
            if (ssl->toInfoOn) {
14140
                ret = AddPacketInfo(ssl, "KeyUpdate", handshake, output, sendSz,
14141
                              WRITE_PROTO, 0, ssl->heap);
14142
                if (ret != 0)
14143
                    return ret;
14144
            }
14145
        #endif
14146
14147
0
        ssl->buffers.outputBuffer.length += (word32)sendSz;
14148
14149
0
        ret = SendBuffered(ssl);
14150
14151
14152
0
        if (ret != 0 && ret != WC_NO_ERR_TRACE(WANT_WRITE))
14153
0
            return ret;
14154
0
    }
14155
14156
    /* In DTLS we must wait for the ack before setting up the new keys */
14157
0
    if (!ssl->options.dtls) {
14158
14159
        /* Future traffic uses new encryption keys. */
14160
0
        if ((ret = DeriveTls13Keys(
14161
0
                       ssl, update_traffic_key, ENCRYPT_SIDE_ONLY, 1))
14162
0
            != 0)
14163
0
            return ret;
14164
0
        if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
14165
0
            return ret;
14166
14167
        /* Count this key update against the RFC 9846 sender limit. */
14168
0
        w64Increment(&ssl->keys.keyUpdateCount);
14169
0
    }
14170
14171
14172
0
    WOLFSSL_LEAVE("SendTls13KeyUpdate", ret);
14173
0
    WOLFSSL_END(WC_FUNC_KEY_UPDATE_SEND);
14174
14175
0
    return ret;
14176
0
}
14177
14178
/* handle processing TLS v1.3 key_update (24) */
14179
/* Parse and handle a TLS v1.3 KeyUpdate message.
14180
 *
14181
 * ssl       The SSL/TLS object.
14182
 * input     The message buffer.
14183
 * inOutIdx  On entry, the index into the message buffer of Finished.
14184
 *           On exit, the index of byte after the Finished message and padding.
14185
 * totalSz   The length of the current handshake message.
14186
 * returns 0 on success and otherwise failure.
14187
 */
14188
static int DoTls13KeyUpdate(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
14189
                            word32 totalSz)
14190
0
{
14191
0
    int    ret;
14192
0
    word32 i = *inOutIdx;
14193
14194
0
    WOLFSSL_START(WC_FUNC_KEY_UPDATE_DO);
14195
0
    WOLFSSL_ENTER("DoTls13KeyUpdate");
14196
14197
    /* check against totalSz */
14198
0
    if (OPAQUE8_LEN != totalSz)
14199
0
        return BUFFER_E;
14200
14201
0
    switch (input[i]) {
14202
0
        case update_not_requested:
14203
            /* This message in response to any outstanding request. */
14204
0
            ssl->keys.keyUpdateRespond = 0;
14205
0
            ssl->keys.updateResponseReq = 0;
14206
0
            break;
14207
0
        case update_requested:
14208
            /* New key update requiring a response. */
14209
0
            ssl->keys.keyUpdateRespond = 1;
14210
0
            break;
14211
0
        default:
14212
0
            WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
14213
0
            return INVALID_PARAMETER;
14214
0
    }
14215
14216
    /* Move index to byte after message. */
14217
0
    *inOutIdx += totalSz;
14218
14219
    /* Future traffic uses new decryption keys. */
14220
0
    if ((ret = DeriveTls13Keys(ssl, update_traffic_key, DECRYPT_SIDE_ONLY, 1))
14221
0
                                                                         != 0) {
14222
0
        return ret;
14223
0
    }
14224
0
    if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0)
14225
0
        return ret;
14226
14227
#ifdef WOLFSSL_DTLS13
14228
    if (ssl->options.dtls) {
14229
        /* Increment on a local copy so ssl->dtls13PeerEpoch is left
14230
         * untouched when the check fails. */
14231
        w64wrapper newEpoch = ssl->dtls13PeerEpoch;
14232
        w64Increment(&newEpoch);
14233
14234
        /* RFC 9147 Section 8: the 2^48-1 cap is sender-only; receivers MUST
14235
         * NOT enforce it. Guard only the wrap-to-zero (Section 4.2.1). */
14236
        if (w64IsZero(newEpoch))
14237
            return BAD_STATE_E;
14238
14239
        ssl->dtls13PeerEpoch = newEpoch;
14240
14241
        ret = Dtls13SetEpochKeys(ssl, ssl->dtls13PeerEpoch, DECRYPT_SIDE_ONLY);
14242
        if (ret != 0)
14243
            return ret;
14244
    }
14245
#endif /* WOLFSSL_DTLS13 */
14246
14247
0
    if (ssl->keys.keyUpdateRespond) {
14248
14249
#ifdef WOLFSSL_DTLS13
14250
        /* we already sent a keyUpdate (either in response to a previous
14251
           KeyUpdate or initiated by the application) and we are waiting for the
14252
           ack. We can't send a new KeyUpdate right away but to honor the RFC we
14253
           should send another KeyUpdate after the one in-flight is acked. We
14254
           don't do that as it looks redundant, it will make the code more
14255
           complex and I don't see a good use case for that. */
14256
        if (ssl->options.dtls && ssl->dtls13WaitKeyUpdateAck) {
14257
            ssl->keys.keyUpdateRespond = 0;
14258
            return 0;
14259
        }
14260
#endif /* WOLFSSL_DTLS13 */
14261
14262
#if defined(HAVE_WRITE_DUP) && defined(WOLFSSL_TLS13)
14263
        /* Read side cannot write; delegate the response to the write side.
14264
         * The key update cap is deliberately not checked here: the two sides
14265
         * are separate WOLFSSL objects with separate keys, and only the write
14266
         * side ever sends a KeyUpdate, so this object's keyUpdateCount is not
14267
         * the one the limit applies to. The check is applied on the write side
14268
         * in wolfssl_write_dup_do_tls13_work(). */
14269
        if (ssl->dupWrite != NULL && ssl->dupSide == READ_DUP_SIDE) {
14270
            if (wc_LockMutex(&ssl->dupWrite->dupMutex) != 0)
14271
                return BAD_MUTEX_E;
14272
            ssl->dupWrite->keyUpdateRespond = 1;
14273
            wc_UnLockMutex(&ssl->dupWrite->dupMutex);
14274
            ssl->keys.keyUpdateRespond = 0;
14275
            return 0;
14276
        }
14277
#endif /* HAVE_WRITE_DUP && WOLFSSL_TLS13 */
14278
14279
        /* RFC 9846 Section 4.7.3: a sender that would exceed the key update
14280
         * limit "MUST NOT send its own KeyUpdate ... and SHOULD instead ignore
14281
         * the 'update_requested' flag". Dropping the response rather than
14282
         * failing keeps the connection alive on the current keys until the
14283
         * Section 5.5 data limits eventually force it closed. */
14284
0
        if (Tls13KeyUpdateLimitReached(ssl)) {
14285
0
            WOLFSSL_MSG("Key update limit reached; ignoring update_requested");
14286
0
            ssl->keys.keyUpdateRespond = 0;
14287
0
            return 0;
14288
0
        }
14289
14290
0
#ifndef WOLFSSL_RW_THREADED
14291
0
        return SendTls13KeyUpdate(ssl);
14292
#else
14293
        ssl->options.sendKeyUpdate = 1;
14294
        return 0;
14295
#endif
14296
0
    }
14297
14298
0
    WOLFSSL_LEAVE("DoTls13KeyUpdate", ret);
14299
0
    WOLFSSL_END(WC_FUNC_KEY_UPDATE_DO);
14300
14301
0
    return 0;
14302
0
}
14303
14304
#ifdef WOLFSSL_EARLY_DATA
14305
#ifndef NO_WOLFSSL_CLIENT
14306
/* Send the TLS v1.3 EndOfEarlyData message to indicate that there will be no
14307
 * more early application data.
14308
 * The encryption key now changes to the pre-calculated handshake key.
14309
 *
14310
 * ssl  The SSL/TLS object.
14311
 * returns 0 on success and otherwise failure.
14312
 */
14313
static int SendTls13EndOfEarlyData(WOLFSSL* ssl)
14314
{
14315
    byte*  output;
14316
    int    ret;
14317
    int    sendSz;
14318
    word32 length;
14319
    word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
14320
14321
    WOLFSSL_START(WC_FUNC_END_OF_EARLY_DATA_SEND);
14322
    WOLFSSL_ENTER("SendTls13EndOfEarlyData");
14323
14324
    length = 0;
14325
    sendSz = (int)(idx + length + MAX_MSG_EXTRA);
14326
    ssl->options.buildingMsg = 1;
14327
14328
    /* Check buffers are big enough and grow if needed. */
14329
    if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
14330
        return ret;
14331
14332
    /* Get position in output buffer to write new message to. */
14333
    output = GetOutputBuffer(ssl);
14334
14335
    /* Put the record and handshake headers on. */
14336
    AddTls13Headers(output, length, end_of_early_data, ssl);
14337
14338
    /* This message is always encrypted. */
14339
    sendSz = BuildTls13Message(ssl, output, sendSz, output + RECORD_HEADER_SZ,
14340
                               idx - RECORD_HEADER_SZ, handshake, 1, 0, 0);
14341
    if (sendSz < 0)
14342
        return sendSz;
14343
14344
    ssl->buffers.outputBuffer.length += sendSz;
14345
14346
    if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
14347
        return ret;
14348
14349
    ssl->options.buildingMsg = 0;
14350
    if (!ssl->options.groupMessages)
14351
        ret = SendBuffered(ssl);
14352
14353
    ssl->earlyData = done_early_data;
14354
14355
    WOLFSSL_LEAVE("SendTls13EndOfEarlyData", ret);
14356
    WOLFSSL_END(WC_FUNC_END_OF_EARLY_DATA_SEND);
14357
14358
    return ret;
14359
}
14360
#endif /* !NO_WOLFSSL_CLIENT */
14361
14362
#ifndef NO_WOLFSSL_SERVER
14363
/* handle processing of TLS 1.3 end_of_early_data (5) */
14364
/* Parse the TLS v1.3 EndOfEarlyData message that indicates that there will be
14365
 * no more early application data.
14366
 * The decryption key now changes to the pre-calculated handshake key.
14367
 *
14368
 * ssl  The SSL/TLS object.
14369
 * returns 0 on success and otherwise failure.
14370
 */
14371
static int DoTls13EndOfEarlyData(WOLFSSL* ssl, const byte* input,
14372
                                 word32* inOutIdx, word32 size)
14373
{
14374
    int    ret;
14375
    word32 begin = *inOutIdx;
14376
14377
    (void)input;
14378
14379
    WOLFSSL_START(WC_FUNC_END_OF_EARLY_DATA_DO);
14380
    WOLFSSL_ENTER("DoTls13EndOfEarlyData");
14381
14382
    if ((*inOutIdx - begin) != size)
14383
        return BUFFER_ERROR;
14384
14385
    if (ssl->earlyData == no_early_data) {
14386
        WOLFSSL_MSG("EndOfEarlyData received unexpectedly");
14387
        SendAlert(ssl, alert_fatal, unexpected_message);
14388
        WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
14389
        return OUT_OF_ORDER_E;
14390
    }
14391
14392
    ssl->earlyData = done_early_data;
14393
14394
    ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY);
14395
14396
    WOLFSSL_LEAVE("DoTls13EndOfEarlyData", ret);
14397
    WOLFSSL_END(WC_FUNC_END_OF_EARLY_DATA_DO);
14398
14399
    return ret;
14400
}
14401
#endif /* !NO_WOLFSSL_SERVER */
14402
#endif /* WOLFSSL_EARLY_DATA */
14403
14404
#if defined(HAVE_SESSION_TICKET) && defined(WOLFSSL_TICKET_NONCE_MALLOC) &&    \
14405
    (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
14406
int SessionTicketNoncePopulate(WOLFSSL_SESSION *session, const byte *nonce,
14407
    byte len)
14408
{
14409
    if (session->ticketNonce.data
14410
            != session->ticketNonce.dataStatic) {
14411
         XFREE(session->ticketNonce.data, session->heap,
14412
             DYNAMIC_TYPE_SESSION_TICK);
14413
         session->ticketNonce.data = session->ticketNonce.dataStatic;
14414
         session->ticketNonce.len = 0;
14415
    }
14416
14417
    if (len > MAX_TICKET_NONCE_STATIC_SZ) {
14418
        WOLFSSL_MSG("Using dynamic nonce buffer");
14419
        session->ticketNonce.data = (byte*)XMALLOC(len,
14420
            session->heap, DYNAMIC_TYPE_SESSION_TICK);
14421
        if (session->ticketNonce.data == NULL)
14422
            return MEMORY_ERROR;
14423
    }
14424
    XMEMCPY(session->ticketNonce.data, nonce, len);
14425
    session->ticketNonce.len = len;
14426
    return 0;
14427
}
14428
#endif
14429
#ifndef NO_WOLFSSL_CLIENT
14430
/* Handle a New Session Ticket handshake message.
14431
 * Message contains the information required to perform resumption.
14432
 *
14433
 * ssl       The SSL/TLS object.
14434
 * input     The message buffer.
14435
 * inOutIdx  On entry, the index into the message buffer of Finished.
14436
 *           On exit, the index of byte after the Finished message and padding.
14437
 * size      The length of the current handshake message.
14438
 * returns 0 on success, otherwise failure.
14439
 */
14440
static int DoTls13NewSessionTicket(WOLFSSL* ssl, const byte* input,
14441
                                   word32* inOutIdx, word32 size)
14442
0
{
14443
#ifdef HAVE_SESSION_TICKET
14444
    int    ret;
14445
    word32 begin = *inOutIdx;
14446
    word32 lifetime;
14447
    word32 ageAdd;
14448
    word16 length;
14449
#ifdef WOLFSSL_32BIT_MILLI_TIME
14450
    word32 now;
14451
#else
14452
    sword64 now;
14453
#endif
14454
    const byte* nonce;
14455
    byte        nonceLength;
14456
14457
    WOLFSSL_START(WC_FUNC_NEW_SESSION_TICKET_DO);
14458
    WOLFSSL_ENTER("DoTls13NewSessionTicket");
14459
14460
#ifdef HAVE_ECH
14461
    /* ignore session ticket when ECH is rejected */
14462
    if (ssl->echConfigs != NULL && !ssl->options.disableECH &&
14463
            !ssl->options.echAccepted) {
14464
        *inOutIdx += size + ssl->keys.padSz;
14465
        return 0;
14466
    }
14467
#endif
14468
14469
    /* Lifetime hint. */
14470
    if ((*inOutIdx - begin) + SESSION_HINT_SZ > size)
14471
        return BUFFER_ERROR;
14472
    ato32(input + *inOutIdx, &lifetime);
14473
    *inOutIdx += SESSION_HINT_SZ;
14474
    if (lifetime > MAX_LIFETIME) {
14475
        WOLFSSL_ERROR_VERBOSE(SERVER_HINT_ERROR);
14476
        return SERVER_HINT_ERROR;
14477
    }
14478
14479
    /* Age add. */
14480
    if ((*inOutIdx - begin) + SESSION_ADD_SZ > size)
14481
        return BUFFER_ERROR;
14482
    ato32(input + *inOutIdx, &ageAdd);
14483
    *inOutIdx += SESSION_ADD_SZ;
14484
14485
    /* Ticket nonce. */
14486
    if ((*inOutIdx - begin) + 1 > size)
14487
        return BUFFER_ERROR;
14488
    nonceLength = input[*inOutIdx];
14489
#if !defined(WOLFSSL_TICKET_NONCE_MALLOC) &&                                   \
14490
    (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,3))
14491
    if (nonceLength > MAX_TICKET_NONCE_STATIC_SZ) {
14492
        WOLFSSL_MSG("Nonce length not supported");
14493
        WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
14494
        return INVALID_PARAMETER;
14495
    }
14496
#endif /* WOLFSSL_TICKET_NONCE_MALLOC && FIPS_VERSION_GE(5,3) */
14497
    *inOutIdx += 1;
14498
    if ((*inOutIdx - begin) + nonceLength > size)
14499
        return BUFFER_ERROR;
14500
    nonce = input + *inOutIdx;
14501
    *inOutIdx += nonceLength;
14502
14503
    /* Ticket length. */
14504
    if ((*inOutIdx - begin) + LENGTH_SZ > size)
14505
        return BUFFER_ERROR;
14506
    ato16(input + *inOutIdx, &length);
14507
    *inOutIdx += LENGTH_SZ;
14508
    if ((*inOutIdx - begin) + length > size)
14509
        return BUFFER_ERROR;
14510
    /* note: we reject zero length ticket here, and not in SetTicket(),
14511
     * because zero length is valid for TLS 1.2 */
14512
    if (length == 0)
14513
        return BUFFER_ERROR;
14514
14515
    if ((ret = SetTicket(ssl, input + *inOutIdx, length)) != 0)
14516
        return ret;
14517
    *inOutIdx += length;
14518
14519
    now = TimeNowInMilliseconds();
14520
    if (now == 0)
14521
        return GETTIME_ERROR;
14522
    /* Copy in ticket data (server identity). */
14523
    ssl->timeout                  = lifetime;
14524
    ssl->session->timeout         = lifetime;
14525
    ssl->session->cipherSuite0    = ssl->options.cipherSuite0;
14526
    ssl->session->cipherSuite     = ssl->options.cipherSuite;
14527
    ssl->session->ticketSeen      = now;
14528
    ssl->session->ticketAdd       = ageAdd;
14529
    #ifdef WOLFSSL_EARLY_DATA
14530
    ssl->session->maxEarlyDataSz  = ssl->options.maxEarlyDataSz;
14531
    #endif
14532
14533
#if defined(WOLFSSL_TICKET_NONCE_MALLOC) &&                                    \
14534
    (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
14535
    ret = SessionTicketNoncePopulate(ssl->session, nonce, nonceLength);
14536
    if (ret != 0)
14537
        return ret;
14538
#else
14539
    ssl->session->ticketNonce.len = nonceLength;
14540
    if (nonceLength > MAX_TICKET_NONCE_STATIC_SZ) {
14541
        ret = BUFFER_ERROR;
14542
        return ret;
14543
    }
14544
    if (nonceLength > 0)
14545
        XMEMCPY(ssl->session->ticketNonce.data, nonce, nonceLength);
14546
#endif /* defined(WOLFSSL_TICKET_NONCE_MALLOC) && FIPS_VERSION_GE(5,3) */
14547
14548
    ssl->session->namedGroup      = ssl->namedGroup;
14549
14550
    if ((*inOutIdx - begin) + EXTS_SZ > size)
14551
        return BUFFER_ERROR;
14552
    ato16(input + *inOutIdx, &length);
14553
    *inOutIdx += EXTS_SZ;
14554
    if ((*inOutIdx - begin) + length != size)
14555
        return BUFFER_ERROR;
14556
    /* RFC 9846 Section 4.7.1: the extensions are Section 4.3 Extension TLVs.
14557
     * Malformed framing is a syntax error even when no extension in the list
14558
     * is one we act on. */
14559
    ret = TLSX_Parse(ssl, input + *inOutIdx, length, session_ticket, NULL);
14560
    if (ret != 0)
14561
        return ret;
14562
    *inOutIdx += length;
14563
14564
    SetupSession(ssl);
14565
    #ifndef NO_SESSION_CACHE
14566
        AddSession(ssl);
14567
    #endif
14568
14569
    ssl->expect_session_ticket = 0;
14570
#else
14571
0
    (void)ssl;
14572
0
    (void)input;
14573
14574
0
    WOLFSSL_ENTER("DoTls13NewSessionTicket");
14575
14576
0
    *inOutIdx += size;
14577
0
#endif /* HAVE_SESSION_TICKET */
14578
14579
0
    WOLFSSL_LEAVE("DoTls13NewSessionTicket", 0);
14580
0
    WOLFSSL_END(WC_FUNC_NEW_SESSION_TICKET_DO);
14581
14582
0
    return 0;
14583
0
}
14584
#endif /* NO_WOLFSSL_CLIENT */
14585
14586
#ifndef NO_WOLFSSL_SERVER
14587
    #ifdef HAVE_SESSION_TICKET
14588
14589
#ifdef WOLFSSL_TLS13_TICKET_BEFORE_FINISHED
14590
/* Offset of the MAC size in the finished message. */
14591
#define FINISHED_MSG_SIZE_OFFSET    3
14592
14593
/* Calculate the resumption secret which includes the unseen client finished
14594
 * message.
14595
 *
14596
 * ssl  The SSL/TLS object.
14597
 * returns 0 on success, otherwise failure.
14598
 */
14599
static int ExpectedResumptionSecret(WOLFSSL* ssl)
14600
{
14601
    int         ret;
14602
    int         saveRet = 0;
14603
    word32      finishedSz = 0;
14604
    byte        mac[WC_MAX_DIGEST_SIZE];
14605
    Digest      digest;
14606
    byte header[] = { 0x14, 0x00, 0x00, 0x00 };
14607
14608
    XMEMSET(&digest, 0, sizeof(Digest));
14609
14610
    /* Copy the running hash so we can restore it after. */
14611
    switch (ssl->specs.mac_algorithm) {
14612
    #ifndef NO_SHA256
14613
        case sha256_mac:
14614
            ret = wc_Sha256Copy(&ssl->hsHashes->hashSha256, &digest.sha256);
14615
            if (ret != 0)
14616
                return ret;
14617
            break;
14618
    #endif
14619
    #ifdef WOLFSSL_SHA384
14620
        case sha384_mac:
14621
            ret = wc_Sha384Copy(&ssl->hsHashes->hashSha384, &digest.sha384);
14622
            if (ret != 0)
14623
                return ret;
14624
            break;
14625
    #endif
14626
    #ifdef WOLFSSL_TLS13_SHA512
14627
        case sha512_mac:
14628
            ret = wc_Sha512Copy(&ssl->hsHashes->hashSha512, &digest.sha512);
14629
            if (ret != 0)
14630
                return ret;
14631
            break;
14632
    #endif
14633
    #ifdef WOLFSSL_SM3
14634
        case sm3_mac:
14635
            ret = wc_Sm3Copy(&ssl->hsHashes->hashSm3, &digest.sm3);
14636
            if (ret != 0)
14637
                return ret;
14638
            break;
14639
    #endif
14640
    }
14641
14642
    /* Generate the Client's Finished message and hash it. */
14643
    ret = BuildTls13HandshakeHmac(ssl, ssl->keys.client_write_MAC_secret, mac,
14644
                                  &finishedSz);
14645
    if (ret != 0)
14646
        goto restore;
14647
    header[FINISHED_MSG_SIZE_OFFSET] = finishedSz;
14648
#ifdef WOLFSSL_EARLY_DATA
14649
    if (ssl->earlyData != no_early_data) {
14650
        static byte endOfEarlyData[] = { 0x05, 0x00, 0x00, 0x00 };
14651
        ret = HashRaw(ssl, endOfEarlyData, sizeof(endOfEarlyData));
14652
        if (ret != 0)
14653
            goto restore;
14654
    }
14655
#endif
14656
    if ((ret = HashRaw(ssl, header, sizeof(header))) != 0)
14657
        goto restore;
14658
    if ((ret = HashRaw(ssl, mac, finishedSz)) != 0)
14659
        goto restore;
14660
14661
    if ((ret = DeriveResumptionSecret(ssl, ssl->session->masterSecret)) != 0)
14662
        goto restore;
14663
14664
    /* Restore the hash inline with currently seen messages. */
14665
restore:
14666
    /* The restore result must not mask the error that got here, or a
14667
     * WC_PENDING_E would be reported as success with the derive skipped. */
14668
    saveRet = ret;
14669
    switch (ssl->specs.mac_algorithm) {
14670
    #ifndef NO_SHA256
14671
        case sha256_mac:
14672
            wc_Sha256Free(&ssl->hsHashes->hashSha256);
14673
            ret = wc_Sha256Copy(&digest.sha256, &ssl->hsHashes->hashSha256);
14674
            wc_Sha256Free(&digest.sha256);
14675
            break;
14676
    #endif
14677
    #ifdef WOLFSSL_SHA384
14678
        case sha384_mac:
14679
            wc_Sha384Free(&ssl->hsHashes->hashSha384);
14680
            ret = wc_Sha384Copy(&digest.sha384, &ssl->hsHashes->hashSha384);
14681
            wc_Sha384Free(&digest.sha384);
14682
            break;
14683
    #endif
14684
    #ifdef WOLFSSL_TLS13_SHA512
14685
        case sha512_mac:
14686
            wc_Sha512Free(&ssl->hsHashes->hashSha512);
14687
            ret = wc_Sha512Copy(&digest.sha512, &ssl->hsHashes->hashSha512);
14688
            wc_Sha512Free(&digest.sha512);
14689
            break;
14690
    #endif
14691
    #ifdef WOLFSSL_SM3
14692
        case sm3_mac:
14693
            wc_Sm3Free(&ssl->hsHashes->hashSm3);
14694
            ret = wc_Sm3Copy(&digest.sm3, &ssl->hsHashes->hashSm3);
14695
            wc_Sm3Free(&digest.sm3);
14696
            break;
14697
    #endif
14698
    }
14699
    if (saveRet != 0)
14700
        ret = saveRet;
14701
14702
    ForceZero(mac, sizeof(mac));
14703
    return ret;
14704
}
14705
#endif
14706
14707
/* Check the client advertised a PSK key exchange mode a resumption ticket can
14708
 * be used with.
14709
 *
14710
 * RFC 9846 Section 4.3.9: psk_key_exchange_modes restricts both the PSKs
14711
 * offered in the ClientHello and those the server might supply through
14712
 * NewSessionTicket, and servers should not send tickets that are incompatible
14713
 * with the advertised modes. RFC 9846 Section 4.7.1 makes sending a ticket
14714
 * conditional on the client's hello carrying a suitable extension.
14715
 *
14716
 * ssl  The SSL/TLS object.
14717
 * returns 0 when a ticket may be sent, MISSING_HANDSHAKE_DATA when the
14718
 *         extension was not received and PSK_KEY_ERROR when none of the
14719
 *         advertised modes is usable.
14720
 */
14721
static int CheckTls13TicketPskModes(WOLFSSL* ssl)
14722
{
14723
#ifdef WOLFSSL_TLS13_TICKET_CHECK_PSK_MODES
14724
    if (!ssl->options.pskKeModesRecvd) {
14725
        WOLFSSL_MSG("No psk_key_exchange_modes in ClientHello");
14726
        return MISSING_HANDSHAKE_DATA;
14727
    }
14728
14729
    if ((ssl->options.pskKeModes & (1 << PSK_KE)) != 0
14730
    #ifdef HAVE_SUPPORTED_CURVES
14731
        && !ssl->options.onlyPskDheKe
14732
    #endif
14733
        ) {
14734
        return 0;
14735
    }
14736
    /* The configured policy, not noPskDheKe - a certificate handshake clears
14737
     * that one before the ticket is sent, which would make this always true. */
14738
    if ((ssl->options.pskKeModes & (1 << PSK_DHE_KE)) != 0 &&
14739
            !ssl->options.noPskDheKePolicy) {
14740
        return 0;
14741
    }
14742
14743
    WOLFSSL_MSG("No usable psk_key_exchange_modes advertised by client");
14744
    return PSK_KEY_ERROR;
14745
#else
14746
    (void)ssl;
14747
    return 0;
14748
#endif
14749
}
14750
14751
/* Send New Session Ticket handshake message.
14752
 * Message contains the information required to perform resumption.
14753
 *
14754
 * ssl  The SSL/TLS object.
14755
 * returns 0 on success, otherwise failure.
14756
 */
14757
static int SendTls13NewSessionTicket(WOLFSSL* ssl)
14758
{
14759
    byte*  output;
14760
    int    ret;
14761
    word32 length;
14762
    int    sendSz;
14763
    word16 extSz;
14764
    word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
14765
14766
    WOLFSSL_START(WC_FUNC_NEW_SESSION_TICKET_SEND);
14767
    WOLFSSL_ENTER("SendTls13NewSessionTicket");
14768
14769
    if (DefTicketHintTooLarge(ssl)) {
14770
        WOLFSSL_MSG("Ticket hint exceeds half the ticket key lifetime; "
14771
                    "skipping ticket");
14772
        return 0;
14773
    }
14774
14775
    if (CheckTls13TicketPskModes(ssl) != 0) {
14776
        WOLFSSL_MSG("Client advertised no usable PSK key exchange mode; "
14777
                    "skipping ticket");
14778
        return 0;
14779
    }
14780
14781
#ifdef WOLFSSL_DTLS13
14782
    if (ssl->options.dtls)
14783
        idx = Dtls13GetRlHeaderLength(ssl, 1) + DTLS_HANDSHAKE_HEADER_SZ;
14784
#endif /* WOLFSSL_DTLS13 */
14785
14786
#ifdef WOLFSSL_TLS13_TICKET_BEFORE_FINISHED
14787
    if (!ssl->msgsReceived.got_finished) {
14788
        if ((ret = ExpectedResumptionSecret(ssl)) != 0)
14789
            return ret;
14790
    }
14791
#endif
14792
14793
    /* Start ticket nonce at 0 and go up to 255. */
14794
    if (ssl->session->ticketNonce.len == 0) {
14795
        ssl->session->ticketNonce.len = DEF_TICKET_NONCE_SZ;
14796
        ssl->session->ticketNonce.data[0] = 0;
14797
    }
14798
    else
14799
    #ifdef WOLFSSL_ASYNC_CRYPT
14800
        if (ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E))
14801
    #endif
14802
    {
14803
        if (ssl->session->ticketNonce.data[0] == 255) {
14804
            /* RFC8446 Section 4.6.1: Each ticket must have a unique nonce
14805
             * value. As the nonce is only a single byte, we have to prevent
14806
             * the overflow and abort. */
14807
            return SESSION_TICKET_NONCE_OVERFLOW;
14808
        }
14809
        else
14810
            ssl->session->ticketNonce.data[0]++;
14811
    }
14812
14813
    if ((ssl->options.mask & WOLFSSL_OP_NO_TICKET) != 0) {
14814
        /* In this case we only send the ID as the ticket. Let's generate a new
14815
         * ID for the new ticket so that we don't overwrite any old ones */
14816
        ret = wc_RNG_GenerateBlock(ssl->rng, ssl->session->altSessionID,
14817
                                   ID_LEN);
14818
        if (ret != 0)
14819
            return ret;
14820
        ssl->session->haveAltSessionID = 1;
14821
    }
14822
14823
    if (!ssl->options.noTicketTls13) {
14824
        if ((ret = SetupTicket(ssl)) != 0)
14825
            return ret;
14826
        /* No need to create the ticket if we only send the ID */
14827
        if ((ssl->options.mask & WOLFSSL_OP_NO_TICKET) == 0) {
14828
            if ((ret = CreateTicket(ssl)) != 0)
14829
                return ret;
14830
        }
14831
    }
14832
14833
#ifdef WOLFSSL_EARLY_DATA
14834
    ssl->session->maxEarlyDataSz = ssl->options.maxEarlyDataSz;
14835
    if (ssl->session->maxEarlyDataSz > 0)
14836
        TLSX_EarlyData_Use(ssl, ssl->session->maxEarlyDataSz, 1);
14837
    extSz = 0;
14838
    ret = TLSX_GetResponseSize(ssl, session_ticket, &extSz);
14839
    if (ret != 0)
14840
        return ret;
14841
#else
14842
    extSz = EXTS_SZ;
14843
#endif
14844
    /* Lifetime | Age Add | Ticket session ID | Extensions */
14845
    length = SESSION_HINT_SZ + SESSION_ADD_SZ + LENGTH_SZ;
14846
    if ((ssl->options.mask & WOLFSSL_OP_NO_TICKET) != 0)
14847
        length += ID_LEN + extSz;
14848
    else
14849
        length += ssl->session->ticketLen + extSz;
14850
    /* Nonce */
14851
    length += TICKET_NONCE_LEN_SZ + DEF_TICKET_NONCE_SZ;
14852
14853
    sendSz = (int)(idx + length + MAX_MSG_EXTRA);
14854
14855
    /* Check buffers are big enough and grow if needed. */
14856
    if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
14857
        return ret;
14858
14859
    /* Get position in output buffer to write new message to. */
14860
    output = GetOutputBuffer(ssl);
14861
14862
    /* Put the record and handshake headers on. */
14863
    AddTls13Headers(output, length, session_ticket, ssl);
14864
14865
    /* Lifetime hint */
14866
    c32toa(ssl->ctx->ticketHint, output + idx);
14867
    idx += SESSION_HINT_SZ;
14868
    /* Age add - obfuscator */
14869
    c32toa(ssl->session->ticketAdd, output + idx);
14870
    idx += SESSION_ADD_SZ;
14871
14872
    output[idx++] = ssl->session->ticketNonce.len;
14873
    output[idx++] = ssl->session->ticketNonce.data[0];
14874
14875
    /* length */
14876
    if ((ssl->options.mask & WOLFSSL_OP_NO_TICKET) != 0) {
14877
        c16toa(ID_LEN, output + idx);
14878
    }
14879
    else {
14880
        c16toa(ssl->session->ticketLen, output + idx);
14881
    }
14882
14883
    idx += LENGTH_SZ;
14884
    /* ticket */
14885
    if ((ssl->options.mask & WOLFSSL_OP_NO_TICKET) != 0) {
14886
        if (ssl->session->haveAltSessionID)
14887
            XMEMCPY(output + idx, ssl->session->altSessionID, ID_LEN);
14888
        else
14889
            return BAD_FUNC_ARG; /* Should not happen */
14890
        idx += ID_LEN;
14891
    }
14892
    else {
14893
        XMEMCPY(output + idx, ssl->session->ticket, ssl->session->ticketLen);
14894
        idx += ssl->session->ticketLen;
14895
    }
14896
14897
#ifdef WOLFSSL_EARLY_DATA
14898
    extSz = 0;
14899
    ret = TLSX_WriteResponse(ssl, output + idx, session_ticket, &extSz);
14900
    if (ret != 0)
14901
        return ret;
14902
    idx += extSz;
14903
#else
14904
    /* No extension support - empty extensions. */
14905
    c16toa(0, output + idx);
14906
    idx += EXTS_SZ;
14907
#endif
14908
14909
    if (idx > WOLFSSL_MAX_16BIT ||
14910
        sendSz > (int)WOLFSSL_MAX_16BIT) {
14911
        return BAD_LENGTH_E;
14912
    }
14913
14914
    ssl->options.haveSessionId = 1;
14915
14916
    SetupSession(ssl);
14917
    /* Only add to cache when support built in and when the ticket contains
14918
     * an ID. Otherwise we have no way to actually retrieve the ticket from the
14919
     * cache. */
14920
#if !defined(NO_SESSION_CACHE) && defined(WOLFSSL_TICKET_HAVE_ID)
14921
    AddSession(ssl);
14922
#endif
14923
14924
#ifdef WOLFSSL_DTLS13
14925
    if (ssl->options.dtls)
14926
        return Dtls13HandshakeSend(ssl, output, (word16)sendSz,
14927
                                   (word16)idx, session_ticket, 0);
14928
#endif /* WOLFSSL_DTLS13 */
14929
14930
    /* This message is always encrypted. */
14931
    sendSz = BuildTls13Message(ssl, output, sendSz,
14932
                               output + RECORD_HEADER_SZ,
14933
                               (word16)idx - RECORD_HEADER_SZ,
14934
                               handshake, 0, 0, 0);
14935
    if (sendSz < 0)
14936
        return sendSz;
14937
14938
    ssl->buffers.outputBuffer.length += sendSz;
14939
14940
    /* Always send as this is either directly after server's Finished or only
14941
     * message after client's Finished.
14942
     */
14943
    ret = SendBuffered(ssl);
14944
14945
    WOLFSSL_LEAVE("SendTls13NewSessionTicket", 0);
14946
    WOLFSSL_END(WC_FUNC_NEW_SESSION_TICKET_SEND);
14947
14948
    return ret;
14949
}
14950
    #endif /* HAVE_SESSION_TICKET */
14951
#endif /* NO_WOLFSSL_SERVER */
14952
14953
/* Make sure no duplicates, no fast forward, or other problems
14954
 *
14955
 * ssl   The SSL/TLS object.
14956
 * type  Type of handshake message received.
14957
 * returns 0 on success, otherwise failure.
14958
 */
14959
static int SanityCheckTls13MsgReceived(WOLFSSL* ssl, byte type)
14960
0
{
14961
    /* verify not a duplicate, mark received, check state */
14962
0
    switch (type) {
14963
14964
0
#ifndef NO_WOLFSSL_SERVER
14965
0
        case client_hello:
14966
0
        #ifndef NO_WOLFSSL_CLIENT
14967
            /* Only valid when received on SERVER side. */
14968
0
            if (ssl->options.side == WOLFSSL_CLIENT_END) {
14969
0
                WOLFSSL_MSG("ClientHello received by client");
14970
0
                WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
14971
0
                return SIDE_ERROR;
14972
0
            }
14973
0
        #endif
14974
            /* A replay after a pend arrives with got_client_hello cleared
14975
             * (see exit_dch); a genuine duplicate arrives with it set. */
14976
0
            if (ssl->options.clientState >= CLIENT_HELLO_COMPLETE
14977
        #ifdef WOLFSSL_ASYNC_CRYPT
14978
                && ssl->msgsReceived.got_client_hello != 0
14979
        #endif
14980
0
                ) {
14981
0
                WOLFSSL_MSG("ClientHello received out of order");
14982
0
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
14983
0
                return OUT_OF_ORDER_E;
14984
0
            }
14985
            /* Check previously seen. */
14986
            /* Initial and after HelloRetryRequest - no more than 2. */
14987
0
            if (ssl->msgsReceived.got_client_hello == 2) {
14988
0
                WOLFSSL_MSG("Too many ClientHello received");
14989
0
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
14990
0
                return DUPLICATE_MSG_E;
14991
0
            }
14992
            /* Second only after HelloRetryRequest seen. */
14993
0
            if (ssl->msgsReceived.got_client_hello == 1 &&
14994
0
                ssl->options.serverState !=
14995
0
                                          SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
14996
0
                WOLFSSL_MSG("Duplicate ClientHello received");
14997
0
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
14998
0
                return DUPLICATE_MSG_E;
14999
0
            }
15000
0
            ssl->msgsReceived.got_client_hello++;
15001
15002
0
            break;
15003
0
#endif
15004
15005
0
#ifndef NO_WOLFSSL_CLIENT
15006
0
        case server_hello:
15007
0
        #ifndef NO_WOLFSSL_SERVER
15008
            /* Only valid when received on CLIENT side. */
15009
0
            if (ssl->options.side == WOLFSSL_SERVER_END) {
15010
0
                WOLFSSL_MSG("ServerHello received by server");
15011
0
                WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
15012
0
                return SIDE_ERROR;
15013
0
            }
15014
0
        #endif
15015
            /* Check state. */
15016
0
            if (ssl->options.serverState >= SERVER_HELLO_COMPLETE) {
15017
0
                WOLFSSL_MSG("ServerHello received out of order");
15018
0
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15019
0
                return OUT_OF_ORDER_E;
15020
0
            }
15021
            /* Check previously seen. */
15022
            /* Only once after ClientHello.
15023
             * HelloRetryRequest has ServerHello type but count fixed up later
15024
             * - see DoTls13ServerHello().
15025
             */
15026
0
            if (ssl->msgsReceived.got_server_hello) {
15027
0
                WOLFSSL_MSG("Duplicate ServerHello received");
15028
0
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
15029
0
                return DUPLICATE_MSG_E;
15030
0
            }
15031
0
            ssl->msgsReceived.got_server_hello = 1;
15032
15033
0
            break;
15034
0
#endif
15035
15036
0
#ifndef NO_WOLFSSL_CLIENT
15037
0
        case session_ticket:
15038
0
        #ifndef NO_WOLFSSL_SERVER
15039
            /* Only valid when received on CLIENT side. */
15040
0
            if (ssl->options.side == WOLFSSL_SERVER_END) {
15041
0
                WOLFSSL_MSG("NewSessionTicket received by server");
15042
0
                WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
15043
0
                return SIDE_ERROR;
15044
0
            }
15045
0
        #endif
15046
            /* Check state. */
15047
        #ifdef WOLFSSL_TLS13_TICKET_BEFORE_FINISHED
15048
            /* Only allowed after server's Finished message. */
15049
            if (ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
15050
                WOLFSSL_MSG("NewSessionTicket received out of order");
15051
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15052
                return OUT_OF_ORDER_E;
15053
            }
15054
        #else
15055
            /* Only allowed after client's Finished message. */
15056
0
            if (ssl->options.clientState < CLIENT_FINISHED_COMPLETE) {
15057
0
                WOLFSSL_MSG("NewSessionTicket received out of order");
15058
0
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15059
0
                return OUT_OF_ORDER_E;
15060
0
            }
15061
0
        #endif
15062
            /* Many SessionTickets can be sent. */
15063
0
            ssl->msgsReceived.got_session_ticket = 1;
15064
15065
0
            break;
15066
0
#endif
15067
15068
0
#ifndef NO_WOLFSSL_SERVER
15069
    #ifdef WOLFSSL_EARLY_DATA
15070
        case end_of_early_data:
15071
        #ifndef NO_WOLFSSL_CLIENT
15072
            /* Only valid when received on SERVER side. */
15073
            if (ssl->options.side == WOLFSSL_CLIENT_END) {
15074
                WOLFSSL_MSG("EndOfEarlyData received by client");
15075
                WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
15076
                return SIDE_ERROR;
15077
            }
15078
        #endif
15079
            /* Check state. */
15080
            /* Only after server's Finished and before client's Finished. */
15081
            if (ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
15082
                WOLFSSL_MSG("EndOfEarlyData received out of order");
15083
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15084
                return OUT_OF_ORDER_E;
15085
            }
15086
            if (ssl->options.clientState >= CLIENT_FINISHED_COMPLETE) {
15087
                WOLFSSL_MSG("EndOfEarlyData received out of order");
15088
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15089
                return OUT_OF_ORDER_E;
15090
            }
15091
            /* Check previously seen. */
15092
            if (ssl->msgsReceived.got_end_of_early_data) {
15093
                WOLFSSL_MSG("Too many EndOfEarlyData received");
15094
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
15095
                return DUPLICATE_MSG_E;
15096
            }
15097
            ssl->msgsReceived.got_end_of_early_data = 1;
15098
15099
            break;
15100
    #endif
15101
0
#endif
15102
15103
0
#ifndef NO_WOLFSSL_CLIENT
15104
0
        case encrypted_extensions:
15105
0
        #ifndef NO_WOLFSSL_SERVER
15106
            /* Only valid when received on CLIENT side. */
15107
0
            if (ssl->options.side == WOLFSSL_SERVER_END) {
15108
0
                WOLFSSL_MSG("EncryptedExtensions received by server");
15109
0
                WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
15110
0
                return SIDE_ERROR;
15111
0
            }
15112
0
        #endif
15113
            /* Check state. */
15114
            /* Must be received directly after ServerHello.
15115
             * DoTls13EncryptedExtensions() changes state to:
15116
             *   SERVER_ENCRYPTED_EXTENSIONS_COMPLETE.
15117
             */
15118
0
            if (ssl->options.serverState != SERVER_HELLO_COMPLETE) {
15119
0
                WOLFSSL_MSG("EncryptedExtensions received out of order");
15120
0
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15121
0
                return OUT_OF_ORDER_E;
15122
0
            }
15123
            /* Check previously seen. */
15124
0
            if (ssl->msgsReceived.got_encrypted_extensions) {
15125
0
                WOLFSSL_MSG("Duplicate EncryptedExtensions received");
15126
0
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
15127
0
                return DUPLICATE_MSG_E;
15128
0
            }
15129
0
            ssl->msgsReceived.got_encrypted_extensions = 1;
15130
15131
0
            break;
15132
0
#endif
15133
15134
0
        case certificate:
15135
            /* Valid on both sides. */
15136
0
    #ifndef NO_WOLFSSL_CLIENT
15137
            /* Check state. */
15138
            /* On client, seen after EncryptedExtension and CertificateRequest
15139
             * (if sent) and before CertificateVerify and Finished.
15140
             * DoTls13Certificate() sets serverState to SERVER_CERT_COMPLETE.
15141
             */
15142
0
            if (ssl->options.side == WOLFSSL_CLIENT_END &&
15143
0
                ssl->options.serverState !=
15144
0
                                         SERVER_ENCRYPTED_EXTENSIONS_COMPLETE) {
15145
0
                WOLFSSL_MSG("Certificate received out of order - Client");
15146
0
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15147
0
                return OUT_OF_ORDER_E;
15148
0
            }
15149
        #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
15150
            /* Server's authenticating with PSK must not send this. */
15151
            if (ssl->options.side == WOLFSSL_CLIENT_END &&
15152
                             ssl->options.serverState == SERVER_CERT_COMPLETE &&
15153
                             ssl->options.pskNegotiated
15154
#ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
15155
                             && !ssl->options.certWithExternPsk
15156
#endif
15157
               ) {
15158
                WOLFSSL_MSG("Certificate received while using PSK");
15159
                WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
15160
                return SANITY_MSG_E;
15161
            }
15162
        #endif
15163
0
    #endif
15164
0
    #ifndef NO_WOLFSSL_SERVER
15165
            /* Check state. */
15166
            /* On Server, valid after ClientHello received and ServerFinished
15167
             * sent. */
15168
0
            if (ssl->options.side == WOLFSSL_SERVER_END &&
15169
0
                ssl->options.clientState != CLIENT_HELLO_COMPLETE &&
15170
0
                ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
15171
0
                WOLFSSL_MSG("Certificate received out of order - Server");
15172
0
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15173
0
                return OUT_OF_ORDER_E;
15174
0
            }
15175
        #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
15176
            /* RFC 8446 4.4.2: the client only sends this in response to a
15177
             * CertificateRequest, which a server authenticating with a PSK
15178
             * does not send in the main handshake (but may post-handshake). */
15179
            if (ssl->options.side == WOLFSSL_SERVER_END &&
15180
                ssl->options.pskNegotiated && !TLS13_AFTER_HANDSHAKE(ssl)
15181
#ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
15182
                && !ssl->options.certWithExternPsk
15183
#endif
15184
               ) {
15185
                WOLFSSL_MSG("Certificate received while using PSK - Server");
15186
                WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
15187
                return SANITY_MSG_E;
15188
            }
15189
        #endif
15190
0
    #endif
15191
            /* Check previously seen. */
15192
0
            if (ssl->msgsReceived.got_certificate) {
15193
0
                WOLFSSL_MSG("Duplicate Certificate received");
15194
0
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
15195
0
                return DUPLICATE_MSG_E;
15196
0
            }
15197
0
            ssl->msgsReceived.got_certificate = 1;
15198
15199
0
            break;
15200
15201
0
#ifndef NO_WOLFSSL_CLIENT
15202
0
        case certificate_request:
15203
0
        #ifndef NO_WOLFSSL_SERVER
15204
            /* Only valid when received on CLIENT side. */
15205
0
            if (ssl->options.side == WOLFSSL_SERVER_END) {
15206
0
                WOLFSSL_MSG("CertificateRequest received by server");
15207
0
                WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
15208
0
                return SIDE_ERROR;
15209
0
            }
15210
0
        #endif
15211
            /* Check state. */
15212
0
        #ifndef WOLFSSL_POST_HANDSHAKE_AUTH
15213
            /* Only valid when sent after EncryptedExtensions and before
15214
             * Certificate. */
15215
0
            if (ssl->options.serverState !=
15216
0
                                         SERVER_ENCRYPTED_EXTENSIONS_COMPLETE) {
15217
0
                WOLFSSL_MSG("CertificateRequest received out of order");
15218
0
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15219
0
                return OUT_OF_ORDER_E;
15220
0
            }
15221
        #else
15222
            /* Valid when sent after EncryptedExtensions and before Certificate
15223
             * and after both client and server have sent Finished (Post
15224
             * Handshake Authentication). */
15225
            if (ssl->options.serverState !=
15226
                                         SERVER_ENCRYPTED_EXTENSIONS_COMPLETE &&
15227
                       (ssl->options.serverState < SERVER_FINISHED_COMPLETE ||
15228
                        ssl->options.clientState != CLIENT_FINISHED_COMPLETE)) {
15229
                WOLFSSL_MSG("CertificateRequest received out of order");
15230
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15231
                return OUT_OF_ORDER_E;
15232
            }
15233
            /* RFC 8446 4.6.2: A client that receives a post-handshake
15234
             * CertificateRequest message without having sent the
15235
             * "post_handshake_auth" extension MUST send an
15236
             * "unexpected_message" fatal alert. wolfSSL_allow_post_handshake_auth()
15237
             * must be called before wolfSSL_connect() so postHandshakeAuth
15238
             * reflects whether the extension was offered. */
15239
            if (ssl->options.serverState >= SERVER_FINISHED_COMPLETE &&
15240
                ssl->options.clientState == CLIENT_FINISHED_COMPLETE &&
15241
                !ssl->options.postHandshakeAuth) {
15242
                WOLFSSL_MSG("Post-handshake CertificateRequest received "
15243
                            "without having sent post_handshake_auth "
15244
                            "extension");
15245
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15246
                return OUT_OF_ORDER_E;
15247
            }
15248
        #endif
15249
        #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
15250
            /* RFC 8446 4.3.2: a server authenticating with a PSK must not send
15251
             * this in the main handshake, but may send it post-handshake. */
15252
            if (ssl->options.pskNegotiated && !TLS13_AFTER_HANDSHAKE(ssl)
15253
#ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
15254
                && !ssl->options.certWithExternPsk
15255
#endif
15256
               ) {
15257
                WOLFSSL_MSG("CertificateRequest received while using PSK");
15258
                WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
15259
                return SANITY_MSG_E;
15260
            }
15261
        #endif
15262
            /* Check previously seen. */
15263
0
        #ifndef WOLFSSL_POST_HANDSHAKE_AUTH
15264
            /* Only once during handshake. */
15265
0
            if (ssl->msgsReceived.got_certificate_request) {
15266
0
                WOLFSSL_MSG("Duplicate CertificateRequest received");
15267
0
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
15268
0
                return DUPLICATE_MSG_E;
15269
0
            }
15270
        #else
15271
            /* Only once during handshake. */
15272
            if (ssl->msgsReceived.got_certificate_request &&
15273
                ssl->options.clientState != CLIENT_FINISHED_COMPLETE) {
15274
                WOLFSSL_MSG("Duplicate CertificateRequest received");
15275
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
15276
                return DUPLICATE_MSG_E;
15277
            }
15278
        #endif
15279
0
            ssl->msgsReceived.got_certificate_request = 1;
15280
15281
0
            break;
15282
0
#endif
15283
15284
0
        case certificate_verify:
15285
            /* Valid on both sides. */
15286
0
    #ifndef NO_WOLFSSL_CLIENT
15287
            /* Check state on client.
15288
             * Valid only directly after a Certificate message. */
15289
0
            if (ssl->options.side == WOLFSSL_CLIENT_END) {
15290
0
                if (ssl->options.serverState != SERVER_CERT_COMPLETE) {
15291
0
                    WOLFSSL_MSG("No Cert before CertVerify");
15292
0
                    WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15293
0
                    return OUT_OF_ORDER_E;
15294
0
                }
15295
            #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
15296
                /* Server's authenticating with PSK must not send this. */
15297
                if (ssl->options.pskNegotiated
15298
#ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
15299
                    && !ssl->options.certWithExternPsk
15300
#endif
15301
                   ) {
15302
                    WOLFSSL_MSG("CertificateVerify received while using PSK");
15303
                    WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
15304
                    return SANITY_MSG_E;
15305
                }
15306
            #endif
15307
0
            }
15308
0
    #endif
15309
0
    #ifndef NO_WOLFSSL_SERVER
15310
            /* Check state on server. */
15311
0
            if (ssl->options.side == WOLFSSL_SERVER_END) {
15312
                /* Server must have sent Finished message. */
15313
0
                if (ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
15314
0
                    WOLFSSL_MSG("CertificateVerify received out of order");
15315
0
                    WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15316
0
                    return OUT_OF_ORDER_E;
15317
0
                }
15318
                /* Valid only directly after a Certificate message. */
15319
0
                if (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
15320
0
                    WOLFSSL_MSG("CertificateVerify before ClientHello done");
15321
0
                    WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15322
0
                    return OUT_OF_ORDER_E;
15323
0
                }
15324
0
                if (!ssl->msgsReceived.got_certificate) {
15325
0
                    WOLFSSL_MSG("No Cert before CertificateVerify");
15326
0
                    WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15327
0
                    return OUT_OF_ORDER_E;
15328
0
                }
15329
0
            }
15330
0
    #endif
15331
            /* Check previously seen. */
15332
0
            if (ssl->msgsReceived.got_certificate_verify) {
15333
0
                WOLFSSL_MSG("Duplicate CertificateVerify received");
15334
0
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
15335
0
                return DUPLICATE_MSG_E;
15336
0
            }
15337
0
            ssl->msgsReceived.got_certificate_verify = 1;
15338
15339
0
            break;
15340
15341
0
        case finished:
15342
            /* Valid on both sides. */
15343
0
        #ifndef NO_WOLFSSL_CLIENT
15344
            /* Check state on client. */
15345
0
            if (ssl->options.side == WOLFSSL_CLIENT_END) {
15346
                /* After sending ClientHello */
15347
0
                if (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
15348
0
                    WOLFSSL_MSG("Finished received out of order - clientState");
15349
0
                    WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15350
0
                    return OUT_OF_ORDER_E;
15351
0
                }
15352
                /* Must have seen certificate and verify from server except when
15353
                 * using PSK. */
15354
            #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
15355
                if (ssl->options.pskNegotiated) {
15356
#ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
15357
                    if (ssl->options.certWithExternPsk) {
15358
                        if (ssl->options.serverState !=
15359
                                                SERVER_CERT_VERIFY_COMPLETE) {
15360
                            WOLFSSL_MSG("Finished received out of order - "
15361
                                        "cert_with_extern_psk");
15362
                            WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15363
                            return OUT_OF_ORDER_E;
15364
                        }
15365
                    }
15366
                    else
15367
#endif
15368
                    {
15369
                        if (ssl->options.serverState !=
15370
                                         SERVER_ENCRYPTED_EXTENSIONS_COMPLETE) {
15371
                            WOLFSSL_MSG("Finished received out of order - PSK");
15372
                            WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15373
                            return OUT_OF_ORDER_E;
15374
                        }
15375
                    }
15376
                }
15377
                else
15378
            #endif
15379
0
                if (ssl->options.serverState != SERVER_CERT_VERIFY_COMPLETE) {
15380
0
                    WOLFSSL_MSG("Finished received out of order - serverState");
15381
0
                    WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15382
0
                    return OUT_OF_ORDER_E;
15383
0
                }
15384
0
            }
15385
0
        #endif
15386
0
        #ifndef NO_WOLFSSL_SERVER
15387
            /* Check state on server. */
15388
0
            if (ssl->options.side == WOLFSSL_SERVER_END) {
15389
0
                if (ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
15390
0
                    WOLFSSL_MSG("Finished received out of order - serverState");
15391
0
                    WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15392
0
                    return OUT_OF_ORDER_E;
15393
0
                }
15394
0
                if (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
15395
0
                    WOLFSSL_MSG("Finished received out of order - clientState");
15396
0
                    WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15397
0
                    return OUT_OF_ORDER_E;
15398
0
                }
15399
            #ifdef WOLFSSL_EARLY_DATA
15400
                if (ssl->earlyData == process_early_data &&
15401
                    /* early data may be lost when using DTLS */
15402
                    !ssl->options.dtls
15403
                    /* QUIC does not use EndOfEarlyData records */
15404
                    && !WOLFSSL_IS_QUIC(ssl)) {
15405
                    WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15406
                    return OUT_OF_ORDER_E;
15407
                }
15408
            #endif
15409
0
            }
15410
0
        #endif
15411
        #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
15412
            if (!ssl->options.pskNegotiated ||
15413
                (ssl->options.side == WOLFSSL_SERVER_END &&
15414
                 TLS13_AFTER_HANDSHAKE(ssl))
15415
#ifdef WOLFSSL_CERT_WITH_EXTERN_PSK
15416
                || ssl->options.certWithExternPsk
15417
#endif
15418
            )
15419
        #endif
15420
0
            {
15421
                /* Must have received a Certificate message from client if
15422
                 * verifying the peer. Empty certificate message indicates
15423
                 * no certificate available.
15424
                 */
15425
0
                if (ssl->options.verifyPeer &&
15426
                #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
15427
                    /* The post-handshake-auth exemption is only valid during
15428
                     * the enclosing handshake. Once the server has requested a
15429
                     * certificate post-handshake, one is required again.
15430
                     * Whether an empty Certificate is then accepted follows the
15431
                     * verify mode (FAIL_IF_NO_PEER_CERT), exactly as for
15432
                     * first-handshake client authentication. */
15433
                    (!ssl->options.verifyPostHandshake ||
15434
                     TLS13_AFTER_HANDSHAKE(ssl)) &&
15435
                #endif
15436
0
                                           !ssl->msgsReceived.got_certificate) {
15437
0
                    WOLFSSL_MSG("Finished received out of order - "
15438
0
                                "missing Certificate message");
15439
0
                    WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15440
0
                    return OUT_OF_ORDER_E;
15441
0
                }
15442
                /* Mutual authentication on server requires a certificate from
15443
                 * peer. Verify peer set on client side requires a certificate
15444
                 * from peer as not doing PSK.
15445
                 */
15446
0
                if ((ssl->options.mutualAuth ||
15447
0
                    (ssl->options.side == WOLFSSL_CLIENT_END &&
15448
0
                     ssl->options.verifyPeer)) && !ssl->options.havePeerCert) {
15449
0
                    WOLFSSL_MSG("Finished received out of order - "
15450
0
                                "no valid certificate");
15451
0
                    WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15452
0
                    return OUT_OF_ORDER_E;
15453
0
                }
15454
0
            }
15455
            /* Must have received a valid CertificateVerify if got a peer
15456
             * certificate. A certificate without proof of possession is never
15457
             * acceptable, regardless of how the handshake was authenticated.
15458
             */
15459
0
            if (ssl->options.havePeerCert && !ssl->options.havePeerVerify) {
15460
0
                WOLFSSL_MSG("Finished received out of order - "
15461
0
                            "Certificate message but no CertificateVerify");
15462
0
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15463
0
                return OUT_OF_ORDER_E;
15464
0
            }
15465
            /* Check previously seen. */
15466
0
            if (ssl->msgsReceived.got_finished) {
15467
0
                WOLFSSL_MSG("Duplicate Finished received");
15468
0
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
15469
0
                return DUPLICATE_MSG_E;
15470
0
            }
15471
0
            ssl->msgsReceived.got_finished = 1;
15472
15473
0
            break;
15474
15475
0
        case key_update:
15476
            /* Valid on both sides. */
15477
#ifdef WOLFSSL_QUIC
15478
            /* RFC 9001 Section 6: QUIC performs key updates at the QUIC
15479
             * packet-protection layer, so a TLS KeyUpdate message must be
15480
             * rejected as a fatal unexpected_message connection error. The
15481
             * caller sends that alert for any sanity failure. */
15482
            if (WOLFSSL_IS_QUIC(ssl)) {
15483
                WOLFSSL_MSG("KeyUpdate received over QUIC");
15484
                WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
15485
                return SANITY_MSG_E;
15486
            }
15487
#endif
15488
            /* Check state.
15489
             * Client and server must have received finished message from other
15490
             * side.
15491
             */
15492
0
            if (!ssl->msgsReceived.got_finished) {
15493
0
                WOLFSSL_MSG("No KeyUpdate before Finished");
15494
0
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15495
0
                return OUT_OF_ORDER_E;
15496
0
            }
15497
            /* Multiple KeyUpdates can be sent. */
15498
0
            break;
15499
#if defined(WOLFSSL_DTLS13) && !defined(WOLFSSL_NO_TLS12)
15500
        case hello_verify_request:
15501
            if (!ssl->options.dtls) {
15502
                WOLFSSL_MSG("HelloVerifyRequest when not in DTLS");
15503
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15504
                return OUT_OF_ORDER_E;
15505
            }
15506
            if (ssl->msgsReceived.got_hello_verify_request) {
15507
                WOLFSSL_MSG("Duplicate HelloVerifyRequest received");
15508
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
15509
                return DUPLICATE_MSG_E;
15510
            }
15511
            ssl->msgsReceived.got_hello_verify_request = 1;
15512
            if (ssl->msgsReceived.got_hello_retry_request) {
15513
                WOLFSSL_MSG(
15514
                    "Both HelloVerifyRequest and HelloRetryRequest received");
15515
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
15516
                return DUPLICATE_MSG_E;
15517
            }
15518
            if (ssl->options.serverState >=
15519
                    SERVER_HELLO_RETRY_REQUEST_COMPLETE ||
15520
                ssl->options.connectState != CLIENT_HELLO_SENT) {
15521
                WOLFSSL_MSG("HelloVerifyRequest received out of order");
15522
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15523
                return OUT_OF_ORDER_E;
15524
            }
15525
            if (ssl->options.side == WOLFSSL_SERVER_END) {
15526
                WOLFSSL_MSG("HelloVerifyRequest received on the server");
15527
                WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
15528
                return SIDE_ERROR;
15529
            }
15530
            if (!ssl->options.downgrade ||
15531
                ssl->options.minDowngrade < DTLSv1_2_MINOR) {
15532
                WOLFSSL_MSG(
15533
                    "HelloVerifyRequest received but not DTLSv1.2 allowed");
15534
                WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
15535
                return VERSION_ERROR;
15536
            }
15537
            break;
15538
#endif /* WOLFSSL_DTLS13 && !WOLFSSL_NO_TLS12*/
15539
15540
#if defined(WOLFSSL_DTLS13) && defined(WOLFSSL_DTLS_CID)
15541
        case request_connection_id:
15542
        case new_connection_id:
15543
        {
15544
            CIDInfo* cidInfo = ssl->dtlsCidInfo;
15545
15546
            /* DTLS 1.3 only (RFC 9147) */
15547
            if (!ssl->options.dtls) {
15548
                WOLFSSL_MSG("CID message received but not DTLS");
15549
                WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
15550
                return SANITY_MSG_E;
15551
            }
15552
            /* RFC 9147 Section 9: if CIDs were not negotiated, MUST abort
15553
             * with an unexpected_message alert */
15554
            if (cidInfo == NULL || !cidInfo->negotiated) {
15555
                WOLFSSL_MSG("CID message received but CID not negotiated");
15556
                WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
15557
                return SANITY_MSG_E;
15558
            }
15559
            if (ssl->options.handShakeState != HANDSHAKE_DONE) {
15560
                WOLFSSL_MSG("CID message received out of order");
15561
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15562
                return OUT_OF_ORDER_E;
15563
            }
15564
            if (type == request_connection_id) {
15565
                /* the peer MUST NOT request CIDs while sending an empty
15566
                 * CID itself */
15567
                if (cidInfo->rx == NULL || cidInfo->rx->length == 0) {
15568
                    WOLFSSL_MSG("RequestConnectionId from peer sending an "
15569
                                "empty CID");
15570
                    WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
15571
                    return SANITY_MSG_E;
15572
                }
15573
            }
15574
            else {
15575
                /* the peer MUST NOT issue CIDs after negotiating receiving
15576
                 * an empty CID */
15577
                if (cidInfo->tx == NULL || cidInfo->tx->length == 0) {
15578
                    WOLFSSL_MSG("NewConnectionId from peer that negotiated "
15579
                                "an empty CID");
15580
                    WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
15581
                    return SANITY_MSG_E;
15582
                }
15583
            }
15584
            break;
15585
        }
15586
#endif /* WOLFSSL_DTLS13 && WOLFSSL_DTLS_CID */
15587
15588
0
        default:
15589
0
            WOLFSSL_MSG("Unknown message type");
15590
0
            WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
15591
0
            return SANITY_MSG_E;
15592
0
    }
15593
15594
0
    return 0;
15595
0
}
15596
15597
/* Handle a type of handshake message that has been received.
15598
 *
15599
 * ssl       The SSL/TLS object.
15600
 * input     The message buffer.
15601
 * inOutIdx  On entry, the index into the buffer of the current message.
15602
 *           On exit, the index into the buffer of the next message.
15603
 * size      The length of the current handshake message.
15604
 * totalSz   Length of remaining data in the message buffer.
15605
 * returns 0 on success and otherwise failure.
15606
 */
15607
/* Run the key schedule belonging to a just-processed handshake message.
15608
 * A pend here cannot replay the message (its handler already advanced
15609
 * state); the record is consumed and this is called again from
15610
 * DoProcessReplyEx() entry, pre-dispatch, or the reply-loop exits.
15611
 * Returns 0, WC_PENDING_E while the device is busy, else an error. */
15612
int DoTls13MsgDerives(WOLFSSL* ssl, byte type)
15613
0
{
15614
0
    int ret = 0;
15615
15616
0
    (void)ssl;
15617
0
    (void)type;
15618
15619
0
#ifndef NO_WOLFSSL_CLIENT
15620
0
    if (ssl->options.side == WOLFSSL_CLIENT_END) {
15621
0
        if (type == server_hello) {
15622
            /* Entered before the first derive, or a pend there would
15623
             * route the retry back to the message handler. */
15624
0
            if (ssl->kdfMsgStep == TLS13_MSG_KDF_NONE) {
15625
0
                ssl->kdfMsgStep = TLS13_MSG_KDF_SH_ENTERED;
15626
0
                ssl->kdfMsgType = type;
15627
0
            }
15628
15629
0
            if (ssl->kdfMsgStep <= TLS13_MSG_KDF_SH_ENTERED) {
15630
0
                ret = DeriveEarlySecret(ssl);
15631
0
                if (ret != 0) {
15632
0
                    if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
15633
0
                        ssl->kdfMsgStep = TLS13_MSG_KDF_NONE;
15634
0
                    return ret;
15635
0
                }
15636
0
                ssl->kdfMsgStep = TLS13_MSG_KDF_SH_EARLY_SECRET;
15637
0
            }
15638
0
            if (ssl->kdfMsgStep <= TLS13_MSG_KDF_SH_EARLY_SECRET) {
15639
0
                ret = DeriveHandshakeSecret(ssl);
15640
0
                if (ret != 0) {
15641
0
                    if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
15642
0
                        ssl->kdfMsgStep = TLS13_MSG_KDF_NONE;
15643
0
                    return ret;
15644
0
                }
15645
0
                ssl->kdfMsgStep = TLS13_MSG_KDF_SH_HS_SECRET;
15646
0
            }
15647
0
            if (ssl->kdfMsgStep <= TLS13_MSG_KDF_SH_HS_SECRET) {
15648
0
                ret = DeriveTls13Keys(ssl, handshake_key,
15649
0
                                      ENCRYPT_AND_DECRYPT_SIDE, 1);
15650
0
                if (ret != 0) {
15651
0
                    if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
15652
0
                        ssl->kdfMsgStep = TLS13_MSG_KDF_NONE;
15653
0
                    return ret;
15654
0
                }
15655
0
                ssl->kdfMsgStep = TLS13_MSG_KDF_SH_HS_KEYS;
15656
0
            }
15657
    #ifdef WOLFSSL_EARLY_DATA
15658
            if (ssl->earlyData != no_early_data) {
15659
                if (ssl->kdfMsgStep <= TLS13_MSG_KDF_SH_HS_KEYS) {
15660
                    ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY);
15661
                    if (ret != 0) {
15662
                        if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
15663
                            ssl->kdfMsgStep = TLS13_MSG_KDF_NONE;
15664
                        return ret;
15665
                    }
15666
                    ssl->kdfMsgStep = TLS13_MSG_KDF_SH_KEYS_SET;
15667
                }
15668
            }
15669
            else
15670
    #endif
15671
0
            {
15672
0
                if (ssl->kdfMsgStep <= TLS13_MSG_KDF_SH_HS_KEYS) {
15673
0
                    ret = SetKeysSide(ssl, ENCRYPT_AND_DECRYPT_SIDE);
15674
0
                    if (ret != 0) {
15675
0
                        if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
15676
0
                            ssl->kdfMsgStep = TLS13_MSG_KDF_NONE;
15677
0
                        return ret;
15678
0
                    }
15679
0
                    ssl->kdfMsgStep = TLS13_MSG_KDF_SH_KEYS_SET;
15680
0
                }
15681
0
            }
15682
15683
#ifdef WOLFSSL_DTLS13
15684
            if (ssl->options.dtls) {
15685
                w64wrapper epochHandshake;
15686
                epochHandshake = w64From32(0, DTLS13_EPOCH_HANDSHAKE);
15687
                ssl->dtls13Epoch = epochHandshake;
15688
                ssl->dtls13PeerEpoch = epochHandshake;
15689
15690
                if (ssl->kdfMsgStep <= TLS13_MSG_KDF_SH_KEYS_SET) {
15691
                    ret = Dtls13SetEpochKeys(ssl, epochHandshake,
15692
                                             ENCRYPT_AND_DECRYPT_SIDE);
15693
                    if (ret != 0) {
15694
                        if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
15695
                            ssl->kdfMsgStep = TLS13_MSG_KDF_NONE;
15696
                        return ret;
15697
                    }
15698
                    ssl->kdfMsgStep = TLS13_MSG_KDF_SH_DTLS_EPOCH;
15699
                }
15700
            }
15701
#endif /* WOLFSSL_DTLS13 */
15702
0
            ssl->kdfMsgStep = TLS13_MSG_KDF_NONE;
15703
0
        }
15704
15705
0
        if (type == finished) {
15706
            /* Mark the phase entered before the first derive, so a pending
15707
             * there still routes the retry back here. */
15708
0
            if (ssl->kdfMsgStep == TLS13_MSG_KDF_NONE) {
15709
0
                ssl->kdfMsgStep = TLS13_MSG_KDF_FIN_ENTERED;
15710
0
                ssl->kdfMsgType = type;
15711
0
            }
15712
15713
0
            if (ssl->kdfMsgStep <= TLS13_MSG_KDF_FIN_ENTERED) {
15714
0
                if ((ret = DeriveMasterSecret(ssl)) != 0) {
15715
0
                    if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
15716
0
                        ssl->kdfMsgStep = TLS13_MSG_KDF_NONE;
15717
0
                    return ret;
15718
0
                }
15719
                /* Zeroized only after the derive completed: a pend retry
15720
                 * still reads preMasterSecret. */
15721
0
                ForceZero(ssl->arrays->preMasterSecret,
15722
0
                    ssl->arrays->preMasterSz);
15723
0
                ssl->kdfMsgStep = TLS13_MSG_KDF_FIN_MASTER_SECRET;
15724
0
            }
15725
    #ifdef WOLFSSL_EARLY_DATA
15726
    #ifdef WOLFSSL_QUIC
15727
            if (ssl->kdfMsgStep <= TLS13_MSG_KDF_FIN_MASTER_SECRET) {
15728
                if (WOLFSSL_IS_QUIC(ssl) &&
15729
                        ssl->earlyData != no_early_data) {
15730
                    /* QUIC never sends/receives EndOfEarlyData, but
15731
                     * having early data means the last encryption keys
15732
                     * had not been set yet. */
15733
                    if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0) {
15734
                        if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
15735
                            ssl->kdfMsgStep = TLS13_MSG_KDF_NONE;
15736
                        return ret;
15737
                    }
15738
                }
15739
                ssl->kdfMsgStep = TLS13_MSG_KDF_FIN_QUIC_EARLY_KEYS;
15740
            }
15741
    #endif
15742
            if (ssl->kdfMsgStep <= TLS13_MSG_KDF_FIN_QUIC_EARLY_KEYS) {
15743
                ret = DeriveTls13Keys(ssl, traffic_key,
15744
                            ENCRYPT_AND_DECRYPT_SIDE,
15745
                            ssl->earlyData == no_early_data);
15746
                if (ret != 0) {
15747
                    if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
15748
                        ssl->kdfMsgStep = TLS13_MSG_KDF_NONE;
15749
                    return ret;
15750
                }
15751
                ssl->kdfMsgStep = TLS13_MSG_KDF_FIN_TRAFFIC_KEYS;
15752
            }
15753
            if (ssl->earlyData != no_early_data) {
15754
                if (ssl->kdfMsgStep <= TLS13_MSG_KDF_FIN_TRAFFIC_KEYS) {
15755
                    if ((ret = DeriveTls13Keys(ssl, no_key,
15756
                                            DECRYPT_SIDE_ONLY, 1)) != 0) {
15757
                        if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
15758
                            ssl->kdfMsgStep = TLS13_MSG_KDF_NONE;
15759
                        return ret;
15760
                    }
15761
                    ssl->kdfMsgStep = TLS13_MSG_KDF_FIN_TRAFFIC_DONE;
15762
                }
15763
            }
15764
    #else
15765
0
            if (ssl->kdfMsgStep <= TLS13_MSG_KDF_FIN_QUIC_EARLY_KEYS) {
15766
0
                ret = DeriveTls13Keys(ssl, traffic_key,
15767
0
                            ENCRYPT_AND_DECRYPT_SIDE, 1);
15768
0
                if (ret != 0) {
15769
0
                    if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
15770
0
                        ssl->kdfMsgStep = TLS13_MSG_KDF_NONE;
15771
0
                    return ret;
15772
0
                }
15773
0
                ssl->kdfMsgStep = TLS13_MSG_KDF_FIN_TRAFFIC_DONE;
15774
0
            }
15775
0
    #endif
15776
            /* Setup keys for application data messages. */
15777
0
            if (ssl->kdfMsgStep <= TLS13_MSG_KDF_FIN_TRAFFIC_DONE) {
15778
0
                if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0) {
15779
0
                    if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
15780
0
                        ssl->kdfMsgStep = TLS13_MSG_KDF_NONE;
15781
0
                    return ret;
15782
0
                }
15783
0
                ssl->kdfMsgStep = TLS13_MSG_KDF_FIN_KEYS_SET;
15784
0
            }
15785
0
            ssl->kdfMsgStep = TLS13_MSG_KDF_NONE;
15786
0
        }
15787
0
    }
15788
0
#endif /* NO_WOLFSSL_CLIENT */
15789
15790
0
#ifndef NO_WOLFSSL_SERVER
15791
    #if defined(HAVE_SESSION_TICKET)
15792
        if (ssl->options.side == WOLFSSL_SERVER_END && type == finished) {
15793
            if (ssl->kdfMsgStep == TLS13_MSG_KDF_NONE) {
15794
                ssl->kdfMsgStep = TLS13_MSG_KDF_SFIN_ENTERED;
15795
                ssl->kdfMsgType = type;
15796
            }
15797
            if (ssl->kdfMsgStep <= TLS13_MSG_KDF_SFIN_ENTERED) {
15798
                ret = DeriveResumptionSecret(ssl, ssl->session->masterSecret);
15799
                if (ret != 0) {
15800
                    if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
15801
                        ssl->kdfMsgStep = TLS13_MSG_KDF_NONE;
15802
                    return ret;
15803
                }
15804
                ssl->kdfMsgStep = TLS13_MSG_KDF_SFIN_RESUMPTION_SECRET;
15805
            }
15806
            ssl->kdfMsgStep = TLS13_MSG_KDF_NONE;
15807
        }
15808
    #endif
15809
0
#endif /* NO_WOLFSSL_SERVER */
15810
15811
0
    return ret;
15812
0
}
15813
15814
int DoTls13HandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx,
15815
                            byte type, word32 size, word32 totalSz)
15816
0
{
15817
0
    int ret = 0, tmp;
15818
0
    word32 inIdx = *inOutIdx;
15819
0
    int alertType;
15820
0
    int skipSanity = 0;
15821
#if defined(HAVE_ECH) && !defined(NO_WOLFSSL_SERVER)
15822
    TLSX* echX = NULL;
15823
    word32 echInOutIdx;
15824
#endif
15825
15826
0
    (void)totalSz;
15827
15828
0
    WOLFSSL_ENTER("DoTls13HandShakeMsgType");
15829
15830
    /* make sure we can read the message */
15831
0
    if (*inOutIdx + size > totalSz)
15832
0
        return INCOMPLETE_DATA;
15833
15834
#ifdef WOLFSSL_ASYNC_CRYPT
15835
    /* A message being replayed after its own handler pended has already
15836
     * passed its sanity check and advanced the got_* state on the first
15837
     * pass; the handler restores its cleared marker on completion. Consume
15838
     * the one-shot marker here so only that replayed message skips the
15839
     * check - messages dispatched after it (ssl->error may still read
15840
     * WC_PENDING_E from a trailing key-schedule pend) are still checked. */
15841
    skipSanity = ssl->options.asyncReplayMsg;
15842
    ssl->options.asyncReplayMsg = 0;
15843
#endif
15844
15845
    /* Sanity check msg received. Skipped on a WC_PENDING_E resume (it
15846
     * would reject the replay against already-advanced state); handlers
15847
     * restore their cleared got_* markers on completion instead. */
15848
0
    if (!skipSanity &&
15849
0
            (ret = SanityCheckTls13MsgReceived(ssl, type)) != 0) {
15850
0
        WOLFSSL_MSG("Sanity Check on handshake message type received failed");
15851
0
        if (ret == WC_NO_ERR_TRACE(VERSION_ERROR))
15852
0
            SendAlert(ssl, alert_fatal, wolfssl_alert_protocol_version);
15853
0
        else
15854
0
            SendAlert(ssl, alert_fatal, unexpected_message);
15855
0
        return ret;
15856
0
    }
15857
15858
#if defined(WOLFSSL_CALLBACKS)
15859
    /* add name later, add on record and handshake header part back on */
15860
    if (ssl->toInfoOn) {
15861
        ret = AddPacketInfo(ssl, 0, handshake, input + *inOutIdx -
15862
            HANDSHAKE_HEADER_SZ, size + HANDSHAKE_HEADER_SZ, READ_PROTO,
15863
            RECORD_HEADER_SZ, ssl->heap);
15864
        if (ret != 0)
15865
            return ret;
15866
        AddLateRecordHeader(&ssl->curRL, &ssl->timeoutInfo);
15867
    }
15868
#endif
15869
15870
0
    if (ssl->options.handShakeState == HANDSHAKE_DONE &&
15871
0
            type != session_ticket && type != certificate_request &&
15872
0
            type != certificate && type != key_update && type != finished
15873
#if defined(WOLFSSL_DTLS13) && defined(WOLFSSL_DTLS_CID)
15874
            && type != request_connection_id && type != new_connection_id
15875
#endif
15876
0
            ) {
15877
0
        WOLFSSL_MSG("HandShake message after handshake complete");
15878
0
        SendAlert(ssl, alert_fatal, unexpected_message);
15879
0
        WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15880
0
        return OUT_OF_ORDER_E;
15881
0
    }
15882
15883
0
    if (ssl->options.side == WOLFSSL_CLIENT_END &&
15884
0
               ssl->options.serverState == NULL_STATE &&
15885
0
               type != server_hello && type != hello_retry_request
15886
#if defined(WOLFSSL_DTLS13) && !defined(WOLFSSL_NO_TLS12)
15887
        && (!ssl->options.dtls || type != hello_verify_request)
15888
#endif /* defined(WOLFSSL_DTLS13) && !defined(WOLFSSL_NO_TLS12) */
15889
0
        ) {
15890
0
        WOLFSSL_MSG("First server message not server hello");
15891
0
        SendAlert(ssl, alert_fatal, unexpected_message);
15892
0
        WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15893
0
        return OUT_OF_ORDER_E;
15894
0
    }
15895
15896
0
    if (ssl->options.side == WOLFSSL_SERVER_END &&
15897
0
               ssl->options.clientState == NULL_STATE && type != client_hello) {
15898
0
        WOLFSSL_MSG("First client message not client hello");
15899
0
        SendAlert(ssl, alert_fatal, unexpected_message);
15900
0
        WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
15901
0
        return OUT_OF_ORDER_E;
15902
0
    }
15903
15904
    /* above checks handshake state */
15905
    /* Finish an earlier message's key schedule before this message is
15906
     * judged: it installs state this one is checked against. */
15907
0
    if (ssl->kdfMsgStep > 0) {
15908
0
        ret = DoTls13MsgDerives(ssl, ssl->kdfMsgType);
15909
0
        if (ret != 0)
15910
0
            return ret;
15911
        /* A resolved pend must not suppress the next sanity check. */
15912
0
        if (ssl->error == WC_NO_ERR_TRACE(WC_PENDING_E)) {
15913
0
            ssl->error = 0;
15914
0
        }
15915
0
    }
15916
15917
0
    switch (type) {
15918
0
#ifndef NO_WOLFSSL_CLIENT
15919
    /* Messages only received by client. */
15920
0
    case server_hello:
15921
0
        WOLFSSL_MSG("processing server hello");
15922
0
        ret = DoTls13ServerHello(ssl, input, inOutIdx, size, &type);
15923
    #if !defined(WOLFSSL_NO_CLIENT_AUTH) && \
15924
               ((defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)) || \
15925
                (defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)))
15926
        if (ssl->options.resuming || !IsAtLeastTLSv1_2(ssl) ||
15927
                                               IsAtLeastTLSv1_3(ssl->version)) {
15928
            ssl->options.cacheMessages = 0;
15929
            if ((ssl->hsHashes != NULL) && (ssl->hsHashes->messages != NULL)) {
15930
                ForceZero(ssl->hsHashes->messages, ssl->hsHashes->length);
15931
                XFREE(ssl->hsHashes->messages, ssl->heap, DYNAMIC_TYPE_HASHES);
15932
                ssl->hsHashes->messages = NULL;
15933
            }
15934
        }
15935
    #endif
15936
0
        break;
15937
15938
0
    case encrypted_extensions:
15939
0
        WOLFSSL_MSG("processing encrypted extensions");
15940
0
        ret = DoTls13EncryptedExtensions(ssl, input, inOutIdx, size);
15941
0
        break;
15942
15943
0
    #ifndef NO_CERTS
15944
0
    case certificate_request:
15945
0
        WOLFSSL_MSG("processing certificate request");
15946
0
        ret = DoTls13CertificateRequest(ssl, input, inOutIdx, size);
15947
0
        break;
15948
0
    #endif
15949
15950
0
    case session_ticket:
15951
0
        WOLFSSL_MSG("processing new session ticket");
15952
0
        ret = DoTls13NewSessionTicket(ssl, input, inOutIdx, size);
15953
0
        break;
15954
0
#endif /* !NO_WOLFSSL_CLIENT */
15955
15956
0
#ifndef NO_WOLFSSL_SERVER
15957
    /* Messages only received by server. */
15958
0
    case client_hello:
15959
0
        WOLFSSL_MSG("processing client hello");
15960
#if defined(HAVE_ECH)
15961
        /* keep the start idx so we can restore it for the inner call */
15962
        echInOutIdx = *inOutIdx;
15963
#endif
15964
0
        ret = DoTls13ClientHello(ssl, input, inOutIdx, size);
15965
    #if !defined(WOLFSSL_NO_CLIENT_AUTH) && \
15966
               ((defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)) || \
15967
                (defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)))
15968
        if ((ssl->options.resuming || !ssl->options.verifyPeer ||
15969
               !IsAtLeastTLSv1_2(ssl) || IsAtLeastTLSv1_3(ssl->version))
15970
        #ifdef WOLFSSL_DTLS13
15971
               && (!ssl->options.dtls)
15972
        #endif
15973
               ) {
15974
        #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP)
15975
            if (ret != WC_NO_ERR_TRACE(WC_PENDING_E) &&
15976
                ret != WC_NO_ERR_TRACE(OCSP_WANT_READ))
15977
        #endif
15978
            {
15979
                ssl->options.cacheMessages = 0;
15980
                if ((ssl->hsHashes != NULL) &&
15981
                        (ssl->hsHashes->messages != NULL)) {
15982
                    ForceZero(ssl->hsHashes->messages, ssl->hsHashes->length);
15983
                    XFREE(ssl->hsHashes->messages, ssl->heap,
15984
                        DYNAMIC_TYPE_HASHES);
15985
                    ssl->hsHashes->messages = NULL;
15986
                }
15987
            }
15988
        }
15989
    #endif
15990
#if defined(HAVE_ECH)
15991
        if (ret == 0) {
15992
            echX = TLSX_Find(ssl->extensions, TLSX_ECH);
15993
15994
            if (echX != NULL &&
15995
                    ((WOLFSSL_ECH*)echX->data)->state == ECH_WRITE_NONE &&
15996
                    ((WOLFSSL_ECH*)echX->data)->innerClientHello != NULL) {
15997
                byte copyRandom = ((WOLFSSL_ECH*)echX->data)->innerCount == 0;
15998
                /* reset the inOutIdx to the outer start */
15999
                *inOutIdx = echInOutIdx;
16000
                /* call again with the inner hello */
16001
                if (ret == 0) {
16002
                    echInOutIdx = HANDSHAKE_HEADER_SZ;
16003
#ifdef WOLFSSL_DTLS13
16004
                    if (ssl->options.dtls)
16005
                        echInOutIdx = DTLS13_HANDSHAKE_HEADER_SZ;
16006
#endif
16007
                    ssl->options.echProcessingInner = 1;
16008
                    ret = DoTls13ClientHello(ssl,
16009
                        ((WOLFSSL_ECH*)echX->data)->innerClientHello,
16010
                        &echInOutIdx,
16011
                        ((WOLFSSL_ECH*)echX->data)->innerClientHelloLen);
16012
                    ssl->options.echProcessingInner = 0;
16013
                }
16014
                if (ret == 0 && ((WOLFSSL_ECH*)echX->data)->state !=
16015
                        ECH_PARSED_INTERNAL) {
16016
                    WOLFSSL_MSG("ECH: inner ClientHello missing ECH extension");
16017
                    ret = INVALID_PARAMETER;
16018
                }
16019
                /* if the inner ech parsed successfully we have successfully
16020
                 * handled the hello and can skip the whole message */
16021
                if (ret == 0) {
16022
                    /* Copy inner client random for ECH acceptance calculation.
16023
                     * Only on first inner ClientHello (before HRR), not CH2. */
16024
                    if (copyRandom) {
16025
                        XMEMCPY(ssl->arrays->clientRandomInner,
16026
                                ssl->arrays->clientRandom, RAN_LEN);
16027
                    }
16028
                    *inOutIdx += size;
16029
                }
16030
            }
16031
        }
16032
#endif /* HAVE_ECH */
16033
0
        break;
16034
16035
    #ifdef WOLFSSL_EARLY_DATA
16036
    case end_of_early_data:
16037
        WOLFSSL_MSG("processing end of early data");
16038
        ret = DoTls13EndOfEarlyData(ssl, input, inOutIdx, size);
16039
        break;
16040
    #endif
16041
0
#endif /* !NO_WOLFSSL_SERVER */
16042
16043
    /* Messages received by both client and server. */
16044
0
#if !defined(NO_CERTS) && (!defined(NO_WOLFSSL_CLIENT) || \
16045
0
                           !defined(WOLFSSL_NO_CLIENT_AUTH))
16046
0
    case certificate:
16047
0
        WOLFSSL_MSG("processing certificate");
16048
0
        ret = DoTls13Certificate(ssl, input, inOutIdx, size);
16049
0
        break;
16050
0
#endif
16051
16052
0
#if (!defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
16053
0
     defined(HAVE_ED448) || defined(HAVE_FALCON) || \
16054
0
     defined(WOLFSSL_HAVE_MLDSA) || defined(WOLFSSL_HAVE_SLHDSA)) && \
16055
0
    !defined(NO_CERTS)
16056
0
    case certificate_verify:
16057
0
        WOLFSSL_MSG("processing certificate verify");
16058
0
        ret = DoTls13CertificateVerify(ssl, input, inOutIdx, size);
16059
0
        break;
16060
0
#endif
16061
0
    case finished:
16062
0
        WOLFSSL_MSG("processing finished");
16063
0
        ret = DoTls13Finished(ssl, input, inOutIdx, size, totalSz, NO_SNIFF);
16064
0
        break;
16065
16066
0
    case key_update:
16067
0
        WOLFSSL_MSG("processing key update");
16068
0
        ret = DoTls13KeyUpdate(ssl, input, inOutIdx, size);
16069
0
        break;
16070
16071
#if defined(WOLFSSL_DTLS13) && defined(WOLFSSL_DTLS_CID)
16072
    case request_connection_id:
16073
        WOLFSSL_MSG("processing request connection id");
16074
        ret = DoDtls13RequestConnectionId(ssl, input, inOutIdx, size);
16075
        break;
16076
16077
    case new_connection_id:
16078
        WOLFSSL_MSG("processing new connection id");
16079
        ret = DoDtls13NewConnectionId(ssl, input, inOutIdx, size);
16080
        break;
16081
#endif /* WOLFSSL_DTLS13 && WOLFSSL_DTLS_CID */
16082
16083
#if defined(WOLFSSL_DTLS13) && !defined(WOLFSSL_NO_TLS12) && \
16084
    !defined(NO_WOLFSSL_CLIENT)
16085
    case hello_verify_request:
16086
        WOLFSSL_MSG("processing hello verify request");
16087
        ret = DoHelloVerifyRequest(ssl, input, inOutIdx, size);
16088
        break;
16089
#endif
16090
0
    default:
16091
0
        WOLFSSL_MSG("Unknown handshake message type");
16092
0
        ret = UNKNOWN_HANDSHAKE_TYPE;
16093
0
        break;
16094
0
    }
16095
16096
#ifdef WOLFSSL_ASYNC_CRYPT
16097
    /* Handler pended: this exact message will be replayed. Mark it so the
16098
     * replay skips its sanity check (it already passed and advanced state).
16099
     * Set from the handler's own ret, before the trailing key-schedule
16100
     * derive below can re-raise WC_PENDING_E for an already-done message. */
16101
    if (ret == WC_NO_ERR_TRACE(WC_PENDING_E))
16102
        ssl->options.asyncReplayMsg = 1;
16103
#endif
16104
16105
0
#if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_ASYNC_IO)
16106
    /* if async, offset index so this msg will be processed again */
16107
    /* NOTE: check this now before other calls can overwrite ret */
16108
0
    if ((ret == WC_NO_ERR_TRACE(WC_PENDING_E) ||
16109
0
         ret == WC_NO_ERR_TRACE(OCSP_WANT_READ)) && *inOutIdx > 0) {
16110
        /* DTLS always stores a message in a buffer when async is enable, so we
16111
         * don't need to adjust for the extra bytes here (*inOutIdx is always
16112
         * == 0) */
16113
0
        *inOutIdx -= HANDSHAKE_HEADER_SZ;
16114
0
    }
16115
16116
    /* make sure async error is cleared */
16117
0
    if (ret == 0 &&
16118
0
        (ssl->error == WC_NO_ERR_TRACE(WC_PENDING_E) ||
16119
0
         ssl->error == WC_NO_ERR_TRACE(OCSP_WANT_READ))) {
16120
0
        ssl->error = 0;
16121
0
    }
16122
0
#endif
16123
#if defined(HAVE_WRITE_DUP) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
16124
    /* Read side: a fresh PHA CertificateRequest. Resume from the transcript
16125
     * the write side published after the previous PHA response, so this CR is
16126
     * hashed onto the same base the server has. */
16127
    if (ret == 0 && type == certificate_request &&
16128
            ssl->options.side == WOLFSSL_CLIENT_END &&
16129
            ssl->dupSide == READ_DUP_SIDE &&
16130
            ssl->options.handShakeState == HANDSHAKE_DONE &&
16131
            ssl->dupWrite != NULL) {
16132
        if (wc_LockMutex(&ssl->dupWrite->dupMutex) != 0)
16133
            return BAD_MUTEX_E;
16134
        if (ssl->dupWrite->postHandshakeSyncedHashState != NULL) {
16135
            FreeHandshakeHashes(ssl);
16136
            ssl->hsHashes = ssl->dupWrite->postHandshakeSyncedHashState;
16137
            ssl->dupWrite->postHandshakeSyncedHashState = NULL;
16138
        }
16139
        wc_UnLockMutex(&ssl->dupWrite->dupMutex);
16140
    }
16141
#endif /* HAVE_WRITE_DUP && WOLFSSL_POST_HANDSHAKE_AUTH */
16142
0
    if (ret == 0 && type != client_hello && type != session_ticket &&
16143
0
                                                           type != key_update
16144
#if defined(WOLFSSL_DTLS13) && defined(WOLFSSL_DTLS_CID)
16145
            && type != request_connection_id && type != new_connection_id
16146
#endif
16147
0
            ) {
16148
0
        ret = HashInput(ssl, input + inIdx, (int)size);
16149
0
    }
16150
16151
0
    alertType = TranslateErrorToAlert(ret);
16152
16153
    /* Skip when a fatal alert already went out for this error. The message
16154
     * handlers reached above send their own, more specific alert before
16155
     * returning (a protocol_version from the version checks in DoClientHello,
16156
     * decode_error, illegal_parameter, inappropriate_fallback), and a second
16157
     * fatal alert on a connection that is already being torn down is not a
16158
     * message the peer can act on. Matches the guard in
16159
     * SendFatalAlertOnly(). */
16160
0
    if (alertType != invalid_alert &&
16161
0
            ssl->alert_history.last_tx.level != alert_fatal) {
16162
#ifdef WOLFSSL_DTLS13
16163
        if (type == client_hello && ssl->options.dtls)
16164
            DtlsSetSeqNumForReply(ssl);
16165
#endif
16166
0
        tmp = SendAlert(ssl, alert_fatal, alertType);
16167
        /* propagate socket error instead of tls error to be sure the error is
16168
         * not ignored by DTLS code */
16169
0
        if (tmp == WC_NO_ERR_TRACE(SOCKET_ERROR_E))
16170
0
            ret = SOCKET_ERROR_E;
16171
0
    }
16172
16173
0
    if (ret == 0 && ssl->options.tls1_3) {
16174
        /* The message is hashed by now; run the key schedule that belongs to
16175
         * it. */
16176
0
        ret = DoTls13MsgDerives(ssl, type);
16177
0
        if (ret != 0)
16178
0
            return ret;
16179
16180
    #if !defined(NO_WOLFSSL_CLIENT) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
16181
        if (ssl->options.side == WOLFSSL_CLIENT_END) {
16182
            if (type == certificate_request &&
16183
                                ssl->options.handShakeState == HANDSHAKE_DONE) {
16184
#if defined(HAVE_WRITE_DUP)
16185
                /* Read side cannot write; delegate the cert response to the
16186
                 * write side by saving auth state in the shared WriteDup. */
16187
                if (ssl->dupSide == READ_DUP_SIDE) {
16188
                    if (ssl->dupWrite == NULL)
16189
                        return BAD_STATE_E;
16190
                    if (wc_LockMutex(&ssl->dupWrite->dupMutex) != 0)
16191
                        return BAD_MUTEX_E;
16192
                    /* Copy the current transcript so the write side can
16193
                     * compute the correct Finished MAC. */
16194
                    ret = InitHandshakeHashesAndCopy(ssl, ssl->hsHashes,
16195
                                      &ssl->dupWrite->postHandshakeHashState);
16196
                    if (ret == 0) {
16197
                        /* Copy the cert request context. */
16198
                        CertReqCtx** tail = &ssl->certReqCtx;
16199
                        while (*tail != NULL)
16200
                            tail = &(*tail)->next;
16201
                        *tail = ssl->dupWrite->postHandshakeCertReqCtx;
16202
                        ssl->dupWrite->postHandshakeCertReqCtx = ssl->certReqCtx;
16203
                        ssl->certReqCtx = NULL;
16204
                        ssl->dupWrite->postHandshakeSendVerify =
16205
                            ssl->options.sendVerify;
16206
                        ssl->dupWrite->postHandshakeSigAlgo =
16207
                            ssl->options.sigAlgo;
16208
                        ssl->dupWrite->postHandshakeHashAlgo =
16209
                            ssl->options.hashAlgo;
16210
                    #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
16211
                        /* The request just parsed decides whether the chain
16212
                         * about to be sent may be SHA-1 signed. */
16213
                        ssl->dupWrite->postHandshakeSha1CertOk =
16214
                            (byte)ssl->options.peerSha1CertOk;
16215
                    #endif
16216
                        ssl->dupWrite->postHandshakeAuthPending = 1;
16217
                    }
16218
                    wc_UnLockMutex(&ssl->dupWrite->dupMutex);
16219
                    /* Leave ssl->options unchanged: read side must not reset
16220
                     * its states or call wolfSSL_connect_TLSv13. */
16221
                }
16222
                else
16223
#endif /* HAVE_WRITE_DUP */
16224
                {
16225
                    /* reset handshake states */
16226
                    ssl->options.clientState = CLIENT_HELLO_COMPLETE;
16227
                    ssl->options.connectState  = FIRST_REPLY_DONE;
16228
                    ssl->options.handShakeState = CLIENT_HELLO_COMPLETE;
16229
                    ssl->options.processReply = 0; /* doProcessInit */
16230
16231
                    /*
16232
                       DTLSv1.3 note: We can't reset serverState to
16233
                       SERVER_FINISHED_COMPLETE with the goal that this connect
16234
                       blocks until the cert/cert_verify/finished flight gets ACKed
16235
                       by the server. The problem is that we will invoke
16236
                       ProcessReplyEx() in that case, but we came here from
16237
                       ProcessReplyEx() and it is not re-entrant safe (the input
16238
                       buffer would still have the certificate_request message). */
16239
16240
                    if (wolfSSL_connect_TLSv13(ssl) != WOLFSSL_SUCCESS) {
16241
                        ret = ssl->error;
16242
                        if (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
16243
                            ret = POST_HAND_AUTH_ERROR;
16244
                    }
16245
                }
16246
            }
16247
        }
16248
    #endif /* !NO_WOLFSSL_CLIENT && WOLFSSL_POST_HANDSHAKE_AUTH */
16249
0
    }
16250
16251
#ifdef WOLFSSL_DTLS13
16252
    if (ssl->options.dtls && !ssl->options.dtlsStateful) {
16253
        DtlsResetState(ssl);
16254
        if (DtlsIgnoreError(ret))
16255
            ret = 0;
16256
    }
16257
#endif
16258
16259
0
    WOLFSSL_LEAVE("DoTls13HandShakeMsgType()", ret);
16260
0
    return ret;
16261
0
}
16262
16263
16264
/* Handle a handshake message that has been received.
16265
 *
16266
 * ssl       The SSL/TLS object.
16267
 * input     The message buffer.
16268
 * inOutIdx  On entry, the index into the buffer of the current message.
16269
 *           On exit, the index into the buffer of the next message.
16270
 * totalSz   Length of remaining data in the message buffer.
16271
 * returns 0 on success and otherwise failure.
16272
 */
16273
int DoTls13HandShakeMsg(WOLFSSL* ssl, byte* input, word32* inOutIdx,
16274
                        word32 totalSz)
16275
0
{
16276
0
    int    ret = 0;
16277
0
    word32 inputLength;
16278
0
    byte   type;
16279
0
    word32 size = 0;
16280
#if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP)
16281
    /* Nonzero on entry: an earlier message's schedule is unfinished, so a
16282
     * pend from its pre-dispatch drain must re-present this message. */
16283
    byte   kdfStepEntry = ssl->kdfMsgStep;
16284
#endif
16285
16286
0
    WOLFSSL_ENTER("DoTls13HandShakeMsg");
16287
16288
    /* totalSz is now curStartIdx + curSize (content-only, padSz already
16289
     * subtracted in ProcessReply). */
16290
0
    if (*inOutIdx > totalSz)
16291
0
        return BUFFER_ERROR;
16292
0
    inputLength = totalSz - *inOutIdx;
16293
16294
    /* If there is a pending fragmented handshake message,
16295
     * pending message size will be non-zero. */
16296
0
    if (ssl->pendingMsgSz == 0) {
16297
    #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP)
16298
        word32 startIdx = *inOutIdx;
16299
    #endif
16300
16301
0
        if (GetHandshakeHeader(ssl, input, inOutIdx, &type, &size,
16302
0
                               totalSz) != 0) {
16303
0
            WOLFSSL_ERROR_VERBOSE(PARSE_ERROR);
16304
0
            return PARSE_ERROR;
16305
0
        }
16306
16307
0
        ret = EarlySanityCheckMsgReceived(ssl, type,
16308
0
                (inputLength > HANDSHAKE_HEADER_SZ) ?
16309
0
                min(inputLength - HANDSHAKE_HEADER_SZ, size) : 0);
16310
0
        if (ret != 0) {
16311
0
            WOLFSSL_ERROR(ret);
16312
0
            return ret;
16313
0
        }
16314
16315
        /* Cap the maximum size of a handshake message to something reasonable.
16316
         * By default is the maximum size of a certificate message assuming
16317
         * nine 2048-bit RSA certificates in the chain. */
16318
0
        if (size > MAX_HANDSHAKE_SZ) {
16319
0
            WOLFSSL_MSG("Handshake message too large");
16320
0
            WOLFSSL_ERROR_VERBOSE(HANDSHAKE_SIZE_ERROR);
16321
0
            return HANDSHAKE_SIZE_ERROR;
16322
0
        }
16323
16324
        /* size is the size of the certificate message payload */
16325
0
        if (inputLength - HANDSHAKE_HEADER_SZ < size) {
16326
            /* Commit pending state only after the allocation succeeds. */
16327
0
            ssl->pendingMsg = (byte*)XMALLOC(size + HANDSHAKE_HEADER_SZ,
16328
0
                                             ssl->heap, DYNAMIC_TYPE_ARRAYS);
16329
0
            if (ssl->pendingMsg == NULL)
16330
0
                return MEMORY_E;
16331
0
            ssl->pendingMsgType = type;
16332
0
            ssl->pendingMsgSz = size + HANDSHAKE_HEADER_SZ;
16333
0
            XMEMCPY(ssl->pendingMsg,
16334
0
                    input + *inOutIdx - HANDSHAKE_HEADER_SZ,
16335
0
                    inputLength);
16336
0
            ssl->pendingMsgOffset = inputLength;
16337
0
            *inOutIdx += inputLength - HANDSHAKE_HEADER_SZ;
16338
0
            return 0;
16339
0
        }
16340
16341
0
        ret = DoTls13HandShakeMsgType(ssl, input, inOutIdx, type, size,
16342
0
                                      totalSz);
16343
    #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP)
16344
        if ((ret == WC_NO_ERR_TRACE(WC_PENDING_E) &&
16345
                 (ssl->kdfMsgStep == 0 || kdfStepEntry != 0) &&
16346
                 ssl->options.processReply != 0 /* doProcessInit */) ||
16347
                ret == WC_NO_ERR_TRACE(OCSP_WANT_READ)) {
16348
            /* Re-present for in-handler pends and pre-dispatch drain pends.
16349
             * Not for post-handler pends, which committed the message: a
16350
             * key-schedule pend (kdfMsgStep != 0) resumes through
16351
             * DoTls13MsgDerives(), and a post-handshake-auth send pend
16352
             * (processReply reset to doProcessInit) resumes through
16353
             * wolfSSL_negotiate(). */
16354
            *inOutIdx = startIdx;
16355
        }
16356
    #endif
16357
0
    }
16358
0
    else {
16359
0
        if (inputLength + ssl->pendingMsgOffset > ssl->pendingMsgSz) {
16360
0
            inputLength = ssl->pendingMsgSz - ssl->pendingMsgOffset;
16361
0
        }
16362
16363
0
        ret = EarlySanityCheckMsgReceived(ssl, ssl->pendingMsgType,
16364
0
                inputLength);
16365
0
        if (ret != 0) {
16366
0
            WOLFSSL_ERROR(ret);
16367
0
            return ret;
16368
0
        }
16369
16370
0
        XMEMCPY(ssl->pendingMsg + ssl->pendingMsgOffset,
16371
0
                input + *inOutIdx, inputLength);
16372
0
        ssl->pendingMsgOffset += inputLength;
16373
0
        *inOutIdx += inputLength;
16374
16375
0
        if (ssl->pendingMsgOffset == ssl->pendingMsgSz)
16376
0
        {
16377
0
            word32 idx = 0;
16378
0
            ret = DoTls13HandShakeMsgType(ssl,
16379
0
                                ssl->pendingMsg + HANDSHAKE_HEADER_SZ,
16380
0
                                &idx, ssl->pendingMsgType,
16381
0
                                ssl->pendingMsgSz - HANDSHAKE_HEADER_SZ,
16382
0
                                ssl->pendingMsgSz);
16383
        #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP)
16384
            if ((ret == WC_NO_ERR_TRACE(WC_PENDING_E) &&
16385
                 (ssl->kdfMsgStep == 0 || kdfStepEntry != 0) &&
16386
                 ssl->options.processReply != 0 /* doProcessInit */) ||
16387
                ret == WC_NO_ERR_TRACE(OCSP_WANT_READ)) {
16388
                /* Re-present the fragment; a post-handler pend falls
16389
                 * through and consumes the message. */
16390
                ssl->pendingMsgOffset -= inputLength;
16391
                *inOutIdx -= inputLength;
16392
            }
16393
            else
16394
        #endif
16395
0
            {
16396
0
                XFREE(ssl->pendingMsg, ssl->heap, DYNAMIC_TYPE_ARRAYS);
16397
0
                ssl->pendingMsg = NULL;
16398
0
                ssl->pendingMsgSz = 0;
16399
0
            }
16400
0
        }
16401
0
    }
16402
16403
0
    WOLFSSL_LEAVE("DoTls13HandShakeMsg", ret);
16404
0
    return ret;
16405
0
}
16406
16407
#ifndef NO_WOLFSSL_CLIENT
16408
16409
/* The client connecting to the server.
16410
 * The protocol version is expecting to be TLS v1.3.
16411
 * If the server downgrades, and older versions of the protocol are compiled
16412
 * in, the client will fallback to wolfSSL_connect().
16413
 * Please see note at top of README if you get an error from connect.
16414
 *
16415
 * ssl  The SSL/TLS object.
16416
 * returns WOLFSSL_SUCCESS on successful handshake, WOLFSSL_FATAL_ERROR when
16417
 * unrecoverable error occurs and 0 otherwise.
16418
 * For more error information use wolfSSL_get_error().
16419
 */
16420
int wolfSSL_connect_TLSv13(WOLFSSL* ssl)
16421
0
{
16422
0
    int advanceState;
16423
0
    int ret = 0;
16424
16425
0
    WOLFSSL_ENTER("wolfSSL_connect_TLSv13");
16426
16427
0
#ifdef HAVE_ERRNO_H
16428
0
    errno = 0;
16429
0
#endif
16430
16431
0
    if (ssl == NULL)
16432
0
        return BAD_FUNC_ARG;
16433
16434
0
    if (ssl->options.side != WOLFSSL_CLIENT_END) {
16435
0
        ssl->error = SIDE_ERROR;
16436
0
        WOLFSSL_ERROR(ssl->error);
16437
0
        return WOLFSSL_FATAL_ERROR;
16438
0
    }
16439
16440
    /* make sure this wolfSSL object has arrays and rng setup. Protects
16441
     * case where the WOLFSSL object is reused via wolfSSL_clear() */
16442
0
    if ((ret = ReinitSSL(ssl, ssl->ctx, 0)) != 0) {
16443
0
        return ret;
16444
0
    }
16445
16446
#ifdef WOLFSSL_DTLS
16447
    if (ssl->version.major == DTLS_MAJOR) {
16448
        ssl->options.dtls   = 1;
16449
        ssl->options.dtlsStateful = 1;
16450
    }
16451
#endif
16452
16453
#ifdef WOLFSSL_WOLFSENTRY_HOOKS
16454
    if ((ssl->ConnectFilter != NULL) &&
16455
        (ssl->options.connectState == CONNECT_BEGIN))
16456
    {
16457
        wolfSSL_netfilter_decision_t res;
16458
        if ((ssl->ConnectFilter(ssl, ssl->ConnectFilter_arg, &res) ==
16459
             WOLFSSL_SUCCESS) &&
16460
            (res == WOLFSSL_NETFILTER_REJECT)) {
16461
            ssl->error = SOCKET_FILTERED_E;
16462
            WOLFSSL_ERROR(ssl->error);
16463
            return WOLFSSL_FATAL_ERROR;
16464
        }
16465
    }
16466
#endif /* WOLFSSL_WOLFSENTRY_HOOKS */
16467
16468
    /* fragOffset is non-zero when sending fragments. On the last
16469
     * fragment, fragOffset is zero again, and the state can be
16470
     * advanced. Also, only advance from states in which we send data */
16471
0
    advanceState = (ssl->options.connectState == CONNECT_BEGIN ||
16472
0
            ssl->options.connectState == HELLO_AGAIN ||
16473
0
            (ssl->options.connectState >= FIRST_REPLY_DONE &&
16474
0
             ssl->options.connectState <= FIRST_REPLY_FOURTH));
16475
16476
#ifdef WOLFSSL_DTLS13
16477
    if (ssl->options.dtls)
16478
        advanceState = advanceState && !ssl->dtls13SendingFragments
16479
            && !ssl->dtls13SendingAckOrRtx;
16480
#endif /* WOLFSSL_DTLS13 */
16481
16482
0
    if (ssl->buffers.outputBuffer.length > 0
16483
    #ifdef WOLFSSL_ASYNC_CRYPT
16484
        /* do not send buffered or advance state if last error was an
16485
            async pending operation */
16486
        && ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E)
16487
    #endif
16488
0
    ) {
16489
0
        if ((ret = SendBuffered(ssl)) == 0) {
16490
0
            if (ssl->fragOffset == 0 && !ssl->options.buildingMsg) {
16491
0
                if (advanceState) {
16492
#ifdef WOLFSSL_DTLS13
16493
                    if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version) &&
16494
                        ssl->options.connectState == FIRST_REPLY_FOURTH) {
16495
                    /* WAIT_FINISHED_ACK is a state added afterwards, but it
16496
                       can't follow FIRST_REPLY_FOURTH in the enum order. Indeed
16497
                       the value of the enum ConnectState is stored in
16498
                       serialized session. This would make importing serialized
16499
                       session from other wolfSSL version incompatible */
16500
                        ssl->options.connectState = WAIT_FINISHED_ACK;
16501
                    }
16502
                    else
16503
#endif /* WOLFSSL_DTLS13 */
16504
0
                    {
16505
0
                        ssl->options.connectState++;
16506
0
                    }
16507
0
                    WOLFSSL_MSG("connect state: "
16508
0
                                "Advanced from last buffered fragment send");
16509
0
#ifdef WOLFSSL_ASYNC_IO
16510
0
                    FreeAsyncCtx(ssl, 0);
16511
0
#endif
16512
16513
0
                }
16514
0
            }
16515
0
            else {
16516
0
                WOLFSSL_MSG("connect state: "
16517
0
                            "Not advanced, more fragments to send");
16518
0
            }
16519
#ifdef WOLFSSL_DTLS13
16520
            if (ssl->options.dtls)
16521
                ssl->dtls13SendingAckOrRtx = 0;
16522
#endif /* WOLFSSL_DTLS13 */
16523
16524
0
        }
16525
0
        else {
16526
0
            ssl->error = ret;
16527
0
            WOLFSSL_ERROR(ssl->error);
16528
0
            return WOLFSSL_FATAL_ERROR;
16529
0
        }
16530
0
    }
16531
16532
0
    ret = RetrySendAlert(ssl);
16533
0
    if (ret != 0) {
16534
0
        ssl->error = ret;
16535
0
        WOLFSSL_ERROR(ssl->error);
16536
0
        return WOLFSSL_FATAL_ERROR;
16537
0
    }
16538
16539
#ifdef WOLFSSL_DTLS13
16540
    if (ssl->options.dtls && ssl->dtls13SendingFragments) {
16541
        if ((ssl->error = Dtls13FragmentsContinue(ssl)) != 0) {
16542
                WOLFSSL_ERROR(ssl->error);
16543
                return WOLFSSL_FATAL_ERROR;
16544
        }
16545
16546
        /* we sent all the fragments. Advance state. */
16547
        ssl->options.connectState++;
16548
    }
16549
#endif /* WOLFSSL_DTLS13 */
16550
16551
0
    switch (ssl->options.connectState) {
16552
16553
0
        case CONNECT_BEGIN:
16554
            /* Always send client hello first. */
16555
0
            if ((ssl->error = SendTls13ClientHello(ssl)) != 0) {
16556
0
                WOLFSSL_ERROR(ssl->error);
16557
0
                return WOLFSSL_FATAL_ERROR;
16558
0
            }
16559
16560
0
            ssl->options.connectState = CLIENT_HELLO_SENT;
16561
0
            WOLFSSL_MSG("TLSv13 connect state: CLIENT_HELLO_SENT");
16562
0
            FALL_THROUGH;
16563
16564
0
        case CLIENT_HELLO_SENT:
16565
    #ifdef WOLFSSL_EARLY_DATA
16566
            if (ssl->earlyData != no_early_data &&
16567
                ssl->options.handShakeState != CLIENT_HELLO_COMPLETE) {
16568
        #if defined(WOLFSSL_TLS13_MIDDLEBOX_COMPAT)
16569
                    if (!ssl->options.dtls && !ssl->options.sentChangeCipher
16570
                            && ssl->options.tls13MiddleBoxCompat) {
16571
                        ssl->error = SendChangeCipher(ssl);
16572
                        /* A short send leaves the record queued in the output
16573
                         * buffer, so a resumed connect must not build a second
16574
                         * one. Same on every other site. */
16575
                        if (ssl->error == 0 ||
16576
                                ssl->error == WC_NO_ERR_TRACE(WANT_WRITE)) {
16577
                            ssl->options.sentChangeCipher = 1;
16578
                        }
16579
                        if (ssl->error != 0) {
16580
                            WOLFSSL_ERROR(ssl->error);
16581
                            return WOLFSSL_FATAL_ERROR;
16582
                        }
16583
                    }
16584
        #endif
16585
                ssl->options.handShakeState = CLIENT_HELLO_COMPLETE;
16586
                return WOLFSSL_SUCCESS;
16587
            }
16588
    #endif
16589
            /* Get the response/s from the server. */
16590
0
            while (ssl->options.serverState <
16591
0
                    SERVER_HELLOVERIFYREQUEST_COMPLETE) {
16592
0
                if ((ssl->error = ProcessReply(ssl)) < 0) {
16593
0
                        WOLFSSL_ERROR(ssl->error);
16594
0
                        return WOLFSSL_FATAL_ERROR;
16595
0
                }
16596
16597
#ifdef WOLFSSL_DTLS13
16598
                if (ssl->options.dtls) {
16599
                    if ((ssl->error = Dtls13DoScheduledWork(ssl)) < 0) {
16600
                        WOLFSSL_ERROR(ssl->error);
16601
                        return WOLFSSL_FATAL_ERROR;
16602
                    }
16603
                }
16604
#endif /* WOLFSSL_DTLS13 */
16605
0
            }
16606
16607
0
            if (!ssl->options.tls1_3) {
16608
0
    #ifndef WOLFSSL_NO_TLS12
16609
0
                if (ssl->options.downgrade)
16610
0
                    return wolfSSL_connect(ssl);
16611
0
    #endif
16612
0
                WOLFSSL_MSG("Client using higher version, fatal error");
16613
0
                WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
16614
0
                return VERSION_ERROR;
16615
0
            }
16616
16617
0
            ssl->options.connectState = HELLO_AGAIN;
16618
0
            WOLFSSL_MSG("connect state: HELLO_AGAIN");
16619
0
            FALL_THROUGH;
16620
16621
0
        case HELLO_AGAIN:
16622
16623
0
            if (ssl->options.serverState ==
16624
0
                                          SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
16625
        #if defined(WOLFSSL_TLS13_MIDDLEBOX_COMPAT)
16626
                if (!ssl->options.dtls && !ssl->options.sentChangeCipher
16627
                    && ssl->options.tls13MiddleBoxCompat) {
16628
                    ssl->error = SendChangeCipher(ssl);
16629
                    if (ssl->error == 0 ||
16630
                            ssl->error == WC_NO_ERR_TRACE(WANT_WRITE)) {
16631
                        ssl->options.sentChangeCipher = 1;
16632
                    }
16633
                    if (ssl->error != 0) {
16634
                        /* The second ClientHello still has to follow, so hold
16635
                         * the state machine on this case while the record
16636
                         * drains. */
16637
                        ssl->options.buildingMsg = 1;
16638
                        WOLFSSL_ERROR(ssl->error);
16639
                        return WOLFSSL_FATAL_ERROR;
16640
                    }
16641
                }
16642
        #endif
16643
                /* Try again with different security parameters. */
16644
0
                if ((ssl->error = SendTls13ClientHello(ssl)) != 0) {
16645
0
                    WOLFSSL_ERROR(ssl->error);
16646
0
                    return WOLFSSL_FATAL_ERROR;
16647
0
                }
16648
0
            }
16649
16650
0
            ssl->options.connectState = HELLO_AGAIN_REPLY;
16651
0
            WOLFSSL_MSG("connect state: HELLO_AGAIN_REPLY");
16652
0
            FALL_THROUGH;
16653
16654
0
        case HELLO_AGAIN_REPLY:
16655
            /* Get the response/s from the server. */
16656
0
            while (ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
16657
#ifdef WOLFSSL_DTLS13
16658
                if (!IsAtLeastTLSv1_3(ssl->version)) {
16659
        #ifndef WOLFSSL_NO_TLS12
16660
                    if (ssl->options.downgrade)
16661
                        return wolfSSL_connect(ssl);
16662
        #endif
16663
                }
16664
#endif /* WOLFSSL_DTLS13 */
16665
0
                if ((ssl->error = ProcessReply(ssl)) < 0) {
16666
0
                        WOLFSSL_ERROR(ssl->error);
16667
0
                        return WOLFSSL_FATAL_ERROR;
16668
0
                }
16669
16670
#ifdef WOLFSSL_DTLS13
16671
                if (ssl->options.dtls) {
16672
                    if ((ssl->error = Dtls13DoScheduledWork(ssl)) < 0) {
16673
                        WOLFSSL_ERROR(ssl->error);
16674
                        return WOLFSSL_FATAL_ERROR;
16675
                    }
16676
                }
16677
#endif /* WOLFSSL_DTLS13 */
16678
0
            }
16679
16680
            /* Finish a key schedule the Finished handler left pending:
16681
             * it must complete before this side's sends advance the
16682
             * transcript the traffic secrets hash. */
16683
0
            if (ssl->kdfMsgStep > 0) {
16684
0
                ssl->error = DoTls13MsgDerives(ssl, ssl->kdfMsgType);
16685
0
                if (ssl->error != 0) {
16686
0
                    WOLFSSL_ERROR(ssl->error);
16687
0
                    return WOLFSSL_FATAL_ERROR;
16688
0
                }
16689
0
            }
16690
16691
0
            ssl->options.connectState = FIRST_REPLY_DONE;
16692
0
            WOLFSSL_MSG("connect state: FIRST_REPLY_DONE");
16693
0
            FALL_THROUGH;
16694
16695
0
        case FIRST_REPLY_DONE:
16696
0
            if (ssl->options.certOnly)
16697
0
                return WOLFSSL_SUCCESS;
16698
        #ifdef WOLFSSL_EARLY_DATA
16699
            if (!ssl->options.dtls && ssl->earlyData != no_early_data
16700
                && !WOLFSSL_IS_QUIC(ssl)) {
16701
                if ((ssl->error = SendTls13EndOfEarlyData(ssl)) != 0) {
16702
                    WOLFSSL_ERROR(ssl->error);
16703
                    return WOLFSSL_FATAL_ERROR;
16704
                }
16705
                WOLFSSL_MSG("sent: end_of_early_data");
16706
            }
16707
        #endif
16708
16709
0
            ssl->options.connectState = FIRST_REPLY_FIRST;
16710
0
            WOLFSSL_MSG("connect state: FIRST_REPLY_FIRST");
16711
0
            FALL_THROUGH;
16712
16713
0
        case FIRST_REPLY_FIRST:
16714
        #if defined(WOLFSSL_TLS13_MIDDLEBOX_COMPAT)
16715
            if (!ssl->options.sentChangeCipher && !ssl->options.dtls
16716
                && ssl->options.tls13MiddleBoxCompat) {
16717
                ssl->error = SendChangeCipher(ssl);
16718
                if (ssl->error == 0 ||
16719
                        ssl->error == WC_NO_ERR_TRACE(WANT_WRITE)) {
16720
                    ssl->options.sentChangeCipher = 1;
16721
                }
16722
                if (ssl->error != 0) {
16723
                    WOLFSSL_ERROR(ssl->error);
16724
                    return WOLFSSL_FATAL_ERROR;
16725
                }
16726
            }
16727
        #endif
16728
16729
0
            ssl->options.connectState = FIRST_REPLY_SECOND;
16730
0
            WOLFSSL_MSG("connect state: FIRST_REPLY_SECOND");
16731
0
            FALL_THROUGH;
16732
16733
0
        case FIRST_REPLY_SECOND:
16734
            /* CLIENT: check peer authentication. */
16735
0
            if (!ssl->options.peerAuthGood) {
16736
0
                WOLFSSL_MSG("Server authentication did not happen");
16737
0
                WOLFSSL_ERROR_VERBOSE(WOLFSSL_FATAL_ERROR);
16738
0
                return WOLFSSL_FATAL_ERROR;
16739
0
            }
16740
0
        #ifndef NO_CERTS
16741
0
            if ((!ssl->options.resuming || TLS13_AFTER_HANDSHAKE(ssl)) &&
16742
0
                    ssl->options.sendVerify) {
16743
0
                ssl->error = SendTls13Certificate(ssl);
16744
0
                if (ssl->error != 0) {
16745
0
                    wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
16746
0
                    WOLFSSL_ERROR(ssl->error);
16747
0
                    return WOLFSSL_FATAL_ERROR;
16748
0
                }
16749
0
                WOLFSSL_MSG("sent: certificate");
16750
0
            }
16751
0
        #endif
16752
16753
0
            ssl->options.connectState = FIRST_REPLY_THIRD;
16754
0
            WOLFSSL_MSG("connect state: FIRST_REPLY_THIRD");
16755
0
            FALL_THROUGH;
16756
16757
0
        case FIRST_REPLY_THIRD:
16758
0
        #if (!defined(NO_CERTS) && (!defined(NO_RSA) || defined(HAVE_ECC) || \
16759
0
             defined(HAVE_ED25519) || defined(HAVE_ED448) || \
16760
0
             defined(HAVE_FALCON) || defined(WOLFSSL_HAVE_MLDSA) || \
16761
0
             defined(WOLFSSL_HAVE_SLHDSA))) && \
16762
0
             (!defined(NO_WOLFSSL_SERVER) || !defined(WOLFSSL_NO_CLIENT_AUTH))
16763
0
            if ((!ssl->options.resuming || TLS13_AFTER_HANDSHAKE(ssl)) &&
16764
0
                    ssl->options.sendVerify) {
16765
0
                ssl->error = SendTls13CertificateVerify(ssl);
16766
0
                if (ssl->error != 0) {
16767
0
                    wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
16768
0
                    WOLFSSL_ERROR(ssl->error);
16769
0
                    return WOLFSSL_FATAL_ERROR;
16770
0
                }
16771
0
                WOLFSSL_MSG("sent: certificate verify");
16772
0
            }
16773
0
        #endif
16774
16775
0
            ssl->options.connectState = FIRST_REPLY_FOURTH;
16776
0
            WOLFSSL_MSG("connect state: FIRST_REPLY_FOURTH");
16777
0
            FALL_THROUGH;
16778
16779
0
        case FIRST_REPLY_FOURTH:
16780
0
            if ((ssl->error = SendTls13Finished(ssl)) != 0) {
16781
0
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
16782
0
                WOLFSSL_ERROR(ssl->error);
16783
0
                return WOLFSSL_FATAL_ERROR;
16784
0
            }
16785
0
            WOLFSSL_MSG("sent: finished");
16786
16787
#ifdef WOLFSSL_DTLS13
16788
            ssl->options.connectState = WAIT_FINISHED_ACK;
16789
            WOLFSSL_MSG("connect state: WAIT_FINISHED_ACK");
16790
            FALL_THROUGH;
16791
16792
        case WAIT_FINISHED_ACK:
16793
            if (ssl->options.dtls) {
16794
                while (ssl->options.serverState != SERVER_FINISHED_ACKED) {
16795
                    if ((ssl->error = ProcessReply(ssl)) < 0) {
16796
                        WOLFSSL_ERROR(ssl->error);
16797
                        return WOLFSSL_FATAL_ERROR;
16798
                    }
16799
16800
                    if ((ssl->error = Dtls13DoScheduledWork(ssl)) < 0) {
16801
                        WOLFSSL_ERROR(ssl->error);
16802
                        return WOLFSSL_FATAL_ERROR;
16803
                    }
16804
                }
16805
            }
16806
#endif /* WOLFSSL_DTLS13 */
16807
0
            ssl->options.connectState = FINISHED_DONE;
16808
0
            WOLFSSL_MSG("connect state: FINISHED_DONE");
16809
0
            FALL_THROUGH;
16810
16811
0
        case FINISHED_DONE:
16812
0
        #ifndef NO_HANDSHAKE_DONE_CB
16813
0
            if (ssl->hsDoneCb != NULL) {
16814
0
                int cbret = ssl->hsDoneCb(ssl, ssl->hsDoneCtx);
16815
0
                if (cbret < 0) {
16816
0
                    ssl->error = cbret;
16817
0
                    WOLFSSL_ERROR_VERBOSE(ssl->error);
16818
0
                    WOLFSSL_MSG("HandShake Done Cb don't continue error");
16819
0
                    return WOLFSSL_FATAL_ERROR;
16820
0
                }
16821
0
            }
16822
0
        #endif /* NO_HANDSHAKE_DONE_CB */
16823
16824
        #if defined(HAVE_ECH)
16825
            /* RFC 9849 s6.1.6: if we offered ECH but the server rejected it,
16826
             * send ech_required alert and abort before returning to the app */
16827
            if (ssl->echConfigs != NULL && !ssl->options.disableECH &&
16828
                    !ssl->options.echAccepted) {
16829
                if (ssl->echRetryConfigs != NULL) {
16830
                    ssl->options.echRetryConfigsAccepted = 1;
16831
                }
16832
                SendAlert(ssl, alert_fatal, ech_required);
16833
                ssl->error = ECH_REQUIRED_E;
16834
                WOLFSSL_ERROR_VERBOSE(ECH_REQUIRED_E);
16835
                return WOLFSSL_FATAL_ERROR;
16836
            }
16837
        #endif /* HAVE_ECH */
16838
16839
0
            if (!ssl->options.keepResources) {
16840
0
                FreeHandshakeResources(ssl);
16841
0
            }
16842
0
        #if defined(WOLFSSL_ASYNC_IO) && !defined(WOLFSSL_ASYNC_CRYPT)
16843
            /* Free the remaining async context if not using it for crypto */
16844
0
            FreeAsyncCtx(ssl, 1);
16845
0
        #endif
16846
16847
0
            ssl->error = 0; /* clear the error */
16848
16849
0
            WOLFSSL_LEAVE("wolfSSL_connect_TLSv13", WOLFSSL_SUCCESS);
16850
0
            return WOLFSSL_SUCCESS;
16851
16852
0
        default:
16853
0
            WOLFSSL_MSG("Unknown connect state ERROR");
16854
0
            return WOLFSSL_FATAL_ERROR; /* unknown connect state */
16855
0
    }
16856
0
}
16857
#endif
16858
16859
#if defined(WOLFSSL_SEND_HRR_COOKIE)
16860
/* Send a cookie with the HelloRetryRequest to avoid storing state.
16861
 *
16862
 * ssl       SSL/TLS object.
16863
 * secret    Secret to use when generating integrity check for cookie.
16864
 *           A value of NULL indicates to generate a new random secret.
16865
 * secretSz  Size of secret data in bytes.
16866
 *           Use a value of 0 to indicate use of default size.
16867
 * returns BAD_FUNC_ARG when ssl is NULL or not using TLS v1.3, SIDE_ERROR when
16868
 * called on a client; WOLFSSL_SUCCESS on success and otherwise failure.
16869
 */
16870
int wolfSSL_send_hrr_cookie(WOLFSSL* ssl, const unsigned char* secret,
16871
                            unsigned int secretSz)
16872
{
16873
    int ret;
16874
16875
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
16876
        return BAD_FUNC_ARG;
16877
 #ifndef NO_WOLFSSL_SERVER
16878
    if (ssl->options.side == WOLFSSL_CLIENT_END)
16879
        return SIDE_ERROR;
16880
16881
    if (secretSz == 0) {
16882
    #ifndef NO_SHA256
16883
        secretSz = WC_SHA256_DIGEST_SIZE;
16884
    #elif defined(WOLFSSL_SHA384)
16885
        secretSz = WC_SHA384_DIGEST_SIZE;
16886
    #elif defined(WOLFSSL_TLS13_SHA512)
16887
        secretSz = WC_SHA512_DIGEST_SIZE;
16888
    #elif defined(WOLFSSL_SM3)
16889
        secretSz = WC_SM3_DIGEST_SIZE;
16890
    #else
16891
        #error "No digest to available to use with HMAC for cookies."
16892
    #endif /* NO_SHA */
16893
    }
16894
16895
    if (secretSz != ssl->buffers.tls13CookieSecret.length) {
16896
        byte* newSecret;
16897
16898
        if (ssl->buffers.tls13CookieSecret.buffer != NULL) {
16899
            ForceZero(ssl->buffers.tls13CookieSecret.buffer,
16900
                      ssl->buffers.tls13CookieSecret.length);
16901
            XFREE(ssl->buffers.tls13CookieSecret.buffer,
16902
                  ssl->heap, DYNAMIC_TYPE_COOKIE_PWD);
16903
        }
16904
16905
        newSecret = (byte*)XMALLOC(secretSz, ssl->heap,
16906
                                   DYNAMIC_TYPE_COOKIE_PWD);
16907
        if (newSecret == NULL) {
16908
            ssl->buffers.tls13CookieSecret.buffer = NULL;
16909
            ssl->buffers.tls13CookieSecret.length = 0;
16910
            WOLFSSL_MSG("couldn't allocate new cookie secret");
16911
            return MEMORY_ERROR;
16912
        }
16913
        ssl->buffers.tls13CookieSecret.buffer = newSecret;
16914
        ssl->buffers.tls13CookieSecret.length = secretSz;
16915
    #ifdef WOLFSSL_CHECK_MEM_ZERO
16916
        wc_MemZero_Add("wolfSSL_send_hrr_cookie secret",
16917
            ssl->buffers.tls13CookieSecret.buffer,
16918
            ssl->buffers.tls13CookieSecret.length);
16919
    #endif
16920
    }
16921
16922
    /* If the supplied secret is NULL, randomly generate a new secret. */
16923
    if (secret == NULL) {
16924
        ret = wc_RNG_GenerateBlock(ssl->rng,
16925
                               ssl->buffers.tls13CookieSecret.buffer, secretSz);
16926
        if (ret < 0)
16927
            return ret;
16928
    }
16929
    else
16930
        XMEMCPY(ssl->buffers.tls13CookieSecret.buffer, secret, secretSz);
16931
16932
    ssl->options.sendCookie = 1;
16933
16934
    ret = WOLFSSL_SUCCESS;
16935
#else
16936
    (void)secret;
16937
    (void)secretSz;
16938
16939
    ret = SIDE_ERROR;
16940
#endif
16941
16942
    return ret;
16943
}
16944
16945
int wolfSSL_disable_hrr_cookie(WOLFSSL* ssl)
16946
{
16947
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
16948
        return BAD_FUNC_ARG;
16949
16950
#ifdef NO_WOLFSSL_SERVER
16951
    return SIDE_ERROR;
16952
#else
16953
    if (ssl->options.side == WOLFSSL_CLIENT_END)
16954
        return SIDE_ERROR;
16955
16956
    if (ssl->buffers.tls13CookieSecret.buffer != NULL) {
16957
        ForceZero(ssl->buffers.tls13CookieSecret.buffer,
16958
            ssl->buffers.tls13CookieSecret.length);
16959
        XFREE(ssl->buffers.tls13CookieSecret.buffer, ssl->heap,
16960
            DYNAMIC_TYPE_COOKIE_PWD);
16961
        ssl->buffers.tls13CookieSecret.buffer = NULL;
16962
        ssl->buffers.tls13CookieSecret.length = 0;
16963
    }
16964
16965
    if (ssl->buffers.tls13CookieSecretSecondary.buffer != NULL) {
16966
        ForceZero(ssl->buffers.tls13CookieSecretSecondary.buffer,
16967
            ssl->buffers.tls13CookieSecretSecondary.length);
16968
        XFREE(ssl->buffers.tls13CookieSecretSecondary.buffer, ssl->heap,
16969
            DYNAMIC_TYPE_COOKIE_PWD);
16970
        ssl->buffers.tls13CookieSecretSecondary.buffer = NULL;
16971
        ssl->buffers.tls13CookieSecretSecondary.length = 0;
16972
    }
16973
16974
    ssl->options.sendCookie = 0;
16975
    return WOLFSSL_SUCCESS;
16976
#endif /* NO_WOLFSSL_SERVER */
16977
}
16978
16979
/* Set a secondary HelloRetryRequest cookie secret used only when verifying a
16980
 * received cookie, and only if the primary secret (set by
16981
 * wolfSSL_send_hrr_cookie()) fails to verify it.
16982
 *
16983
 * This supports an application-driven cookie-secret rotation on a stateless
16984
 * DTLS 1.3 server: after rotating the primary secret, install the previous
16985
 * secret here so that cookies already issued under it are still accepted for
16986
 * an overlap window.  It is never used to issue cookies.
16987
 *
16988
 * This API is DTLS only - TLS 1.3 over a reliable transport does not operate
16989
 * statelessly across the HelloRetryRequest exchange, so a secondary cookie
16990
 * secret has no use there.
16991
 *
16992
 * ssl       SSL/TLS object.
16993
 * secret    Secondary secret to verify cookies against.  A value of NULL (or a
16994
 *           secretSz of 0) clears any previously set secondary secret.
16995
 * secretSz  Size of secret data in bytes.
16996
 * returns BAD_FUNC_ARG when ssl is NULL, not TLS v1.3 or not DTLS; SIDE_ERROR
16997
 * when called on a client; WOLFSSL_SUCCESS on success and otherwise failure.
16998
 */
16999
int wolfSSL_set_hrr_cookie_secret_secondary(WOLFSSL* ssl,
17000
    const unsigned char* secret, unsigned int secretSz)
17001
{
17002
    int ret;
17003
17004
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
17005
        return BAD_FUNC_ARG;
17006
#ifndef NO_WOLFSSL_SERVER
17007
    if (ssl->options.side == WOLFSSL_CLIENT_END)
17008
        return SIDE_ERROR;
17009
    /* DTLS only - TLS 1.3 does not verify cookies statelessly. */
17010
    if (!ssl->options.dtls) {
17011
        WOLFSSL_MSG("Secondary HRR cookie secret is DTLS only");
17012
        return BAD_FUNC_ARG;
17013
    }
17014
17015
    /* Clear any existing secondary secret. */
17016
    if (ssl->buffers.tls13CookieSecretSecondary.buffer != NULL) {
17017
        ForceZero(ssl->buffers.tls13CookieSecretSecondary.buffer,
17018
                  ssl->buffers.tls13CookieSecretSecondary.length);
17019
        XFREE(ssl->buffers.tls13CookieSecretSecondary.buffer, ssl->heap,
17020
              DYNAMIC_TYPE_COOKIE_PWD);
17021
        ssl->buffers.tls13CookieSecretSecondary.buffer = NULL;
17022
        ssl->buffers.tls13CookieSecretSecondary.length = 0;
17023
    }
17024
17025
    /* A NULL/empty secret just clears the secondary secret. */
17026
    if (secret == NULL || secretSz == 0) {
17027
        ret = WOLFSSL_SUCCESS;
17028
    }
17029
    else {
17030
        byte* newSecret = (byte*)XMALLOC(secretSz, ssl->heap,
17031
                                         DYNAMIC_TYPE_COOKIE_PWD);
17032
        if (newSecret == NULL) {
17033
            WOLFSSL_MSG("couldn't allocate secondary cookie secret");
17034
            ret = MEMORY_ERROR;
17035
        }
17036
        else {
17037
            XMEMCPY(newSecret, secret, secretSz);
17038
            ssl->buffers.tls13CookieSecretSecondary.buffer = newSecret;
17039
            ssl->buffers.tls13CookieSecretSecondary.length = secretSz;
17040
        #ifdef WOLFSSL_CHECK_MEM_ZERO
17041
            wc_MemZero_Add("wolfSSL_set_hrr_cookie_secret_secondary secret",
17042
                ssl->buffers.tls13CookieSecretSecondary.buffer,
17043
                ssl->buffers.tls13CookieSecretSecondary.length);
17044
        #endif
17045
            ret = WOLFSSL_SUCCESS;
17046
        }
17047
    }
17048
#else
17049
    (void)secret;
17050
    (void)secretSz;
17051
17052
    ret = SIDE_ERROR;
17053
#endif
17054
17055
    return ret;
17056
}
17057
17058
#endif /* defined(WOLFSSL_SEND_HRR_COOKIE) */
17059
17060
#ifdef HAVE_SUPPORTED_CURVES
17061
/* Create a key share entry from group.
17062
 * Generates a key pair.
17063
 *
17064
 * ssl    The SSL/TLS object.
17065
 * group  The named group.
17066
 * returns 0 on success, otherwise failure.
17067
 *   for async can return WC_PENDING_E and should be called again
17068
 */
17069
int wolfSSL_UseKeyShare(WOLFSSL* ssl, word16 group)
17070
0
{
17071
0
    int ret;
17072
17073
0
    if (ssl == NULL)
17074
0
        return BAD_FUNC_ARG;
17075
17076
#ifdef WOLFSSL_ASYNC_CRYPT
17077
    ret = wolfSSL_AsyncPop(ssl, NULL);
17078
    if (ret != WC_NO_ERR_TRACE(WC_NO_PENDING_E)) {
17079
        /* Check for error */
17080
        if (ret < 0)
17081
            return ret;
17082
    }
17083
#endif
17084
17085
0
#if defined(WOLFSSL_HAVE_MLKEM)
17086
0
    if (WOLFSSL_NAMED_GROUP_IS_PQC(group) ||
17087
0
        WOLFSSL_NAMED_GROUP_IS_PQC_HYBRID(group)) {
17088
17089
0
        if (!IsAtLeastTLSv1_3(ssl->version)) {
17090
0
            return BAD_FUNC_ARG;
17091
0
        }
17092
17093
0
        if (ssl->options.side == WOLFSSL_SERVER_END) {
17094
            /* If I am the server of a KEM connection, do not do keygen because
17095
             * I'm going to encapsulate with the client's public key. Note that
17096
             * I might be the client and ssl->option.side has not been properly
17097
             * set yet. In that case the KeyGen operation will be deferred to
17098
             * connection time. */
17099
0
            return WOLFSSL_SUCCESS;
17100
0
        }
17101
0
    }
17102
0
#endif
17103
#if defined(NO_TLS)
17104
    (void)ret;
17105
    (void)group;
17106
#else
17107
    /* Check if the group is supported. */
17108
0
    if (!TLSX_IsGroupSupported(group, ssl->options.side)) {
17109
0
        WOLFSSL_MSG("Group not supported.");
17110
0
        return BAD_FUNC_ARG;
17111
0
    }
17112
17113
0
    ret = TLSX_KeyShare_Use(ssl, group, 0, NULL, NULL, &ssl->extensions);
17114
0
    if (ret != 0)
17115
0
        return ret;
17116
0
#endif /* NO_TLS */
17117
0
    return WOLFSSL_SUCCESS;
17118
0
}
17119
17120
/* Send no key share entries - use HelloRetryRequest to negotiate shared group.
17121
 *
17122
 * ssl    The SSL/TLS object.
17123
 * returns 0 on success, otherwise failure.
17124
 */
17125
int wolfSSL_NoKeyShares(WOLFSSL* ssl)
17126
0
{
17127
0
    int ret;
17128
17129
0
    if (ssl == NULL)
17130
0
        return BAD_FUNC_ARG;
17131
0
    if (ssl->options.side == WOLFSSL_SERVER_END)
17132
0
        return SIDE_ERROR;
17133
#if defined(NO_TLS)
17134
    (void)ret;
17135
#else
17136
0
    ret = TLSX_KeyShare_Empty(ssl);
17137
0
    if (ret != 0)
17138
0
        return ret;
17139
0
#endif /* NO_TLS */
17140
0
    return WOLFSSL_SUCCESS;
17141
0
}
17142
#endif
17143
17144
#ifdef WOLFSSL_DUAL_ALG_CERTS
17145
int wolfSSL_UseCKS(WOLFSSL* ssl, byte *sigSpec, word16 sigSpecSz)
17146
{
17147
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->ctx->method->version) ||
17148
        sigSpec == NULL || sigSpecSz == 0)
17149
        return BAD_FUNC_ARG;
17150
17151
    ssl->sigSpec = sigSpec;
17152
    ssl->sigSpecSz = sigSpecSz;
17153
    return WOLFSSL_SUCCESS;
17154
}
17155
17156
int wolfSSL_CTX_UseCKS(WOLFSSL_CTX* ctx, byte *sigSpec, word16 sigSpecSz)
17157
{
17158
    if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version) ||
17159
        sigSpec == NULL || sigSpecSz == 0)
17160
        return BAD_FUNC_ARG;
17161
17162
    ctx->sigSpec = sigSpec;
17163
    ctx->sigSpecSz = sigSpecSz;
17164
    return WOLFSSL_SUCCESS;
17165
}
17166
#endif /* WOLFSSL_DUAL_ALG_CERTS */
17167
17168
/* Do not send a ticket after TLS v1.3 handshake for resumption.
17169
 *
17170
 * ctx  The SSL/TLS CTX object.
17171
 * returns BAD_FUNC_ARG when ctx is NULL and 0 on success.
17172
 */
17173
int wolfSSL_CTX_no_ticket_TLSv13(WOLFSSL_CTX* ctx)
17174
0
{
17175
0
    if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
17176
0
        return BAD_FUNC_ARG;
17177
0
    if (ctx->method->side == WOLFSSL_CLIENT_END)
17178
0
        return SIDE_ERROR;
17179
17180
#ifdef HAVE_SESSION_TICKET
17181
    ctx->noTicketTls13 = 1;
17182
#endif
17183
17184
0
    return 0;
17185
0
}
17186
17187
/* Do not send a ticket after TLS v1.3 handshake for resumption.
17188
 *
17189
 * ssl  The SSL/TLS object.
17190
 * returns BAD_FUNC_ARG when ssl is NULL, not using TLS v1.3, or called on
17191
 * a client and 0 on success.
17192
 */
17193
int wolfSSL_no_ticket_TLSv13(WOLFSSL* ssl)
17194
0
{
17195
0
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
17196
0
        return BAD_FUNC_ARG;
17197
0
    if (ssl->options.side == WOLFSSL_CLIENT_END)
17198
0
        return SIDE_ERROR;
17199
17200
#ifdef HAVE_SESSION_TICKET
17201
    ssl->options.noTicketTls13 = 1;
17202
#endif
17203
17204
0
    return 0;
17205
0
}
17206
17207
/* Disallow (EC)DHE key exchange when using pre-shared keys.
17208
 *
17209
 * ctx  The SSL/TLS CTX object.
17210
 * returns BAD_FUNC_ARG when ctx is NULL and 0 on success.
17211
 */
17212
int wolfSSL_CTX_no_dhe_psk(WOLFSSL_CTX* ctx)
17213
0
{
17214
0
    if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
17215
0
        return BAD_FUNC_ARG;
17216
17217
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
17218
    ctx->noPskDheKe = 1;
17219
#endif
17220
17221
0
    return 0;
17222
0
}
17223
17224
/* Disallow (EC)DHE key exchange when using pre-shared keys.
17225
 *
17226
 * ssl  The SSL/TLS object.
17227
 * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3 and 0 on
17228
 * success.
17229
 */
17230
int wolfSSL_no_dhe_psk(WOLFSSL* ssl)
17231
0
{
17232
0
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
17233
0
        return BAD_FUNC_ARG;
17234
17235
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
17236
    ssl->options.noPskDheKe = 1;
17237
    ssl->options.noPskDheKePolicy = 1;
17238
#endif
17239
17240
0
    return 0;
17241
0
}
17242
17243
#ifdef HAVE_SUPPORTED_CURVES
17244
/* Only allow (EC)DHE key exchange when using pre-shared keys.
17245
 *
17246
 * ctx  The SSL/TLS CTX object.
17247
 * returns BAD_FUNC_ARG when ctx is NULL and 0 on success.
17248
 */
17249
int wolfSSL_CTX_only_dhe_psk(WOLFSSL_CTX* ctx)
17250
0
{
17251
0
    if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
17252
0
        return BAD_FUNC_ARG;
17253
17254
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
17255
    ctx->onlyPskDheKe = 1;
17256
#endif
17257
17258
0
    return 0;
17259
0
}
17260
17261
/* Only allow (EC)DHE key exchange when using pre-shared keys.
17262
 *
17263
 * ssl  The SSL/TLS object.
17264
 * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3 and 0 on
17265
 * success.
17266
 */
17267
int wolfSSL_only_dhe_psk(WOLFSSL* ssl)
17268
0
{
17269
0
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
17270
0
        return BAD_FUNC_ARG;
17271
17272
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
17273
    ssl->options.onlyPskDheKe = 1;
17274
#endif
17275
17276
0
    return 0;
17277
0
}
17278
#endif /* HAVE_SUPPORTED_CURVES */
17279
17280
/* Require that an external Pre-Shared Key is negotiated for the handshake to
17281
 * succeed. TLS 1.3 / DTLS 1.3 only - in (D)TLS 1.2 the use of a PSK is
17282
 * determined by the negotiated cipher suite, so a mandatory PSK is configured
17283
 * there by restricting the cipher suite list to PSK suites.
17284
 *
17285
 * ctx  The SSL/TLS CTX object.
17286
 * returns BAD_FUNC_ARG when ctx is NULL or not at least TLS v1.3, 0 on success.
17287
 */
17288
int wolfSSL_CTX_require_psk(WOLFSSL_CTX* ctx)
17289
0
{
17290
0
    if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
17291
0
        return BAD_FUNC_ARG;
17292
17293
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
17294
    ctx->failNoPSK = 1;
17295
    /* The requirement can only be enforced for (D)TLS 1.3, so keep it
17296
     * fail-closed by disabling a version downgrade. Otherwise a
17297
     * downgrade-capable context (e.g. from a v23 method) could silently fall
17298
     * back to (D)TLS 1.2 and complete without any PSK. */
17299
    ctx->method->downgrade = 0;
17300
#endif
17301
17302
0
    return 0;
17303
0
}
17304
17305
/* Require that an external Pre-Shared Key is negotiated for the handshake to
17306
 * succeed. See wolfSSL_CTX_require_psk().
17307
 *
17308
 * ssl  The SSL/TLS object.
17309
 * returns BAD_FUNC_ARG when ssl is NULL or not at least TLS v1.3, 0 on success.
17310
 */
17311
int wolfSSL_require_psk(WOLFSSL* ssl)
17312
0
{
17313
0
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
17314
0
        return BAD_FUNC_ARG;
17315
17316
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
17317
    ssl->options.failNoPSK = 1;
17318
    /* See wolfSSL_CTX_require_psk() - keep the requirement fail-closed by
17319
     * disabling a version downgrade to (D)TLS 1.2. */
17320
    ssl->options.downgrade = 0;
17321
#endif
17322
17323
0
    return 0;
17324
0
}
17325
17326
int Tls13UpdateKeys(WOLFSSL* ssl)
17327
0
{
17328
0
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
17329
0
        return BAD_FUNC_ARG;
17330
17331
#ifdef WOLFSSL_QUIC
17332
    /* RFC 9001 Section 6: a QUIC connection must not send a TLS KeyUpdate;
17333
     * key updates are handled at the QUIC packet-protection layer. */
17334
    if (WOLFSSL_IS_QUIC(ssl))
17335
        return BAD_FUNC_ARG;
17336
#endif
17337
17338
#ifdef WOLFSSL_DTLS13
17339
    /* we are already waiting for the ack of a sent key update message. We can't
17340
       send another one before receiving its ack. Either wolfSSL_update_keys()
17341
       was invoked multiple times over a short period of time or we replied to a
17342
       KeyUpdate with update request. We'll just ignore sending this
17343
       KeyUpdate. */
17344
    /* TODO: add WOLFSSL_ERROR_ALREADY_IN_PROGRESS type of error here */
17345
    if (ssl->options.dtls && ssl->dtls13WaitKeyUpdateAck)
17346
        return 0;
17347
#endif /* WOLFSSL_DTLS13 */
17348
17349
0
    return SendTls13KeyUpdate(ssl);
17350
0
}
17351
17352
/* Update the keys for encryption and decryption.
17353
 * If using non-blocking I/O and WOLFSSL_ERROR_WANT_WRITE is returned then
17354
 * calling wolfSSL_write() will have the message sent when ready.
17355
 *
17356
 * ssl  The SSL/TLS object.
17357
 * returns BAD_FUNC_ARG when ssl is NULL, not using TLS v1.3, or running over
17358
 * QUIC (RFC 9001 handles key updates at the QUIC packet-protection layer),
17359
 * WOLFSSL_ERROR_WANT_WRITE when non-blocking I/O is not ready to write,
17360
 * WOLFSSL_SUCCESS on success and otherwise failure.
17361
 */
17362
int wolfSSL_update_keys(WOLFSSL* ssl)
17363
0
{
17364
0
    int ret;
17365
0
    ret = Tls13UpdateKeys(ssl);
17366
0
    if (ret == WC_NO_ERR_TRACE(WANT_WRITE))
17367
0
        ret = WOLFSSL_ERROR_WANT_WRITE;
17368
0
    else if (ret == 0)
17369
0
        ret = WOLFSSL_SUCCESS;
17370
0
    return ret;
17371
0
}
17372
17373
/* Whether a response is waiting for key update request.
17374
 *
17375
 * ssl        The SSL/TLS object.
17376
 * required   0 when no key update response required.
17377
 *            1 when no key update response required.
17378
 * return  0 on success.
17379
 * return  BAD_FUNC_ARG when ssl is NULL or not using TLS v1.3
17380
 */
17381
int wolfSSL_key_update_response(WOLFSSL* ssl, int* required)
17382
0
{
17383
0
    if (required == NULL || ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
17384
0
        return BAD_FUNC_ARG;
17385
17386
0
    *required = ssl->keys.updateResponseReq;
17387
17388
0
    return 0;
17389
0
}
17390
17391
#if !defined(NO_CERTS) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
17392
/* Allow post-handshake authentication in TLS v1.3 connections.
17393
 *
17394
 * ctx  The SSL/TLS CTX object.
17395
 * returns BAD_FUNC_ARG when ctx is NULL, SIDE_ERROR when not a client and
17396
 * 0 on success.
17397
 */
17398
int wolfSSL_CTX_allow_post_handshake_auth(WOLFSSL_CTX* ctx)
17399
{
17400
    if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
17401
        return BAD_FUNC_ARG;
17402
    if (ctx->method->side == WOLFSSL_SERVER_END)
17403
        return SIDE_ERROR;
17404
17405
    ctx->postHandshakeAuth = 1;
17406
17407
    return 0;
17408
}
17409
17410
/* Allow post-handshake authentication in TLS v1.3 connection.
17411
 *
17412
 * ssl  The SSL/TLS object.
17413
 * returns BAD_FUNC_ARG when ssl is NULL, not using TLS v1.3, or running over
17414
 * QUIC, SIDE_ERROR when not a client, BAD_STATE_E when called after the
17415
 * handshake has started, and 0 on success.
17416
 *
17417
 * Must be called before wolfSSL_connect() so the post_handshake_auth
17418
 * extension can be included in the ClientHello.
17419
 */
17420
int wolfSSL_allow_post_handshake_auth(WOLFSSL* ssl)
17421
{
17422
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
17423
        return BAD_FUNC_ARG;
17424
#ifdef WOLFSSL_QUIC
17425
    if (WOLFSSL_IS_QUIC(ssl))
17426
        return BAD_FUNC_ARG;
17427
#endif
17428
    if (ssl->options.side == WOLFSSL_SERVER_END)
17429
        return SIDE_ERROR;
17430
    if (ssl->options.handShakeState != NULL_STATE)
17431
        return BAD_STATE_E;
17432
17433
    ssl->options.postHandshakeAuth = 1;
17434
17435
    return 0;
17436
}
17437
17438
/* Request a certificate of the client.
17439
 * Can be called any time after handshake completion.
17440
 * A maximum of 256 requests can be sent on a connection.
17441
 *
17442
 * ssl  SSL/TLS object.
17443
 */
17444
int wolfSSL_request_certificate(WOLFSSL* ssl)
17445
{
17446
    int         ret;
17447
#ifndef NO_WOLFSSL_SERVER
17448
    CertReqCtx* certReqCtx;
17449
#endif
17450
17451
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
17452
        return BAD_FUNC_ARG;
17453
#ifdef WOLFSSL_QUIC
17454
    if (WOLFSSL_IS_QUIC(ssl))
17455
        return BAD_FUNC_ARG;
17456
#endif
17457
#ifndef NO_WOLFSSL_SERVER
17458
    if (ssl->options.side == WOLFSSL_CLIENT_END)
17459
        return SIDE_ERROR;
17460
    if (ssl->options.handShakeState != HANDSHAKE_DONE)
17461
        return NOT_READY_ERROR;
17462
    if (!ssl->options.postHandshakeAuth)
17463
        return POST_HAND_AUTH_ERROR;
17464
    if (ssl->certReqCtx != NULL) {
17465
        if (ssl->certReqCtx->len != 1)
17466
            return BAD_STATE_E;
17467
        /* We support sending up to 255 certificate requests */
17468
        if (ssl->certReqCtx->ctx == 255)
17469
            return BAD_STATE_E;
17470
    }
17471
17472
    certReqCtx = (CertReqCtx*)XMALLOC(sizeof(CertReqCtx), ssl->heap,
17473
                                                       DYNAMIC_TYPE_TMP_BUFFER);
17474
    if (certReqCtx == NULL)
17475
        return MEMORY_E;
17476
    XMEMSET(certReqCtx, 0, sizeof(CertReqCtx));
17477
    certReqCtx->next = ssl->certReqCtx;
17478
    certReqCtx->len = 1;
17479
    if (certReqCtx->next != NULL)
17480
        certReqCtx->ctx = certReqCtx->next->ctx + 1;
17481
    ssl->certReqCtx = certReqCtx;
17482
17483
    ssl->msgsReceived.got_certificate = 0;
17484
    ssl->msgsReceived.got_certificate_verify = 0;
17485
    ssl->msgsReceived.got_finished = 0;
17486
    /* Each round must prove possession again; these are only ever set to 1. */
17487
    ssl->options.havePeerCert = 0;
17488
    ssl->options.havePeerVerify = 0;
17489
17490
    ret = SendTls13CertificateRequest(ssl, &certReqCtx->ctx, certReqCtx->len);
17491
    if (ret == WC_NO_ERR_TRACE(WANT_WRITE))
17492
        ret = WOLFSSL_ERROR_WANT_WRITE;
17493
    else if (ret == 0)
17494
        ret = WOLFSSL_SUCCESS;
17495
#else
17496
    ret = SIDE_ERROR;
17497
#endif
17498
17499
    return ret;
17500
}
17501
#endif /* !NO_CERTS && WOLFSSL_POST_HANDSHAKE_AUTH */
17502
17503
#if !defined(WOLFSSL_NO_SERVER_GROUPS_EXT)
17504
/* Get the preferred key exchange group.
17505
 *
17506
 * ssl  The SSL/TLS object.
17507
 * returns BAD_FUNC_ARG when ssl is NULL or not using TLS v1.3,
17508
 * SIDE_ERROR when not a client, NOT_READY_ERROR when handshake not complete
17509
 * and group number on success.
17510
 */
17511
int wolfSSL_preferred_group(WOLFSSL* ssl)
17512
0
{
17513
0
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
17514
0
        return BAD_FUNC_ARG;
17515
0
#ifndef NO_WOLFSSL_CLIENT
17516
0
    if (ssl->options.side == WOLFSSL_SERVER_END)
17517
0
        return SIDE_ERROR;
17518
0
    if (ssl->options.handShakeState != HANDSHAKE_DONE)
17519
0
        return NOT_READY_ERROR;
17520
17521
0
#ifdef HAVE_SUPPORTED_CURVES
17522
    /* Return supported groups only. */
17523
0
    return TLSX_SupportedCurve_Preferred(ssl, 1);
17524
#else
17525
    return 0;
17526
#endif
17527
#else
17528
    return SIDE_ERROR;
17529
#endif
17530
0
}
17531
#endif
17532
17533
#ifndef NO_PSK
17534
/* Set the PSK callback, that is passed the cipher suite, for a client to use
17535
 * against context object.
17536
 *
17537
 * @param [in, out] ctx  SSL/TLS context object.
17538
 * @param [in]      cb   Client PSK callback passed a cipher suite.
17539
 */
17540
void wolfSSL_CTX_set_psk_client_cs_callback(WOLFSSL_CTX* ctx,
17541
                                            wc_psk_client_cs_callback cb)
17542
{
17543
    WOLFSSL_ENTER("wolfSSL_CTX_set_psk_client_cs_callback");
17544
17545
    if (ctx == NULL)
17546
        return;
17547
17548
    ctx->havePSK = 1;
17549
    ctx->client_psk_cs_cb = cb;
17550
}
17551
17552
/* Set the PSK callback, that is passed the cipher suite, for a client to use
17553
 * against SSL object.
17554
 *
17555
 * @param [in, out] ssl  SSL/TLS object.
17556
 * @param [in]      cb   Client PSK callback passed a cipher suite.
17557
 */
17558
void wolfSSL_set_psk_client_cs_callback(WOLFSSL* ssl,
17559
                                        wc_psk_client_cs_callback cb)
17560
{
17561
    byte haveRSA = 1;
17562
    int  keySz   = 0;
17563
17564
    WOLFSSL_ENTER("wolfSSL_set_psk_client_cs_callback");
17565
17566
    if (ssl == NULL)
17567
        return;
17568
17569
    ssl->options.havePSK = 1;
17570
    ssl->options.client_psk_cs_cb = cb;
17571
17572
    #ifdef NO_RSA
17573
        haveRSA = 0;
17574
    #endif
17575
    #ifndef NO_CERTS
17576
        keySz = ssl->buffers.keySz;
17577
    #endif
17578
    if (AllocateSuites(ssl) != 0)
17579
        return;
17580
    InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE,
17581
               ssl->options.haveDH, ssl->options.haveECDSAsig,
17582
               ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
17583
               ssl->options.useAnon, TRUE, TRUE, TRUE, TRUE, ssl->options.side);
17584
}
17585
17586
/* Set the PSK callback that returns the cipher suite for a client to use
17587
 * against context object.
17588
 *
17589
 * @param [in, out] ctx  SSL/TLS context object.
17590
 * @param [in]      cb   Client PSK callback returning cipher suite.
17591
 */
17592
void wolfSSL_CTX_set_psk_client_tls13_callback(WOLFSSL_CTX* ctx,
17593
                                               wc_psk_client_tls13_callback cb)
17594
{
17595
    WOLFSSL_ENTER("wolfSSL_CTX_set_psk_client_tls13_callback");
17596
17597
    if (ctx == NULL)
17598
        return;
17599
17600
    ctx->havePSK = 1;
17601
    ctx->client_psk_tls13_cb = cb;
17602
}
17603
17604
/* Set the PSK callback that returns the cipher suite for a client to use
17605
 * against SSL object.
17606
 *
17607
 * @param [in, out] ssl  SSL/TLS object.
17608
 * @param [in]      cb   Client PSK callback returning cipher suite.
17609
 */
17610
void wolfSSL_set_psk_client_tls13_callback(WOLFSSL* ssl,
17611
                                           wc_psk_client_tls13_callback cb)
17612
{
17613
    byte haveRSA = 1;
17614
    int  keySz   = 0;
17615
17616
    WOLFSSL_ENTER("wolfSSL_set_psk_client_tls13_callback");
17617
17618
    if (ssl == NULL)
17619
        return;
17620
17621
    ssl->options.havePSK = 1;
17622
    ssl->options.client_psk_tls13_cb = cb;
17623
17624
    #ifdef NO_RSA
17625
        haveRSA = 0;
17626
    #endif
17627
    #ifndef NO_CERTS
17628
        keySz = ssl->buffers.keySz;
17629
    #endif
17630
    if (AllocateSuites(ssl) != 0)
17631
        return;
17632
    InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE,
17633
               ssl->options.haveDH, ssl->options.haveECDSAsig,
17634
               ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
17635
               ssl->options.useAnon, TRUE, TRUE, TRUE, TRUE, ssl->options.side);
17636
}
17637
17638
/* Set the PSK callback that returns the cipher suite for a server to use
17639
 * against context object.
17640
 *
17641
 * @param [in, out] ctx  SSL/TLS context object.
17642
 * @param [in]      cb   Server PSK callback returning cipher suite.
17643
 */
17644
void wolfSSL_CTX_set_psk_server_tls13_callback(WOLFSSL_CTX* ctx,
17645
                                               wc_psk_server_tls13_callback cb)
17646
{
17647
    WOLFSSL_ENTER("wolfSSL_CTX_set_psk_server_tls13_callback");
17648
    if (ctx == NULL)
17649
        return;
17650
    ctx->havePSK = 1;
17651
    ctx->server_psk_tls13_cb = cb;
17652
}
17653
17654
/* Set the PSK callback that returns the cipher suite for a server to use
17655
 * against SSL object.
17656
 *
17657
 * @param [in, out] ssl  SSL/TLS object.
17658
 * @param [in]      cb   Server PSK callback returning cipher suite.
17659
 */
17660
void wolfSSL_set_psk_server_tls13_callback(WOLFSSL* ssl,
17661
                                           wc_psk_server_tls13_callback cb)
17662
{
17663
    byte haveRSA = 1;
17664
    int  keySz   = 0;
17665
17666
    WOLFSSL_ENTER("wolfSSL_set_psk_server_tls13_callback");
17667
    if (ssl == NULL)
17668
        return;
17669
17670
    ssl->options.havePSK = 1;
17671
    ssl->options.server_psk_tls13_cb = cb;
17672
17673
    #ifdef NO_RSA
17674
        haveRSA = 0;
17675
    #endif
17676
    #ifndef NO_CERTS
17677
        keySz = ssl->buffers.keySz;
17678
    #endif
17679
    if (AllocateSuites(ssl) != 0)
17680
        return;
17681
    InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE,
17682
               ssl->options.haveDH, ssl->options.haveECDSAsig,
17683
               ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
17684
               ssl->options.useAnon, TRUE, TRUE, TRUE, TRUE, ssl->options.side);
17685
}
17686
17687
/* Get name of first supported cipher suite that uses the hash indicated.
17688
 *
17689
 * @param [in] ssl   SSL/TLS object.
17690
 * @param [in] hash  Name of hash algorithm. e.g. "SHA256", "SHA384"
17691
 * @return  Name of cipher suite.
17692
 * @return  NULL on failure.
17693
 */
17694
const char* wolfSSL_get_cipher_name_by_hash(WOLFSSL* ssl, const char* hash)
17695
{
17696
    const char* name = NULL;
17697
    byte mac = no_mac;
17698
    int i;
17699
    const Suites* suites;
17700
17701
    if (hash == NULL || ssl == NULL ||
17702
        (ssl->suites == NULL && ssl->ctx == NULL))
17703
        return NULL;
17704
17705
    suites = WOLFSSL_SUITES(ssl);
17706
    if (suites == NULL)
17707
        return NULL;
17708
17709
    if (XSTRCMP(hash, "SHA256") == 0) {
17710
        mac = sha256_mac;
17711
    }
17712
    else if (XSTRCMP(hash, "SHA384") == 0) {
17713
        mac = sha384_mac;
17714
    }
17715
    if (mac != no_mac) {
17716
        for (i = 0; i < suites->suiteSz; i += 2) {
17717
            if (SuiteMac(suites->suites + i) == mac) {
17718
                name = GetCipherNameInternal(suites->suites[i + 0],
17719
                                             suites->suites[i + 1]);
17720
                break;
17721
            }
17722
        }
17723
    }
17724
    return name;
17725
}
17726
#endif /* !NO_PSK */
17727
17728
17729
#ifndef NO_WOLFSSL_SERVER
17730
17731
/* Send the RFC 8446 Appendix D.4 ChangeCipherSpec a server owes a client that
17732
 * offered a non-empty legacy_session_id.
17733
 *
17734
 * ssl    The SSL/TLS object.
17735
 * flush  Force the record out on its own. A HelloRetryRequest needs this
17736
 *        because SendTls13ServerHello has already sent it, unlike a
17737
 *        ServerHello, which waits for the rest of its flight.
17738
 * returns 0 on success.
17739
 */
17740
static int SendTls13ServerChangeCipher(WOLFSSL* ssl, int flush)
17741
0
{
17742
0
    int ret;
17743
17744
    /* DoTls13ClientHello clears tls13MiddleBoxCompat for a QUIC peer, so the
17745
     * check here is a local backstop, 0 when QUIC is not built. */
17746
0
    if (ssl->options.dtls || WOLFSSL_IS_QUIC(ssl)
17747
0
            || !ssl->options.tls13MiddleBoxCompat
17748
0
            || ssl->options.sentChangeCipher) {
17749
0
        return 0;
17750
0
    }
17751
17752
0
    ret = SendChangeCipher(ssl);
17753
    /* A short send leaves the record queued in the output buffer. Mark it sent
17754
     * anyway, or the resumed accept, which comes back in at the ServerHello
17755
     * case, puts a second record on the wire. */
17756
0
    if (ret == 0 || ret == WC_NO_ERR_TRACE(WANT_WRITE))
17757
0
        ssl->options.sentChangeCipher = 1;
17758
0
    if (ret == 0 && flush && ssl->options.groupMessages)
17759
0
        ret = SendBuffered(ssl);
17760
17761
0
    return ret;
17762
0
}
17763
17764
/* The server accepting a connection from a client.
17765
 * The protocol version is expecting to be TLS v1.3.
17766
 * If the client downgrades, and older versions of the protocol are compiled
17767
 * in, the server will fallback to wolfSSL_accept().
17768
 * Please see note at top of README if you get an error from accept.
17769
 *
17770
 * ssl  The SSL/TLS object.
17771
 * returns WOLFSSL_SUCCESS on successful handshake, WOLFSSL_FATAL_ERROR when
17772
 * unrecoverable error occurs and 0 otherwise.
17773
 * For more error information use wolfSSL_get_error().
17774
 */
17775
int wolfSSL_accept_TLSv13(WOLFSSL* ssl)
17776
0
{
17777
#if !defined(NO_CERTS) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
17778
    word16 havePSK = 0;
17779
#endif
17780
0
    int ret = 0;
17781
17782
0
    WOLFSSL_ENTER("wolfSSL_accept_TLSv13");
17783
17784
0
#ifdef HAVE_ERRNO_H
17785
0
    errno = 0;
17786
0
#endif
17787
17788
0
    if (ssl == NULL)
17789
0
        return WOLFSSL_FATAL_ERROR;
17790
17791
#if !defined(NO_CERTS) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
17792
    havePSK = ssl->options.havePSK;
17793
#endif
17794
17795
0
    if (ssl->options.side != WOLFSSL_SERVER_END) {
17796
0
        ssl->error = SIDE_ERROR;
17797
0
        WOLFSSL_ERROR(ssl->error);
17798
0
        return WOLFSSL_FATAL_ERROR;
17799
0
    }
17800
17801
    /* make sure this wolfSSL object has arrays and rng setup. Protects
17802
     * case where the WOLFSSL object is reused via wolfSSL_clear() */
17803
0
    if ((ret = ReinitSSL(ssl, ssl->ctx, 0)) != 0) {
17804
0
        return ret;
17805
0
    }
17806
17807
#ifdef WOLFSSL_DTLS
17808
    if (ssl->version.major == DTLS_MAJOR) {
17809
        ssl->options.dtls   = 1;
17810
        if (!IsDtlsNotSctpMode(ssl) || !ssl->options.sendCookie)
17811
            ssl->options.dtlsStateful = 1;
17812
    }
17813
#endif
17814
17815
#ifdef WOLFSSL_WOLFSENTRY_HOOKS
17816
    if ((ssl->AcceptFilter != NULL) &&
17817
            ((ssl->options.acceptState == TLS13_ACCEPT_BEGIN)
17818
#ifdef HAVE_SECURE_RENEGOTIATION
17819
             || (ssl->options.acceptState == TLS13_ACCEPT_BEGIN_RENEG)
17820
#endif
17821
                ))
17822
    {
17823
        wolfSSL_netfilter_decision_t res;
17824
        if ((ssl->AcceptFilter(ssl, ssl->AcceptFilter_arg, &res) ==
17825
             WOLFSSL_SUCCESS) &&
17826
            (res == WOLFSSL_NETFILTER_REJECT)) {
17827
            ssl->error = SOCKET_FILTERED_E;
17828
            WOLFSSL_ERROR(ssl->error);
17829
            return WOLFSSL_FATAL_ERROR;
17830
        }
17831
    }
17832
#endif /* WOLFSSL_WOLFSENTRY_HOOKS */
17833
17834
0
#ifndef NO_CERTS
17835
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
17836
    if (!havePSK)
17837
#endif
17838
0
    {
17839
    #if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) || \
17840
        defined(WOLFSSL_NGINX) || defined (WOLFSSL_HAPROXY)
17841
        if (ssl->ctx->certSetupCb != NULL) {
17842
            WOLFSSL_MSG("CertSetupCb set. server cert and "
17843
                        "key not checked");
17844
        }
17845
        else
17846
    #endif
17847
0
        {
17848
0
            if (!ssl->buffers.certificate ||
17849
0
                !ssl->buffers.certificate->buffer) {
17850
17851
0
                WOLFSSL_MSG("accept error: server cert required");
17852
0
                ssl->error = NO_PRIVATE_KEY;
17853
0
                WOLFSSL_ERROR(ssl->error);
17854
0
                return WOLFSSL_FATAL_ERROR;
17855
0
            }
17856
17857
0
            if (!ssl->buffers.key || !ssl->buffers.key->buffer) {
17858
                /* allow no private key if using existing key */
17859
            #ifdef WOLF_PRIVATE_KEY_ID
17860
                if (ssl->devId != INVALID_DEVID
17861
                #ifdef HAVE_PK_CALLBACKS
17862
                    || wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)
17863
                #endif
17864
                ) {
17865
                    WOLFSSL_MSG("Allowing no server private key (external)");
17866
                }
17867
                else
17868
            #endif
17869
0
                {
17870
0
                    WOLFSSL_MSG("accept error: server key required");
17871
0
                    ssl->error = NO_PRIVATE_KEY;
17872
0
                    WOLFSSL_ERROR(ssl->error);
17873
0
                    return WOLFSSL_FATAL_ERROR;
17874
0
                }
17875
0
            }
17876
0
        }
17877
0
    }
17878
0
#endif /* NO_CERTS */
17879
17880
0
    if (ssl->buffers.outputBuffer.length > 0
17881
    #ifdef WOLFSSL_ASYNC_CRYPT
17882
        /* do not send buffered or advance state if last error was an
17883
            async pending operation */
17884
        && ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E)
17885
    #endif
17886
0
    ) {
17887
17888
        /* fragOffset is non-zero when sending fragments. On the last
17889
         * fragment, fragOffset is zero again, and the state can be
17890
         * advanced. */
17891
0
        int advanceState =
17892
0
            (ssl->options.acceptState == TLS13_ACCEPT_CLIENT_HELLO_DONE ||
17893
0
                ssl->options.acceptState ==
17894
0
                    TLS13_ACCEPT_HELLO_RETRY_REQUEST_DONE ||
17895
0
                ssl->options.acceptState == TLS13_ACCEPT_SECOND_REPLY_DONE ||
17896
0
                ssl->options.acceptState == TLS13_SERVER_HELLO_SENT ||
17897
0
                ssl->options.acceptState == TLS13_ACCEPT_THIRD_REPLY_DONE ||
17898
0
                ssl->options.acceptState == TLS13_SERVER_EXTENSIONS_SENT ||
17899
0
                ssl->options.acceptState == TLS13_CERT_REQ_SENT ||
17900
0
                ssl->options.acceptState == TLS13_CERT_SENT ||
17901
0
                ssl->options.acceptState == TLS13_CERT_VERIFY_SENT ||
17902
0
                ssl->options.acceptState == TLS13_ACCEPT_FINISHED_SENT ||
17903
0
                ssl->options.acceptState == TLS13_ACCEPT_FINISHED_DONE);
17904
17905
#ifdef WOLFSSL_DTLS13
17906
        if (ssl->options.dtls)
17907
            advanceState = advanceState && !ssl->dtls13SendingFragments
17908
                && !ssl->dtls13SendingAckOrRtx;
17909
#endif /* WOLFSSL_DTLS13 */
17910
17911
0
        ret = SendBuffered(ssl);
17912
0
        if (ret == 0) {
17913
0
            if (ssl->fragOffset == 0 && !ssl->options.buildingMsg) {
17914
0
                if (advanceState) {
17915
0
                    ssl->options.acceptState++;
17916
0
                    WOLFSSL_MSG("accept state: "
17917
0
                                "Advanced from last buffered fragment send");
17918
0
#ifdef WOLFSSL_ASYNC_IO
17919
0
                    FreeAsyncCtx(ssl, 0);
17920
0
#endif
17921
0
                }
17922
0
            }
17923
0
            else {
17924
0
                WOLFSSL_MSG("accept state: "
17925
0
                            "Not advanced, more fragments to send");
17926
0
            }
17927
17928
#ifdef WOLFSSL_DTLS13
17929
            if (ssl->options.dtls)
17930
                ssl->dtls13SendingAckOrRtx = 0;
17931
#endif /* WOLFSSL_DTLS13 */
17932
17933
0
        }
17934
0
        else {
17935
0
            ssl->error = ret;
17936
0
            WOLFSSL_ERROR(ssl->error);
17937
0
            return WOLFSSL_FATAL_ERROR;
17938
0
        }
17939
0
    }
17940
17941
0
    ret = RetrySendAlert(ssl);
17942
0
    if (ret != 0) {
17943
0
        ssl->error = ret;
17944
0
        WOLFSSL_ERROR(ssl->error);
17945
0
        return WOLFSSL_FATAL_ERROR;
17946
0
    }
17947
#ifdef WOLFSSL_DTLS13
17948
    if (ssl->options.dtls && ssl->dtls13SendingFragments) {
17949
        if ((ssl->error = Dtls13FragmentsContinue(ssl)) != 0) {
17950
                WOLFSSL_ERROR(ssl->error);
17951
                return WOLFSSL_FATAL_ERROR;
17952
        }
17953
17954
        /* we sent all the fragments. Advance state. */
17955
        ssl->options.acceptState++;
17956
    }
17957
#endif /* WOLFSSL_DTLS13 */
17958
17959
0
    switch (ssl->options.acceptState) {
17960
17961
#ifdef HAVE_SECURE_RENEGOTIATION
17962
        case TLS13_ACCEPT_BEGIN_RENEG:
17963
#endif
17964
0
        case TLS13_ACCEPT_BEGIN :
17965
            /* get client_hello */
17966
17967
0
            while (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
17968
0
                if ((ssl->error = ProcessReply(ssl)) < 0) {
17969
0
                    WOLFSSL_ERROR(ssl->error);
17970
0
                    return WOLFSSL_FATAL_ERROR;
17971
0
                }
17972
17973
#ifdef WOLFSSL_DTLS13
17974
                if (ssl->options.dtls) {
17975
                    if ((ssl->error = Dtls13DoScheduledWork(ssl)) < 0) {
17976
                        WOLFSSL_ERROR(ssl->error);
17977
                        return WOLFSSL_FATAL_ERROR;
17978
                    }
17979
                }
17980
#endif /* WOLFSSL_DTLS13 */
17981
17982
0
            }
17983
17984
0
            ssl->options.acceptState = TLS13_ACCEPT_CLIENT_HELLO_DONE;
17985
0
            WOLFSSL_MSG("accept state ACCEPT_CLIENT_HELLO_DONE");
17986
0
            if (!IsAtLeastTLSv1_3(ssl->version))
17987
0
                return wolfSSL_accept(ssl);
17988
0
            FALL_THROUGH;
17989
17990
0
        case TLS13_ACCEPT_CLIENT_HELLO_DONE :
17991
0
            if (ssl->options.serverState ==
17992
0
                                          SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
17993
0
                if ((ssl->error = SendTls13ServerHello(ssl,
17994
0
                                                   hello_retry_request)) != 0) {
17995
0
                    WOLFSSL_ERROR(ssl->error);
17996
0
                    return WOLFSSL_FATAL_ERROR;
17997
0
                }
17998
0
            }
17999
18000
0
            ssl->options.acceptState = TLS13_ACCEPT_HELLO_RETRY_REQUEST_DONE;
18001
0
            WOLFSSL_MSG("accept state ACCEPT_HELLO_RETRY_REQUEST_DONE");
18002
0
            FALL_THROUGH;
18003
18004
0
        case TLS13_ACCEPT_HELLO_RETRY_REQUEST_DONE :
18005
0
            if (ssl->options.serverState ==
18006
0
                                          SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
18007
0
                ssl->error = SendTls13ServerChangeCipher(ssl, 1);
18008
0
                if (ssl->error != 0) {
18009
0
                    WOLFSSL_ERROR(ssl->error);
18010
0
                    return WOLFSSL_FATAL_ERROR;
18011
0
                }
18012
0
            }
18013
0
            ssl->options.acceptState = TLS13_ACCEPT_FIRST_REPLY_DONE;
18014
0
            WOLFSSL_MSG("accept state ACCEPT_FIRST_REPLY_DONE");
18015
0
            FALL_THROUGH;
18016
18017
0
        case TLS13_ACCEPT_FIRST_REPLY_DONE :
18018
0
            if (ssl->options.serverState ==
18019
0
                                          SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
18020
0
                ssl->options.clientState = CLIENT_HELLO_RETRY;
18021
0
                while (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
18022
0
                    if ((ssl->error = ProcessReply(ssl)) < 0) {
18023
0
                        WOLFSSL_ERROR(ssl->error);
18024
0
                        return WOLFSSL_FATAL_ERROR;
18025
0
                    }
18026
18027
#ifdef WOLFSSL_DTLS13
18028
                if (ssl->options.dtls) {
18029
                    if ((ssl->error = Dtls13DoScheduledWork(ssl)) < 0) {
18030
                        WOLFSSL_ERROR(ssl->error);
18031
                        return WOLFSSL_FATAL_ERROR;
18032
                    }
18033
                }
18034
#endif /* WOLFSSL_DTLS13 */
18035
18036
0
                }
18037
0
            }
18038
18039
0
            ssl->options.acceptState = TLS13_ACCEPT_SECOND_REPLY_DONE;
18040
0
            WOLFSSL_MSG("accept state ACCEPT_SECOND_REPLY_DONE");
18041
0
            FALL_THROUGH;
18042
18043
0
        case TLS13_ACCEPT_SECOND_REPLY_DONE :
18044
0
            if (ssl->options.returnOnGoodCh) {
18045
                /* Higher level in stack wants us to return. Simulate a
18046
                 * WANT_WRITE to accomplish this. */
18047
0
                ssl->error = WANT_WRITE;
18048
0
                return WOLFSSL_FATAL_ERROR;
18049
0
            }
18050
18051
0
            if ((ssl->error = SendTls13ServerHello(ssl, server_hello)) != 0) {
18052
0
                WOLFSSL_ERROR(ssl->error);
18053
0
                return WOLFSSL_FATAL_ERROR;
18054
0
            }
18055
0
            ssl->options.acceptState = TLS13_SERVER_HELLO_SENT;
18056
0
            WOLFSSL_MSG("accept state SERVER_HELLO_SENT");
18057
0
            FALL_THROUGH;
18058
18059
0
        case TLS13_SERVER_HELLO_SENT :
18060
0
            ssl->error = SendTls13ServerChangeCipher(ssl, 0);
18061
0
            if (ssl->error != 0) {
18062
0
                WOLFSSL_ERROR(ssl->error);
18063
0
                return WOLFSSL_FATAL_ERROR;
18064
0
            }
18065
18066
0
            ssl->options.acceptState = TLS13_ACCEPT_THIRD_REPLY_DONE;
18067
0
            WOLFSSL_MSG("accept state ACCEPT_THIRD_REPLY_DONE");
18068
0
            FALL_THROUGH;
18069
18070
0
        case TLS13_ACCEPT_THIRD_REPLY_DONE :
18071
0
    #ifdef HAVE_SUPPORTED_CURVES
18072
        #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
18073
            if (!ssl->options.noPskDheKe)
18074
        #endif
18075
0
            {
18076
0
                ssl->error = TLSX_KeyShare_DeriveSecret(ssl);
18077
0
                if (ssl->error != 0)
18078
0
                    return WOLFSSL_FATAL_ERROR;
18079
0
            }
18080
0
    #endif
18081
18082
0
            if ((ssl->error = SendTls13EncryptedExtensions(ssl)) != 0) {
18083
0
                WOLFSSL_ERROR(ssl->error);
18084
0
                return WOLFSSL_FATAL_ERROR;
18085
0
            }
18086
0
            ssl->options.acceptState = TLS13_SERVER_EXTENSIONS_SENT;
18087
0
            WOLFSSL_MSG("accept state SERVER_EXTENSIONS_SENT");
18088
0
            FALL_THROUGH;
18089
18090
0
        case TLS13_SERVER_EXTENSIONS_SENT :
18091
0
#ifndef NO_CERTS
18092
0
            if (!ssl->options.resuming) {
18093
0
                if (ssl->options.verifyPeer
18094
    #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
18095
                    && !ssl->options.verifyPostHandshake
18096
    #endif
18097
0
                   ) {
18098
0
                    ssl->error = SendTls13CertificateRequest(ssl, NULL, 0);
18099
0
                    if (ssl->error != 0) {
18100
0
                        WOLFSSL_ERROR(ssl->error);
18101
0
                        return WOLFSSL_FATAL_ERROR;
18102
0
                    }
18103
0
                }
18104
0
                else {
18105
                    /* SERVER: Peer auth good if not verifying client. */
18106
0
                    ssl->options.peerAuthGood = 1;
18107
0
                }
18108
0
            }
18109
0
#endif
18110
0
            ssl->options.acceptState = TLS13_CERT_REQ_SENT;
18111
0
            WOLFSSL_MSG("accept state CERT_REQ_SENT");
18112
0
            FALL_THROUGH;
18113
18114
0
        case TLS13_CERT_REQ_SENT :
18115
0
#ifndef NO_CERTS
18116
0
            if (!ssl->options.resuming && ssl->options.sendVerify) {
18117
0
                if ((ssl->error = SendTls13Certificate(ssl)) != 0) {
18118
0
                    WOLFSSL_ERROR(ssl->error);
18119
0
                    return WOLFSSL_FATAL_ERROR;
18120
0
                }
18121
0
            }
18122
0
#endif
18123
0
            ssl->options.acceptState = TLS13_CERT_SENT;
18124
0
            WOLFSSL_MSG("accept state CERT_SENT");
18125
0
            FALL_THROUGH;
18126
18127
0
        case TLS13_CERT_SENT :
18128
0
#if !defined(NO_CERTS) && (!defined(NO_RSA) || defined(HAVE_ECC) || \
18129
0
     defined(HAVE_ED25519) || defined(HAVE_ED448) || defined(HAVE_FALCON) || \
18130
0
     defined(WOLFSSL_HAVE_MLDSA) || defined(WOLFSSL_HAVE_SLHDSA))
18131
0
            if (!ssl->options.resuming && ssl->options.sendVerify) {
18132
0
                if ((ssl->error = SendTls13CertificateVerify(ssl)) != 0) {
18133
0
                    WOLFSSL_ERROR(ssl->error);
18134
0
                    return WOLFSSL_FATAL_ERROR;
18135
0
                }
18136
0
            }
18137
0
#endif
18138
0
            ssl->options.acceptState = TLS13_CERT_VERIFY_SENT;
18139
0
            WOLFSSL_MSG("accept state CERT_VERIFY_SENT");
18140
0
            FALL_THROUGH;
18141
18142
0
        case TLS13_CERT_VERIFY_SENT :
18143
0
            if ((ssl->error = SendTls13Finished(ssl)) != 0) {
18144
0
                WOLFSSL_ERROR(ssl->error);
18145
0
                return WOLFSSL_FATAL_ERROR;
18146
0
            }
18147
18148
0
            ssl->options.acceptState = TLS13_ACCEPT_FINISHED_SENT;
18149
0
            WOLFSSL_MSG("accept state ACCEPT_FINISHED_SENT");
18150
0
            FALL_THROUGH;
18151
18152
0
        case TLS13_ACCEPT_FINISHED_SENT:
18153
#ifdef WOLFSSL_EARLY_DATA
18154
            if (ssl->earlyData != no_early_data &&
18155
                    ssl->options.handShakeState != SERVER_FINISHED_COMPLETE) {
18156
                ssl->options.handShakeState = SERVER_FINISHED_COMPLETE;
18157
                return WOLFSSL_SUCCESS;
18158
            }
18159
#endif
18160
#ifdef HAVE_SESSION_TICKET
18161
    #ifdef WOLFSSL_TLS13_TICKET_BEFORE_FINISHED
18162
            if (!ssl->options.verifyPeer && !ssl->options.noTicketTls13 &&
18163
                    ssl->ctx->ticketEncCb != NULL &&
18164
                    ssl->options.maxTicketTls13 > 0) {
18165
                if ((ssl->error = SendTls13NewSessionTicket(ssl)) != 0) {
18166
                    WOLFSSL_ERROR(ssl->error);
18167
                    return WOLFSSL_FATAL_ERROR;
18168
                }
18169
                ssl->options.ticketsSent = 1;
18170
            }
18171
    #endif
18172
#endif /* HAVE_SESSION_TICKET */
18173
0
            ssl->options.acceptState = TLS13_PRE_TICKET_SENT;
18174
0
            WOLFSSL_MSG("accept state  TICKET_SENT");
18175
0
            FALL_THROUGH;
18176
18177
0
        case TLS13_PRE_TICKET_SENT :
18178
0
            while (ssl->options.clientState < CLIENT_FINISHED_COMPLETE) {
18179
0
                if ( (ssl->error = ProcessReply(ssl)) < 0) {
18180
0
                        WOLFSSL_ERROR(ssl->error);
18181
0
                        return WOLFSSL_FATAL_ERROR;
18182
0
                    }
18183
18184
#ifdef WOLFSSL_DTLS13
18185
                if (ssl->options.dtls) {
18186
                    if ((ssl->error = Dtls13DoScheduledWork(ssl)) < 0) {
18187
                        WOLFSSL_ERROR(ssl->error);
18188
                        return WOLFSSL_FATAL_ERROR;
18189
                    }
18190
                }
18191
#endif /* WOLFSSL_DTLS13 */
18192
0
            }
18193
18194
            /* Finish a key schedule the Finished handler left pending:
18195
             * it must complete before this side's sends advance the
18196
             * transcript the traffic secrets hash. */
18197
0
            if (ssl->kdfMsgStep > 0) {
18198
0
                ssl->error = DoTls13MsgDerives(ssl, ssl->kdfMsgType);
18199
0
                if (ssl->error != 0) {
18200
0
                    WOLFSSL_ERROR(ssl->error);
18201
0
                    return WOLFSSL_FATAL_ERROR;
18202
0
                }
18203
0
            }
18204
18205
0
            ssl->options.acceptState = TLS13_ACCEPT_FINISHED_DONE;
18206
0
            WOLFSSL_MSG("accept state ACCEPT_FINISHED_DONE");
18207
0
            FALL_THROUGH;
18208
18209
0
        case TLS13_ACCEPT_FINISHED_DONE :
18210
            /* SERVER: When not resuming and verifying peer but no certificate
18211
             * received and not failing when not received then peer auth good.
18212
             */
18213
0
            if (!ssl->options.resuming && ssl->options.verifyPeer &&
18214
        #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
18215
                !ssl->options.verifyPostHandshake &&
18216
        #endif
18217
0
                !ssl->options.havePeerCert && !ssl->options.failNoCert) {
18218
0
                ssl->options.peerAuthGood = 1;
18219
0
            }
18220
            /* SERVER: check peer authentication. */
18221
0
            if (!ssl->options.peerAuthGood) {
18222
0
                WOLFSSL_MSG("Client authentication did not happen");
18223
0
                return WOLFSSL_FATAL_ERROR;
18224
0
            }
18225
#ifdef HAVE_SESSION_TICKET
18226
            while (ssl->options.ticketsSent < ssl->options.maxTicketTls13) {
18227
                if (!ssl->options.noTicketTls13 && ssl->ctx->ticketEncCb
18228
                        != NULL) {
18229
                    if ((ssl->error = SendTls13NewSessionTicket(ssl)) != 0) {
18230
                        WOLFSSL_ERROR(ssl->error);
18231
                        return WOLFSSL_FATAL_ERROR;
18232
                    }
18233
                }
18234
                ssl->options.ticketsSent++;
18235
18236
                /* only one session ticket is sent on session resumption */
18237
                if (ssl->options.resuming) {
18238
                    break;
18239
                }
18240
            }
18241
#endif /* HAVE_SESSION_TICKET */
18242
0
            ssl->options.acceptState = TLS13_TICKET_SENT;
18243
0
            WOLFSSL_MSG("accept state TICKET_SENT");
18244
0
            FALL_THROUGH;
18245
18246
0
        case TLS13_TICKET_SENT :
18247
0
#ifndef NO_HANDSHAKE_DONE_CB
18248
0
            if (ssl->hsDoneCb) {
18249
0
                int cbret = ssl->hsDoneCb(ssl, ssl->hsDoneCtx);
18250
0
                if (cbret < 0) {
18251
0
                    ssl->error = cbret;
18252
0
                    WOLFSSL_MSG("HandShake Done Cb don't continue error");
18253
0
                    return WOLFSSL_FATAL_ERROR;
18254
0
                }
18255
0
            }
18256
0
#endif /* NO_HANDSHAKE_DONE_CB */
18257
18258
0
            if (!ssl->options.keepResources) {
18259
0
                FreeHandshakeResources(ssl);
18260
0
            }
18261
18262
0
#if defined(WOLFSSL_ASYNC_IO) && !defined(WOLFSSL_ASYNC_CRYPT)
18263
            /* Free the remaining async context if not using it for crypto */
18264
0
            FreeAsyncCtx(ssl, 1);
18265
0
#endif
18266
18267
0
            ssl->error = 0; /* clear the error */
18268
18269
0
            WOLFSSL_LEAVE("wolfSSL_accept", WOLFSSL_SUCCESS);
18270
0
            return WOLFSSL_SUCCESS;
18271
18272
0
        default:
18273
0
            WOLFSSL_MSG("Unknown accept state ERROR");
18274
0
            return WOLFSSL_FATAL_ERROR;
18275
0
    }
18276
0
}
18277
#endif
18278
18279
#if !defined(NO_WOLFSSL_SERVER) && defined(HAVE_SESSION_TICKET)
18280
/* Server sends a session ticket to the peer.
18281
 *
18282
 * RFC 8446, section 4.6.1, para 1.
18283
 *
18284
 * ssl  The SSL/TLS object.
18285
 * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3,
18286
 *         SIDE_ERROR when not a server,
18287
 *         NOT_READY_ERROR when handshake not complete,
18288
 *         MISSING_HANDSHAKE_DATA when the ClientHello had no
18289
 *         psk_key_exchange_modes extension and
18290
 *         WOLFSSL_TLS13_TICKET_CHECK_PSK_MODES is defined,
18291
 *         PSK_KEY_ERROR when no advertised PSK key exchange mode is usable and
18292
 *         WOLFSSL_TLS13_TICKET_CHECK_PSK_MODES is defined,
18293
 *         WOLFSSL_FATAL_ERROR when creating or sending message fails, and
18294
 *         WOLFSSL_SUCCESS on success.
18295
 */
18296
int wolfSSL_send_SessionTicket(WOLFSSL* ssl)
18297
{
18298
    int ret;
18299
18300
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
18301
        return BAD_FUNC_ARG;
18302
    if (ssl->options.side == WOLFSSL_CLIENT_END)
18303
        return SIDE_ERROR;
18304
    if (ssl->options.handShakeState != HANDSHAKE_DONE)
18305
        return NOT_READY_ERROR;
18306
    ret = CheckTls13TicketPskModes(ssl);
18307
    if (ret != 0) {
18308
        WOLFSSL_ERROR_VERBOSE(ret);
18309
        return ret;
18310
    }
18311
18312
    if ((ssl->error = SendTls13NewSessionTicket(ssl)) != 0) {
18313
        WOLFSSL_ERROR(ssl->error);
18314
        return WOLFSSL_FATAL_ERROR;
18315
    }
18316
    ssl->options.ticketsSent++;
18317
18318
    return WOLFSSL_SUCCESS;
18319
}
18320
#endif
18321
18322
#ifdef WOLFSSL_EARLY_DATA
18323
/* Sets the maximum amount of early data that can be seen by server when using
18324
 * session tickets for resumption.
18325
 * A value of zero indicates no early data is to be sent by client using session
18326
 * tickets.
18327
 *
18328
 * The default value is zero: per RFC 8446 Appendix E.5, TLS implementations
18329
 * "MUST NOT enable 0-RTT (either sending or accepting) unless specifically
18330
 * requested by the application." Servers must explicitly opt in by calling
18331
 * this function (or the per-SSL equivalent) with a non-zero value.
18332
 *
18333
 * ctx  The SSL/TLS CTX object.
18334
 * sz   Maximum size of the early data.
18335
 * returns BAD_FUNC_ARG when ctx is NULL, SIDE_ERROR when not a server and
18336
 * 0 on success.
18337
 */
18338
int wolfSSL_CTX_set_max_early_data(WOLFSSL_CTX* ctx, unsigned int sz)
18339
{
18340
    if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
18341
        return BAD_FUNC_ARG;
18342
    if (ctx->method->side == WOLFSSL_CLIENT_END)
18343
        return SIDE_ERROR;
18344
18345
    ctx->maxEarlyDataSz = sz;
18346
18347
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_ERROR_CODE_OPENSSL)
18348
    /* 1 on success in OpenSSL*/
18349
    return WOLFSSL_SUCCESS;
18350
#else
18351
    return 0;
18352
#endif
18353
}
18354
18355
/* Disable the RFC 8446 Section 8.2 fresh start protection. Early data is
18356
 * then accepted for tickets minted before this ctx was created. Only use
18357
 * this when the anti-replay state reliably survives server restarts.
18358
 *
18359
 * The check needs TimeNowInMilliseconds() to be comparable across restarts.
18360
 * On ports where it counts from boot the check never fires for tickets
18361
 * minted before a reboot.
18362
 *
18363
 * ctx  The SSL/TLS CTX object.
18364
 * returns BAD_FUNC_ARG when ctx is NULL or not TLS v1.3, SIDE_ERROR when
18365
 * called with a client and 0 on success.
18366
 */
18367
int wolfSSL_CTX_no_early_data_fresh_start_check(WOLFSSL_CTX* ctx)
18368
{
18369
    if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
18370
        return BAD_FUNC_ARG;
18371
    if (ctx->method->side == WOLFSSL_CLIENT_END)
18372
        return SIDE_ERROR;
18373
18374
#ifdef HAVE_SESSION_TICKET
18375
    ctx->noFreshStartCheck = 1;
18376
#endif
18377
18378
    return 0;
18379
}
18380
18381
/* Sets the maximum amount of early data that a client or server would like
18382
 * to exchange. Servers will advertise this value in session tickets sent
18383
 * to a client.
18384
 * A value of zero indicates no early data will be sent by a client, or
18385
 * no early data is accepted by a server (and announced as such in send out
18386
 * session tickets).
18387
 *
18388
 * ssl  The SSL/TLS object.
18389
 * sz   Maximum size of the early data.
18390
 * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3,
18391
 * and 0 on success.
18392
 */
18393
int wolfSSL_set_max_early_data(WOLFSSL* ssl, unsigned int sz)
18394
{
18395
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
18396
        return BAD_FUNC_ARG;
18397
18398
    ssl->options.maxEarlyDataSz = sz;
18399
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_ERROR_CODE_OPENSSL)
18400
    /* 1 on success in OpenSSL*/
18401
    return WOLFSSL_SUCCESS;
18402
#else
18403
    return 0;
18404
#endif
18405
}
18406
18407
/* Gets the maximum amount of early data that can be seen by server when using
18408
 * session tickets for resumption.
18409
 * A value of zero indicates no early data is to be sent by client using session
18410
 * tickets.
18411
 *
18412
 * ctx  The SSL/TLS CTX object.
18413
 * returns BAD_FUNC_ARG when ctx is NULL, SIDE_ERROR when not a server and
18414
 * returns the maximum amount of early data to be set
18415
 */
18416
int wolfSSL_CTX_get_max_early_data(WOLFSSL_CTX* ctx)
18417
{
18418
    if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
18419
        return BAD_FUNC_ARG;
18420
    if (ctx->method->side == WOLFSSL_CLIENT_END)
18421
        return SIDE_ERROR;
18422
18423
    return ctx->maxEarlyDataSz;
18424
}
18425
18426
/* Gets the maximum amount of early data that can be seen by server when using
18427
 * session tickets for resumption.
18428
 * A value of zero indicates no early data is to be sent by client using session
18429
 * tickets.
18430
 *
18431
 * ssl  The SSL/TLS object.
18432
 * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3,
18433
 * SIDE_ERROR when not a server and
18434
 * returns the maximum amount of early data to be set
18435
 */
18436
int wolfSSL_get_max_early_data(WOLFSSL* ssl)
18437
{
18438
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
18439
        return BAD_FUNC_ARG;
18440
18441
    return ssl->options.maxEarlyDataSz;
18442
}
18443
18444
/* Write early data to the server.
18445
 *
18446
 * ssl    The SSL/TLS object.
18447
 * data   Early data to write
18448
 * sz     The size of the early data in bytes.
18449
 * outSz  The number of early data bytes written.
18450
 * returns BAD_FUNC_ARG when: ssl, data or outSz is NULL; sz is negative;
18451
 * or not using TLS v1.3. SIDE ERROR when not a server. BAD_STATE_E if invoked
18452
 * without a valid session or without a valid PSK CB.
18453
 * Otherwise the number of early data bytes written.
18454
 */
18455
int wolfSSL_write_early_data(WOLFSSL* ssl, const void* data, int sz, int* outSz)
18456
{
18457
    int ret = 0;
18458
18459
    WOLFSSL_ENTER("wolfSSL_write_early_data");
18460
18461
    if (ssl == NULL || data == NULL || sz < 0 || outSz == NULL)
18462
        return BAD_FUNC_ARG;
18463
    if (!IsAtLeastTLSv1_3(ssl->version))
18464
        return BAD_FUNC_ARG;
18465
18466
    *outSz = 0;
18467
18468
#ifndef NO_WOLFSSL_CLIENT
18469
    if (ssl->options.side == WOLFSSL_SERVER_END)
18470
        return SIDE_ERROR;
18471
18472
    /* Early data requires PSK or session resumption */
18473
    if (!EarlyDataPossible(ssl)) {
18474
        return BAD_STATE_E;
18475
    }
18476
18477
    if (ssl->options.handShakeState == NULL_STATE) {
18478
        /* avoid re-setting ssl->earlyData if we re-enter the function because
18479
         * of WC_PENDING_E, WANT_WRITE or WANT_READ */
18480
        if (ssl->error == 0)
18481
            ssl->earlyData = expecting_early_data;
18482
        ret = wolfSSL_connect_TLSv13(ssl);
18483
        if (ret != WOLFSSL_SUCCESS)
18484
            return WOLFSSL_FATAL_ERROR;
18485
        /* on client side, status is set to rejected        */
18486
        /* until sever accepts the early data extension.    */
18487
        ssl->earlyDataStatus = WOLFSSL_EARLY_DATA_REJECTED;
18488
    }
18489
    if (ssl->options.handShakeState == CLIENT_HELLO_COMPLETE) {
18490
#ifdef OPENSSL_EXTRA
18491
        /* when processed early data exceeds max size */
18492
        if (ssl->session->maxEarlyDataSz > 0 &&
18493
            (ssl->earlyDataSz + sz > ssl->session->maxEarlyDataSz)) {
18494
            ssl->error = TOO_MUCH_EARLY_DATA;
18495
            return WOLFSSL_FATAL_ERROR;
18496
        }
18497
#endif
18498
        ret = SendData(ssl, data, sz);
18499
        if (ret > 0) {
18500
            *outSz = ret;
18501
            /* store amount of processed early data from client */
18502
            ssl->earlyDataSz += ret;
18503
        }
18504
    }
18505
#else
18506
    return SIDE_ERROR;
18507
#endif
18508
18509
    WOLFSSL_LEAVE("wolfSSL_write_early_data", ret);
18510
18511
    if (ret < 0)
18512
        ret = WOLFSSL_FATAL_ERROR;
18513
    return ret;
18514
}
18515
18516
/* Read the any early data from the client.
18517
 *
18518
 * ssl    The SSL/TLS object.
18519
 * data   Buffer to put the early data into.
18520
 * sz     The size of the buffer in bytes.
18521
 * outSz  The number of early data bytes read.
18522
 * returns BAD_FUNC_ARG when: ssl, data or outSz is NULL; sz is negative;
18523
 * or not using TLS v1.3. SIDE ERROR when not a server. Otherwise the number of
18524
 * early data bytes read.
18525
 */
18526
int wolfSSL_read_early_data(WOLFSSL* ssl, void* data, int sz, int* outSz)
18527
{
18528
    int ret = 0;
18529
18530
    WOLFSSL_ENTER("wolfSSL_read_early_data");
18531
18532
18533
    if (ssl == NULL || data == NULL || sz < 0 || outSz == NULL)
18534
        return BAD_FUNC_ARG;
18535
    if (!IsAtLeastTLSv1_3(ssl->version))
18536
        return BAD_FUNC_ARG;
18537
18538
    *outSz = 0;
18539
#ifndef NO_WOLFSSL_SERVER
18540
    if (ssl->options.side == WOLFSSL_CLIENT_END)
18541
        return SIDE_ERROR;
18542
18543
    if (ssl->options.handShakeState == NULL_STATE) {
18544
        /* the server flight can return WANT_WRITE and we re-enter here after
18545
         * setting ssl->earlyData = process_early_data, set earlyData to
18546
         * expecting_early_data just once */
18547
        if (ssl->earlyData < expecting_early_data)
18548
            ssl->earlyData = expecting_early_data;
18549
        /* this used to be: ret = wolfSSL_accept_TLSv13(ssl);
18550
         * However, wolfSSL_accept_TLSv13() expects a certificate to
18551
         * be installed already, which is not the case in servers
18552
         * such as HAProxy. They do it after inspecting the ClientHello.
18553
         * The common wolfssl_accept() allows that. */
18554
        ret = wolfSSL_accept(ssl);
18555
        if (ret <= 0)
18556
            return WOLFSSL_FATAL_ERROR;
18557
    }
18558
    if (ssl->options.handShakeState == SERVER_FINISHED_COMPLETE) {
18559
        ssl->options.clientInEarlyData = 1;
18560
        ret = ReceiveData(ssl, (byte*)data, (size_t)sz, FALSE);
18561
        ssl->options.clientInEarlyData = 0;
18562
        if (ret > 0)
18563
            *outSz = ret;
18564
        if (ssl->error == WC_NO_ERR_TRACE(APP_DATA_READY)) {
18565
            ret = 0;
18566
            ssl->error = WOLFSSL_ERROR_NONE;
18567
#ifdef WOLFSSL_DTLS13
18568
            if (ssl->options.dtls) {
18569
                ret = Dtls13DoScheduledWork(ssl);
18570
                if (ret  < 0) {
18571
                    ssl->error = ret;
18572
                    WOLFSSL_ERROR(ssl->error);
18573
                    return WOLFSSL_FATAL_ERROR;
18574
                }
18575
            }
18576
#endif /* WOLFSSL_DTLS13 */
18577
        }
18578
    }
18579
#ifdef WOLFSSL_DTLS13
18580
    else if (ssl->buffers.outputBuffer.length > 0 &&
18581
        ssl->options.dtls && ssl->dtls13SendingAckOrRtx) {
18582
        ret = SendBuffered(ssl);
18583
        if (ret == 0) {
18584
            ssl->dtls13SendingAckOrRtx = 0;
18585
        }
18586
        else {
18587
            ssl->error = ret;
18588
            WOLFSSL_ERROR(ssl->error);
18589
            return WOLFSSL_FATAL_ERROR;
18590
        }
18591
    }
18592
#endif /* WOLFSSL_DTLS13 */
18593
    else
18594
        ret = 0;
18595
#else
18596
    return SIDE_ERROR;
18597
#endif
18598
18599
    WOLFSSL_LEAVE("wolfSSL_read_early_data", ret);
18600
18601
    if (ret < 0)
18602
        ret = WOLFSSL_FATAL_ERROR;
18603
    return ret;
18604
}
18605
18606
/* Returns early data status
18607
 *
18608
 * ssl    The SSL/TLS object.
18609
 * returns WOLFSSL_EARLY_DATA_ACCEPTED if the data was accepted
18610
 *         WOLFSSL_EARLY_DATA_REJECTED if the data was rejected
18611
 *         WOLFSSL_EARLY_DATA_NOT_SENT if no early data was sent
18612
 */
18613
int wolfSSL_get_early_data_status(const WOLFSSL* ssl)
18614
{
18615
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
18616
        return BAD_FUNC_ARG;
18617
18618
    return ssl->earlyDataStatus;
18619
}
18620
#endif
18621
18622
#ifdef HAVE_SECRET_CALLBACK
18623
int wolfSSL_set_tls13_secret_cb(WOLFSSL* ssl, Tls13SecretCb cb, void* ctx)
18624
{
18625
    WOLFSSL_ENTER("wolfSSL_set_tls13_secret_cb");
18626
    if (ssl == NULL)
18627
        return WOLFSSL_FATAL_ERROR;
18628
18629
    ssl->tls13SecretCb = cb;
18630
    ssl->tls13SecretCtx = ctx;
18631
18632
    return WOLFSSL_SUCCESS;
18633
}
18634
18635
#if defined(SHOW_SECRETS) && defined(WOLFSSL_SSLKEYLOGFILE)
18636
int tls13ShowSecrets(WOLFSSL* ssl, int id, const unsigned char* secret,
18637
    int secretSz, void* ctx)
18638
{
18639
    int i;
18640
    const char* str = NULL;
18641
    byte clientRandom[RAN_LEN];
18642
    int clientRandomSz;
18643
    XFILE fp;
18644
#if defined(WOLFSSL_SSLKEYLOGFILE_OUTPUT) && defined(WOLFSSL_SSLKEYLOGFILE_USE_ENV)
18645
    const char* keyLogFile;
18646
#endif
18647
18648
    (void) ctx;
18649
#ifdef WOLFSSL_SSLKEYLOGFILE_OUTPUT
18650
#ifdef WOLFSSL_SSLKEYLOGFILE_USE_ENV
18651
    /* RFC 9850: prefer the SSLKEYLOGFILE environment variable so tools such as
18652
     * curl and Wireshark can share the path, else use the compile-time path.
18653
     * XGETENV resolves to NULL where environment access is unavailable. Opt-in
18654
     * so a build with the variable exported for other applications is not
18655
     * affected. */
18656
    keyLogFile = XGETENV("SSLKEYLOGFILE");
18657
    if (keyLogFile == NULL || keyLogFile[0] == '\0')
18658
        keyLogFile = WOLFSSL_SSLKEYLOGFILE_OUTPUT;
18659
    fp = XFOPEN(keyLogFile, "ab");
18660
#else
18661
    fp = XFOPEN(WOLFSSL_SSLKEYLOGFILE_OUTPUT, "ab");
18662
#endif
18663
    if (fp == XBADFILE) {
18664
        return BAD_FUNC_ARG;
18665
    }
18666
#else
18667
    fp = stderr;
18668
#endif
18669
18670
    clientRandomSz = (int)wolfSSL_get_client_random(ssl, clientRandom,
18671
        sizeof(clientRandom));
18672
18673
    if (clientRandomSz <= 0) {
18674
        printf("Error getting server random %d\n", clientRandomSz);
18675
        return BAD_FUNC_ARG;
18676
    }
18677
18678
#if 0
18679
    printf("TLS Server Secret CB: Rand %d, Secret %d\n",
18680
        serverRandomSz, secretSz);
18681
#endif
18682
18683
    switch (id) {
18684
        case CLIENT_EARLY_TRAFFIC_SECRET:
18685
            str = "CLIENT_EARLY_TRAFFIC_SECRET"; break;
18686
        case EARLY_EXPORTER_SECRET:
18687
            str = "EARLY_EXPORTER_SECRET"; break;
18688
        case CLIENT_HANDSHAKE_TRAFFIC_SECRET:
18689
            str = "CLIENT_HANDSHAKE_TRAFFIC_SECRET"; break;
18690
        case SERVER_HANDSHAKE_TRAFFIC_SECRET:
18691
            str = "SERVER_HANDSHAKE_TRAFFIC_SECRET"; break;
18692
        case CLIENT_TRAFFIC_SECRET:
18693
            str = "CLIENT_TRAFFIC_SECRET_0"; break;
18694
        case SERVER_TRAFFIC_SECRET:
18695
            str = "SERVER_TRAFFIC_SECRET_0"; break;
18696
        case EXPORTER_SECRET:
18697
            str = "EXPORTER_SECRET"; break;
18698
#ifdef HAVE_ECH
18699
        case ECH_SECRET:
18700
            str = "ECH_SECRET"; break;
18701
        case ECH_CONFIG:
18702
            str = "ECH_CONFIG"; break;
18703
#endif
18704
        default:
18705
#ifdef WOLFSSL_SSLKEYLOGFILE_OUTPUT
18706
            XFCLOSE(fp);
18707
#endif
18708
            return BAD_FUNC_ARG;
18709
            break;
18710
    }
18711
18712
    fprintf(fp, "%s ", str);
18713
    for (i = 0; i < (int)clientRandomSz; i++) {
18714
        fprintf(fp, "%02x", clientRandom[i]);
18715
    }
18716
    fprintf(fp, " ");
18717
    for (i = 0; i < secretSz; i++) {
18718
        fprintf(fp, "%02x", secret[i]);
18719
    }
18720
    fprintf(fp, "\n");
18721
18722
#ifdef WOLFSSL_SSLKEYLOGFILE_OUTPUT
18723
    XFCLOSE(fp);
18724
#endif
18725
18726
    return 0;
18727
}
18728
#endif
18729
#endif
18730
18731
#undef ERROR_OUT
18732
18733
#endif /* !WOLFCRYPT_ONLY */
18734
18735
#endif /* !NO_TLS && WOLFSSL_TLS13 */