Coverage Report

Created: 2022-08-24 06:26

/src/wolfssl-sp-math/src/tls13.c
Line
Count
Source (jump to first uncovered line)
1
/* tls13.c
2
 *
3
 * Copyright (C) 2006-2022 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 2 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
23
/*
24
 * BUILD_GCM
25
 *    Enables AES-GCM ciphersuites.
26
 * HAVE_AESCCM
27
 *    Enables AES-CCM ciphersuites.
28
 * HAVE_SESSION_TICKET
29
 *    Enables session tickets - required for TLS 1.3 resumption.
30
 * NO_PSK
31
 *    Do not enable Pre-Shared Keys.
32
 * HAVE_KEYING_MATERIAL
33
 *    Enables exporting keying material based on section 7.5 of RFC 8446.
34
 * WOLFSSL_ASYNC_CRYPT
35
 *    Enables the use of asynchronous cryptographic operations.
36
 *    This is available for ciphers and certificates.
37
 * HAVE_CHACHA && HAVE_POLY1305
38
 *    Enables use of CHACHA20-POLY1305 ciphersuites.
39
 * WOLFSSL_DEBUG_TLS
40
 *    Writes out details of TLS 1.3 protocol including handshake message buffers
41
 *    and key generation input and output.
42
 * WOLFSSL_EARLY_DATA
43
 *    Allow 0-RTT Handshake using Early Data extensions and handshake message
44
 * WOLFSSL_EARLY_DATA_GROUP
45
 *    Group EarlyData message with ClientHello when sending
46
 * WOLFSSL_NO_SERVER_GROUPS_EXT
47
 *    Do not send the server's groups in an extension when the server's top
48
 *    preference is not in client's list.
49
 * WOLFSSL_POST_HANDSHAKE_AUTH
50
 *    Allow TLS v1.3 code to perform post-handshake authentication of the
51
 *    client.
52
 * WOLFSSL_SEND_HRR_COOKIE
53
 *    Send a cookie in hello_retry_request message to enable stateless tracking
54
 *    of ClientHello replies.
55
 * WOLFSSL_TLS13
56
 *    Enable TLS 1.3 protocol implementation.
57
 * WOLFSSL_TLS13_MIDDLEBOX_COMPAT
58
 *    Enable middlebox compatibility in the TLS 1.3 handshake.
59
 *    This includes sending ChangeCipherSpec before encrypted messages and
60
 *    including a session id.
61
 * WOLFSSL_TLS13_SHA512
62
 *    Allow generation of SHA-512 digests in handshake - no ciphersuite
63
 *    requires SHA-512 at this time.
64
 * WOLFSSL_TLS13_TICKET_BEFORE_FINISHED
65
 *    Allow a NewSessionTicket message to be sent by server before Client's
66
 *    Finished message.
67
 *    See TLS v1.3 specification, Section 4.6.1, Paragraph 4 (Note).
68
 * WOLFSSL_PSK_ONE_ID
69
 *    When only one PSK ID is used and only one call to the PSK callback can
70
 *    be made per connect.
71
 *    You cannot use wc_psk_client_cs_callback type callback on client.
72
 * WOLFSSL_CHECK_ALERT_ON_ERR
73
 *    Check for alerts during the handshake in the event of an error.
74
 * WOLFSSL_NO_CLIENT_CERT_ERROR
75
 *    Requires client to set a client certificate
76
 * WOLFSSL_PSK_MULTI_ID_PER_CS
77
 *    When multiple PSK identities are available for the same cipher suite.
78
 *    Sets the first byte of the client identity to the count of identites
79
 *    that have been seen so far for the cipher suite.
80
 */
81
82
#ifdef HAVE_CONFIG_H
83
    #include <config.h>
84
#endif
85
86
#include <wolfssl/wolfcrypt/settings.h>
87
88
#ifdef WOLFSSL_TLS13
89
#ifdef HAVE_SESSION_TICKET
90
    #include <wolfssl/wolfcrypt/wc_port.h>
91
#endif
92
93
#ifndef WOLFCRYPT_ONLY
94
95
#ifdef HAVE_ERRNO_H
96
    #include <errno.h>
97
#endif
98
99
#if defined(__MACH__) || defined(__FreeBSD__)
100
#include <sys/time.h>
101
#endif /* __MACH__ || __FreeBSD__ */
102
103
104
#include <wolfssl/internal.h>
105
#include <wolfssl/error-ssl.h>
106
#include <wolfssl/wolfcrypt/asn.h>
107
#include <wolfssl/wolfcrypt/dh.h>
108
#include <wolfssl/wolfcrypt/kdf.h>
109
#ifdef NO_INLINE
110
    #include <wolfssl/wolfcrypt/misc.h>
111
#else
112
    #define WOLFSSL_MISC_INCLUDED
113
    #include <wolfcrypt/src/misc.c>
114
#endif
115
116
#ifdef __sun
117
    #include <sys/filio.h>
118
#endif
119
120
#ifndef TRUE
121
    #define TRUE  1
122
#endif
123
#ifndef FALSE
124
    #define FALSE 0
125
#endif
126
127
#ifndef HAVE_HKDF
128
    #ifndef _MSC_VER
129
        #error "The build option HAVE_HKDF is required for TLS 1.3"
130
    #else
131
        #pragma message("error: The build option HAVE_HKDF is required for TLS 1.3")
132
    #endif
133
#endif
134
135
#ifndef HAVE_TLS_EXTENSIONS
136
    #ifndef _MSC_VER
137
        #error "The build option HAVE_TLS_EXTENSIONS is required for TLS 1.3"
138
    #else
139
        #pragma message("error: The build option HAVE_TLS_EXTENSIONS is required for TLS 1.3")
140
    #endif
141
#endif
142
143
144
/* Set ret to error value and jump to label.
145
 *
146
 * err     The error value to set.
147
 * eLabel  The label to jump to.
148
 */
149
0
#define ERROR_OUT(err, eLabel) { ret = (err); goto eLabel; }
150
151
/* Size of the TLS v1.3 label use when deriving keys. */
152
0
#define TLS13_PROTOCOL_LABEL_SZ    6
153
/* The protocol label for TLS v1.3. */
154
static const byte tls13ProtocolLabel[TLS13_PROTOCOL_LABEL_SZ + 1] = "tls13 ";
155
156
#ifdef WOLFSSL_DTLS13
157
#define DTLS13_PROTOCOL_LABEL_SZ    6
158
static const byte dtls13ProtocolLabel[DTLS13_PROTOCOL_LABEL_SZ + 1] = "dtls13";
159
#endif /* WOLFSSL_DTLS13 */
160
161
/* Derive a key from a message.
162
 *
163
 * ssl        The SSL/TLS object.
164
 * output     The buffer to hold the derived key.
165
 * outputLen  The length of the derived key.
166
 * secret     The secret used to derive the key (HMAC secret).
167
 * label      The label used to distinguish the context.
168
 * labelLen   The length of the label.
169
 * msg        The message data to derive key from.
170
 * msgLen     The length of the message data to derive key from.
171
 * hashAlgo   The hash algorithm to use in the HMAC.
172
 * returns 0 on success, otherwise failure.
173
 */
174
static int DeriveKeyMsg(WOLFSSL* ssl, byte* output, int outputLen,
175
                        const byte* secret, const byte* label, word32 labelLen,
176
                        byte* msg, int msgLen, int hashAlgo)
177
0
{
178
0
    byte        hash[WC_MAX_DIGEST_SIZE];
179
0
    Digest      digest;
180
0
    word32      hashSz = 0;
181
0
    const byte* protocol;
182
0
    word32      protocolLen;
183
0
    int         digestAlg = -1;
184
0
    int         ret = BAD_FUNC_ARG;
185
186
0
    switch (hashAlgo) {
187
0
#ifndef NO_WOLFSSL_SHA256
188
0
        case sha256_mac:
189
0
            ret = wc_InitSha256_ex(&digest.sha256, ssl->heap, INVALID_DEVID);
190
0
            if (ret == 0) {
191
0
                    ret = wc_Sha256Update(&digest.sha256, msg, msgLen);
192
0
                if (ret == 0)
193
0
                    ret = wc_Sha256Final(&digest.sha256, hash);
194
0
                wc_Sha256Free(&digest.sha256);
195
0
            }
196
0
            hashSz = WC_SHA256_DIGEST_SIZE;
197
0
            digestAlg = WC_SHA256;
198
0
            break;
199
0
#endif
200
0
#ifdef WOLFSSL_SHA384
201
0
        case sha384_mac:
202
0
            ret = wc_InitSha384_ex(&digest.sha384, ssl->heap, INVALID_DEVID);
203
0
            if (ret == 0) {
204
0
                ret = wc_Sha384Update(&digest.sha384, msg, msgLen);
205
0
                if (ret == 0)
206
0
                    ret = wc_Sha384Final(&digest.sha384, hash);
207
0
                wc_Sha384Free(&digest.sha384);
208
0
            }
209
0
            hashSz = WC_SHA384_DIGEST_SIZE;
210
0
            digestAlg = WC_SHA384;
211
0
            break;
212
0
#endif
213
#ifdef WOLFSSL_TLS13_SHA512
214
        case sha512_mac:
215
            ret = wc_InitSha512_ex(&digest.sha512, ssl->heap, INVALID_DEVID);
216
            if (ret == 0) {
217
                ret = wc_Sha512Update(&digest.sha512, msg, msgLen);
218
                if (ret == 0)
219
                    ret = wc_Sha512Final(&digest.sha512, hash);
220
                wc_Sha512Free(&digest.sha512);
221
            }
222
            hashSz = WC_SHA512_DIGEST_SIZE;
223
            digestAlg = WC_SHA512;
224
            break;
225
#endif
226
0
        default:
227
0
            digestAlg = -1;
228
0
            break;
229
0
    }
230
231
0
    if (digestAlg < 0)
232
0
        return HASH_TYPE_E;
233
234
0
    if (ret != 0)
235
0
        return ret;
236
237
0
    switch (ssl->version.minor) {
238
0
        case TLSv1_3_MINOR:
239
0
            protocol = tls13ProtocolLabel;
240
0
            protocolLen = TLS13_PROTOCOL_LABEL_SZ;
241
0
            break;
242
#ifdef WOLFSSL_DTLS13
243
        case DTLSv1_3_MINOR:
244
            if (!ssl->options.dtls)
245
                return VERSION_ERROR;
246
247
            protocol = dtls13ProtocolLabel;
248
            protocolLen = DTLS13_PROTOCOL_LABEL_SZ;
249
            break;
250
#endif /* WOLFSSL_DTLS13 */
251
0
        default:
252
0
            return VERSION_ERROR;
253
0
    }
254
0
    if (outputLen == -1)
255
0
        outputLen = hashSz;
256
257
0
    PRIVATE_KEY_UNLOCK();
258
0
    ret = wc_Tls13_HKDF_Expand_Label(output, outputLen, secret, hashSz,
259
0
                             protocol, protocolLen, label, labelLen,
260
0
                             hash, hashSz, digestAlg);
261
0
    PRIVATE_KEY_LOCK();
262
0
    return ret;
263
0
}
264
265
/* Derive a key.
266
 *
267
 * ssl          The SSL/TLS object.
268
 * output       The buffer to hold the derived key.
269
 * outputLen    The length of the derived key.
270
 * secret       The secret used to derive the key (HMAC secret).
271
 * label        The label used to distinguish the context.
272
 * labelLen     The length of the label.
273
 * hashAlgo     The hash algorithm to use in the HMAC.
274
 * includeMsgs  Whether to include a hash of the handshake messages so far.
275
 * returns 0 on success, otherwise failure.
276
 */
277
int Tls13DeriveKey(WOLFSSL* ssl, byte* output, int outputLen,
278
                   const byte* secret, const byte* label, word32 labelLen,
279
                   int hashAlgo, int includeMsgs)
280
0
{
281
0
    int         ret = 0;
282
0
    byte        hash[WC_MAX_DIGEST_SIZE];
283
0
    word32      hashSz = 0;
284
0
    word32      hashOutSz = 0;
285
0
    const byte* protocol;
286
0
    word32      protocolLen;
287
0
    int         digestAlg = 0;
288
289
0
    switch (hashAlgo) {
290
0
    #ifndef NO_SHA256
291
0
        case sha256_mac:
292
0
            hashSz    = WC_SHA256_DIGEST_SIZE;
293
0
            digestAlg = WC_SHA256;
294
0
            if (includeMsgs)
295
0
                ret = wc_Sha256GetHash(&ssl->hsHashes->hashSha256, hash);
296
0
            break;
297
0
    #endif
298
299
0
    #ifdef WOLFSSL_SHA384
300
0
        case sha384_mac:
301
0
            hashSz    = WC_SHA384_DIGEST_SIZE;
302
0
            digestAlg = WC_SHA384;
303
0
            if (includeMsgs)
304
0
                ret = wc_Sha384GetHash(&ssl->hsHashes->hashSha384, hash);
305
0
            break;
306
0
    #endif
307
308
    #ifdef WOLFSSL_TLS13_SHA512
309
        case sha512_mac:
310
            hashSz    = WC_SHA512_DIGEST_SIZE;
311
            digestAlg = WC_SHA512;
312
            if (includeMsgs)
313
                ret = wc_Sha512GetHash(&ssl->hsHashes->hashSha512, hash);
314
            break;
315
    #endif
316
317
0
        default:
318
0
            ret = HASH_TYPE_E;
319
0
            break;
320
0
    }
321
0
    if (ret != 0)
322
0
        return ret;
323
324
0
    protocol = tls13ProtocolLabel;
325
0
    protocolLen = TLS13_PROTOCOL_LABEL_SZ;
326
327
#ifdef WOLFSSL_DTLS13
328
    if (ssl->options.dtls) {
329
         protocol = dtls13ProtocolLabel;
330
         protocolLen = DTLS13_PROTOCOL_LABEL_SZ;
331
    }
332
#endif /* WOLFSSL_DTLS13 */
333
334
0
    if (outputLen == -1)
335
0
        outputLen = hashSz;
336
0
    if (includeMsgs)
337
0
        hashOutSz = hashSz;
338
339
    /* hash buffer may not be fully initialized, but the sending length won't
340
     * extend beyond the initialized span.
341
     */
342
0
    PRAGMA_GCC_DIAG_PUSH;
343
0
    PRAGMA_GCC("GCC diagnostic ignored \"-Wmaybe-uninitialized\"");
344
0
    PRIVATE_KEY_UNLOCK();
345
    #if defined(HAVE_FIPS) && defined(wc_Tls13_HKDF_Expand_Label)
346
    ret = wc_Tls13_HKDF_Expand_Label_fips(output, outputLen, secret, hashSz,
347
                             protocol, protocolLen, label, labelLen,
348
                             hash, hashOutSz, digestAlg);
349
    #else
350
0
    ret = wc_Tls13_HKDF_Expand_Label(output, outputLen, secret, hashSz,
351
0
                             protocol, protocolLen, label, labelLen,
352
0
                             hash, hashOutSz, digestAlg);
353
0
    #endif
354
0
    PRIVATE_KEY_LOCK();
355
356
#ifdef WOLFSSL_CHECK_MEM_ZERO
357
    wc_MemZero_Add("TLS 1.3 derived key", output, outputLen);
358
#endif
359
0
    return ret;
360
0
    PRAGMA_GCC_DIAG_POP;
361
0
}
362
363
/* Convert TLS mac ID to a hash algorithm ID
364
 *
365
 * mac Mac ID to convert
366
 * returns hash ID on success, or the NONE type.
367
 */
368
static WC_INLINE int mac2hash(int mac)
369
0
{
370
0
    int hash;
371
0
    switch (mac) {
372
0
        #ifndef NO_SHA256
373
0
        case sha256_mac:
374
0
            hash = WC_SHA256;
375
0
            break;
376
0
        #endif
377
378
0
        #ifdef WOLFSSL_SHA384
379
0
        case sha384_mac:
380
0
            hash = WC_SHA384;
381
0
            break;
382
0
        #endif
383
384
        #ifdef WOLFSSL_TLS13_SHA512
385
        case sha512_mac:
386
            hash = WC_SHA512;
387
            break;
388
        #endif
389
0
    default:
390
0
        hash = WC_HASH_TYPE_NONE;
391
0
    }
392
0
    return hash;
393
0
}
394
395
#ifndef NO_PSK
396
/* The length of the binder key label. */
397
#define BINDER_KEY_LABEL_SZ         10
398
/* The binder key label. */
399
static const byte binderKeyLabel[BINDER_KEY_LABEL_SZ + 1] =
400
    "ext binder";
401
402
/* Derive the binder key.
403
 *
404
 * ssl  The SSL/TLS object.
405
 * key  The derived key.
406
 * returns 0 on success, otherwise failure.
407
 */
408
static int DeriveBinderKey(WOLFSSL* ssl, byte* key)
409
{
410
    WOLFSSL_MSG("Derive Binder Key");
411
    if (ssl == NULL || ssl->arrays == NULL) {
412
        return BAD_FUNC_ARG;
413
    }
414
    return DeriveKeyMsg(ssl, key, -1, ssl->arrays->secret,
415
                        binderKeyLabel, BINDER_KEY_LABEL_SZ,
416
                        NULL, 0, ssl->specs.mac_algorithm);
417
}
418
#endif /* !NO_PSK */
419
420
#if defined(HAVE_SESSION_TICKET) && \
421
    (!defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER))
422
/* The length of the binder key resume label. */
423
#define BINDER_KEY_RESUME_LABEL_SZ  10
424
/* The binder key resume label. */
425
static const byte binderKeyResumeLabel[BINDER_KEY_RESUME_LABEL_SZ + 1] =
426
    "res binder";
427
428
/* Derive the binder resumption key.
429
 *
430
 * ssl  The SSL/TLS object.
431
 * key  The derived key.
432
 * returns 0 on success, otherwise failure.
433
 */
434
static int DeriveBinderKeyResume(WOLFSSL* ssl, byte* key)
435
{
436
    WOLFSSL_MSG("Derive Binder Key - Resumption");
437
    if (ssl == NULL || ssl->arrays == NULL) {
438
        return BAD_FUNC_ARG;
439
    }
440
    return DeriveKeyMsg(ssl, key, -1, ssl->arrays->secret,
441
                        binderKeyResumeLabel, BINDER_KEY_RESUME_LABEL_SZ,
442
                        NULL, 0, ssl->specs.mac_algorithm);
443
}
444
#endif /* HAVE_SESSION_TICKET && (!NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER) */
445
446
#ifdef WOLFSSL_EARLY_DATA
447
448
/* The length of the early traffic label. */
449
#define EARLY_TRAFFIC_LABEL_SZ      11
450
/* The early traffic label. */
451
static const byte earlyTrafficLabel[EARLY_TRAFFIC_LABEL_SZ + 1] =
452
    "c e traffic";
453
454
/* Derive the early traffic key.
455
 *
456
 * ssl  The SSL/TLS object.
457
 * key  The derived key.
458
 * returns 0 on success, otherwise failure.
459
 */
460
static int DeriveEarlyTrafficSecret(WOLFSSL* ssl, byte* key)
461
{
462
    int ret;
463
    WOLFSSL_MSG("Derive Early Traffic Secret");
464
    if (ssl == NULL || ssl->arrays == NULL) {
465
        return BAD_FUNC_ARG;
466
    }
467
    ret = Tls13DeriveKey(ssl, key, -1, ssl->arrays->secret,
468
                    earlyTrafficLabel, EARLY_TRAFFIC_LABEL_SZ,
469
                    ssl->specs.mac_algorithm, 1);
470
#ifdef HAVE_SECRET_CALLBACK
471
    if (ret == 0 && ssl->tls13SecretCb != NULL) {
472
        ret = ssl->tls13SecretCb(ssl, CLIENT_EARLY_TRAFFIC_SECRET, key,
473
                                 ssl->specs.hash_size, ssl->tls13SecretCtx);
474
        if (ret != 0) {
475
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
476
            return TLS13_SECRET_CB_E;
477
        }
478
    }
479
#ifdef OPENSSL_EXTRA
480
    if (ret == 0 && ssl->tls13KeyLogCb != NULL) {
481
        ret = ssl->tls13KeyLogCb(ssl, CLIENT_EARLY_TRAFFIC_SECRET, key,
482
                                ssl->specs.hash_size, NULL);
483
        if (ret != 0) {
484
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
485
            return TLS13_SECRET_CB_E;
486
        }
487
    }
488
#endif /* OPENSSL_EXTRA */
489
#endif /* HAVE_SECRET_CALLBACK */
490
    return ret;
491
}
492
493
#endif
494
495
/* The length of the client handshake label. */
496
0
#define CLIENT_HANDSHAKE_LABEL_SZ   12
497
/* The client handshake label. */
498
static const byte clientHandshakeLabel[CLIENT_HANDSHAKE_LABEL_SZ + 1] =
499
    "c hs traffic";
500
501
/* Derive the client handshake key.
502
 *
503
 * ssl  The SSL/TLS object.
504
 * key  The derived key.
505
 * returns 0 on success, otherwise failure.
506
 */
507
static int DeriveClientHandshakeSecret(WOLFSSL* ssl, byte* key)
508
0
{
509
0
    int ret;
510
0
    WOLFSSL_MSG("Derive Client Handshake Secret");
511
0
    if (ssl == NULL || ssl->arrays == NULL) {
512
0
        return BAD_FUNC_ARG;
513
0
    }
514
#if defined(WOLFSSL_RENESAS_TSIP_TLS) && (WOLFSSL_RENESAS_TSIP_Ver >= 115)
515
    (void)key;
516
    ret = tsip_DeriveClientHandshakeSecret(ssl);
517
    if (ret != CRYPTOCB_UNAVAILABLE) {
518
        return ret;
519
    }
520
#endif
521
0
    ret = Tls13DeriveKey(ssl, key, -1, ssl->arrays->preMasterSecret,
522
0
                    clientHandshakeLabel, CLIENT_HANDSHAKE_LABEL_SZ,
523
0
                    ssl->specs.mac_algorithm, 1);
524
#ifdef HAVE_SECRET_CALLBACK
525
    if (ret == 0 && ssl->tls13SecretCb != NULL) {
526
        ret = ssl->tls13SecretCb(ssl, CLIENT_HANDSHAKE_TRAFFIC_SECRET, key,
527
                                 ssl->specs.hash_size, ssl->tls13SecretCtx);
528
        if (ret != 0) {
529
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
530
            return TLS13_SECRET_CB_E;
531
        }
532
    }
533
#ifdef OPENSSL_EXTRA
534
    if (ret == 0 && ssl->tls13KeyLogCb != NULL) {
535
        ret = ssl->tls13KeyLogCb(ssl, CLIENT_HANDSHAKE_TRAFFIC_SECRET, key,
536
                                ssl->specs.hash_size, NULL);
537
        if (ret != 0) {
538
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
539
            return TLS13_SECRET_CB_E;
540
        }
541
    }
542
#endif /* OPENSSL_EXTRA */
543
#endif /* HAVE_SECRET_CALLBACK */
544
0
    return ret;
545
0
}
546
547
/* The length of the server handshake label. */
548
0
#define SERVER_HANDSHAKE_LABEL_SZ   12
549
/* The server handshake label. */
550
static const byte serverHandshakeLabel[SERVER_HANDSHAKE_LABEL_SZ + 1] =
551
    "s hs traffic";
552
553
/* Derive the server handshake key.
554
 *
555
 * ssl  The SSL/TLS object.
556
 * key  The derived key.
557
 * returns 0 on success, otherwise failure.
558
 */
559
static int DeriveServerHandshakeSecret(WOLFSSL* ssl, byte* key)
560
0
{
561
0
    int ret;
562
0
    WOLFSSL_MSG("Derive Server Handshake Secret");
563
0
    if (ssl == NULL || ssl->arrays == NULL) {
564
0
        return BAD_FUNC_ARG;
565
0
    }
566
0
    ret = Tls13DeriveKey(ssl, key, -1, ssl->arrays->preMasterSecret,
567
0
                    serverHandshakeLabel, SERVER_HANDSHAKE_LABEL_SZ,
568
0
                    ssl->specs.mac_algorithm, 1);
569
#ifdef HAVE_SECRET_CALLBACK
570
    if (ret == 0 && ssl->tls13SecretCb != NULL) {
571
        ret = ssl->tls13SecretCb(ssl, SERVER_HANDSHAKE_TRAFFIC_SECRET, key,
572
                                 ssl->specs.hash_size, ssl->tls13SecretCtx);
573
        if (ret != 0) {
574
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
575
            return TLS13_SECRET_CB_E;
576
        }
577
    }
578
#ifdef OPENSSL_EXTRA
579
    if (ret == 0 && ssl->tls13KeyLogCb != NULL) {
580
        ret = ssl->tls13KeyLogCb(ssl, SERVER_HANDSHAKE_TRAFFIC_SECRET, key,
581
                                ssl->specs.hash_size, NULL);
582
        if (ret != 0) {
583
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
584
            return TLS13_SECRET_CB_E;
585
        }
586
    }
587
#endif /* OPENSSL_EXTRA */
588
#endif /* HAVE_SECRET_CALLBACK */
589
0
    return ret;
590
0
}
591
592
/* The length of the client application traffic label. */
593
0
#define CLIENT_APP_LABEL_SZ         12
594
/* The client application traffic label. */
595
static const byte clientAppLabel[CLIENT_APP_LABEL_SZ + 1] =
596
    "c ap traffic";
597
598
/* Derive the client application traffic key.
599
 *
600
 * ssl  The SSL/TLS object.
601
 * key  The derived key.
602
 * returns 0 on success, otherwise failure.
603
 */
604
static int DeriveClientTrafficSecret(WOLFSSL* ssl, byte* key)
605
0
{
606
0
    int ret;
607
0
    WOLFSSL_MSG("Derive Client Traffic Secret");
608
0
    if (ssl == NULL || ssl->arrays == NULL) {
609
0
        return BAD_FUNC_ARG;
610
0
    }
611
0
    ret = Tls13DeriveKey(ssl, key, -1, ssl->arrays->masterSecret,
612
0
                    clientAppLabel, CLIENT_APP_LABEL_SZ,
613
0
                    ssl->specs.mac_algorithm, 1);
614
#ifdef HAVE_SECRET_CALLBACK
615
    if (ret == 0 && ssl->tls13SecretCb != NULL) {
616
        ret = ssl->tls13SecretCb(ssl, CLIENT_TRAFFIC_SECRET, key,
617
                                 ssl->specs.hash_size, ssl->tls13SecretCtx);
618
        if (ret != 0) {
619
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
620
            return TLS13_SECRET_CB_E;
621
        }
622
    }
623
#ifdef OPENSSL_EXTRA
624
    if (ret == 0 && ssl->tls13KeyLogCb != NULL) {
625
        ret = ssl->tls13KeyLogCb(ssl, CLIENT_TRAFFIC_SECRET, key,
626
                                ssl->specs.hash_size, NULL);
627
        if (ret != 0) {
628
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
629
            return TLS13_SECRET_CB_E;
630
        }
631
    }
632
#endif /* OPENSSL_EXTRA */
633
#endif /* HAVE_SECRET_CALLBACK */
634
0
    return ret;
635
0
}
636
637
/* The length of the server application traffic label. */
638
0
#define SERVER_APP_LABEL_SZ         12
639
/* The  server application traffic label. */
640
static const byte serverAppLabel[SERVER_APP_LABEL_SZ + 1] =
641
    "s ap traffic";
642
643
/* Derive the server application traffic key.
644
 *
645
 * ssl  The SSL/TLS object.
646
 * key  The derived key.
647
 * returns 0 on success, otherwise failure.
648
 */
649
static int DeriveServerTrafficSecret(WOLFSSL* ssl, byte* key)
650
0
{
651
0
    int ret;
652
0
    WOLFSSL_MSG("Derive Server Traffic Secret");
653
0
    if (ssl == NULL || ssl->arrays == NULL) {
654
0
        return BAD_FUNC_ARG;
655
0
    }
656
0
    ret = Tls13DeriveKey(ssl, key, -1, ssl->arrays->masterSecret,
657
0
                    serverAppLabel, SERVER_APP_LABEL_SZ,
658
0
                    ssl->specs.mac_algorithm, 1);
659
#ifdef HAVE_SECRET_CALLBACK
660
    if (ret == 0 && ssl->tls13SecretCb != NULL) {
661
        ret = ssl->tls13SecretCb(ssl, SERVER_TRAFFIC_SECRET, key,
662
                                 ssl->specs.hash_size, ssl->tls13SecretCtx);
663
        if (ret != 0) {
664
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
665
            return TLS13_SECRET_CB_E;
666
        }
667
    }
668
#ifdef OPENSSL_EXTRA
669
    if (ret == 0 && ssl->tls13KeyLogCb != NULL) {
670
        ret = ssl->tls13KeyLogCb(ssl, SERVER_TRAFFIC_SECRET, key,
671
                                ssl->specs.hash_size, NULL);
672
        if (ret != 0) {
673
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
674
            return TLS13_SECRET_CB_E;
675
        }
676
    }
677
#endif /* OPENSSL_EXTRA */
678
#endif /* HAVE_SECRET_CALLBACK */
679
0
    return ret;
680
0
}
681
682
#ifdef HAVE_KEYING_MATERIAL
683
/* The length of the exporter master secret label. */
684
#define EXPORTER_MASTER_LABEL_SZ    10
685
/* The exporter master secret label. */
686
static const byte exporterMasterLabel[EXPORTER_MASTER_LABEL_SZ + 1] =
687
    "exp master";
688
689
/* Derive the exporter secret.
690
 *
691
 * ssl  The SSL/TLS object.
692
 * key  The derived key.
693
 * returns 0 on success, otherwise failure.
694
 */
695
static int DeriveExporterSecret(WOLFSSL* ssl, byte* key)
696
{
697
    int ret;
698
    WOLFSSL_ENTER("Derive Exporter Secret");
699
    if (ssl == NULL || ssl->arrays == NULL) {
700
        return BAD_FUNC_ARG;
701
    }
702
    ret = Tls13DeriveKey(ssl, key, -1, ssl->arrays->masterSecret,
703
                        exporterMasterLabel, EXPORTER_MASTER_LABEL_SZ,
704
                        ssl->specs.mac_algorithm, 1);
705
#ifdef HAVE_SECRET_CALLBACK
706
    if (ret == 0 && ssl->tls13SecretCb != NULL) {
707
        ret = ssl->tls13SecretCb(ssl, EXPORTER_SECRET, key,
708
                                 ssl->specs.hash_size, ssl->tls13SecretCtx);
709
        if (ret != 0) {
710
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
711
            return TLS13_SECRET_CB_E;
712
        }
713
    }
714
#ifdef OPENSSL_EXTRA
715
    if (ret == 0 && ssl->tls13KeyLogCb != NULL) {
716
        ret = ssl->tls13KeyLogCb(ssl, EXPORTER_SECRET, key,
717
                                ssl->specs.hash_size, NULL);
718
        if (ret != 0) {
719
            WOLFSSL_ERROR_VERBOSE(TLS13_SECRET_CB_E);
720
            return TLS13_SECRET_CB_E;
721
        }
722
    }
723
#endif /* OPENSSL_EXTRA */
724
#endif /* HAVE_SECRET_CALLBACK */
725
    return ret;
726
}
727
728
/* The length of the exporter label. */
729
#define EXPORTER_LABEL_SZ    8
730
/* The exporter label. */
731
static const byte exporterLabel[EXPORTER_LABEL_SZ + 1] =
732
    "exporter";
733
/* Hash("") */
734
#ifndef NO_SHA256
735
static const byte emptySHA256Hash[] = {
736
    0xE3, 0xB0, 0xC4, 0x42, 0x98, 0xFC, 0x1C, 0x14, 0x9A, 0xFB, 0xF4, 0xC8,
737
    0x99, 0x6F, 0xB9, 0x24, 0x27, 0xAE, 0x41, 0xE4, 0x64, 0x9B, 0x93, 0x4C,
738
    0xA4, 0x95, 0x99, 0x1B, 0x78, 0x52, 0xB8, 0x55
739
};
740
#endif
741
#ifdef WOLFSSL_SHA384
742
static const byte emptySHA384Hash[] = {
743
    0x38, 0xB0, 0x60, 0xA7, 0x51, 0xAC, 0x96, 0x38, 0x4C, 0xD9, 0x32, 0x7E,
744
    0xB1, 0xB1, 0xE3, 0x6A, 0x21, 0xFD, 0xB7, 0x11, 0x14, 0xBE, 0x07, 0x43,
745
    0x4C, 0x0C, 0xC7, 0xBF, 0x63, 0xF6, 0xE1, 0xDA, 0x27, 0x4E, 0xDE, 0xBF,
746
    0xE7, 0x6F, 0x65, 0xFB, 0xD5, 0x1A, 0xD2, 0xF1, 0x48, 0x98, 0xB9, 0x5B
747
};
748
#endif
749
#ifdef WOLFSSL_TLS13_SHA512
750
static const byte emptySHA512Hash[] = {
751
    0xCF, 0x83, 0xE1, 0x35, 0x7E, 0xEF, 0xB8, 0xBD, 0xF1, 0x54, 0x28, 0x50,
752
    0xD6, 0x6D, 0x80, 0x07, 0xD6, 0x20, 0xE4, 0x05, 0x0B, 0x57, 0x15, 0xDC,
753
    0x83, 0xF4, 0xA9, 0x21, 0xD3, 0x6C, 0xE9, 0xCE, 0x47, 0xD0, 0xD1, 0x3C,
754
    0x5D, 0x85, 0xF2, 0xB0, 0xFF, 0x83, 0x18, 0xD2, 0x87, 0x7E, 0xEC, 0x2F,
755
    0x63, 0xB9, 0x31, 0xBD, 0x47, 0x41, 0x7A, 0x81, 0xA5, 0x38, 0x32, 0x7A,
756
    0xF9, 0x27, 0xDA, 0x3E
757
};
758
#endif
759
/**
760
 * Implement section 7.5 of RFC 8446
761
 * @return  0 on success
762
 *         <0 on failure
763
 */
764
int Tls13_Exporter(WOLFSSL* ssl, unsigned char *out, size_t outLen,
765
        const char *label, size_t labelLen,
766
        const unsigned char *context, size_t contextLen)
767
{
768
    int                 ret;
769
    enum wc_HashType    hashType = WC_HASH_TYPE_NONE;
770
    int                 hashLen = 0;
771
    byte                hashOut[WC_MAX_DIGEST_SIZE];
772
    const byte*         emptyHash = NULL;
773
    byte                firstExpand[WC_MAX_DIGEST_SIZE];
774
    const byte*         protocol = tls13ProtocolLabel;
775
    word32              protocolLen = TLS13_PROTOCOL_LABEL_SZ;
776
777
    if (ssl->version.minor != TLSv1_3_MINOR)
778
        return VERSION_ERROR;
779
780
    switch (ssl->specs.mac_algorithm) {
781
        #ifndef NO_SHA256
782
        case sha256_mac:
783
            hashType  = WC_HASH_TYPE_SHA256;
784
            hashLen   = WC_SHA256_DIGEST_SIZE;
785
            emptyHash = emptySHA256Hash;
786
            break;
787
        #endif
788
789
        #ifdef WOLFSSL_SHA384
790
        case sha384_mac:
791
            hashType  = WC_HASH_TYPE_SHA384;
792
            hashLen   = WC_SHA384_DIGEST_SIZE;
793
            emptyHash = emptySHA384Hash;
794
            break;
795
        #endif
796
797
        #ifdef WOLFSSL_TLS13_SHA512
798
        case sha512_mac:
799
            hashType  = WC_HASH_TYPE_SHA512;
800
            hashLen   = WC_SHA512_DIGEST_SIZE;
801
            emptyHash = emptySHA512Hash;
802
            break;
803
        #endif
804
    }
805
806
    /* Derive-Secret(Secret, label, "") */
807
    PRIVATE_KEY_UNLOCK();
808
    ret = wc_Tls13_HKDF_Expand_Label(firstExpand, hashLen,
809
            ssl->arrays->exporterSecret, hashLen,
810
            protocol, protocolLen, (byte*)label, (word32)labelLen,
811
            emptyHash, hashLen, hashType);
812
    PRIVATE_KEY_LOCK();
813
    if (ret != 0)
814
        return ret;
815
816
    /* Hash(context_value) */
817
    ret = wc_Hash(hashType, context, (word32)contextLen, hashOut, WC_MAX_DIGEST_SIZE);
818
    if (ret != 0)
819
        return ret;
820
821
    PRIVATE_KEY_UNLOCK();
822
    ret = wc_Tls13_HKDF_Expand_Label(out, (word32)outLen, firstExpand, hashLen,
823
            protocol, protocolLen, exporterLabel, EXPORTER_LABEL_SZ,
824
            hashOut, hashLen, hashType);
825
    PRIVATE_KEY_LOCK();
826
827
    return ret;
828
}
829
#endif
830
831
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
832
/* The length of the resumption master secret label. */
833
#define RESUME_MASTER_LABEL_SZ      10
834
/* The resumption master secret label. */
835
static const byte resumeMasterLabel[RESUME_MASTER_LABEL_SZ + 1] =
836
    "res master";
837
838
/* Derive the resumption secret.
839
 *
840
 * ssl  The SSL/TLS object.
841
 * key  The derived key.
842
 * returns 0 on success, otherwise failure.
843
 */
844
int DeriveResumptionSecret(WOLFSSL* ssl, byte* key)
845
{
846
    byte* masterSecret;
847
848
    WOLFSSL_MSG("Derive Resumption Secret");
849
    if (ssl == NULL) {
850
        return BAD_FUNC_ARG;
851
    }
852
    if (ssl->arrays != NULL) {
853
        masterSecret = ssl->arrays->masterSecret;
854
    }
855
    else {
856
        masterSecret = ssl->session->masterSecret;
857
    }
858
    return Tls13DeriveKey(ssl, key, -1, masterSecret, resumeMasterLabel,
859
                     RESUME_MASTER_LABEL_SZ, ssl->specs.mac_algorithm, 1);
860
}
861
#endif
862
863
/* Length of the finished label. */
864
0
#define FINISHED_LABEL_SZ           8
865
/* Finished label for generating finished key. */
866
static const byte finishedLabel[FINISHED_LABEL_SZ+1] = "finished";
867
/* Derive the finished secret.
868
 *
869
 * ssl     The SSL/TLS object.
870
 * key     The key to use with the HMAC.
871
 * secret  The derived secret.
872
 * returns 0 on success, otherwise failure.
873
 */
874
static int DeriveFinishedSecret(WOLFSSL* ssl, byte* key, byte* secret)
875
0
{
876
0
    WOLFSSL_MSG("Derive Finished Secret");
877
0
    return Tls13DeriveKey(ssl, secret, -1, key, finishedLabel, FINISHED_LABEL_SZ,
878
0
                     ssl->specs.mac_algorithm, 0);
879
0
}
880
881
/* The length of the application traffic label. */
882
0
#define APP_TRAFFIC_LABEL_SZ        11
883
/* The application traffic label. */
884
static const byte appTrafficLabel[APP_TRAFFIC_LABEL_SZ + 1] =
885
    "traffic upd";
886
887
/* Update the traffic secret.
888
 *
889
 * ssl     The SSL/TLS object.
890
 * secret  The previous secret and derived secret.
891
 * returns 0 on success, otherwise failure.
892
 */
893
static int DeriveTrafficSecret(WOLFSSL* ssl, byte* secret)
894
0
{
895
0
    WOLFSSL_MSG("Derive New Application Traffic Secret");
896
0
    return Tls13DeriveKey(ssl, secret, -1, secret,
897
0
                     appTrafficLabel, APP_TRAFFIC_LABEL_SZ,
898
0
                     ssl->specs.mac_algorithm, 0);
899
0
}
900
901
902
static int Tls13_HKDF_Extract(WOLFSSL *ssl, byte* prk, const byte* salt, int saltLen,
903
                                 byte* ikm, int ikmLen, int digest)
904
0
{
905
0
    int ret;
906
#ifdef HAVE_PK_CALLBACKS
907
    void *cb_ctx = ssl->HkdfExtractCtx;
908
    CallbackHKDFExtract cb = ssl->ctx->HkdfExtractCb;
909
    if (cb != NULL) {
910
        ret = cb(prk, salt, saltLen, ikm, ikmLen, digest, cb_ctx);
911
    }
912
    else
913
#endif
914
0
    {
915
0
        (void)ssl;
916
0
        ret = wc_Tls13_HKDF_Extract(prk, salt, saltLen, ikm, ikmLen, digest);
917
0
    }
918
0
    return ret;
919
0
}
920
921
/* Derive the early secret using HKDF Extract.
922
 *
923
 * ssl  The SSL/TLS object.
924
 */
925
int DeriveEarlySecret(WOLFSSL* ssl)
926
0
{
927
0
    int ret;
928
929
0
    WOLFSSL_MSG("Derive Early Secret");
930
0
    if (ssl == NULL || ssl->arrays == NULL) {
931
0
        return BAD_FUNC_ARG;
932
0
    }
933
#if defined(WOLFSSL_RENESAS_TSIP_TLS) && (WOLFSSL_RENESAS_TSIP_VER >= 115)
934
    ret = tsip_Tls13DeriveEarlySecret(ssl);
935
    if (ret != CRYPTOCB_UNAVAILABLE)
936
        return ret;
937
#endif
938
0
    PRIVATE_KEY_UNLOCK();
939
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
940
    ret = Tls13_HKDF_Extract(ssl, ssl->arrays->secret, NULL, 0,
941
            ssl->arrays->psk_key, ssl->arrays->psk_keySz,
942
            mac2hash(ssl->specs.mac_algorithm));
943
#else
944
0
    ret = Tls13_HKDF_Extract(ssl, ssl->arrays->secret, NULL, 0,
945
0
            ssl->arrays->masterSecret, 0, mac2hash(ssl->specs.mac_algorithm));
946
0
#endif
947
0
    PRIVATE_KEY_LOCK();
948
0
    return ret;
949
0
}
950
951
/* The length of the derived label. */
952
0
#define DERIVED_LABEL_SZ        7
953
/* The derived label. */
954
static const byte derivedLabel[DERIVED_LABEL_SZ + 1] =
955
    "derived";
956
957
/* Derive the handshake secret using HKDF Extract.
958
 *
959
 * ssl  The SSL/TLS object.
960
 */
961
int DeriveHandshakeSecret(WOLFSSL* ssl)
962
0
{
963
0
    byte key[WC_MAX_DIGEST_SIZE];
964
0
    int ret;
965
0
    WOLFSSL_MSG("Derive Handshake Secret");
966
0
    if (ssl == NULL || ssl->arrays == NULL) {
967
0
        return BAD_FUNC_ARG;
968
0
    }
969
#if defined(WOLFSSL_RENESAS_TSIP_TLS) && (WOLFSSL_RENESAS_TSIP_VER >= 115)
970
    ret = tsip_Tls13DeriveHandshakeSecret(ssl);
971
    if (ret != CRYPTOCB_UNAVAILABLE)
972
        return ret;
973
#endif
974
975
0
    ret = DeriveKeyMsg(ssl, key, -1, ssl->arrays->secret,
976
0
                        derivedLabel, DERIVED_LABEL_SZ,
977
0
                        NULL, 0, ssl->specs.mac_algorithm);
978
0
    if (ret != 0)
979
0
        return ret;
980
981
0
    PRIVATE_KEY_UNLOCK();
982
0
    ret = Tls13_HKDF_Extract(ssl, ssl->arrays->preMasterSecret,
983
0
            key, ssl->specs.hash_size,
984
0
            ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz,
985
0
            mac2hash(ssl->specs.mac_algorithm));
986
0
    PRIVATE_KEY_LOCK();
987
988
0
    return ret;
989
0
}
990
991
/* Derive the master secret using HKDF Extract.
992
 *
993
 * ssl  The SSL/TLS object.
994
 */
995
int DeriveMasterSecret(WOLFSSL* ssl)
996
0
{
997
0
    byte key[WC_MAX_DIGEST_SIZE];
998
0
    int ret;
999
0
    WOLFSSL_MSG("Derive Master Secret");
1000
0
    if (ssl == NULL || ssl->arrays == NULL) {
1001
0
        return BAD_FUNC_ARG;
1002
0
    }
1003
1004
#if defined(WOLFSSL_RENESAS_TSIP_TLS) && (WOLFSSL_RENESAS_TSIP_VER >= 115)
1005
    ret = tsip_Tls13DeriveMasterSecret(ssl);
1006
    if (ret != CRYPTOCB_UNAVAILABLE)
1007
        return ret;
1008
#endif
1009
1010
0
    ret = DeriveKeyMsg(ssl, key, -1, ssl->arrays->preMasterSecret,
1011
0
                        derivedLabel, DERIVED_LABEL_SZ,
1012
0
                        NULL, 0, ssl->specs.mac_algorithm);
1013
0
    if (ret != 0)
1014
0
        return ret;
1015
1016
0
    PRIVATE_KEY_UNLOCK();
1017
0
    ret = Tls13_HKDF_Extract(ssl, ssl->arrays->masterSecret,
1018
0
            key, ssl->specs.hash_size,
1019
0
            ssl->arrays->masterSecret, 0, mac2hash(ssl->specs.mac_algorithm));
1020
0
    PRIVATE_KEY_LOCK();
1021
1022
#ifdef HAVE_KEYING_MATERIAL
1023
    if (ret != 0)
1024
        return ret;
1025
    /* Calculate exporter secret only when saving arrays */
1026
    if (ssl->options.saveArrays)
1027
        ret = DeriveExporterSecret(ssl, ssl->arrays->exporterSecret);
1028
#endif
1029
1030
0
    return ret;
1031
0
}
1032
1033
#if defined(HAVE_SESSION_TICKET)
1034
/* Length of the resumption label. */
1035
#define RESUMPTION_LABEL_SZ         10
1036
/* Resumption label for generating PSK associated with the ticket. */
1037
static const byte resumptionLabel[RESUMPTION_LABEL_SZ+1] = "resumption";
1038
/* Derive the PSK associated with the ticket.
1039
 *
1040
 * ssl       The SSL/TLS object.
1041
 * nonce     The nonce to derive with.
1042
 * nonceLen  The length of the nonce to derive with.
1043
 * secret    The derived secret.
1044
 * returns 0 on success, otherwise failure.
1045
 */
1046
int DeriveResumptionPSK(WOLFSSL* ssl, byte* nonce, byte nonceLen, byte* secret)
1047
{
1048
    int         digestAlg;
1049
    /* Only one protocol version defined at this time. */
1050
    const byte* protocol    = tls13ProtocolLabel;
1051
    word32      protocolLen = TLS13_PROTOCOL_LABEL_SZ;
1052
    int         ret;
1053
1054
    WOLFSSL_MSG("Derive Resumption PSK");
1055
1056
    switch (ssl->specs.mac_algorithm) {
1057
        #ifndef NO_SHA256
1058
        case sha256_mac:
1059
            digestAlg = WC_SHA256;
1060
            break;
1061
        #endif
1062
1063
        #ifdef WOLFSSL_SHA384
1064
        case sha384_mac:
1065
            digestAlg = WC_SHA384;
1066
            break;
1067
        #endif
1068
1069
        #ifdef WOLFSSL_TLS13_SHA512
1070
        case sha512_mac:
1071
            digestAlg = WC_SHA512;
1072
            break;
1073
        #endif
1074
1075
        default:
1076
            return BAD_FUNC_ARG;
1077
    }
1078
1079
    PRIVATE_KEY_UNLOCK();
1080
    ret = wc_Tls13_HKDF_Expand_Label(secret, ssl->specs.hash_size,
1081
                             ssl->session->masterSecret, ssl->specs.hash_size,
1082
                             protocol, protocolLen, resumptionLabel,
1083
                             RESUMPTION_LABEL_SZ, nonce, nonceLen, digestAlg);
1084
    PRIVATE_KEY_LOCK();
1085
    return ret;
1086
}
1087
#endif /* HAVE_SESSION_TICKET */
1088
1089
1090
/* Calculate the HMAC of message data to this point.
1091
 *
1092
 * ssl   The SSL/TLS object.
1093
 * key   The HMAC key.
1094
 * hash  The hash result - verify data.
1095
 * returns length of verify data generated.
1096
 */
1097
static int BuildTls13HandshakeHmac(WOLFSSL* ssl, byte* key, byte* hash,
1098
    word32* pHashSz)
1099
0
{
1100
0
    Hmac verifyHmac;
1101
0
    int  hashType = WC_SHA256;
1102
0
    int  hashSz = WC_SHA256_DIGEST_SIZE;
1103
0
    int  ret = BAD_FUNC_ARG;
1104
1105
0
    if (ssl == NULL || key == NULL || hash == NULL) {
1106
0
        return BAD_FUNC_ARG;
1107
0
    }
1108
1109
    /* Get the hash of the previous handshake messages. */
1110
0
    switch (ssl->specs.mac_algorithm) {
1111
0
    #ifndef NO_SHA256
1112
0
        case sha256_mac:
1113
0
            hashType = WC_SHA256;
1114
0
            hashSz = WC_SHA256_DIGEST_SIZE;
1115
0
            ret = wc_Sha256GetHash(&ssl->hsHashes->hashSha256, hash);
1116
0
            break;
1117
0
    #endif /* !NO_SHA256 */
1118
0
    #ifdef WOLFSSL_SHA384
1119
0
        case sha384_mac:
1120
0
            hashType = WC_SHA384;
1121
0
            hashSz = WC_SHA384_DIGEST_SIZE;
1122
0
            ret = wc_Sha384GetHash(&ssl->hsHashes->hashSha384, hash);
1123
0
            break;
1124
0
    #endif /* WOLFSSL_SHA384 */
1125
    #ifdef WOLFSSL_TLS13_SHA512
1126
        case sha512_mac:
1127
            hashType = WC_SHA512;
1128
            hashSz = WC_SHA512_DIGEST_SIZE;
1129
            ret = wc_Sha512GetHash(&ssl->hsHashes->hashSha512, hash);
1130
            break;
1131
    #endif /* WOLFSSL_TLS13_SHA512 */
1132
0
        default:
1133
0
            break;
1134
0
    }
1135
0
    if (ret != 0)
1136
0
        return ret;
1137
1138
#ifdef WOLFSSL_DEBUG_TLS
1139
    WOLFSSL_MSG("  Key");
1140
    WOLFSSL_BUFFER(key, ssl->specs.hash_size);
1141
    WOLFSSL_MSG("  Msg Hash");
1142
    WOLFSSL_BUFFER(hash, hashSz);
1143
#endif
1144
1145
    /* Calculate the verify data. */
1146
0
    ret = wc_HmacInit(&verifyHmac, ssl->heap, ssl->devId);
1147
0
    if (ret == 0) {
1148
0
        ret = wc_HmacSetKey(&verifyHmac, hashType, key, ssl->specs.hash_size);
1149
0
        if (ret == 0)
1150
0
            ret = wc_HmacUpdate(&verifyHmac, hash, hashSz);
1151
0
        if (ret == 0)
1152
0
            ret = wc_HmacFinal(&verifyHmac, hash);
1153
0
        wc_HmacFree(&verifyHmac);
1154
0
    }
1155
1156
#ifdef WOLFSSL_DEBUG_TLS
1157
    WOLFSSL_MSG("  Hash");
1158
    WOLFSSL_BUFFER(hash, hashSz);
1159
#endif
1160
1161
0
    if (pHashSz)
1162
0
        *pHashSz = hashSz;
1163
1164
0
    return ret;
1165
0
}
1166
1167
/* The length of the label to use when deriving keys. */
1168
0
#define WRITE_KEY_LABEL_SZ     3
1169
/* The length of the label to use when deriving IVs. */
1170
0
#define WRITE_IV_LABEL_SZ      2
1171
/* The label to use when deriving keys. */
1172
static const byte writeKeyLabel[WRITE_KEY_LABEL_SZ+1] = "key";
1173
/* The label to use when deriving IVs. */
1174
static const byte writeIVLabel[WRITE_IV_LABEL_SZ+1]   = "iv";
1175
1176
/* Derive the keys and IVs for TLS v1.3.
1177
 *
1178
 * ssl      The SSL/TLS object.
1179
 * secret   early_data_key when deriving the key and IV for encrypting early
1180
 *          data application data and end_of_early_data messages.
1181
 *          handshake_key when deriving keys and IVs for encrypting handshake
1182
 *          messages.
1183
 *          traffic_key when deriving first keys and IVs for encrypting
1184
 *          traffic messages.
1185
 *          update_traffic_key when deriving next keys and IVs for encrypting
1186
 *          traffic messages.
1187
 * side     ENCRYPT_SIDE_ONLY when only encryption secret needs to be derived.
1188
 *          DECRYPT_SIDE_ONLY when only decryption secret needs to be derived.
1189
 *          ENCRYPT_AND_DECRYPT_SIDE when both secret needs to be derived.
1190
 * store    1 indicates to derive the keys and IVs from derived secret and
1191
 *          store ready for provisioning.
1192
 * returns 0 on success, otherwise failure.
1193
 */
1194
int DeriveTls13Keys(WOLFSSL* ssl, int secret, int side, int store)
1195
0
{
1196
0
    int   ret = BAD_FUNC_ARG; /* Assume failure */
1197
0
    int   i = 0;
1198
0
#ifdef WOLFSSL_SMALL_STACK
1199
0
    byte* key_dig;
1200
#else
1201
    byte  key_dig[MAX_PRF_DIG];
1202
#endif
1203
0
    int   provision;
1204
1205
#if defined(WOLFSSL_RENESAS_TSIP_TLS) && (WOLFSSL_RENESAS_TSIP_VER >= 115)
1206
    ret = tsip_Tls13DeriveKeys(ssl, secret, side);
1207
    if (ret != CRYPTOCB_UNAVAILABLE) {
1208
        return ret;
1209
    }
1210
    ret = BAD_FUNC_ARG; /* Assume failure */
1211
#endif
1212
1213
0
#ifdef WOLFSSL_SMALL_STACK
1214
0
    key_dig = (byte*)XMALLOC(MAX_PRF_DIG, ssl->heap, DYNAMIC_TYPE_DIGEST);
1215
0
    if (key_dig == NULL)
1216
0
        return MEMORY_E;
1217
0
#endif
1218
1219
0
    if (side == ENCRYPT_AND_DECRYPT_SIDE) {
1220
0
        provision = PROVISION_CLIENT_SERVER;
1221
0
    }
1222
0
    else {
1223
0
        provision = ((ssl->options.side != WOLFSSL_CLIENT_END) ^
1224
0
                     (side == ENCRYPT_SIDE_ONLY)) ? PROVISION_CLIENT :
1225
0
                                                    PROVISION_SERVER;
1226
0
    }
1227
1228
    /* Derive the appropriate secret to use in the HKDF. */
1229
0
    switch (secret) {
1230
#ifdef WOLFSSL_EARLY_DATA
1231
        case early_data_key:
1232
            ret = DeriveEarlyTrafficSecret(ssl, ssl->clientSecret);
1233
            if (ret != 0)
1234
                goto end;
1235
            break;
1236
#endif
1237
1238
0
        case handshake_key:
1239
0
            if (provision & PROVISION_CLIENT) {
1240
0
                ret = DeriveClientHandshakeSecret(ssl,
1241
0
                                                  ssl->clientSecret);
1242
0
                if (ret != 0)
1243
0
                    goto end;
1244
0
            }
1245
0
            if (provision & PROVISION_SERVER) {
1246
0
                ret = DeriveServerHandshakeSecret(ssl,
1247
0
                                                  ssl->serverSecret);
1248
0
                if (ret != 0)
1249
0
                    goto end;
1250
0
            }
1251
0
            break;
1252
1253
0
        case traffic_key:
1254
0
            if (provision & PROVISION_CLIENT) {
1255
0
                ret = DeriveClientTrafficSecret(ssl, ssl->clientSecret);
1256
0
                if (ret != 0)
1257
0
                    goto end;
1258
0
            }
1259
0
            if (provision & PROVISION_SERVER) {
1260
0
                ret = DeriveServerTrafficSecret(ssl, ssl->serverSecret);
1261
0
                if (ret != 0)
1262
0
                    goto end;
1263
0
            }
1264
0
            break;
1265
1266
0
        case update_traffic_key:
1267
0
            if (provision & PROVISION_CLIENT) {
1268
0
                ret = DeriveTrafficSecret(ssl, ssl->clientSecret);
1269
0
                if (ret != 0)
1270
0
                    goto end;
1271
0
            }
1272
0
            if (provision & PROVISION_SERVER) {
1273
0
                ret = DeriveTrafficSecret(ssl, ssl->serverSecret);
1274
0
                if (ret != 0)
1275
0
                    goto end;
1276
0
            }
1277
0
            break;
1278
1279
0
        default:
1280
0
            break;
1281
0
    }
1282
1283
#ifdef WOLFSSL_QUIC
1284
    if (WOLFSSL_IS_QUIC(ssl)) {
1285
        ret = wolfSSL_quic_forward_secrets(ssl, secret, side);
1286
        if (ret != 0)
1287
            goto end;
1288
    }
1289
#endif /* WOLFSSL_QUIC */
1290
1291
0
    if (!store)
1292
0
        goto end;
1293
1294
    /* Key data = client key | server key | client IV | server IV */
1295
1296
0
    if (provision & PROVISION_CLIENT) {
1297
        /* Derive the client key.  */
1298
0
        WOLFSSL_MSG("Derive Client Key");
1299
0
        ret = Tls13DeriveKey(ssl, &key_dig[i], ssl->specs.key_size,
1300
0
                        ssl->clientSecret, writeKeyLabel,
1301
0
                        WRITE_KEY_LABEL_SZ, ssl->specs.mac_algorithm, 0);
1302
0
        if (ret != 0)
1303
0
            goto end;
1304
0
        i += ssl->specs.key_size;
1305
0
    }
1306
1307
0
    if (provision & PROVISION_SERVER) {
1308
        /* Derive the server key.  */
1309
0
        WOLFSSL_MSG("Derive Server Key");
1310
0
        ret = Tls13DeriveKey(ssl, &key_dig[i], ssl->specs.key_size,
1311
0
                        ssl->serverSecret, writeKeyLabel,
1312
0
                        WRITE_KEY_LABEL_SZ, ssl->specs.mac_algorithm, 0);
1313
0
        if (ret != 0)
1314
0
            goto end;
1315
0
        i += ssl->specs.key_size;
1316
0
    }
1317
1318
0
    if (provision & PROVISION_CLIENT) {
1319
        /* Derive the client IV.  */
1320
0
        WOLFSSL_MSG("Derive Client IV");
1321
0
        ret = Tls13DeriveKey(ssl, &key_dig[i], ssl->specs.iv_size,
1322
0
                        ssl->clientSecret, writeIVLabel,
1323
0
                        WRITE_IV_LABEL_SZ, ssl->specs.mac_algorithm, 0);
1324
0
        if (ret != 0)
1325
0
            goto end;
1326
0
        i += ssl->specs.iv_size;
1327
0
    }
1328
1329
0
    if (provision & PROVISION_SERVER) {
1330
        /* Derive the server IV.  */
1331
0
        WOLFSSL_MSG("Derive Server IV");
1332
0
        ret = Tls13DeriveKey(ssl, &key_dig[i], ssl->specs.iv_size,
1333
0
                        ssl->serverSecret, writeIVLabel,
1334
0
                        WRITE_IV_LABEL_SZ, ssl->specs.mac_algorithm, 0);
1335
0
        if (ret != 0)
1336
0
            goto end;
1337
0
        i += ssl->specs.iv_size;
1338
0
    }
1339
1340
    /* Store keys and IVs but don't activate them. */
1341
0
    ret = StoreKeys(ssl, key_dig, provision);
1342
1343
#ifdef WOLFSSL_DTLS13
1344
    if (ret != 0)
1345
      goto end;
1346
1347
    if (ssl->options.dtls) {
1348
        ret = Dtls13DeriveSnKeys(ssl, provision);
1349
        if (ret != 0)
1350
            return ret;
1351
    }
1352
1353
#endif /* WOLFSSL_DTLS13 */
1354
1355
0
end:
1356
0
    ForceZero(key_dig, i);
1357
0
#ifdef WOLFSSL_SMALL_STACK
1358
0
    XFREE(key_dig, ssl->heap, DYNAMIC_TYPE_DIGEST);
1359
#elif defined(WOLFSSL_CHECK_MEM_ZERO)
1360
    wc_MemZero_Check(key_dig, MAX_PRF_DIG);
1361
#endif
1362
1363
0
    if (ret != 0) {
1364
0
        WOLFSSL_ERROR_VERBOSE(ret);
1365
0
    }
1366
1367
0
    return ret;
1368
0
}
1369
1370
#if (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
1371
#ifndef NO_ASN_TIME
1372
#if defined(USER_TICKS)
1373
#if 0
1374
    word32 TimeNowInMilliseconds(void)
1375
    {
1376
        /*
1377
        write your own clock tick function if don't want gettimeofday()
1378
        needs millisecond accuracy but doesn't have to correlated to EPOCH
1379
        */
1380
    }
1381
#endif
1382
1383
#elif defined(TIME_OVERRIDES)
1384
#if !defined(NO_ASN) && !defined(NO_ASN_TIME)
1385
    word32 TimeNowInMilliseconds(void)
1386
    {
1387
        return (word32) wc_Time(0) * 1000;
1388
    }
1389
#else
1390
    #ifndef HAVE_TIME_T_TYPE
1391
        typedef long time_t;
1392
    #endif
1393
    extern time_t XTIME(time_t * timer);
1394
1395
    /* The time in milliseconds.
1396
     * Used for tickets to represent difference between when first seen and when
1397
     * sending.
1398
     *
1399
     * returns the time in milliseconds as a 32-bit value.
1400
     */
1401
    word32 TimeNowInMilliseconds(void)
1402
    {
1403
        return (word32) XTIME(0) * 1000;
1404
    }
1405
#endif
1406
1407
#elif defined(XTIME_MS)
1408
    word32 TimeNowInMilliseconds(void)
1409
    {
1410
        return (word32)XTIME_MS(0);
1411
    }
1412
1413
#elif defined(USE_WINDOWS_API)
1414
    /* The time in milliseconds.
1415
     * Used for tickets to represent difference between when first seen and when
1416
     * sending.
1417
     *
1418
     * returns the time in milliseconds as a 32-bit value.
1419
     */
1420
    word32 TimeNowInMilliseconds(void)
1421
    {
1422
        static int           init = 0;
1423
        static LARGE_INTEGER freq;
1424
        LARGE_INTEGER        count;
1425
1426
        if (!init) {
1427
            QueryPerformanceFrequency(&freq);
1428
            init = 1;
1429
        }
1430
1431
        QueryPerformanceCounter(&count);
1432
1433
        return (word32)(count.QuadPart / (freq.QuadPart / 1000));
1434
    }
1435
1436
#elif defined(HAVE_RTP_SYS)
1437
    #include "rtptime.h"
1438
1439
    /* The time in milliseconds.
1440
     * Used for tickets to represent difference between when first seen and when
1441
     * sending.
1442
     *
1443
     * returns the time in milliseconds as a 32-bit value.
1444
     */
1445
    word32 TimeNowInMilliseconds(void)
1446
    {
1447
        return (word32)rtp_get_system_sec() * 1000;
1448
    }
1449
#elif defined(WOLFSSL_DEOS)
1450
    word32 TimeNowInMilliseconds(void)
1451
    {
1452
        const word32 systemTickTimeInHz = 1000000 / systemTickInMicroseconds();
1453
        word32 *systemTickPtr = systemTickPointer();
1454
1455
        return (word32) (*systemTickPtr/systemTickTimeInHz) * 1000;
1456
    }
1457
#elif defined(MICRIUM)
1458
    /* The time in milliseconds.
1459
     * Used for tickets to represent difference between when first seen and when
1460
     * sending.
1461
     *
1462
     * returns the time in milliseconds as a 32-bit value.
1463
     */
1464
    word32 TimeNowInMilliseconds(void)
1465
    {
1466
        OS_TICK ticks = 0;
1467
        OS_ERR  err;
1468
1469
        ticks = OSTimeGet(&err);
1470
1471
        return (word32) (ticks / OSCfg_TickRate_Hz) * 1000;
1472
    }
1473
#elif defined(MICROCHIP_TCPIP_V5)
1474
    /* The time in milliseconds.
1475
     * Used for tickets to represent difference between when first seen and when
1476
     * sending.
1477
     *
1478
     * returns the time in milliseconds as a 32-bit value.
1479
     */
1480
    word32 TimeNowInMilliseconds(void)
1481
    {
1482
        return (word32) (TickGet() / (TICKS_PER_SECOND / 1000));
1483
    }
1484
#elif defined(MICROCHIP_TCPIP)
1485
    #if defined(MICROCHIP_MPLAB_HARMONY)
1486
        #include <system/tmr/sys_tmr.h>
1487
1488
    /* The time in milliseconds.
1489
     * Used for tickets to represent difference between when first seen and when
1490
     * sending.
1491
     *
1492
     * returns the time in milliseconds as a 32-bit value.
1493
     */
1494
    word32 TimeNowInMilliseconds(void)
1495
    {
1496
        return (word32)(SYS_TMR_TickCountGet() /
1497
                        (SYS_TMR_TickCounterFrequencyGet() / 1000));
1498
    }
1499
    #else
1500
    /* The time in milliseconds.
1501
     * Used for tickets to represent difference between when first seen and when
1502
     * sending.
1503
     *
1504
     * returns the time in milliseconds as a 32-bit value.
1505
     */
1506
    word32 TimeNowInMilliseconds(void)
1507
    {
1508
        return (word32)(SYS_TICK_Get() / (SYS_TICK_TicksPerSecondGet() / 1000));
1509
    }
1510
1511
    #endif
1512
1513
#elif defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX)
1514
    /* The time in milliseconds.
1515
     * Used for tickets to represent difference between when first seen and when
1516
     * sending.
1517
     *
1518
     * returns the time in milliseconds as a 32-bit value.
1519
     */
1520
    word32 TimeNowInMilliseconds(void)
1521
    {
1522
        TIME_STRUCT mqxTime;
1523
1524
        _time_get_elapsed(&mqxTime);
1525
1526
        return (word32) mqxTime.SECONDS * 1000;
1527
    }
1528
#elif defined(FREESCALE_FREE_RTOS) || defined(FREESCALE_KSDK_FREERTOS)
1529
    #include "include/task.h"
1530
1531
    /* The time in milliseconds.
1532
     * Used for tickets to represent difference between when first seen and when
1533
     * sending.
1534
     *
1535
     * returns the time in milliseconds as a 32-bit value.
1536
     */
1537
    word32 TimeNowInMilliseconds(void)
1538
    {
1539
        return (unsigned int)(((float)xTaskGetTickCount()) /
1540
                              (configTICK_RATE_HZ / 1000));
1541
    }
1542
#elif defined(FREESCALE_KSDK_BM)
1543
    #include "lwip/sys.h" /* lwIP */
1544
1545
    /* The time in milliseconds.
1546
     * Used for tickets to represent difference between when first seen and when
1547
     * sending.
1548
     *
1549
     * returns the time in milliseconds as a 32-bit value.
1550
     */
1551
    word32 TimeNowInMilliseconds(void)
1552
    {
1553
        return sys_now();
1554
    }
1555
#elif defined(WOLFSSL_TIRTOS)
1556
    /* The time in milliseconds.
1557
     * Used for tickets to represent difference between when first seen and when
1558
     * sending.
1559
     *
1560
     * returns the time in milliseconds as a 32-bit value.
1561
     */
1562
    word32 TimeNowInMilliseconds(void)
1563
    {
1564
        return (word32) Seconds_get() * 1000;
1565
    }
1566
#elif defined(WOLFSSL_UTASKER)
1567
    /* The time in milliseconds.
1568
     * Used for tickets to represent difference between when first seen and when
1569
     * sending.
1570
     *
1571
     * returns the time in milliseconds as a 32-bit value.
1572
     */
1573
    word32 TimeNowInMilliseconds(void)
1574
    {
1575
        return (word32)(uTaskerSystemTick / (TICK_RESOLUTION / 1000));
1576
    }
1577
#elif defined(WOLFSSL_LINUXKM)
1578
    word32 TimeNowInMilliseconds(void)
1579
    {
1580
        s64 t;
1581
#if LINUX_VERSION_CODE < KERNEL_VERSION(4, 0, 0)
1582
        struct timespec ts;
1583
        getnstimeofday(&ts);
1584
        t = ts.tv_sec * (s64)1000;
1585
        t += ts.tv_nsec / (s64)1000000;
1586
#else
1587
        struct timespec64 ts;
1588
#if LINUX_VERSION_CODE < KERNEL_VERSION(5, 0, 0)
1589
        ts = current_kernel_time64();
1590
#else
1591
        ktime_get_coarse_real_ts64(&ts);
1592
#endif
1593
        t = ts.tv_sec * 1000L;
1594
        t += ts.tv_nsec / 1000000L;
1595
#endif
1596
        return (word32)t;
1597
    }
1598
#elif defined(WOLFSSL_QNX_CAAM)
1599
    word32 TimeNowInMilliseconds(void)
1600
    {
1601
        struct timespec now;
1602
        clock_gettime(CLOCK_REALTIME, &now);
1603
        return (word32)(now.tv_sec * 1000 + now.tv_nsec / 1000000);
1604
    }
1605
#elif defined(FUSION_RTOS)
1606
    /* The time in milliseconds.
1607
     * Used for tickets to represent difference between when first seen and when
1608
     * sending.
1609
     *
1610
     * returns the time in milliseconds as a 32-bit value.
1611
     */
1612
    word32 TimeNowInMilliseconds(void)
1613
    {
1614
        struct timeval now;
1615
        if (FCL_GETTIMEOFDAY(&now, 0) < 0)
1616
            return (word32)GETTIME_ERROR; /* TODO: return 0 for failure */
1617
1618
        /* Convert to milliseconds number. */
1619
        return (word32)(now.tv_sec * 1000 + now.tv_usec / 1000);
1620
    }
1621
#elif defined(WOLFSSL_ZEPHYR)
1622
    word32 TimeNowInMilliseconds(void)
1623
    {
1624
    #if defined(CONFIG_ARCH_POSIX)
1625
        k_cpu_idle();
1626
    #endif
1627
        return (word32)k_uptime_get() / 1000;
1628
    }
1629
1630
#else
1631
    /* The time in milliseconds.
1632
     * Used for tickets to represent difference between when first seen and when
1633
     * sending.
1634
     *
1635
     * returns the time in milliseconds as a 32-bit value.
1636
     */
1637
    word32 TimeNowInMilliseconds(void)
1638
    {
1639
        struct timeval now;
1640
1641
        if (gettimeofday(&now, 0) < 0)
1642
            return (word32)GETTIME_ERROR; /* TODO: return 0 for failure */
1643
1644
        /* Convert to milliseconds number. */
1645
        return (word32)(now.tv_sec * 1000 + now.tv_usec / 1000);
1646
    }
1647
#endif
1648
#else
1649
    /* user must supply time in milliseconds function:
1650
     *   word32 TimeNowInMilliseconds(void);
1651
     * The response is milliseconds elapsed
1652
     */
1653
#endif /* !NO_ASN_TIME */
1654
#endif /* HAVE_SESSION_TICKET || !NO_PSK */
1655
1656
1657
/* Extract the handshake header information.
1658
 *
1659
 * ssl       The SSL/TLS object.
1660
 * input     The buffer holding the message data.
1661
 * inOutIdx  On entry, the index into the buffer of the handshake data.
1662
 *           On exit, the start of the handshake data.
1663
 * type      Type of handshake message.
1664
 * size      The length of the handshake message data.
1665
 * totalSz   The total size of data in the buffer.
1666
 * returns BUFFER_E if there is not enough input data and 0 on success.
1667
 */
1668
static int GetHandshakeHeader(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
1669
                              byte* type, word32* size, word32 totalSz)
1670
0
{
1671
0
    const byte* ptr = input + *inOutIdx;
1672
0
    (void)ssl;
1673
1674
0
    *inOutIdx += HANDSHAKE_HEADER_SZ;
1675
0
    if (*inOutIdx > totalSz)
1676
0
        return BUFFER_E;
1677
1678
0
    *type = ptr[0];
1679
0
    c24to32(&ptr[1], size);
1680
1681
0
    return 0;
1682
0
}
1683
1684
/* Add record layer header to message.
1685
 *
1686
 * output  The buffer to write the record layer header into.
1687
 * length  The length of the record data.
1688
 * type    The type of record message.
1689
 * ssl     The SSL/TLS object.
1690
 */
1691
static void AddTls13RecordHeader(byte* output, word32 length, byte type,
1692
                                 WOLFSSL* ssl)
1693
0
{
1694
0
    RecordLayerHeader* rl;
1695
1696
0
    rl = (RecordLayerHeader*)output;
1697
0
    rl->type    = type;
1698
0
    rl->pvMajor = ssl->version.major;
1699
    /* NOTE: May be TLSv1_MINOR when sending first ClientHello. */
1700
0
    rl->pvMinor = TLSv1_2_MINOR;
1701
0
    c16toa((word16)length, rl->length);
1702
0
}
1703
1704
/* Add handshake header to message.
1705
 *
1706
 * output      The buffer to write the handshake header into.
1707
 * length      The length of the handshake data.
1708
 * fragOffset  The offset of the fragment data. (DTLS)
1709
 * fragLength  The length of the fragment data. (DTLS)
1710
 * type        The type of handshake message.
1711
 * ssl         The SSL/TLS object. (DTLS)
1712
 */
1713
static void AddTls13HandShakeHeader(byte* output, word32 length,
1714
                                    word32 fragOffset, word32 fragLength,
1715
                                    byte type, WOLFSSL* ssl)
1716
0
{
1717
0
    HandShakeHeader* hs;
1718
0
    (void)fragOffset;
1719
0
    (void)fragLength;
1720
0
    (void)ssl;
1721
1722
#ifdef WOLFSSL_DTLS13
1723
    /* message_hash type is used for a syntetic message that replaces the first
1724
       ClientHello in the hash transcript when using HelloRetryRequest. It will
1725
       never be transmitted and, as the DTLS-only fields must not be considered
1726
       when computing the hash transcript, we can avoid to use the DTLS
1727
       handshake header. */
1728
    if (ssl->options.dtls && type != message_hash) {
1729
        Dtls13HandshakeAddHeader(ssl, output, (enum HandShakeType)type, length);
1730
        return;
1731
    }
1732
#endif /* WOLFSSL_DTLS13 */
1733
1734
    /* handshake header */
1735
0
    hs = (HandShakeHeader*)output;
1736
0
    hs->type = type;
1737
0
    c32to24(length, hs->length);
1738
0
}
1739
1740
1741
/* Add both record layer and handshake header to message.
1742
 *
1743
 * output      The buffer to write the headers into.
1744
 * length      The length of the handshake data.
1745
 * type        The type of record layer message.
1746
 * ssl         The SSL/TLS object. (DTLS)
1747
 */
1748
static void AddTls13Headers(byte* output, word32 length, byte type,
1749
                            WOLFSSL* ssl)
1750
0
{
1751
0
    word32 lengthAdj = HANDSHAKE_HEADER_SZ;
1752
0
    word32 outputAdj = RECORD_HEADER_SZ;
1753
1754
#ifdef WOLFSSL_DTLS13
1755
    if (ssl->options.dtls) {
1756
        Dtls13AddHeaders(output, length, (enum HandShakeType)type, ssl);
1757
        return;
1758
    }
1759
#endif /* WOLFSSL_DTLS13 */
1760
1761
0
    AddTls13RecordHeader(output, length + lengthAdj, handshake, ssl);
1762
0
    AddTls13HandShakeHeader(output + outputAdj, length, 0, length, type, ssl);
1763
0
}
1764
1765
#if (!defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER)) \
1766
    && !defined(NO_CERTS)
1767
/* Add both record layer and fragment handshake header to message.
1768
 *
1769
 * output      The buffer to write the headers into.
1770
 * fragOffset  The offset of the fragment data. (DTLS)
1771
 * fragLength  The length of the fragment data. (DTLS)
1772
 * length      The length of the handshake data.
1773
 * type        The type of record layer message.
1774
 * ssl         The SSL/TLS object. (DTLS)
1775
 */
1776
static void AddTls13FragHeaders(byte* output, word32 fragSz, word32 fragOffset,
1777
                                word32 length, byte type, WOLFSSL* ssl)
1778
0
{
1779
0
    word32 lengthAdj = HANDSHAKE_HEADER_SZ;
1780
0
    word32 outputAdj = RECORD_HEADER_SZ;
1781
0
    (void)fragSz;
1782
1783
#ifdef WOLFSSL_DTLS13
1784
    /* we ignore fragmentation fields here because fragmentation logic for
1785
       DTLS1.3 is inside dtls13_handshake_send(). */
1786
    if (ssl->options.dtls) {
1787
        Dtls13AddHeaders(output, length, (enum HandShakeType)type, ssl);
1788
        return;
1789
    }
1790
#endif /* WOLFSSL_DTLS13 */
1791
1792
0
    AddTls13RecordHeader(output, fragSz + lengthAdj, handshake, ssl);
1793
0
    AddTls13HandShakeHeader(output + outputAdj, length, fragOffset, fragSz,
1794
0
                            type, ssl);
1795
0
}
1796
#endif /* (!NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER) && !NO_CERTS */
1797
1798
/* Write the sequence number into the buffer.
1799
 * No DTLS v1.3 support.
1800
 *
1801
 * ssl          The SSL/TLS object.
1802
 * verifyOrder  Which set of sequence numbers to use.
1803
 * out          The buffer to write into.
1804
 */
1805
static WC_INLINE void WriteSEQTls13(WOLFSSL* ssl, int verifyOrder, byte* out)
1806
0
{
1807
0
    word32 seq[2] = {0, 0};
1808
1809
0
    if (ssl->options.dtls) {
1810
#ifdef WOLFSSL_DTLS13
1811
        Dtls13GetSeq(ssl, verifyOrder, seq, 1);
1812
#endif /* WOLFSSL_DTLS13 */
1813
0
    }
1814
0
    else if (verifyOrder) {
1815
0
        seq[0] = ssl->keys.peer_sequence_number_hi;
1816
0
        seq[1] = ssl->keys.peer_sequence_number_lo++;
1817
        /* handle rollover */
1818
0
        if (seq[1] > ssl->keys.peer_sequence_number_lo)
1819
0
            ssl->keys.peer_sequence_number_hi++;
1820
0
    }
1821
0
    else {
1822
0
        seq[0] = ssl->keys.sequence_number_hi;
1823
0
        seq[1] = ssl->keys.sequence_number_lo++;
1824
        /* handle rollover */
1825
0
        if (seq[1] > ssl->keys.sequence_number_lo)
1826
0
            ssl->keys.sequence_number_hi++;
1827
0
    }
1828
1829
0
    c32toa(seq[0], out);
1830
0
    c32toa(seq[1], out + OPAQUE32_LEN);
1831
0
}
1832
1833
/* Build the nonce for TLS v1.3 encryption and decryption.
1834
 *
1835
 * ssl    The SSL/TLS object.
1836
 * nonce  The nonce data to use when encrypting or decrypting.
1837
 * iv     The derived IV.
1838
 * order  The side on which the message is to be or was sent.
1839
 */
1840
static WC_INLINE void BuildTls13Nonce(WOLFSSL* ssl, byte* nonce, const byte* iv,
1841
                                   int order)
1842
0
{
1843
0
    int  i;
1844
1845
    /* The nonce is the IV with the sequence XORed into the last bytes. */
1846
0
    WriteSEQTls13(ssl, order, nonce + AEAD_NONCE_SZ - SEQ_SZ);
1847
0
    for (i = 0; i < AEAD_NONCE_SZ - SEQ_SZ; i++)
1848
0
        nonce[i] = iv[i];
1849
0
    for (; i < AEAD_NONCE_SZ; i++)
1850
0
        nonce[i] ^= iv[i];
1851
0
}
1852
1853
#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
1854
/* Encrypt with ChaCha20 and create authentication tag with Poly1305.
1855
 *
1856
 * ssl     The SSL/TLS object.
1857
 * output  The buffer to write encrypted data and authentication tag into.
1858
 *         May be the same pointer as input.
1859
 * input   The data to encrypt.
1860
 * sz      The number of bytes to encrypt.
1861
 * nonce   The nonce to use with ChaCha20.
1862
 * aad     The additional authentication data.
1863
 * aadSz   The size of the addition authentication data.
1864
 * tag     The authentication tag buffer.
1865
 * returns 0 on success, otherwise failure.
1866
 */
1867
static int ChaCha20Poly1305_Encrypt(WOLFSSL* ssl, byte* output,
1868
                                    const byte* input, word16 sz, byte* nonce,
1869
                                    const byte* aad, word16 aadSz, byte* tag)
1870
0
{
1871
0
    int    ret    = 0;
1872
0
    byte   poly[CHACHA20_256_KEY_SIZE];
1873
1874
    /* Poly1305 key is 256 bits of zero encrypted with ChaCha20. */
1875
0
    XMEMSET(poly, 0, sizeof(poly));
1876
1877
    /* Set the nonce for ChaCha and get Poly1305 key. */
1878
0
    ret = wc_Chacha_SetIV(ssl->encrypt.chacha, nonce, 0);
1879
0
    if (ret != 0)
1880
0
        return ret;
1881
    /* Create Poly1305 key using ChaCha20 keystream. */
1882
0
    ret = wc_Chacha_Process(ssl->encrypt.chacha, poly, poly, sizeof(poly));
1883
0
    if (ret != 0)
1884
0
        return ret;
1885
#ifdef WOLFSSL_CHECK_MEM_ZERO
1886
    wc_MemZero_Add("ChaCha20Poly1305_Encrypt poly", poly, sizeof(poly));
1887
#endif
1888
0
    ret = wc_Chacha_SetIV(ssl->encrypt.chacha, nonce, 1);
1889
0
    if (ret != 0)
1890
0
        return ret;
1891
    /* Encrypt the plain text. */
1892
0
    ret = wc_Chacha_Process(ssl->encrypt.chacha, output, input, sz);
1893
0
    if (ret != 0) {
1894
0
        ForceZero(poly, sizeof(poly));
1895
    #ifdef WOLFSSL_CHECK_MEM_ZERO
1896
        wc_MemZero_Check(poly, sizeof(poly));
1897
    #endif
1898
0
        return ret;
1899
0
    }
1900
1901
    /* Set key for Poly1305. */
1902
0
    ret = wc_Poly1305SetKey(ssl->auth.poly1305, poly, sizeof(poly));
1903
0
    ForceZero(poly, sizeof(poly)); /* done with poly1305 key, clear it */
1904
#ifdef WOLFSSL_CHECK_MEM_ZERO
1905
    wc_MemZero_Check(poly, sizeof(poly));
1906
#endif
1907
0
    if (ret != 0)
1908
0
        return ret;
1909
    /* Add authentication code of encrypted data to end. */
1910
0
    ret = wc_Poly1305_MAC(ssl->auth.poly1305, aad, aadSz, output, sz, tag,
1911
0
                                                              POLY1305_AUTH_SZ);
1912
1913
0
    return ret;
1914
0
}
1915
#endif
1916
1917
#ifdef HAVE_NULL_CIPHER
1918
/* Create authentication tag and copy data over input.
1919
 *
1920
 * ssl     The SSL/TLS object.
1921
 * output  The buffer to copy data into.
1922
 *         May be the same pointer as input.
1923
 * input   The data.
1924
 * sz      The number of bytes of data.
1925
 * nonce   The nonce to use with authentication.
1926
 * aad     The additional authentication data.
1927
 * aadSz   The size of the addition authentication data.
1928
 * tag     The authentication tag buffer.
1929
 * returns 0 on success, otherwise failure.
1930
 */
1931
static int Tls13IntegrityOnly_Encrypt(WOLFSSL* ssl, byte* output,
1932
                                      const byte* input, word16 sz,
1933
                                      const byte* nonce,
1934
                                      const byte* aad, word16 aadSz, byte* tag)
1935
{
1936
    int ret;
1937
1938
    /* HMAC: nonce | aad | input  */
1939
    ret = wc_HmacUpdate(ssl->encrypt.hmac, nonce, HMAC_NONCE_SZ);
1940
    if (ret == 0)
1941
        ret = wc_HmacUpdate(ssl->encrypt.hmac, aad, aadSz);
1942
    if (ret == 0)
1943
        ret = wc_HmacUpdate(ssl->encrypt.hmac, input, sz);
1944
    if (ret == 0)
1945
        ret = wc_HmacFinal(ssl->encrypt.hmac, tag);
1946
    /* Copy the input to output if not the same buffer */
1947
    if (ret == 0 && output != input)
1948
        XMEMCPY(output, input, sz);
1949
1950
    return ret;
1951
}
1952
#endif
1953
1954
/* Encrypt data for TLS v1.3.
1955
 *
1956
 * ssl     The SSL/TLS object.
1957
 * output  The buffer to write encrypted data and authentication tag into.
1958
 *         May be the same pointer as input.
1959
 * input   The record header and data to encrypt.
1960
 * sz      The number of bytes to encrypt.
1961
 * aad     The additional authentication data.
1962
 * aadSz   The size of the addition authentication data.
1963
 * asyncOkay If non-zero can return WC_PENDING_E, otherwise blocks on crypto
1964
 * returns 0 on success, otherwise failure.
1965
 */
1966
static int EncryptTls13(WOLFSSL* ssl, byte* output, const byte* input,
1967
                        word16 sz, const byte* aad, word16 aadSz, int asyncOkay)
1968
0
{
1969
0
    int    ret    = 0;
1970
0
    word16 dataSz = sz - ssl->specs.aead_mac_size;
1971
0
    word16 macSz  = ssl->specs.aead_mac_size;
1972
0
    word32 nonceSz = 0;
1973
#ifdef WOLFSSL_ASYNC_CRYPT
1974
    WC_ASYNC_DEV* asyncDev = NULL;
1975
    word32 event_flags = WC_ASYNC_FLAG_CALL_AGAIN;
1976
#endif
1977
1978
0
    WOLFSSL_ENTER("EncryptTls13");
1979
1980
0
    (void)output;
1981
0
    (void)input;
1982
0
    (void)sz;
1983
0
    (void)dataSz;
1984
0
    (void)macSz;
1985
0
    (void)asyncOkay;
1986
0
    (void)nonceSz;
1987
1988
#ifdef WOLFSSL_ASYNC_CRYPT
1989
    if (ssl->error == WC_PENDING_E) {
1990
        ssl->error = 0; /* clear async */
1991
    }
1992
#endif
1993
#if defined(WOLFSSL_RENESAS_TSIP_TLS) && (WOLFSSL_RENESAS_TSIP_VER >= 115)
1994
    ret = tsip_Tls13AesEncrypt(ssl, output, input, dataSz);
1995
    if (ret != CRYPTOCB_UNAVAILABLE) {
1996
        if (ret > 0) {
1997
            ret = 0; /* tsip_Tls13AesEncrypt returns output size */
1998
        }
1999
        return ret;
2000
    }
2001
    ret = 0;
2002
#endif /* WOLFSSL_RENESAS_TSIP_TLS && WOLFSSL_RENESAS_TSIP_VER >= 115 */
2003
2004
0
    switch (ssl->encrypt.state) {
2005
0
        case CIPHER_STATE_BEGIN:
2006
0
        {
2007
        #ifdef WOLFSSL_DEBUG_TLS
2008
            WOLFSSL_MSG("Data to encrypt");
2009
            WOLFSSL_BUFFER(input, dataSz);
2010
            WOLFSSL_MSG("Additional Authentication Data");
2011
            WOLFSSL_BUFFER(aad, aadSz);
2012
        #endif
2013
2014
        #ifdef WOLFSSL_CIPHER_TEXT_CHECK
2015
            if (ssl->specs.bulk_cipher_algorithm != wolfssl_cipher_null) {
2016
                XMEMCPY(ssl->encrypt.sanityCheck, input,
2017
                    min(dataSz, sizeof(ssl->encrypt.sanityCheck)));
2018
            }
2019
        #endif
2020
2021
0
        #ifdef CIPHER_NONCE
2022
0
            if (ssl->encrypt.nonce == NULL) {
2023
0
                ssl->encrypt.nonce = (byte*)XMALLOC(AEAD_NONCE_SZ,
2024
0
                                            ssl->heap, DYNAMIC_TYPE_AES_BUFFER);
2025
            #ifdef WOLFSSL_CHECK_MEM_ZERO
2026
                if (ssl->encrypt.nonce != NULL) {
2027
                    wc_MemZero_Add("EncryptTls13 nonce", ssl->encrypt.nonce,
2028
                        AEAD_NONCE_SZ);
2029
                }
2030
            #endif
2031
0
            }
2032
0
            if (ssl->encrypt.nonce == NULL)
2033
0
                return MEMORY_E;
2034
2035
0
            BuildTls13Nonce(ssl, ssl->encrypt.nonce, ssl->keys.aead_enc_imp_IV,
2036
0
                            CUR_ORDER);
2037
0
        #endif
2038
2039
            /* Advance state and proceed */
2040
0
            ssl->encrypt.state = CIPHER_STATE_DO;
2041
0
        }
2042
0
        FALL_THROUGH;
2043
2044
0
        case CIPHER_STATE_DO:
2045
0
        {
2046
0
            switch (ssl->specs.bulk_cipher_algorithm) {
2047
0
            #ifdef BUILD_AESGCM
2048
0
                case wolfssl_aes_gcm:
2049
                #ifdef WOLFSSL_ASYNC_CRYPT
2050
                    /* initialize event */
2051
                    asyncDev = &ssl->encrypt.aes->asyncDev;
2052
                    ret = wolfSSL_AsyncInit(ssl, asyncDev, event_flags);
2053
                    if (ret != 0)
2054
                        break;
2055
                #endif
2056
2057
0
                    nonceSz = AESGCM_NONCE_SZ;
2058
                #if ((defined(HAVE_FIPS) || defined(HAVE_SELFTEST)) && \
2059
                    (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2)))
2060
                    ret = wc_AesGcmEncrypt(ssl->encrypt.aes, output, input,
2061
                        dataSz, ssl->encrypt.nonce, nonceSz,
2062
                        output + dataSz, macSz, aad, aadSz);
2063
                #else
2064
0
                    ret = wc_AesGcmSetExtIV(ssl->encrypt.aes,
2065
0
                            ssl->encrypt.nonce, nonceSz);
2066
0
                    if (ret == 0) {
2067
0
                        ret = wc_AesGcmEncrypt_ex(ssl->encrypt.aes, output,
2068
0
                                input, dataSz, ssl->encrypt.nonce, nonceSz,
2069
0
                                output + dataSz, macSz, aad, aadSz);
2070
0
                    }
2071
0
                #endif
2072
0
                    break;
2073
0
            #endif
2074
2075
0
            #ifdef HAVE_AESCCM
2076
0
                case wolfssl_aes_ccm:
2077
                #ifdef WOLFSSL_ASYNC_CRYPT
2078
                    /* initialize event */
2079
                    asyncDev = &ssl->encrypt.aes->asyncDev;
2080
                    ret = wolfSSL_AsyncInit(ssl, asyncDev, event_flags);
2081
                    if (ret != 0)
2082
                        break;
2083
                #endif
2084
2085
0
                    nonceSz = AESCCM_NONCE_SZ;
2086
                #if ((defined(HAVE_FIPS) || defined(HAVE_SELFTEST)) && \
2087
                    (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2)))
2088
                    ret = wc_AesCcmEncrypt(ssl->encrypt.aes, output, input,
2089
                        dataSz, ssl->encrypt.nonce, nonceSz,
2090
                        output + dataSz, macSz, aad, aadSz);
2091
                #else
2092
0
                    ret = wc_AesCcmSetNonce(ssl->encrypt.aes,
2093
0
                            ssl->encrypt.nonce, nonceSz);
2094
0
                    if (ret == 0) {
2095
0
                        ret = wc_AesCcmEncrypt_ex(ssl->encrypt.aes, output,
2096
0
                                input, dataSz, ssl->encrypt.nonce, nonceSz,
2097
0
                                output + dataSz, macSz, aad, aadSz);
2098
0
                    }
2099
0
                #endif
2100
0
                    break;
2101
0
            #endif
2102
2103
0
            #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
2104
0
                case wolfssl_chacha:
2105
0
                    ret = ChaCha20Poly1305_Encrypt(ssl, output, input, dataSz,
2106
0
                        ssl->encrypt.nonce, aad, aadSz, output + dataSz);
2107
0
                    break;
2108
0
            #endif
2109
2110
            #ifdef HAVE_NULL_CIPHER
2111
                case wolfssl_cipher_null:
2112
                    ret = Tls13IntegrityOnly_Encrypt(ssl, output, input, dataSz,
2113
                        ssl->encrypt.nonce, aad, aadSz, output + dataSz);
2114
                    break;
2115
            #endif
2116
2117
0
                default:
2118
0
                    WOLFSSL_MSG("wolfSSL Encrypt programming error");
2119
0
                    return ENCRYPT_ERROR;
2120
0
            }
2121
2122
            /* Advance state */
2123
0
            ssl->encrypt.state = CIPHER_STATE_END;
2124
2125
        #ifdef WOLFSSL_ASYNC_CRYPT
2126
            if (ret == WC_PENDING_E) {
2127
                /* if async is not okay, then block */
2128
                if (!asyncOkay) {
2129
                    ret = wc_AsyncWait(ret, asyncDev, event_flags);
2130
                }
2131
                else {
2132
                    /* If pending, then leave and return will resume below */
2133
                    return wolfSSL_AsyncPush(ssl, asyncDev);
2134
                }
2135
            }
2136
        #endif
2137
0
        }
2138
0
        FALL_THROUGH;
2139
2140
0
        case CIPHER_STATE_END:
2141
0
        {
2142
        #ifdef WOLFSSL_DEBUG_TLS
2143
            #ifdef CIPHER_NONCE
2144
                WOLFSSL_MSG("Nonce");
2145
                WOLFSSL_BUFFER(ssl->encrypt.nonce, ssl->specs.iv_size);
2146
            #endif
2147
                WOLFSSL_MSG("Encrypted data");
2148
                WOLFSSL_BUFFER(output, dataSz);
2149
                WOLFSSL_MSG("Authentication Tag");
2150
                WOLFSSL_BUFFER(output + dataSz, macSz);
2151
        #endif
2152
2153
        #ifdef WOLFSSL_CIPHER_TEXT_CHECK
2154
            if (ssl->specs.bulk_cipher_algorithm != wolfssl_cipher_null &&
2155
                XMEMCMP(output, ssl->encrypt.sanityCheck,
2156
                    min(dataSz, sizeof(ssl->encrypt.sanityCheck))) == 0) {
2157
2158
                WOLFSSL_MSG("EncryptTls13 sanity check failed! Glitch?");
2159
                return ENCRYPT_ERROR;
2160
            }
2161
            ForceZero(ssl->encrypt.sanityCheck,
2162
                sizeof(ssl->encrypt.sanityCheck));
2163
        #endif
2164
        #ifdef WOLFSSL_CHECK_MEM_ZERO
2165
            if ((ssl->specs.bulk_cipher_algorithm != wolfssl_cipher_null) &&
2166
                    (output != input) && (ret == 0)) {
2167
                wc_MemZero_Add("TLS 1.3 Encrypt plaintext", input, sz);
2168
            }
2169
        #endif
2170
2171
0
        #ifdef CIPHER_NONCE
2172
0
            ForceZero(ssl->encrypt.nonce, AEAD_NONCE_SZ);
2173
0
        #endif
2174
2175
0
            break;
2176
0
        }
2177
2178
0
        default:
2179
0
            break;
2180
0
    }
2181
2182
2183
    /* Reset state */
2184
0
    ssl->encrypt.state = CIPHER_STATE_BEGIN;
2185
2186
0
    return ret;
2187
0
}
2188
2189
#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
2190
/* Decrypt with ChaCha20 and check authentication tag with Poly1305.
2191
 *
2192
 * ssl     The SSL/TLS object.
2193
 * output  The buffer to write decrypted data into.
2194
 *         May be the same pointer as input.
2195
 * input   The data to decrypt.
2196
 * sz      The number of bytes to decrypt.
2197
 * nonce   The nonce to use with ChaCha20.
2198
 * aad     The additional authentication data.
2199
 * aadSz   The size of the addition authentication data.
2200
 * tagIn   The authentication tag data from packet.
2201
 * returns 0 on success, otherwise failure.
2202
 */
2203
static int ChaCha20Poly1305_Decrypt(WOLFSSL* ssl, byte* output,
2204
                                    const byte* input, word16 sz, byte* nonce,
2205
                                    const byte* aad, word16 aadSz,
2206
                                    const byte* tagIn)
2207
0
{
2208
0
    int ret;
2209
0
    byte tag[POLY1305_AUTH_SZ];
2210
0
    byte poly[CHACHA20_256_KEY_SIZE]; /* generated key for mac */
2211
2212
    /* Poly1305 key is 256 bits of zero encrypted with ChaCha20. */
2213
0
    XMEMSET(poly, 0, sizeof(poly));
2214
2215
    /* Set nonce and get Poly1305 key. */
2216
0
    ret = wc_Chacha_SetIV(ssl->decrypt.chacha, nonce, 0);
2217
0
    if (ret != 0)
2218
0
        return ret;
2219
    /* Use ChaCha20 keystream to get Poly1305 key for tag. */
2220
0
    ret = wc_Chacha_Process(ssl->decrypt.chacha, poly, poly, sizeof(poly));
2221
0
    if (ret != 0)
2222
0
        return ret;
2223
#ifdef WOLFSSL_CHECK_MEM_ZERO
2224
    wc_MemZero_Add("ChaCha20Poly1305_Decrypt poly", poly, sizeof(poly));
2225
#endif
2226
0
    ret = wc_Chacha_SetIV(ssl->decrypt.chacha, nonce, 1);
2227
0
    if (ret != 0) {
2228
0
        ForceZero(poly, sizeof(poly)); /* done with poly1305 key, clear it */
2229
    #ifdef WOLFSSL_CHECK_MEM_ZERO
2230
        wc_MemZero_Check(poly, sizeof(poly));
2231
    #endif
2232
0
        return ret;
2233
0
    }
2234
2235
    /* Set key for Poly1305. */
2236
0
    ret = wc_Poly1305SetKey(ssl->auth.poly1305, poly, sizeof(poly));
2237
0
    ForceZero(poly, sizeof(poly)); /* done with poly1305 key, clear it */
2238
#ifdef WOLFSSL_CHECK_MEM_ZERO
2239
    wc_MemZero_Check(poly, sizeof(poly));
2240
#endif
2241
0
    if (ret != 0)
2242
0
        return ret;
2243
    /* Generate authentication tag for encrypted data. */
2244
0
    if ((ret = wc_Poly1305_MAC(ssl->auth.poly1305, aad, aadSz, input, sz, tag,
2245
0
                                                           sizeof(tag))) != 0) {
2246
0
        return ret;
2247
0
    }
2248
2249
    /* Check tag sent along with packet. */
2250
0
    if (ConstantCompare(tagIn, tag, POLY1305_AUTH_SZ) != 0) {
2251
0
        WOLFSSL_MSG("MAC did not match");
2252
0
        return VERIFY_MAC_ERROR;
2253
0
    }
2254
2255
    /* If the tag was good decrypt message. */
2256
0
    ret = wc_Chacha_Process(ssl->decrypt.chacha, output, input, sz);
2257
2258
0
    return ret;
2259
0
}
2260
#endif
2261
2262
#ifdef HAVE_NULL_CIPHER
2263
/* Check HMAC tag and copy over input.
2264
 *
2265
 * ssl     The SSL/TLS object.
2266
 * output  The buffer to copy data into.
2267
 *         May be the same pointer as input.
2268
 * input   The data.
2269
 * sz      The number of bytes of data.
2270
 * nonce   The nonce to use with authentication.
2271
 * aad     The additional authentication data.
2272
 * aadSz   The size of the addition authentication data.
2273
 * tagIn   The authentication tag data from packet.
2274
 * returns 0 on success, otherwise failure.
2275
 */
2276
static int Tls13IntegrityOnly_Decrypt(WOLFSSL* ssl, byte* output,
2277
                                      const byte* input, word16 sz,
2278
                                      const byte* nonce,
2279
                                      const byte* aad, word16 aadSz,
2280
                                      const byte* tagIn)
2281
{
2282
    int ret;
2283
    byte hmac[WC_MAX_DIGEST_SIZE];
2284
2285
    /* HMAC: nonce | aad | input  */
2286
    ret = wc_HmacUpdate(ssl->decrypt.hmac, nonce, HMAC_NONCE_SZ);
2287
    if (ret == 0)
2288
        ret = wc_HmacUpdate(ssl->decrypt.hmac, aad, aadSz);
2289
    if (ret == 0)
2290
        ret = wc_HmacUpdate(ssl->decrypt.hmac, input, sz);
2291
    if (ret == 0)
2292
        ret = wc_HmacFinal(ssl->decrypt.hmac, hmac);
2293
    /* Check authentication tag matches */
2294
    if (ret == 0 && ConstantCompare(tagIn, hmac, ssl->specs.hash_size) != 0)
2295
        ret = DECRYPT_ERROR;
2296
    /* Copy the input to output if not the same buffer */
2297
    if (ret == 0 && output != input)
2298
        XMEMCPY(output, input, sz);
2299
2300
    return ret;
2301
}
2302
#endif
2303
2304
/* Decrypt data for TLS v1.3.
2305
 *
2306
 * ssl     The SSL/TLS object.
2307
 * output  The buffer to write decrypted data into.
2308
 *         May be the same pointer as input.
2309
 * input   The data to decrypt and authentication tag.
2310
 * sz      The length of the encrypted data plus authentication tag.
2311
 * aad     The additional authentication data.
2312
 * aadSz   The size of the addition authentication data.
2313
 * returns 0 on success, otherwise failure.
2314
 */
2315
int DecryptTls13(WOLFSSL* ssl, byte* output, const byte* input, word16 sz,
2316
                 const byte* aad, word16 aadSz)
2317
0
{
2318
0
    int    ret    = 0;
2319
0
    word16 dataSz = sz - ssl->specs.aead_mac_size;
2320
0
    word16 macSz  = ssl->specs.aead_mac_size;
2321
0
    word32 nonceSz = 0;
2322
2323
0
    WOLFSSL_ENTER("DecryptTls13");
2324
2325
#if defined(WOLFSSL_RENESAS_TSIP_TLS) && (WOLFSSL_RENESAS_TSIP_VER >= 115)
2326
    ret = tsip_Tls13AesDecrypt(ssl, output, input, sz);
2327
2328
    if (ret != CRYPTOCB_UNAVAILABLE) {
2329
        #ifndef WOLFSSL_EARLY_DATA
2330
        if (ret < 0) {
2331
            ret = VERIFY_MAC_ERROR;
2332
            WOLFSSL_ERROR_VERBOSE(ret);
2333
        }
2334
        #endif
2335
        return ret;
2336
    }
2337
#endif
2338
2339
#ifdef WOLFSSL_ASYNC_CRYPT
2340
    ret = wolfSSL_AsyncPop(ssl, &ssl->decrypt.state);
2341
    if (ret != WC_NOT_PENDING_E) {
2342
        /* check for still pending */
2343
        if (ret == WC_PENDING_E)
2344
            return ret;
2345
2346
        ssl->error = 0; /* clear async */
2347
2348
        /* let failures through so CIPHER_STATE_END logic is run */
2349
    }
2350
    else
2351
#endif
2352
0
    {
2353
        /* Reset state */
2354
0
        ret = 0;
2355
0
        ssl->decrypt.state = CIPHER_STATE_BEGIN;
2356
0
    }
2357
2358
0
    (void)output;
2359
0
    (void)input;
2360
0
    (void)sz;
2361
0
    (void)dataSz;
2362
0
    (void)macSz;
2363
0
    (void)nonceSz;
2364
2365
0
    switch (ssl->decrypt.state) {
2366
0
        case CIPHER_STATE_BEGIN:
2367
0
        {
2368
        #ifdef WOLFSSL_DEBUG_TLS
2369
            WOLFSSL_MSG("Data to decrypt");
2370
            WOLFSSL_BUFFER(input, dataSz);
2371
            WOLFSSL_MSG("Additional Authentication Data");
2372
            WOLFSSL_BUFFER(aad, aadSz);
2373
            WOLFSSL_MSG("Authentication tag");
2374
            WOLFSSL_BUFFER(input + dataSz, macSz);
2375
        #endif
2376
2377
0
        #ifdef CIPHER_NONCE
2378
0
            if (ssl->decrypt.nonce == NULL) {
2379
0
                ssl->decrypt.nonce = (byte*)XMALLOC(AEAD_NONCE_SZ,
2380
0
                                            ssl->heap, DYNAMIC_TYPE_AES_BUFFER);
2381
            #ifdef WOLFSSL_CHECK_MEM_ZERO
2382
                if (ssl->decrypt.nonce != NULL) {
2383
                    wc_MemZero_Add("DecryptTls13 nonce", ssl->decrypt.nonce,
2384
                        AEAD_NONCE_SZ);
2385
                }
2386
            #endif
2387
0
            }
2388
0
            if (ssl->decrypt.nonce == NULL)
2389
0
                return MEMORY_E;
2390
2391
0
            BuildTls13Nonce(ssl, ssl->decrypt.nonce, ssl->keys.aead_dec_imp_IV,
2392
0
                            PEER_ORDER);
2393
0
        #endif
2394
2395
            /* Advance state and proceed */
2396
0
            ssl->decrypt.state = CIPHER_STATE_DO;
2397
0
        }
2398
0
        FALL_THROUGH;
2399
2400
0
        case CIPHER_STATE_DO:
2401
0
        {
2402
0
            switch (ssl->specs.bulk_cipher_algorithm) {
2403
0
            #ifdef BUILD_AESGCM
2404
0
                case wolfssl_aes_gcm:
2405
                #ifdef WOLFSSL_ASYNC_CRYPT
2406
                    /* initialize event */
2407
                    ret = wolfSSL_AsyncInit(ssl, &ssl->decrypt.aes->asyncDev,
2408
                        WC_ASYNC_FLAG_NONE);
2409
                    if (ret != 0)
2410
                        break;
2411
                #endif
2412
2413
0
                    nonceSz = AESGCM_NONCE_SZ;
2414
0
                    ret = wc_AesGcmDecrypt(ssl->decrypt.aes, output, input,
2415
0
                        dataSz, ssl->decrypt.nonce, nonceSz,
2416
0
                        input + dataSz, macSz, aad, aadSz);
2417
                #ifdef WOLFSSL_ASYNC_CRYPT
2418
                    if (ret == WC_PENDING_E) {
2419
                        ret = wolfSSL_AsyncPush(ssl,
2420
                                                   &ssl->decrypt.aes->asyncDev);
2421
                    }
2422
                #endif
2423
0
                    break;
2424
0
            #endif
2425
2426
0
            #ifdef HAVE_AESCCM
2427
0
                case wolfssl_aes_ccm:
2428
                #ifdef WOLFSSL_ASYNC_CRYPT
2429
                    /* initialize event */
2430
                    ret = wolfSSL_AsyncInit(ssl, &ssl->decrypt.aes->asyncDev,
2431
                        WC_ASYNC_FLAG_NONE);
2432
                    if (ret != 0)
2433
                        break;
2434
                #endif
2435
2436
0
                    nonceSz = AESCCM_NONCE_SZ;
2437
0
                    ret = wc_AesCcmDecrypt(ssl->decrypt.aes, output, input,
2438
0
                        dataSz, ssl->decrypt.nonce, nonceSz,
2439
0
                        input + dataSz, macSz, aad, aadSz);
2440
                #ifdef WOLFSSL_ASYNC_CRYPT
2441
                    if (ret == WC_PENDING_E) {
2442
                        ret = wolfSSL_AsyncPush(ssl,
2443
                                                   &ssl->decrypt.aes->asyncDev);
2444
                    }
2445
                #endif
2446
0
                    break;
2447
0
            #endif
2448
2449
0
            #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
2450
0
                case wolfssl_chacha:
2451
0
                    ret = ChaCha20Poly1305_Decrypt(ssl, output, input, dataSz,
2452
0
                        ssl->decrypt.nonce, aad, aadSz, input + dataSz);
2453
0
                    break;
2454
0
            #endif
2455
2456
            #ifdef HAVE_NULL_CIPHER
2457
                case wolfssl_cipher_null:
2458
                    ret = Tls13IntegrityOnly_Decrypt(ssl, output, input, dataSz,
2459
                        ssl->decrypt.nonce, aad, aadSz, input + dataSz);
2460
                    break;
2461
            #endif
2462
0
                default:
2463
0
                    WOLFSSL_MSG("wolfSSL Decrypt programming error");
2464
0
                    return DECRYPT_ERROR;
2465
0
            }
2466
2467
            /* Advance state */
2468
0
            ssl->decrypt.state = CIPHER_STATE_END;
2469
2470
        #ifdef WOLFSSL_ASYNC_CRYPT
2471
            /* If pending, leave now */
2472
            if (ret == WC_PENDING_E) {
2473
                return ret;
2474
            }
2475
        #endif
2476
0
        }
2477
0
        FALL_THROUGH;
2478
2479
0
        case CIPHER_STATE_END:
2480
0
        {
2481
        #ifdef WOLFSSL_DEBUG_TLS
2482
            #ifdef CIPHER_NONCE
2483
                WOLFSSL_MSG("Nonce");
2484
                WOLFSSL_BUFFER(ssl->decrypt.nonce, ssl->specs.iv_size);
2485
            #endif
2486
                WOLFSSL_MSG("Decrypted data");
2487
                WOLFSSL_BUFFER(output, dataSz);
2488
        #endif
2489
        #ifdef WOLFSSL_CHECK_MEM_ZERO
2490
            if ((ssl->specs.bulk_cipher_algorithm != wolfssl_cipher_null) &&
2491
                    (ret == 0)) {
2492
                wc_MemZero_Add("TLS 1.3 Decrypted data", output, sz);
2493
            }
2494
        #endif
2495
2496
0
        #ifdef CIPHER_NONCE
2497
0
            ForceZero(ssl->decrypt.nonce, AEAD_NONCE_SZ);
2498
0
        #endif
2499
2500
0
            break;
2501
0
        }
2502
2503
0
       default:
2504
0
            break;
2505
0
    }
2506
2507
0
    if (ret < 0) {
2508
0
        WOLFSSL_ERROR_VERBOSE(ret);
2509
0
    }
2510
2511
0
    return ret;
2512
0
}
2513
2514
/* Persistable BuildTls13Message arguments */
2515
typedef struct BuildMsg13Args {
2516
    word32 sz;
2517
    word32 idx;
2518
    word32 headerSz;
2519
    word16 size;
2520
} BuildMsg13Args;
2521
2522
static void FreeBuildMsg13Args(WOLFSSL* ssl, void* pArgs)
2523
0
{
2524
0
    BuildMsg13Args* args = (BuildMsg13Args*)pArgs;
2525
2526
0
    (void)ssl;
2527
0
    (void)args;
2528
2529
    /* no allocations in BuildTls13Message */
2530
0
}
2531
2532
/* Build SSL Message, encrypted.
2533
 * TLS v1.3 encryption is AEAD only.
2534
 *
2535
 * ssl         The SSL/TLS object.
2536
 * output      The buffer to write record message to.
2537
 * outSz       Size of the buffer being written into.
2538
 * input       The record data to encrypt (excluding record header).
2539
 * inSz        The size of the record data.
2540
 * type        The recorder header content type.
2541
 * hashOutput  Whether to hash the unencrypted record data.
2542
 * sizeOnly    Only want the size of the record message.
2543
 * asyncOkay   If non-zero can return WC_PENDING_E, otherwise blocks on crypto
2544
 * returns the size of the encrypted record message or negative value on error.
2545
 */
2546
int BuildTls13Message(WOLFSSL* ssl, byte* output, int outSz, const byte* input,
2547
                int inSz, int type, int hashOutput, int sizeOnly, int asyncOkay)
2548
0
{
2549
0
    int ret;
2550
0
    BuildMsg13Args* args;
2551
0
    BuildMsg13Args  lcl_args;
2552
2553
0
    WOLFSSL_ENTER("BuildTls13Message");
2554
2555
#ifdef WOLFSSL_ASYNC_CRYPT
2556
    ret = WC_NOT_PENDING_E;
2557
    if (asyncOkay) {
2558
        WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
2559
2560
        if (ssl->async == NULL) {
2561
            ssl->async = (struct WOLFSSL_ASYNC*)
2562
                    XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
2563
                            DYNAMIC_TYPE_ASYNC);
2564
            if (ssl->async == NULL)
2565
                return MEMORY_E;
2566
        }
2567
        args = (BuildMsg13Args*)ssl->async->args;
2568
2569
        ret = wolfSSL_AsyncPop(ssl, &ssl->options.buildMsgState);
2570
        if (ret != WC_NOT_PENDING_E) {
2571
            /* Check for error */
2572
            if (ret < 0)
2573
                goto exit_buildmsg;
2574
        }
2575
    }
2576
    else
2577
#endif
2578
0
    {
2579
0
        args = &lcl_args;
2580
0
    }
2581
2582
    /* Reset state */
2583
#ifdef WOLFSSL_ASYNC_CRYPT
2584
    if (ret == WC_NOT_PENDING_E)
2585
#endif
2586
0
    {
2587
0
        ret = 0;
2588
0
        ssl->options.buildMsgState = BUILD_MSG_BEGIN;
2589
0
        XMEMSET(args, 0, sizeof(BuildMsg13Args));
2590
2591
0
        args->headerSz = RECORD_HEADER_SZ;
2592
#ifdef WOLFSSL_DTLS13
2593
        if (ssl->options.dtls)
2594
            args->headerSz = Dtls13GetRlHeaderLength(ssl, 1);
2595
#endif /* WOLFSSL_DTLS13 */
2596
2597
0
        args->sz = args->headerSz + inSz;
2598
0
        args->idx  = args->headerSz;
2599
2600
    #ifdef WOLFSSL_ASYNC_CRYPT
2601
        if (asyncOkay)
2602
            ssl->async->freeArgs = FreeBuildMsg13Args;
2603
    #endif
2604
0
    }
2605
2606
0
    switch (ssl->options.buildMsgState) {
2607
0
        case BUILD_MSG_BEGIN:
2608
0
        {
2609
           /* catch mistaken sizeOnly parameter */
2610
0
            if (sizeOnly) {
2611
0
                if (output || input) {
2612
0
                    WOLFSSL_MSG("BuildTls13Message with sizeOnly "
2613
0
                                "doesn't need input or output");
2614
0
                    return BAD_FUNC_ARG;
2615
0
                }
2616
0
            }
2617
0
            else if (output == NULL || input == NULL) {
2618
0
                return BAD_FUNC_ARG;
2619
0
            }
2620
2621
            /* Record layer content type at the end of record data. */
2622
0
            args->sz++;
2623
            /* Authentication data at the end. */
2624
0
            args->sz += ssl->specs.aead_mac_size;
2625
2626
0
            if (sizeOnly)
2627
0
                return args->sz;
2628
2629
0
            if (args->sz > (word32)outSz) {
2630
0
                WOLFSSL_MSG("Oops, want to write past output buffer size");
2631
0
                return BUFFER_E;
2632
0
            }
2633
2634
            /* Record data length. */
2635
0
            args->size = (word16)(args->sz - args->headerSz);
2636
            /* Write/update the record header with the new size.
2637
             * Always have the content type as application data for encrypted
2638
             * messages in TLS v1.3.
2639
             */
2640
2641
0
            if (ssl->options.dtls) {
2642
#ifdef WOLFSSL_DTLS13
2643
                Dtls13RlAddCiphertextHeader(ssl, output, args->size);
2644
#endif /* WOLFSSL_DTLS13 */
2645
0
            }
2646
0
            else {
2647
0
                AddTls13RecordHeader(output, args->size, application_data, ssl);
2648
0
            }
2649
2650
            /* TLS v1.3 can do in place encryption. */
2651
0
            if (input != output + args->idx)
2652
0
                XMEMCPY(output + args->idx, input, inSz);
2653
0
            args->idx += inSz;
2654
2655
0
            ssl->options.buildMsgState = BUILD_MSG_HASH;
2656
0
        }
2657
0
        FALL_THROUGH;
2658
2659
0
        case BUILD_MSG_HASH:
2660
0
        {
2661
0
            if (hashOutput) {
2662
0
                ret = HashOutput(ssl, output, args->headerSz + inSz, 0);
2663
0
                if (ret != 0)
2664
0
                    goto exit_buildmsg;
2665
0
            }
2666
2667
            /* The real record content type goes at the end of the data. */
2668
0
            output[args->idx++] = (byte)type;
2669
2670
0
            ssl->options.buildMsgState = BUILD_MSG_ENCRYPT;
2671
0
        }
2672
0
        FALL_THROUGH;
2673
2674
0
        case BUILD_MSG_ENCRYPT:
2675
0
        {
2676
#ifdef WOLFSSL_QUIC
2677
            if (WOLFSSL_IS_QUIC(ssl)) {
2678
                /* QUIC does not use encryption of the TLS Record Layer.
2679
                 * Return the original length + added headers
2680
                 * and restore it in the record header. */
2681
                AddTls13RecordHeader(output, inSz, type, ssl);
2682
                ret = args->headerSz + inSz;
2683
                goto exit_buildmsg;
2684
            }
2685
#endif
2686
        #ifdef ATOMIC_USER
2687
            if (ssl->ctx->MacEncryptCb) {
2688
                /* User Record Layer Callback handling */
2689
                byte* mac = output + args->idx;
2690
                output += args->headerSz;
2691
2692
                ret = ssl->ctx->MacEncryptCb(ssl, mac, output, inSz, type, 0,
2693
                        output, output, args->size, ssl->MacEncryptCtx);
2694
            }
2695
            else
2696
        #endif
2697
0
            {
2698
0
                const byte* aad = output;
2699
0
                output += args->headerSz;
2700
0
                ret = EncryptTls13(ssl, output, output, args->size, aad,
2701
0
                                   (word16)args->headerSz, asyncOkay);
2702
#ifdef WOLFSSL_DTLS13
2703
                if (ret == 0 && ssl->options.dtls) {
2704
                    /* AAD points to the header. Reuse the variable  */
2705
                    ret = Dtls13EncryptRecordNumber(ssl, (byte*)aad, args->sz);
2706
                }
2707
#endif /* WOLFSSL_DTLS13 */
2708
0
            }
2709
0
            break;
2710
0
        }
2711
2712
0
        default:
2713
0
            break;
2714
0
    }
2715
2716
0
exit_buildmsg:
2717
2718
0
    WOLFSSL_LEAVE("BuildTls13Message", ret);
2719
2720
#ifdef WOLFSSL_ASYNC_CRYPT
2721
    if (ret == WC_PENDING_E) {
2722
        return ret;
2723
    }
2724
#endif
2725
2726
    /* make sure build message state is reset */
2727
0
    ssl->options.buildMsgState = BUILD_MSG_BEGIN;
2728
2729
    /* return sz on success */
2730
0
    if (ret == 0) {
2731
0
        ret = args->sz;
2732
0
    }
2733
0
    else {
2734
0
        WOLFSSL_ERROR_VERBOSE(ret);
2735
0
    }
2736
2737
    /* Final cleanup */
2738
#ifdef WOLFSSL_ASYNC_CRYPT
2739
    if (asyncOkay)
2740
        FreeAsyncCtx(ssl, 0);
2741
    else
2742
#endif
2743
0
        FreeBuildMsg13Args(ssl, args);
2744
2745
0
    return ret;
2746
0
}
2747
2748
#if !defined(NO_WOLFSSL_CLIENT) || (!defined(NO_WOLFSSL_SERVER) && \
2749
    (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)) && \
2750
    defined(WOLFSSL_PSK_ONE_ID)) \
2751
/* Find the cipher suite in the suites set in the SSL.
2752
 *
2753
 * ssl    SSL/TLS object.
2754
 * suite  Cipher suite to look for.
2755
 * returns 1 when suite is found in SSL/TLS object's list and 0 otherwise.
2756
 */
2757
static int FindSuiteSSL(WOLFSSL* ssl, byte* suite)
2758
0
{
2759
0
    word16 i;
2760
2761
0
    for (i = 0; i < ssl->suites->suiteSz; i += 2) {
2762
0
        if (ssl->suites->suites[i+0] == suite[0] &&
2763
0
            ssl->suites->suites[i+1] == suite[1]) {
2764
0
            return 1;
2765
0
        }
2766
0
    }
2767
2768
0
    return 0;
2769
0
}
2770
#endif
2771
2772
#ifndef NO_PSK
2773
/* Get the MAC algorithm for the TLS 1.3 cipher suite.
2774
 *
2775
 * @param [in] suite.
2776
 * @return  A value from wc_MACAlgorithm enumeration.
2777
 */
2778
byte SuiteMac(byte* suite)
2779
{
2780
    byte mac = no_mac;
2781
2782
    if (suite[0] == TLS13_BYTE) {
2783
        switch (suite[1]) {
2784
        #ifdef BUILD_TLS_AES_128_GCM_SHA256
2785
            case TLS_AES_128_GCM_SHA256:
2786
                mac = sha256_mac;
2787
                break;
2788
        #endif
2789
        #ifdef BUILD_TLS_CHACHA20_POLY1305_SHA256
2790
            case TLS_CHACHA20_POLY1305_SHA256:
2791
                mac = sha256_mac;
2792
                break;
2793
        #endif
2794
        #ifdef BUILD_TLS_AES_128_CCM_SHA256
2795
            case TLS_AES_128_CCM_SHA256:
2796
                mac = sha256_mac;
2797
                break;
2798
        #endif
2799
        #ifdef BUILD_TLS_AES_128_CCM_8_SHA256
2800
            case TLS_AES_128_CCM_8_SHA256:
2801
                mac = sha256_mac;
2802
                break;
2803
        #endif
2804
        #ifdef BUILD_TLS_AES_256_GCM_SHA384
2805
            case TLS_AES_256_GCM_SHA384:
2806
                mac = sha384_mac;
2807
                break;
2808
        #endif
2809
            default:
2810
                break;
2811
        }
2812
    }
2813
#ifdef HAVE_NULL_CIPHER
2814
    else if (suite[0] == ECC_BYTE) {
2815
        switch (suite[1]) {
2816
        #ifdef BUILD_TLS_SHA256_SHA256
2817
            case TLS_SHA256_SHA256:
2818
                mac = sha256_mac;
2819
                break;
2820
        #endif
2821
        #ifdef BUILD_TLS_SHA384_SHA384
2822
            case TLS_SHA384_SHA384:
2823
                mac = sha384_mac;
2824
                break;
2825
        #endif
2826
            default:
2827
                break;
2828
        }
2829
    }
2830
#endif
2831
2832
    return mac;
2833
}
2834
#endif
2835
2836
#if defined(WOLFSSL_SEND_HRR_COOKIE) && !defined(NO_WOLFSSL_SERVER)
2837
/* Create Cookie extension using the hash of the first ClientHello.
2838
 *
2839
 * ssl     SSL/TLS object.
2840
 * hash    The hash data.
2841
 * hashSz  The size of the hash data in bytes.
2842
 * returns 0 on success, otherwise failure.
2843
 */
2844
static int CreateCookie(WOLFSSL* ssl, byte* hash, byte hashSz)
2845
{
2846
    int  ret;
2847
    byte mac[WC_MAX_DIGEST_SIZE] = {0};
2848
    Hmac cookieHmac;
2849
    byte cookieType = 0;
2850
    byte macSz = 0;
2851
2852
#if !defined(NO_SHA) && defined(NO_SHA256)
2853
    cookieType = SHA;
2854
    macSz = WC_SHA_DIGEST_SIZE;
2855
#endif /* NO_SHA */
2856
#ifndef NO_SHA256
2857
    cookieType = WC_SHA256;
2858
    macSz = WC_SHA256_DIGEST_SIZE;
2859
#endif /* NO_SHA256 */
2860
2861
    ret = wc_HmacInit(&cookieHmac, ssl->heap, INVALID_DEVID);
2862
    if (ret == 0) {
2863
        ret = wc_HmacSetKey(&cookieHmac, cookieType,
2864
                            ssl->buffers.tls13CookieSecret.buffer,
2865
                            ssl->buffers.tls13CookieSecret.length);
2866
    }
2867
    if (ret == 0)
2868
        ret = wc_HmacUpdate(&cookieHmac, hash, hashSz);
2869
#ifdef WOLFSSL_DTLS13
2870
    /* Tie cookie to peer address */
2871
    if (ret == 0) {
2872
        if (ssl->options.dtls && ssl->buffers.dtlsCtx.peer.sz > 0) {
2873
            ret = wc_HmacUpdate(&cookieHmac, ssl->buffers.dtlsCtx.peer.sa,
2874
                                    ssl->buffers.dtlsCtx.peer.sz);
2875
        }
2876
    }
2877
#endif
2878
    if (ret == 0)
2879
        ret = wc_HmacFinal(&cookieHmac, mac);
2880
2881
    wc_HmacFree(&cookieHmac);
2882
    if (ret != 0)
2883
        return ret;
2884
2885
    /* The cookie data is the hash and the integrity check. */
2886
    return TLSX_Cookie_Use(ssl, hash, hashSz, mac, macSz, 1);
2887
}
2888
#endif
2889
2890
#define HRR_MAX_HS_HEADER_SZ HANDSHAKE_HEADER_SZ
2891
2892
/* Restart the handshake hash with a hash of the previous messages.
2893
 *
2894
 * ssl The SSL/TLS object.
2895
 * returns 0 on success, otherwise failure.
2896
 */
2897
int RestartHandshakeHash(WOLFSSL* ssl)
2898
0
{
2899
0
    int    ret;
2900
0
    Hashes hashes;
2901
0
    byte   header[HRR_MAX_HS_HEADER_SZ] = {0};
2902
0
    byte*  hash = NULL;
2903
0
    byte   hashSz = 0;
2904
2905
0
    ret = BuildCertHashes(ssl, &hashes);
2906
0
    if (ret != 0)
2907
0
        return ret;
2908
0
    switch (ssl->specs.mac_algorithm) {
2909
0
    #ifndef NO_SHA256
2910
0
        case sha256_mac:
2911
0
            hash = hashes.sha256;
2912
0
            break;
2913
0
    #endif
2914
0
    #ifdef WOLFSSL_SHA384
2915
0
        case sha384_mac:
2916
0
            hash = hashes.sha384;
2917
0
            break;
2918
0
    #endif
2919
    #ifdef WOLFSSL_TLS13_SHA512
2920
        case sha512_mac:
2921
            hash = hashes.sha512;
2922
            break;
2923
    #endif
2924
0
    }
2925
0
    hashSz = ssl->specs.hash_size;
2926
2927
    /* check hash */
2928
0
    if (hash == NULL && hashSz > 0)
2929
0
        return BAD_FUNC_ARG;
2930
2931
0
    AddTls13HandShakeHeader(header, hashSz, 0, 0, message_hash, ssl);
2932
2933
#ifdef WOLFSSL_DEBUG_TLS
2934
    WOLFSSL_MSG("Restart Hash");
2935
    WOLFSSL_BUFFER(hash, hashSz);
2936
#endif
2937
2938
#if defined(WOLFSSL_SEND_HRR_COOKIE) && !defined(NO_WOLFSSL_SERVER)
2939
    if (ssl->options.sendCookie && ssl->options.side == WOLFSSL_SERVER_END) {
2940
        byte   cookie[OPAQUE8_LEN + WC_MAX_DIGEST_SIZE + OPAQUE16_LEN * 2];
2941
        TLSX*  ext;
2942
        word32 idx = 0;
2943
2944
        /* Cookie Data = Hash Len | Hash | CS | KeyShare Group */
2945
        cookie[idx++] = hashSz;
2946
        if (hash)
2947
            XMEMCPY(cookie + idx, hash, hashSz);
2948
        idx += hashSz;
2949
        cookie[idx++] = ssl->options.cipherSuite0;
2950
        cookie[idx++] = ssl->options.cipherSuite;
2951
        if ((ext = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE)) != NULL) {
2952
            KeyShareEntry* kse = (KeyShareEntry*)ext->data;
2953
            c16toa(kse->group, cookie + idx);
2954
            idx += OPAQUE16_LEN;
2955
        }
2956
        return CreateCookie(ssl, cookie, idx);
2957
    }
2958
#endif
2959
2960
0
    ret = InitHandshakeHashes(ssl);
2961
0
    if (ret != 0)
2962
0
        return ret;
2963
0
    ret = HashRaw(ssl, header, sizeof(header));
2964
0
    if (ret != 0)
2965
0
        return ret;
2966
0
    return HashRaw(ssl, hash, hashSz);
2967
0
}
2968
2969
#if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER)
2970
/* The value in the random field of a ServerHello to indicate
2971
 * HelloRetryRequest.
2972
 */
2973
static byte helloRetryRequestRandom[] = {
2974
    0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11,
2975
    0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91,
2976
    0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E,
2977
    0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C
2978
};
2979
#endif
2980
2981
#ifndef NO_WOLFSSL_CLIENT
2982
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
2983
#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_PSK_ONE_ID) && \
2984
    !defined(NO_PSK)
2985
/**
2986
* convert mac algorithm to WOLFSSL_EVP_MD
2987
* @param mac_alg mac algorithm
2988
* @return const WOLFSSL_EVP_MD on successful, otherwise NULL
2989
*/
2990
static const WOLFSSL_EVP_MD* ssl_handshake_md(const byte mac_alg)
2991
{
2992
    switch(mac_alg) {
2993
        case no_mac:
2994
    #ifndef NO_MD5
2995
        case md5_mac:
2996
            return wolfSSL_EVP_md5();
2997
    #endif
2998
    #ifndef NO_SHA
2999
        case sha_mac:
3000
            return wolfSSL_EVP_sha1();
3001
    #endif
3002
    #ifdef WOLFSSL_SHA224
3003
        case sha224_mac:
3004
            return wolfSSL_EVP_sha224();
3005
    #endif
3006
        case sha256_mac:
3007
            return wolfSSL_EVP_sha256();
3008
    #ifdef WOLFSSL_SHA384
3009
        case sha384_mac:
3010
            return wolfSSL_EVP_sha384();
3011
    #endif
3012
    #ifdef WOLFSSL_SHA512
3013
        case sha512_mac:
3014
            return wolfSSL_EVP_sha512();
3015
    #endif
3016
        case rmd_mac:
3017
        case blake2b_mac:
3018
            WOLFSSL_MSG("no suitable EVP_MD");
3019
            return NULL;
3020
        default:
3021
            WOLFSSL_MSG("Unknown mac algorithm");
3022
            return NULL;
3023
    }
3024
}
3025
#endif
3026
/* Setup pre-shared key based on the details in the extension data.
3027
 *
3028
 * ssl          SSL/TLS object.
3029
 * psk          Pre-shared key extension data.
3030
 * clientHello  Whether called from client_hello construction.
3031
 * returns 0 on success, PSK_KEY_ERROR when the client PSK callback fails and
3032
 * other negative value on failure.
3033
 */
3034
static int SetupPskKey(WOLFSSL* ssl, PreSharedKey* psk, int clientHello)
3035
{
3036
#if defined(HAVE_SESSION_TICKET) || !defined(WOLFSSL_PSK_ONE_ID)
3037
    int ret;
3038
#endif
3039
    byte suite[2];
3040
3041
    if (psk == NULL)
3042
        return BAD_FUNC_ARG;
3043
3044
    suite[0] = ssl->options.cipherSuite0;
3045
    suite[1] = ssl->options.cipherSuite;
3046
3047
#ifdef HAVE_SESSION_TICKET
3048
    if (psk->resumption) {
3049
        if (clientHello) {
3050
            /* Ensure cipher suite is supported or changed suite to one with
3051
             * the same MAC algorithm. */
3052
            if (!FindSuiteSSL(ssl, suite)) {
3053
                WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
3054
                return PSK_KEY_ERROR;
3055
            }
3056
3057
            /* Setting mac for binder and keys for deriving EarlyData. */
3058
            ret = SetCipherSpecs(ssl);
3059
            if (ret != 0)
3060
                return ret;
3061
        }
3062
3063
    #ifdef WOLFSSL_EARLY_DATA
3064
        if (ssl->session->maxEarlyDataSz == 0)
3065
            ssl->earlyData = no_early_data;
3066
    #endif
3067
        /* Resumption PSK is master secret. */
3068
        ssl->arrays->psk_keySz = ssl->specs.hash_size;
3069
        if ((ret = DeriveResumptionPSK(ssl, ssl->session->ticketNonce.data,
3070
                    ssl->session->ticketNonce.len, ssl->arrays->psk_key)) != 0) {
3071
            return ret;
3072
        }
3073
        if (!clientHello) {
3074
            /* CLIENT: using secret in ticket for peer authentication. */
3075
            ssl->options.peerAuthGood = 1;
3076
        }
3077
    }
3078
#endif
3079
#ifndef NO_PSK
3080
    if (!psk->resumption) {
3081
        /* Get the pre-shared key. */
3082
#ifndef WOLFSSL_PSK_ONE_ID
3083
        const char* cipherName = NULL;
3084
    #ifdef OPENSSL_EXTRA
3085
        WOLFSSL_SESSION* psksession = NULL;
3086
    #endif
3087
3088
        /* Set the client identity to use. */
3089
        XMEMSET(ssl->arrays->client_identity, 0,
3090
            sizeof(ssl->arrays->client_identity));
3091
        XMEMCPY(ssl->arrays->client_identity, psk->identity, psk->identityLen);
3092
3093
    #ifdef WOLFSSL_DEBUG_TLS
3094
        WOLFSSL_MSG("PSK cipher suite:");
3095
        WOLFSSL_MSG(GetCipherNameInternal(psk->cipherSuite0, psk->cipherSuite));
3096
    #endif
3097
3098
        /* Get the pre-shared key. */
3099
    #ifdef OPENSSL_EXTRA
3100
        if (ssl->options.session_psk_cb != NULL) {
3101
            const unsigned char* id = NULL;
3102
            size_t idlen = 0;
3103
            const WOLFSSL_EVP_MD* handshake_md = NULL;
3104
3105
            if (ssl->msgsReceived.got_hello_retry_request >= 1) {
3106
                handshake_md = ssl_handshake_md(ssl->specs.mac_algorithm);
3107
            }
3108
            /* OpenSSL compatible callback that gets cached session. */
3109
            if (ssl->options.session_psk_cb(ssl, handshake_md, &id, &idlen,
3110
                                                            &psksession) == 0) {
3111
                wolfSSL_FreeSession(ssl->ctx, psksession);
3112
                WOLFSSL_MSG("psk session callback failed");
3113
                return PSK_KEY_ERROR;
3114
            }
3115
            if (psksession != NULL) {
3116
                if (idlen > MAX_PSK_KEY_LEN) {
3117
                    wolfSSL_FreeSession(ssl->ctx, psksession);
3118
                    WOLFSSL_MSG("psk key length is too long");
3119
                    WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
3120
                    return PSK_KEY_ERROR;
3121
                }
3122
3123
                ssl->arrays->psk_keySz = (word32)idlen;
3124
                XMEMCPY(ssl->arrays->psk_key, id, idlen);
3125
                suite[0] = psksession->cipherSuite0;
3126
                suite[1] = psksession->cipherSuite;
3127
                /* Not needed anymore. */
3128
                wolfSSL_FreeSession(ssl->ctx, psksession);
3129
                /* Leave pointer not NULL to indicate success with callback. */
3130
            }
3131
        }
3132
        if (psksession != NULL) {
3133
            /* Don't try other callbacks - we have an answer. */
3134
        }
3135
        else
3136
    #endif /* OPENSSL_EXTRA */
3137
        if (ssl->options.client_psk_cs_cb != NULL) {
3138
        #ifdef WOLFSSL_PSK_MULTI_ID_PER_CS
3139
            ssl->arrays->client_identity[0] = 0;
3140
        #endif
3141
            /* Lookup key again for next identity. */
3142
            ssl->arrays->psk_keySz = ssl->options.client_psk_cs_cb(
3143
                ssl, ssl->arrays->server_hint,
3144
                ssl->arrays->client_identity, MAX_PSK_ID_LEN,
3145
                ssl->arrays->psk_key, MAX_PSK_KEY_LEN,
3146
                GetCipherNameInternal(psk->cipherSuite0, psk->cipherSuite));
3147
            if (clientHello) {
3148
                /* Use PSK cipher suite. */
3149
                ssl->options.cipherSuite0 = psk->cipherSuite0;
3150
                ssl->options.cipherSuite  = psk->cipherSuite;
3151
            }
3152
            else {
3153
                byte pskCS[2] = { psk->cipherSuite0, psk->cipherSuite };
3154
                /* Ensure PSK and negotiated cipher suites have same hash. */
3155
                if (SuiteMac(pskCS) != SuiteMac(suite)) {
3156
                    WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
3157
                    return PSK_KEY_ERROR;
3158
                }
3159
                /* Negotiated cipher suite is to be used - update PSK. */
3160
                psk->cipherSuite0 = suite[0];
3161
                psk->cipherSuite  = suite[1];
3162
            }
3163
        }
3164
        else if (ssl->options.client_psk_tls13_cb != NULL) {
3165
            byte cipherSuite0;
3166
            byte cipherSuite;
3167
            int cipherSuiteFlags = WOLFSSL_CIPHER_SUITE_FLAG_NONE;
3168
3169
            ssl->arrays->psk_keySz = ssl->options.client_psk_tls13_cb(ssl,
3170
                    ssl->arrays->server_hint, ssl->arrays->client_identity,
3171
                    MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN,
3172
                    &cipherName);
3173
            if (GetCipherSuiteFromName(cipherName, &cipherSuite0,
3174
                                       &cipherSuite, &cipherSuiteFlags) != 0) {
3175
                WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
3176
                return PSK_KEY_ERROR;
3177
            }
3178
            ssl->options.cipherSuite0 = cipherSuite0;
3179
            ssl->options.cipherSuite  = cipherSuite;
3180
            (void)cipherSuiteFlags;
3181
        }
3182
        else {
3183
            ssl->arrays->psk_keySz = ssl->options.client_psk_cb(ssl,
3184
                    ssl->arrays->server_hint, ssl->arrays->client_identity,
3185
                    MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN);
3186
            ssl->options.cipherSuite0 = TLS13_BYTE;
3187
            ssl->options.cipherSuite  = WOLFSSL_DEF_PSK_CIPHER;
3188
        }
3189
        if (ssl->arrays->psk_keySz == 0 ||
3190
                                     ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) {
3191
            WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
3192
            return PSK_KEY_ERROR;
3193
        }
3194
3195
        ret = SetCipherSpecs(ssl);
3196
        if (ret != 0)
3197
            return ret;
3198
#else
3199
        /* PSK information loaded during setting of default TLS extensions. */
3200
#endif /* !WOLFSSL_PSK_ONE_ID */
3201
3202
        if (!clientHello && (psk->cipherSuite0 != suite[0] ||
3203
                                                psk->cipherSuite != suite[1])) {
3204
            WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
3205
            return PSK_KEY_ERROR;
3206
        }
3207
3208
        if (!clientHello) {
3209
            /* CLIENT: using PSK for peer authentication. */
3210
            ssl->options.peerAuthGood = 1;
3211
        }
3212
    }
3213
#endif
3214
3215
    if (ssl->options.noPskDheKe) {
3216
        ssl->arrays->preMasterSz = 0;
3217
    }
3218
3219
    /* Derive the early secret using the PSK. */
3220
    return DeriveEarlySecret(ssl);
3221
}
3222
3223
/* Derive and write the binders into the ClientHello in space left when
3224
 * writing the Pre-Shared Key extension.
3225
 *
3226
 * ssl     The SSL/TLS object.
3227
 * output  The buffer containing the ClientHello.
3228
 * idx     The index at the end of the completed ClientHello.
3229
 * returns 0 on success and otherwise failure.
3230
 */
3231
static int WritePSKBinders(WOLFSSL* ssl, byte* output, word32 idx)
3232
{
3233
    int           ret;
3234
    TLSX*         ext;
3235
    PreSharedKey* current;
3236
    byte          binderKey[WC_MAX_DIGEST_SIZE];
3237
    word16        len;
3238
3239
    WOLFSSL_ENTER("WritePSKBinders");
3240
3241
    ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
3242
    if (ext == NULL)
3243
        return SANITY_MSG_E;
3244
3245
    /* Get the size of the binders to determine where to write binders. */
3246
    ret = TLSX_PreSharedKey_GetSizeBinders((PreSharedKey*)ext->data,
3247
                                                            client_hello, &len);
3248
    if (ret < 0)
3249
        return ret;
3250
    idx -= len;
3251
3252
    /* Hash truncated ClientHello - up to binders. */
3253
#ifdef WOLFSSL_DTLS13
3254
    if (ssl->options.dtls)
3255
        ret = Dtls13HashHandshake(ssl, output + Dtls13GetRlHeaderLength(ssl, 0),
3256
            idx - Dtls13GetRlHeaderLength(ssl, 0));
3257
    else
3258
#endif /* WOLFSSL_DTLS13 */
3259
        ret = HashOutput(ssl, output, idx, 0);
3260
3261
    if (ret != 0)
3262
        return ret;
3263
3264
    current = (PreSharedKey*)ext->data;
3265
#ifdef WOLFSSL_CHECK_MEM_ZERO
3266
    if (current != NULL) {
3267
        wc_MemZero_Add("WritePSKBinders binderKey", binderKey,
3268
            sizeof(binderKey));
3269
    }
3270
#endif
3271
    /* Calculate the binder for each identity based on previous handshake data.
3272
     */
3273
    while (current != NULL) {
3274
        if ((ret = SetupPskKey(ssl, current, 1)) != 0)
3275
            break;
3276
3277
    #ifdef HAVE_SESSION_TICKET
3278
        if (current->resumption)
3279
            ret = DeriveBinderKeyResume(ssl, binderKey);
3280
    #endif
3281
    #ifndef NO_PSK
3282
        if (!current->resumption)
3283
            ret = DeriveBinderKey(ssl, binderKey);
3284
    #endif
3285
        if (ret != 0)
3286
            break;
3287
3288
        /* Derive the Finished message secret. */
3289
        ret = DeriveFinishedSecret(ssl, binderKey,
3290
                                             ssl->keys.client_write_MAC_secret);
3291
        if (ret != 0)
3292
            break;
3293
3294
        /* Build the HMAC of the handshake message data = binder. */
3295
        ret = BuildTls13HandshakeHmac(ssl, ssl->keys.client_write_MAC_secret,
3296
            current->binder, &current->binderLen);
3297
        if (ret != 0)
3298
            break;
3299
3300
        current = current->next;
3301
    }
3302
3303
    ForceZero(binderKey, sizeof(binderKey));
3304
#ifdef WOLFSSL_CHECK_MEM_ZERO
3305
    wc_MemZero_Check(binderKey, sizeof(binderKey));
3306
#endif
3307
    if (ret != 0)
3308
        return ret;
3309
3310
    /* Data entered into extension, now write to message. */
3311
    ret = TLSX_PreSharedKey_WriteBinders((PreSharedKey*)ext->data, output + idx,
3312
                                                            client_hello, &len);
3313
    if (ret < 0)
3314
        return ret;
3315
3316
    /* Hash binders to complete the hash of the ClientHello. */
3317
    ret = HashRaw(ssl, output + idx, len);
3318
    if (ret < 0)
3319
        return ret;
3320
3321
    #ifdef WOLFSSL_EARLY_DATA
3322
    if (ssl->earlyData != no_early_data) {
3323
        if ((ret = SetupPskKey(ssl, (PreSharedKey*)ext->data, 1)) != 0)
3324
            return ret;
3325
3326
        /* Derive early data encryption key. */
3327
        ret = DeriveTls13Keys(ssl, early_data_key, ENCRYPT_SIDE_ONLY, 1);
3328
        if (ret != 0)
3329
            return ret;
3330
        if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
3331
            return ret;
3332
3333
#ifdef WOLFSSL_DTLS13
3334
        if (ssl->options.dtls) {
3335
            ret = Dtls13NewEpoch(
3336
                ssl, w64From32(0x0, DTLS13_EPOCH_EARLYDATA), ENCRYPT_SIDE_ONLY);
3337
            if (ret != 0)
3338
                return ret;
3339
        }
3340
#endif /* WOLFSSL_DTLS13 */
3341
3342
    }
3343
    #endif
3344
3345
    WOLFSSL_LEAVE("WritePSKBinders", ret);
3346
3347
    return ret;
3348
}
3349
#endif
3350
3351
/* handle generation of TLS 1.3 client_hello (1) */
3352
/* Send a ClientHello message to the server.
3353
 * Include the information required to start a handshake with servers using
3354
 * protocol versions less than TLS v1.3.
3355
 * Only a client will send this message.
3356
 *
3357
 * ssl  The SSL/TLS object.
3358
 * returns 0 on success and otherwise failure.
3359
 */
3360
3361
typedef struct Sch13Args {
3362
    byte*  output;
3363
    word32 idx;
3364
    int    sendSz;
3365
    word16 length;
3366
} Sch13Args;
3367
3368
int SendTls13ClientHello(WOLFSSL* ssl)
3369
0
{
3370
0
    int ret;
3371
#ifdef WOLFSSL_ASYNC_CRYPT
3372
    Sch13Args* args = NULL;
3373
    WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
3374
#else
3375
0
    Sch13Args  args[1];
3376
0
#endif
3377
0
    byte major, tls12minor;
3378
3379
3380
0
    WOLFSSL_START(WC_FUNC_CLIENT_HELLO_SEND);
3381
0
    WOLFSSL_ENTER("SendTls13ClientHello");
3382
3383
0
    if (ssl == NULL) {
3384
0
        return BAD_FUNC_ARG;
3385
0
    }
3386
3387
0
    ssl->options.buildingMsg = 1;
3388
0
    major = SSLv3_MAJOR;
3389
0
    tls12minor = TLSv1_2_MINOR;
3390
3391
#ifdef WOLFSSL_DTLS13
3392
    if (ssl->options.dtls) {
3393
        major = DTLS_MAJOR;
3394
        tls12minor = DTLSv1_2_MINOR;
3395
    }
3396
#endif /* WOLFSSL_DTLS */
3397
3398
#ifdef HAVE_SESSION_TICKET
3399
    if (ssl->options.resuming &&
3400
            (ssl->session->version.major != ssl->version.major ||
3401
             ssl->session->version.minor != ssl->version.minor)) {
3402
    #ifndef WOLFSSL_NO_TLS12
3403
        if (ssl->session->version.major == ssl->version.major &&
3404
            ssl->session->version.minor < ssl->version.minor) {
3405
            /* Cannot resume with a different protocol version. */
3406
            ssl->options.resuming = 0;
3407
            ssl->version.major = ssl->session->version.major;
3408
            ssl->version.minor = ssl->session->version.minor;
3409
            return SendClientHello(ssl);
3410
        }
3411
        else
3412
    #endif
3413
        {
3414
            WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
3415
            return VERSION_ERROR;
3416
        }
3417
    }
3418
#endif
3419
3420
0
    if (ssl->suites == NULL) {
3421
0
        WOLFSSL_MSG("Bad suites pointer in SendTls13ClientHello");
3422
0
        return SUITES_ERROR;
3423
0
    }
3424
3425
#ifdef WOLFSSL_ASYNC_CRYPT
3426
    if (ssl->async == NULL) {
3427
        ssl->async = (struct WOLFSSL_ASYNC*)
3428
                XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
3429
                        DYNAMIC_TYPE_ASYNC);
3430
        if (ssl->async == NULL)
3431
            return MEMORY_E;
3432
        ssl->async->freeArgs = NULL;
3433
    }
3434
    args = (Sch13Args*)ssl->async->args;
3435
3436
    ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
3437
    if (ret != WC_NOT_PENDING_E) {
3438
        /* Check for error */
3439
        if (ret < 0)
3440
            return ret;
3441
    }
3442
    else
3443
#endif
3444
0
    {
3445
        /* Reset state */
3446
0
        ssl->options.asyncState = TLS_ASYNC_BEGIN;
3447
0
        XMEMSET(args, 0, sizeof(Sch13Args));
3448
0
    }
3449
3450
0
    switch (ssl->options.asyncState) {
3451
0
    case TLS_ASYNC_BEGIN:
3452
0
    {
3453
3454
0
    args->idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
3455
3456
#ifdef WOLFSSL_DTLS13
3457
    if (ssl->options.dtls)
3458
        args->idx += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
3459
#endif /* WOLFSSL_DTLS13 */
3460
3461
    /* Version | Random | Session Id | Cipher Suites | Compression */
3462
0
    args->length = VERSION_SZ + RAN_LEN + ENUM_LEN + ssl->suites->suiteSz +
3463
0
            SUITE_LEN + COMP_LEN + ENUM_LEN;
3464
#ifdef WOLFSSL_QUIC
3465
    if (WOLFSSL_IS_QUIC(ssl)) {
3466
        /* RFC 9001 ch. 8.4 sessionID in ClientHello MUST be 0 length */
3467
        ssl->session->sessionIDSz = 0;
3468
        ssl->options.tls13MiddleBoxCompat = 0;
3469
    }
3470
    else
3471
#endif
3472
#if defined(WOLFSSL_TLS13_MIDDLEBOX_COMPAT)
3473
    {
3474
        args->length += ID_LEN;
3475
        ssl->options.tls13MiddleBoxCompat = 1;
3476
    }
3477
#else
3478
0
    if (ssl->session->sessionIDSz > 0)
3479
0
        args->length += ssl->session->sessionIDSz;
3480
0
#endif
3481
3482
#ifdef WOLFSSL_DTLS13
3483
    if (ssl->options.dtls) {
3484
        /* legacy_cookie_id len */
3485
        args->length += ENUM_LEN;
3486
3487
        /* server sent us an HelloVerifyRequest and we allow downgrade  */
3488
        if (ssl->arrays->cookieSz > 0 && ssl->options.downgrade)
3489
            args->length += ssl->arrays->cookieSz;
3490
    }
3491
#endif /* WOLFSSL_DTLS13 */
3492
3493
    /* Advance state and proceed */
3494
0
    ssl->options.asyncState = TLS_ASYNC_BUILD;
3495
0
    } /* case TLS_ASYNC_BEGIN */
3496
0
    FALL_THROUGH;
3497
3498
0
    case TLS_ASYNC_BUILD:
3499
0
    case TLS_ASYNC_DO:
3500
0
    {
3501
    /* Auto populate extensions supported unless user defined. */
3502
0
    if ((ret = TLSX_PopulateExtensions(ssl, 0)) != 0)
3503
0
        return ret;
3504
3505
    /* Advance state and proceed */
3506
0
    ssl->options.asyncState = TLS_ASYNC_FINALIZE;
3507
0
    } /* case TLS_ASYNC_BUILD */
3508
0
    FALL_THROUGH;
3509
3510
0
    case TLS_ASYNC_FINALIZE:
3511
0
    {
3512
#ifdef WOLFSSL_EARLY_DATA
3513
    #ifndef NO_PSK
3514
        if (!ssl->options.resuming &&
3515
                                     ssl->options.client_psk_tls13_cb == NULL &&
3516
                                     ssl->options.client_psk_cb == NULL)
3517
    #else
3518
        if (!ssl->options.resuming)
3519
    #endif
3520
            ssl->earlyData = no_early_data;
3521
    if (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST_COMPLETE)
3522
        ssl->earlyData = no_early_data;
3523
    if (ssl->earlyData == no_early_data)
3524
        TLSX_Remove(&ssl->extensions, TLSX_EARLY_DATA, ssl->heap);
3525
    if (ssl->earlyData != no_early_data &&
3526
        (ret = TLSX_EarlyData_Use(ssl, 0, 0)) < 0) {
3527
        return ret;
3528
    }
3529
#endif
3530
#ifdef WOLFSSL_QUIC
3531
    if (WOLFSSL_IS_QUIC(ssl) && IsAtLeastTLSv1_3(ssl->version)) {
3532
        ret = wolfSSL_quic_add_transport_extensions(ssl, client_hello);
3533
        if (ret != 0)
3534
            return ret;
3535
    }
3536
#endif
3537
    /* Include length of TLS extensions. */
3538
0
    ret = TLSX_GetRequestSize(ssl, client_hello, &args->length);
3539
0
    if (ret != 0)
3540
0
        return ret;
3541
3542
    /* Total message size. */
3543
0
    args->sendSz = args->length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ;
3544
3545
#ifdef WOLFSSL_DTLS13
3546
    if (ssl->options.dtls)
3547
        args->sendSz += DTLS_RECORD_EXTRA + DTLS_HANDSHAKE_EXTRA;
3548
#endif /* WOLFSSL_DTLS13 */
3549
3550
    /* Check buffers are big enough and grow if needed. */
3551
0
    if ((ret = CheckAvailableSize(ssl, args->sendSz)) != 0)
3552
0
        return ret;
3553
3554
    /* Get position in output buffer to write new message to. */
3555
0
    args->output = ssl->buffers.outputBuffer.buffer +
3556
0
                   ssl->buffers.outputBuffer.length;
3557
3558
    /* Put the record and handshake headers on. */
3559
0
    AddTls13Headers(args->output, args->length, client_hello, ssl);
3560
3561
    /* Protocol version - negotiation now in extension: supported_versions. */
3562
0
    args->output[args->idx++] = major;
3563
0
    args->output[args->idx++] = tls12minor;
3564
3565
    /* Keep for downgrade. */
3566
0
    ssl->chVersion = ssl->version;
3567
3568
0
    if (ssl->arrays == NULL) {
3569
0
        return BAD_FUNC_ARG;
3570
0
    }
3571
    /* Client Random */
3572
0
    if (ssl->options.connectState == CONNECT_BEGIN) {
3573
0
        ret = wc_RNG_GenerateBlock(ssl->rng, args->output + args->idx, RAN_LEN);
3574
0
        if (ret != 0)
3575
0
            return ret;
3576
3577
        /* Store random for possible second ClientHello. */
3578
0
        XMEMCPY(ssl->arrays->clientRandom, args->output + args->idx, RAN_LEN);
3579
0
    }
3580
0
    else
3581
0
        XMEMCPY(args->output + args->idx, ssl->arrays->clientRandom, RAN_LEN);
3582
0
    args->idx += RAN_LEN;
3583
3584
0
    if (ssl->session->sessionIDSz > 0) {
3585
        /* Session resumption for old versions of protocol. */
3586
0
        args->output[args->idx++] = ID_LEN;
3587
0
        XMEMCPY(args->output + args->idx, ssl->session->sessionID,
3588
0
            ssl->session->sessionIDSz);
3589
0
        args->idx += ID_LEN;
3590
0
    }
3591
0
    else {
3592
    #ifdef WOLFSSL_TLS13_MIDDLEBOX_COMPAT
3593
        if (ssl->options.tls13MiddleBoxCompat) {
3594
            args->output[args->idx++] = ID_LEN;
3595
            XMEMCPY(args->output + args->idx, ssl->arrays->clientRandom, ID_LEN);
3596
            args->idx += ID_LEN;
3597
        }
3598
        else
3599
    #endif /* WOLFSSL_TLS13_MIDDLEBOX_COMPAT */
3600
0
        {
3601
            /* TLS v1.3 does not use session id - 0 length. */
3602
0
            args->output[args->idx++] = 0;
3603
0
        }
3604
0
    }
3605
3606
#ifdef WOLFSSL_DTLS13
3607
    if (ssl->options.dtls) {
3608
        args->output[args->idx++] = ssl->arrays->cookieSz;
3609
3610
        if (ssl->arrays->cookieSz > 0) {
3611
            /* We have a cookie saved, so the server sent us an
3612
             * HelloVerifyRequest, it means it is a v1.2 server */
3613
            if (!ssl->options.downgrade)
3614
                return VERSION_ERROR;
3615
            XMEMCPY(args->output + args->idx, ssl->arrays->cookie,
3616
                ssl->arrays->cookieSz);
3617
            args->idx += ssl->arrays->cookieSz;
3618
        }
3619
    }
3620
#endif /* WOLFSSL_DTLS13 */
3621
3622
    /* Cipher suites */
3623
0
    c16toa(ssl->suites->suiteSz, args->output + args->idx);
3624
0
    args->idx += OPAQUE16_LEN;
3625
0
    XMEMCPY(args->output + args->idx, &ssl->suites->suites,
3626
0
        ssl->suites->suiteSz);
3627
0
    args->idx += ssl->suites->suiteSz;
3628
#ifdef WOLFSSL_DEBUG_TLS
3629
    {
3630
        int ii;
3631
        WOLFSSL_MSG("Ciphers:");
3632
        for (ii = 0 ; ii < ssl->suites->suiteSz; ii += 2) {
3633
            WOLFSSL_MSG(GetCipherNameInternal(ssl->suites->suites[ii+0],
3634
                                              ssl->suites->suites[ii+1]));
3635
        }
3636
    }
3637
#endif
3638
3639
    /* Compression not supported in TLS v1.3. */
3640
0
    args->output[args->idx++] = COMP_LEN;
3641
0
    args->output[args->idx++] = NO_COMPRESSION;
3642
3643
    /* Write out extensions for a request. */
3644
0
    args->length = 0;
3645
0
    ret = TLSX_WriteRequest(ssl, args->output + args->idx, client_hello,
3646
0
        &args->length);
3647
0
    if (ret != 0)
3648
0
        return ret;
3649
0
    args->idx += args->length;
3650
3651
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
3652
    /* Resumption has a specific set of extensions and binder is calculated
3653
     * for each identity.
3654
     */
3655
    if (TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY)) {
3656
        ret = WritePSKBinders(ssl, args->output, args->idx);
3657
    }
3658
    else
3659
#endif
3660
0
        {
3661
#ifdef WOLFSSL_DTLS13
3662
        if (ssl->options.dtls)
3663
            ret = Dtls13HashHandshake(ssl,
3664
                args->output + Dtls13GetRlHeaderLength(ssl, 0),
3665
                args->idx - Dtls13GetRlHeaderLength(ssl, 0));
3666
        else
3667
#endif /* WOLFSSL_DTLS13 */
3668
0
                ret = HashOutput(ssl, args->output, args->idx, 0);
3669
0
        }
3670
0
    if (ret != 0)
3671
0
        return ret;
3672
3673
0
    ssl->options.clientState = CLIENT_HELLO_COMPLETE;
3674
3675
#if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
3676
    if (ssl->hsInfoOn) AddPacketName(ssl, "ClientHello");
3677
    if (ssl->toInfoOn) {
3678
        AddPacketInfo(ssl, "ClientHello", handshake, args->output, args->sendSz,
3679
                      WRITE_PROTO, ssl->heap);
3680
    }
3681
#endif
3682
3683
0
    ssl->options.buildingMsg = 0;
3684
#ifdef WOLFSSL_DTLS13
3685
    if (ssl->options.dtls) {
3686
        ret = Dtls13HandshakeSend(ssl, args->output, args->sendSz,
3687
                                  args->idx, client_hello, 0);
3688
3689
        WOLFSSL_LEAVE("SendTls13ClientHello", ret);
3690
        WOLFSSL_END(WC_FUNC_CLIENT_HELLO_SEND);
3691
        return ret;
3692
    }
3693
#endif /* WOLFSSL_DTLS13 */
3694
3695
0
    ssl->buffers.outputBuffer.length += args->sendSz;
3696
3697
    /* Advance state and proceed */
3698
0
    ssl->options.asyncState = TLS_ASYNC_END;
3699
    /* case TLS_ASYNC_BUILD */
3700
0
    FALL_THROUGH;
3701
3702
0
    case TLS_ASYNC_END:
3703
#ifdef WOLFSSL_EARLY_DATA_GROUP
3704
    /* QUIC needs to forward records at their encryption level
3705
     * and is therefore unable to group here */
3706
    if (ssl->earlyData == no_early_data || WOLFSSL_IS_QUIC(ssl))
3707
#endif
3708
0
        ret = SendBuffered(ssl);
3709
3710
0
    break;
3711
0
    }
3712
0
    default:
3713
0
        ret = INPUT_CASE_ERROR;
3714
0
    } /* switch (ssl->options.asyncState) */
3715
3716
#ifdef WOLFSSL_ASYNC_CRYPT
3717
    if (ret == 0)
3718
        FreeAsyncCtx(ssl, 0);
3719
#endif
3720
3721
0
    WOLFSSL_LEAVE("SendTls13ClientHello", ret);
3722
0
    WOLFSSL_END(WC_FUNC_CLIENT_HELLO_SEND);
3723
3724
0
    return ret;
3725
0
}
3726
3727
#if defined(WOLFSSL_DTLS13) && !defined(WOLFSSL_NO_CLIENT)
3728
static int Dtls13DoDowngrade(WOLFSSL* ssl)
3729
{
3730
    int ret;
3731
    if (ssl->dtls13ClientHello == NULL)
3732
        return BAD_STATE_E;
3733
3734
    /* v1.3 and v1.2 hash messages to compute the transcript hash. When we are
3735
     * using DTLSv1.3 we hash the first clientHello following v1.3 but the
3736
     * server can negotiate a lower version. So we need to re-hash the
3737
     * clientHello to adhere to DTLS <= v1.2 rules. */
3738
    ret = InitHandshakeHashes(ssl);
3739
    if (ret != 0)
3740
        return ret;
3741
    ret = HashRaw(ssl, ssl->dtls13ClientHello, ssl->dtls13ClientHelloSz);
3742
    XFREE(ssl->dtls13ClientHello, ssl->heap, DYNAMIC_TYPE_DTLS_MSG);
3743
    ssl->dtls13ClientHello = NULL;
3744
    ssl->dtls13ClientHelloSz = 0;
3745
    ssl->keys.dtls_sequence_number_hi =
3746
        w64GetHigh32(ssl->dtls13EncryptEpoch->nextSeqNumber);
3747
    ssl->keys.dtls_sequence_number_lo =
3748
        w64GetLow32(ssl->dtls13EncryptEpoch->nextSeqNumber);
3749
    return ret;
3750
}
3751
#endif /* WOLFSSL_DTLS13 && !WOLFSSL_NO_CLIENT*/
3752
3753
/* handle processing of TLS 1.3 server_hello (2) and hello_retry_request (6) */
3754
/* Handle the ServerHello message from the server.
3755
 * Only a client will receive this message.
3756
 *
3757
 * ssl       The SSL/TLS object.
3758
 * input     The message buffer.
3759
 * inOutIdx  On entry, the index into the message buffer of ServerHello.
3760
 *           On exit, the index of byte after the ServerHello message.
3761
 * helloSz   The length of the current handshake message.
3762
 * returns 0 on success and otherwise failure.
3763
 */
3764
3765
typedef struct Dsh13Args {
3766
    ProtocolVersion pv;
3767
    word32          idx;
3768
    word32          begin;
3769
    const byte*     sessId;
3770
    word16          totalExtSz;
3771
    byte            sessIdSz;
3772
    byte            extMsgType;
3773
} Dsh13Args;
3774
3775
int DoTls13ServerHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
3776
                       word32 helloSz, byte* extMsgType)
3777
0
{
3778
0
    int ret;
3779
0
    byte suite[2];
3780
0
    byte tls12minor;
3781
#ifdef WOLFSSL_ASYNC_CRYPT
3782
    Dsh13Args* args = NULL;
3783
    WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
3784
#else
3785
0
    Dsh13Args  args[1];
3786
0
#endif
3787
3788
0
    WOLFSSL_START(WC_FUNC_SERVER_HELLO_DO);
3789
0
    WOLFSSL_ENTER("DoTls13ServerHello");
3790
3791
0
    tls12minor = TLSv1_2_MINOR;
3792
3793
#ifdef WOLFSSL_DTLS13
3794
    if (ssl->options.dtls)
3795
        tls12minor = DTLSv1_2_MINOR;
3796
#endif /*  WOLFSSL_DTLS13 */
3797
3798
3799
0
    if (ssl == NULL || ssl->arrays == NULL)
3800
0
        return BAD_FUNC_ARG;
3801
3802
#ifdef WOLFSSL_ASYNC_CRYPT
3803
    if (ssl->async == NULL) {
3804
        ssl->async = (struct WOLFSSL_ASYNC*)
3805
                XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
3806
                        DYNAMIC_TYPE_ASYNC);
3807
        if (ssl->async == NULL)
3808
            return MEMORY_E;
3809
        ssl->async->freeArgs = NULL;
3810
    }
3811
    args = (Dsh13Args*)ssl->async->args;
3812
3813
    ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
3814
    if (ret != WC_NOT_PENDING_E) {
3815
        /* Check for error */
3816
        if (ret < 0) {
3817
            if (ret == WC_PENDING_E) {
3818
                /* Mark message as not received so it can process again */
3819
                ssl->msgsReceived.got_server_hello = 0;
3820
            }
3821
            return ret;
3822
        }
3823
    }
3824
    else
3825
#endif
3826
0
    {
3827
        /* Reset state */
3828
0
        ssl->options.asyncState = TLS_ASYNC_BEGIN;
3829
0
        XMEMSET(args, 0, sizeof(Dsh13Args));
3830
0
    }
3831
3832
0
    switch (ssl->options.asyncState) {
3833
0
    case TLS_ASYNC_BEGIN:
3834
0
    {
3835
0
    byte b;
3836
#ifdef WOLFSSL_CALLBACKS
3837
    if (ssl->hsInfoOn) AddPacketName(ssl, "ServerHello");
3838
    if (ssl->toInfoOn) AddLateName("ServerHello", &ssl->timeoutInfo);
3839
#endif
3840
3841
    /* Protocol version length check. */
3842
0
    if (helloSz < OPAQUE16_LEN)
3843
0
        return BUFFER_ERROR;
3844
3845
0
    args->idx = *inOutIdx;
3846
0
    args->begin = args->idx;
3847
3848
    /* Protocol version */
3849
0
    XMEMCPY(&args->pv, input + args->idx, OPAQUE16_LEN);
3850
0
    args->idx += OPAQUE16_LEN;
3851
3852
#ifdef WOLFSSL_DTLS
3853
    if (ssl->options.dtls &&
3854
        (args->pv.major != DTLS_MAJOR || args->pv.minor == DTLS_BOGUS_MINOR))
3855
        return VERSION_ERROR;
3856
#endif /* WOLFSSL_DTLS */
3857
3858
0
#ifndef WOLFSSL_NO_TLS12
3859
0
    {
3860
0
        byte wantDowngrade;
3861
3862
0
        wantDowngrade = args->pv.major == ssl->version.major &&
3863
0
            args->pv.minor < TLSv1_2_MINOR;
3864
3865
#ifdef WOLFSSL_DTLS13
3866
        if (ssl->options.dtls)
3867
            wantDowngrade = args->pv.major == ssl->version.major &&
3868
                args->pv.minor > DTLSv1_2_MINOR;
3869
#endif /* WOLFSSL_DTLS13 */
3870
3871
0
        if (wantDowngrade && ssl->options.downgrade) {
3872
            /* Force client hello version 1.2 to work for static RSA. */
3873
0
            ssl->chVersion.minor = TLSv1_2_MINOR;
3874
0
            ssl->version.minor = TLSv1_2_MINOR;
3875
3876
#ifdef WOLFSSL_DTLS13
3877
            if (ssl->options.dtls) {
3878
                ssl->chVersion.minor = DTLSv1_2_MINOR;
3879
                ssl->version.minor = DTLSv1_2_MINOR;
3880
                ret = Dtls13DoDowngrade(ssl);
3881
                if (ret != 0)
3882
                    return ret;
3883
            }
3884
#endif /* WOLFSSL_DTLS13 */
3885
3886
0
            return DoServerHello(ssl, input, inOutIdx, helloSz);
3887
0
        }
3888
0
    }
3889
0
#endif
3890
3891
0
    if (args->pv.major != ssl->version.major ||
3892
0
        args->pv.minor != tls12minor) {
3893
0
        WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
3894
0
        return VERSION_ERROR;
3895
0
    }
3896
3897
    /* Random and session id length check */
3898
0
    if ((args->idx - args->begin) + RAN_LEN + ENUM_LEN > helloSz)
3899
0
        return BUFFER_ERROR;
3900
3901
    /* Check if hello retry request */
3902
0
    if (XMEMCMP(input + args->idx, helloRetryRequestRandom, RAN_LEN) == 0) {
3903
0
        WOLFSSL_MSG("HelloRetryRequest format");
3904
0
        *extMsgType = hello_retry_request;
3905
3906
        /* A HelloRetryRequest comes in as an ServerHello for MiddleBox compat.
3907
         * Found message to be a HelloRetryRequest.
3908
         * Don't allow more than one HelloRetryRequest or ServerHello.
3909
         */
3910
0
        if (ssl->msgsReceived.got_hello_retry_request) {
3911
0
            WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
3912
0
            return DUPLICATE_MSG_E;
3913
0
        }
3914
0
    }
3915
0
    args->extMsgType = *extMsgType;
3916
3917
    /* Server random - keep for debugging. */
3918
0
    XMEMCPY(ssl->arrays->serverRandom, input + args->idx, RAN_LEN);
3919
0
    args->idx += RAN_LEN;
3920
3921
    /* Session id */
3922
0
    args->sessIdSz = input[args->idx++];
3923
0
    if ((args->idx - args->begin) + args->sessIdSz > helloSz)
3924
0
        return BUFFER_ERROR;
3925
0
    args->sessId = input + args->idx;
3926
0
    args->idx += args->sessIdSz;
3927
3928
0
    ssl->options.haveSessionId = 1;
3929
3930
    /* Ciphersuite and compression check */
3931
0
    if ((args->idx - args->begin) + OPAQUE16_LEN + OPAQUE8_LEN > helloSz)
3932
0
        return BUFFER_ERROR;
3933
3934
    /* Set the cipher suite from the message. */
3935
0
    ssl->options.cipherSuite0 = input[args->idx++];
3936
0
    ssl->options.cipherSuite  = input[args->idx++];
3937
#ifdef WOLFSSL_DEBUG_TLS
3938
    WOLFSSL_MSG("Chosen cipher suite:");
3939
    WOLFSSL_MSG(GetCipherNameInternal(ssl->options.cipherSuite0,
3940
                                      ssl->options.cipherSuite));
3941
#endif
3942
3943
    /* Compression */
3944
0
    b = input[args->idx++];
3945
0
    if (b != 0) {
3946
0
        WOLFSSL_MSG("Must be no compression types in list");
3947
0
        WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
3948
0
        return INVALID_PARAMETER;
3949
0
    }
3950
3951
0
    if ((args->idx - args->begin) + OPAQUE16_LEN > helloSz) {
3952
0
        if (!ssl->options.downgrade)
3953
0
            return BUFFER_ERROR;
3954
0
#ifndef WOLFSSL_NO_TLS12
3955
        /* Force client hello version 1.2 to work for static RSA. */
3956
0
        ssl->chVersion.minor = TLSv1_2_MINOR;
3957
0
        ssl->version.minor = TLSv1_2_MINOR;
3958
3959
#ifdef WOLFSSL_DTLS13
3960
        if (ssl->options.dtls) {
3961
            ssl->chVersion.minor = DTLSv1_2_MINOR;
3962
            ssl->version.minor = DTLSv1_2_MINOR;
3963
            ret = Dtls13DoDowngrade(ssl);
3964
            if (ret != 0)
3965
                return ret;
3966
        }
3967
#endif /* WOLFSSL_DTLS13 */
3968
3969
0
#endif
3970
0
        ssl->options.haveEMS = 0;
3971
0
        if (args->pv.minor < ssl->options.minDowngrade)
3972
0
            return VERSION_ERROR;
3973
0
#ifndef WOLFSSL_NO_TLS12
3974
0
        return DoServerHello(ssl, input, inOutIdx, helloSz);
3975
#else
3976
        return VERSION_ERROR;
3977
#endif
3978
0
    }
3979
3980
0
    if ((args->idx - args->begin) < helloSz) {
3981
0
        int foundVersion;
3982
3983
        /* Get extension length and length check. */
3984
0
        if ((args->idx - args->begin) + OPAQUE16_LEN > helloSz)
3985
0
            return BUFFER_ERROR;
3986
0
        ato16(&input[args->idx], &args->totalExtSz);
3987
0
        args->idx += OPAQUE16_LEN;
3988
0
        if ((args->idx - args->begin) + args->totalExtSz > helloSz)
3989
0
            return BUFFER_ERROR;
3990
3991
        /* Need to negotiate version first. */
3992
0
        if ((ret = TLSX_ParseVersion(ssl, input + args->idx,
3993
0
            args->totalExtSz, *extMsgType, &foundVersion))) {
3994
0
            return ret;
3995
0
        }
3996
0
        if (!foundVersion) {
3997
0
            if (!ssl->options.downgrade) {
3998
0
                WOLFSSL_MSG("Server trying to downgrade to version less than "
3999
0
                            "TLS v1.3");
4000
0
                WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
4001
0
                return VERSION_ERROR;
4002
0
            }
4003
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
4004
    defined(WOLFSSL_WPAS_SMALL)
4005
            /* Check if client has disabled TLS 1.2 */
4006
            if (args->pv.minor == TLSv1_2_MINOR &&
4007
                (ssl->options.mask & SSL_OP_NO_TLSv1_2) == SSL_OP_NO_TLSv1_2) {
4008
                WOLFSSL_MSG("\tOption set to not allow TLSv1.2");
4009
                WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
4010
                return VERSION_ERROR;
4011
            }
4012
#endif
4013
4014
0
            if (!ssl->options.dtls &&
4015
0
                args->pv.minor < ssl->options.minDowngrade) {
4016
0
                WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
4017
0
                return VERSION_ERROR;
4018
0
            }
4019
4020
0
            if (ssl->options.dtls &&
4021
0
                args->pv.minor > ssl->options.minDowngrade) {
4022
0
                WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
4023
0
                return VERSION_ERROR;
4024
0
            }
4025
4026
0
            ssl->version.minor = args->pv.minor;
4027
4028
#ifdef WOLFSSL_DTLS13
4029
            if (ssl->options.dtls) {
4030
                ret = Dtls13DoDowngrade(ssl);
4031
                if (ret != 0)
4032
                    return ret;
4033
            }
4034
#endif /* WOLFSSL_DTLS13 */
4035
0
        }
4036
0
    }
4037
4038
#ifdef WOLFSSL_DTLS13
4039
    /* we are sure that version is >= v1.3 now, we can get rid of buffered
4040
     * ClientHello that was buffered to re-compute the hash in case of
4041
     * downgrade */
4042
    if (ssl->options.dtls && ssl->dtls13ClientHello != NULL) {
4043
        XFREE(ssl->dtls13ClientHello, ssl->heap, DYNAMIC_TYPE_DTLS_MSG);
4044
        ssl->dtls13ClientHello = NULL;
4045
        ssl->dtls13ClientHelloSz = 0;
4046
    }
4047
#endif /* WOLFSSL_DTLS13 */
4048
4049
    /* Advance state and proceed */
4050
0
    ssl->options.asyncState = TLS_ASYNC_BUILD;
4051
0
    } /* case TLS_ASYNC_BEGIN */
4052
0
    FALL_THROUGH;
4053
4054
0
    case TLS_ASYNC_BUILD:
4055
0
    case TLS_ASYNC_DO:
4056
0
    {
4057
    /* restore message type */
4058
0
    *extMsgType = args->extMsgType;
4059
4060
0
    if (args->totalExtSz > 0) {
4061
        /* Parse and handle extensions. */
4062
0
        ret = TLSX_Parse(ssl, input + args->idx, args->totalExtSz,
4063
0
            *extMsgType, NULL);
4064
0
        if (ret != 0) {
4065
        #ifdef WOLFSSL_ASYNC_CRYPT
4066
            /* Handle async operation */
4067
            if (ret == WC_PENDING_E) {
4068
                /* Mark message as not received so it can process again */
4069
                ssl->msgsReceived.got_server_hello = 0;
4070
            }
4071
        #endif
4072
0
            return ret;
4073
0
        }
4074
4075
0
        if (*extMsgType == hello_retry_request) {
4076
            /* Update counts to reflect change of message type. */
4077
0
            ssl->msgsReceived.got_hello_retry_request = 1;
4078
0
            ssl->msgsReceived.got_server_hello = 0;
4079
0
        }
4080
4081
0
        args->idx += args->totalExtSz;
4082
0
    }
4083
4084
#ifdef WOLFSSL_DTLS_CID
4085
    if (ssl->options.useDtlsCID)
4086
        DtlsCIDOnExtensionsParsed(ssl);
4087
#endif /* WOLFSSL_DTLS_CID */
4088
4089
0
    *inOutIdx = args->idx;
4090
4091
0
    ssl->options.serverState = SERVER_HELLO_COMPLETE;
4092
4093
#ifdef HAVE_SECRET_CALLBACK
4094
    if (ssl->sessionSecretCb != NULL
4095
#ifdef HAVE_SESSION_TICKET
4096
            && ssl->session->ticketLen > 0
4097
#endif
4098
            ) {
4099
        int secretSz = SECRET_LEN;
4100
        ret = ssl->sessionSecretCb(ssl, ssl->session->masterSecret,
4101
                                   &secretSz, ssl->sessionSecretCtx);
4102
        if (ret != 0 || secretSz != SECRET_LEN) {
4103
            WOLFSSL_ERROR_VERBOSE(SESSION_SECRET_CB_E);
4104
            return SESSION_SECRET_CB_E;
4105
        }
4106
    }
4107
#endif /* HAVE_SECRET_CALLBACK */
4108
4109
    /* Version only negotiated in extensions for TLS v1.3.
4110
     * Only now do we know how to deal with session id.
4111
     */
4112
0
    if (!IsAtLeastTLSv1_3(ssl->version)) {
4113
0
#ifndef WOLFSSL_NO_TLS12
4114
0
        ssl->arrays->sessionIDSz = args->sessIdSz;
4115
4116
0
        if (ssl->arrays->sessionIDSz > ID_LEN) {
4117
0
            WOLFSSL_MSG("Invalid session ID size");
4118
0
            ssl->arrays->sessionIDSz = 0;
4119
0
            return BUFFER_ERROR;
4120
0
        }
4121
0
        else if (ssl->arrays->sessionIDSz) {
4122
0
            XMEMCPY(ssl->arrays->sessionID, args->sessId,
4123
0
                ssl->arrays->sessionIDSz);
4124
0
            ssl->options.haveSessionId = 1;
4125
0
        }
4126
4127
        /* Force client hello version 1.2 to work for static RSA. */
4128
0
        ssl->chVersion.minor = TLSv1_2_MINOR;
4129
        /* Complete TLS v1.2 processing of ServerHello. */
4130
0
        ret = CompleteServerHello(ssl);
4131
#else
4132
        WOLFSSL_MSG("Client using higher version, fatal error");
4133
        WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
4134
        ret = VERSION_ERROR;
4135
#endif
4136
4137
0
        WOLFSSL_LEAVE("DoTls13ServerHello", ret);
4138
4139
0
        return ret;
4140
0
    }
4141
4142
    /* Advance state and proceed */
4143
0
    ssl->options.asyncState = TLS_ASYNC_FINALIZE;
4144
0
    } /* case TLS_ASYNC_BUILD || TLS_ASYNC_DO */
4145
0
    FALL_THROUGH;
4146
4147
0
    case TLS_ASYNC_FINALIZE:
4148
0
    {
4149
#ifdef WOLFSSL_TLS13_MIDDLEBOX_COMPAT
4150
    if (ssl->options.tls13MiddleBoxCompat) {
4151
        if (args->sessIdSz == 0) {
4152
            WOLFSSL_MSG("args->sessIdSz == 0");
4153
            WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
4154
            return INVALID_PARAMETER;
4155
        }
4156
        if (ssl->session->sessionIDSz != 0) {
4157
            if (ssl->session->sessionIDSz != args->sessIdSz ||
4158
                XMEMCMP(ssl->session->sessionID, args->sessId,
4159
                    args->sessIdSz) != 0) {
4160
                WOLFSSL_MSG("session id doesn't match");
4161
                WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
4162
                return INVALID_PARAMETER;
4163
            }
4164
        }
4165
        else if (XMEMCMP(ssl->arrays->clientRandom, args->sessId,
4166
                args->sessIdSz) != 0) {
4167
            WOLFSSL_MSG("session id doesn't match client random");
4168
            WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
4169
            return INVALID_PARAMETER;
4170
    }
4171
    else
4172
#endif /* WOLFSSL_TLS13_MIDDLEBOX_COMPAT */
4173
#ifdef WOLFSSL_QUIC
4174
    if (WOLFSSL_IS_QUIC(ssl)) {
4175
        if (args->sessIdSz != 0) {
4176
            WOLFSSL_MSG("args->sessIdSz != 0");
4177
            WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
4178
            return INVALID_PARAMETER;
4179
        }
4180
    }
4181
    else
4182
#endif /* WOLFSSL_QUIC */
4183
0
    if (args->sessIdSz != ssl->session->sessionIDSz || (args->sessIdSz > 0 &&
4184
0
        XMEMCMP(ssl->session->sessionID, args->sessId, args->sessIdSz) != 0))
4185
0
    {
4186
0
        WOLFSSL_MSG("Server sent different session id");
4187
0
        WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
4188
0
        return INVALID_PARAMETER;
4189
0
    }
4190
4191
0
    ret = SetCipherSpecs(ssl);
4192
0
    if (ret != 0)
4193
0
        return ret;
4194
#ifdef HAVE_NULL_CIPHER
4195
    if (ssl->options.cipherSuite0 == ECC_BYTE &&
4196
                              (ssl->options.cipherSuite == TLS_SHA256_SHA256 ||
4197
                               ssl->options.cipherSuite == TLS_SHA384_SHA384)) {
4198
        ;
4199
    }
4200
    else
4201
#endif
4202
    /* Check that the negotiated ciphersuite matches protocol version. */
4203
0
    if (ssl->options.cipherSuite0 != TLS13_BYTE) {
4204
0
        WOLFSSL_MSG("Server sent non-TLS13 cipher suite in TLS 1.3 packet");
4205
0
        WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
4206
0
        return INVALID_PARAMETER;
4207
0
    }
4208
4209
0
    suite[0] = ssl->options.cipherSuite0;
4210
0
    suite[1] = ssl->options.cipherSuite;
4211
0
    if (!FindSuiteSSL(ssl, suite)) {
4212
0
        WOLFSSL_MSG("Cipher suite not supported on client");
4213
0
        WOLFSSL_ERROR_VERBOSE(MATCH_SUITE_ERROR);
4214
0
        return MATCH_SUITE_ERROR;
4215
0
    }
4216
4217
0
    if (*extMsgType == server_hello) {
4218
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
4219
        PreSharedKey* psk = NULL;
4220
        TLSX* ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
4221
        if (ext != NULL)
4222
            psk = (PreSharedKey*)ext->data;
4223
        while (psk != NULL && !psk->chosen)
4224
            psk = psk->next;
4225
        if (psk == NULL) {
4226
            ssl->options.resuming = 0;
4227
            ssl->arrays->psk_keySz = 0;
4228
            XMEMSET(ssl->arrays->psk_key, 0, MAX_PSK_KEY_LEN);
4229
        }
4230
        else {
4231
            if ((ret = SetupPskKey(ssl, psk, 0)) != 0)
4232
                return ret;
4233
            ssl->options.pskNegotiated = 1;
4234
        }
4235
#endif
4236
4237
0
        ssl->keys.encryptionOn = 1;
4238
0
        ssl->options.serverState = SERVER_HELLO_COMPLETE;
4239
0
    }
4240
0
    else {
4241
0
        ssl->options.tls1_3 = 1;
4242
0
        ssl->options.serverState = SERVER_HELLO_RETRY_REQUEST_COMPLETE;
4243
4244
0
        ret = RestartHandshakeHash(ssl);
4245
0
    }
4246
4247
0
    break;
4248
0
    } /* case TLS_ASYNC_FINALIZE */
4249
0
    default:
4250
0
        ret = INPUT_CASE_ERROR;
4251
0
    } /* switch (ssl->options.asyncState) */
4252
4253
#ifdef WOLFSSL_ASYNC_CRYPT
4254
    if (ret == 0)
4255
        FreeAsyncCtx(ssl, 0);
4256
#endif
4257
4258
0
    WOLFSSL_LEAVE("DoTls13ServerHello", ret);
4259
0
    WOLFSSL_END(WC_FUNC_SERVER_HELLO_DO);
4260
4261
0
    return ret;
4262
0
}
4263
4264
/* handle processing TLS 1.3 encrypted_extensions (8) */
4265
/* Parse and handle an EncryptedExtensions message.
4266
 * Only a client will receive this message.
4267
 *
4268
 * ssl       The SSL/TLS object.
4269
 * input     The message buffer.
4270
 * inOutIdx  On entry, the index into the message buffer of
4271
 *           EncryptedExtensions.
4272
 *           On exit, the index of byte after the EncryptedExtensions
4273
 *           message.
4274
 * totalSz   The length of the current handshake message.
4275
 * returns 0 on success and otherwise failure.
4276
 */
4277
static int DoTls13EncryptedExtensions(WOLFSSL* ssl, const byte* input,
4278
                                      word32* inOutIdx, word32 totalSz)
4279
0
{
4280
0
    int    ret;
4281
0
    word32 begin = *inOutIdx;
4282
0
    word32 i = begin;
4283
0
    word16 totalExtSz;
4284
4285
0
    WOLFSSL_START(WC_FUNC_ENCRYPTED_EXTENSIONS_DO);
4286
0
    WOLFSSL_ENTER("DoTls13EncryptedExtensions");
4287
4288
#ifdef WOLFSSL_CALLBACKS
4289
    if (ssl->hsInfoOn) AddPacketName(ssl, "EncryptedExtensions");
4290
    if (ssl->toInfoOn) AddLateName("EncryptedExtensions", &ssl->timeoutInfo);
4291
#endif
4292
4293
    /* Length field of extension data. */
4294
0
    if (totalSz < OPAQUE16_LEN)
4295
0
        return BUFFER_ERROR;
4296
0
    ato16(&input[i], &totalExtSz);
4297
0
    i += OPAQUE16_LEN;
4298
4299
    /* Extension data. */
4300
0
    if (i - begin + totalExtSz > totalSz)
4301
0
        return BUFFER_ERROR;
4302
0
    if ((ret = TLSX_Parse(ssl, input + i, totalExtSz, encrypted_extensions,
4303
0
                                                                       NULL))) {
4304
0
        return ret;
4305
0
    }
4306
4307
    /* Move index to byte after message. */
4308
0
    *inOutIdx = i + totalExtSz;
4309
4310
    /* Always encrypted. */
4311
0
    *inOutIdx += ssl->keys.padSz;
4312
4313
#ifdef WOLFSSL_EARLY_DATA
4314
    if (ssl->earlyData != no_early_data) {
4315
        TLSX* ext = TLSX_Find(ssl->extensions, TLSX_EARLY_DATA);
4316
        if (ext == NULL || !ext->val)
4317
            ssl->earlyData = no_early_data;
4318
    }
4319
#endif
4320
4321
#ifdef WOLFSSL_EARLY_DATA
4322
    if (ssl->earlyData == no_early_data) {
4323
        ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY);
4324
        if (ret != 0)
4325
            return ret;
4326
    }
4327
#endif
4328
4329
0
    ssl->options.serverState = SERVER_ENCRYPTED_EXTENSIONS_COMPLETE;
4330
4331
0
    WOLFSSL_LEAVE("DoTls13EncryptedExtensions", ret);
4332
0
    WOLFSSL_END(WC_FUNC_ENCRYPTED_EXTENSIONS_DO);
4333
4334
0
    return ret;
4335
0
}
4336
4337
#ifndef NO_CERTS
4338
/* handle processing TLS v1.3 certificate_request (13) */
4339
/* Handle a TLS v1.3 CertificateRequest message.
4340
 * This message is always encrypted.
4341
 * Only a client will receive this message.
4342
 *
4343
 * ssl       The SSL/TLS object.
4344
 * input     The message buffer.
4345
 * inOutIdx  On entry, the index into the message buffer of CertificateRequest.
4346
 *           On exit, the index of byte after the CertificateRequest message.
4347
 * size      The length of the current handshake message.
4348
 * returns 0 on success and otherwise failure.
4349
 */
4350
static int DoTls13CertificateRequest(WOLFSSL* ssl, const byte* input,
4351
                                     word32* inOutIdx, word32 size)
4352
0
{
4353
0
    word16      len;
4354
0
    word32      begin = *inOutIdx;
4355
0
    int         ret = 0;
4356
0
    Suites      peerSuites;
4357
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
4358
    CertReqCtx* certReqCtx;
4359
#endif
4360
4361
0
    WOLFSSL_START(WC_FUNC_CERTIFICATE_REQUEST_DO);
4362
0
    WOLFSSL_ENTER("DoTls13CertificateRequest");
4363
4364
0
    XMEMSET(&peerSuites, 0, sizeof(Suites));
4365
4366
#ifdef WOLFSSL_CALLBACKS
4367
    if (ssl->hsInfoOn) AddPacketName(ssl, "CertificateRequest");
4368
    if (ssl->toInfoOn) AddLateName("CertificateRequest", &ssl->timeoutInfo);
4369
#endif
4370
4371
0
    if (OPAQUE8_LEN > size)
4372
0
        return BUFFER_ERROR;
4373
4374
    /* Length of the request context. */
4375
0
    len = input[(*inOutIdx)++];
4376
0
    if ((*inOutIdx - begin) + len > size)
4377
0
        return BUFFER_ERROR;
4378
0
    if (ssl->options.connectState < FINISHED_DONE && len > 0)
4379
0
        return BUFFER_ERROR;
4380
4381
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
4382
    /* CertReqCtx has one byte at end for context value.
4383
     * Increase size to handle other implementations sending more than one byte.
4384
     * That is, allocate extra space, over one byte, to hold the context value.
4385
     */
4386
    certReqCtx = (CertReqCtx*)XMALLOC(sizeof(CertReqCtx) + len - 1, ssl->heap,
4387
                                                       DYNAMIC_TYPE_TMP_BUFFER);
4388
    if (certReqCtx == NULL)
4389
        return MEMORY_E;
4390
    certReqCtx->next = ssl->certReqCtx;
4391
    certReqCtx->len = len;
4392
    XMEMCPY(&certReqCtx->ctx, input + *inOutIdx, len);
4393
    ssl->certReqCtx = certReqCtx;
4394
#endif
4395
0
    *inOutIdx += len;
4396
4397
    /* TODO: Add support for more extensions:
4398
     *   signed_certificate_timestamp, certificate_authorities, oid_filters.
4399
     */
4400
    /* Certificate extensions */
4401
0
    if ((*inOutIdx - begin) + OPAQUE16_LEN > size)
4402
0
        return BUFFER_ERROR;
4403
0
    ato16(input + *inOutIdx, &len);
4404
0
    *inOutIdx += OPAQUE16_LEN;
4405
0
    if ((*inOutIdx - begin) + len > size)
4406
0
        return BUFFER_ERROR;
4407
0
    if (len == 0)
4408
0
        return INVALID_PARAMETER;
4409
0
    if ((ret = TLSX_Parse(ssl, input + *inOutIdx, len, certificate_request,
4410
0
                                                                &peerSuites))) {
4411
0
        return ret;
4412
0
    }
4413
0
    *inOutIdx += len;
4414
4415
0
    if ((ssl->buffers.certificate && ssl->buffers.certificate->buffer &&
4416
0
        ((ssl->buffers.key && ssl->buffers.key->buffer)
4417
        #ifdef HAVE_PK_CALLBACKS
4418
            || wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)
4419
        #endif
4420
0
    ))
4421
        #ifdef OPENSSL_EXTRA
4422
            || ssl->ctx->certSetupCb != NULL
4423
        #endif
4424
0
            ) {
4425
0
        if (PickHashSigAlgo(ssl, peerSuites.hashSigAlgo,
4426
0
                                               peerSuites.hashSigAlgoSz) != 0) {
4427
0
            WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
4428
0
            return INVALID_PARAMETER;
4429
0
        }
4430
0
        ssl->options.sendVerify = SEND_CERT;
4431
0
    }
4432
0
    else {
4433
0
#ifndef WOLFSSL_NO_CLIENT_CERT_ERROR
4434
0
        ssl->options.sendVerify = SEND_BLANK_CERT;
4435
#else
4436
        WOLFSSL_MSG("Certificate required but none set on client");
4437
        SendAlert(ssl, alert_fatal, illegal_parameter);
4438
        WOLFSSL_ERROR_VERBOSE(NO_CERT_ERROR);
4439
        return NO_CERT_ERROR;
4440
#endif
4441
0
    }
4442
4443
    /* This message is always encrypted so add encryption padding. */
4444
0
    *inOutIdx += ssl->keys.padSz;
4445
4446
0
    WOLFSSL_LEAVE("DoTls13CertificateRequest", ret);
4447
0
    WOLFSSL_END(WC_FUNC_CERTIFICATE_REQUEST_DO);
4448
4449
0
    return ret;
4450
0
}
4451
#endif /* !NO_CERTS */
4452
#endif /* !NO_WOLFSSL_CLIENT */
4453
4454
#ifndef NO_WOLFSSL_SERVER
4455
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
4456
/* Refine list of supported cipher suites to those common to server and client.
4457
 *
4458
 * ssl         SSL/TLS object.
4459
 * peerSuites  The peer's advertised list of supported cipher suites.
4460
 */
4461
static void RefineSuites(WOLFSSL* ssl, Suites* peerSuites)
4462
{
4463
    byte   suites[WOLFSSL_MAX_SUITE_SZ];
4464
    word16 suiteSz = 0;
4465
    word16 i, j;
4466
4467
    XMEMSET(suites, 0, WOLFSSL_MAX_SUITE_SZ);
4468
4469
    for (i = 0; i < ssl->suites->suiteSz; i += 2) {
4470
        for (j = 0; j < peerSuites->suiteSz; j += 2) {
4471
            if (ssl->suites->suites[i+0] == peerSuites->suites[j+0] &&
4472
                ssl->suites->suites[i+1] == peerSuites->suites[j+1]) {
4473
                suites[suiteSz++] = peerSuites->suites[j+0];
4474
                suites[suiteSz++] = peerSuites->suites[j+1];
4475
            }
4476
        }
4477
    }
4478
4479
    ssl->suites->suiteSz = suiteSz;
4480
    XMEMCPY(ssl->suites->suites, &suites, sizeof(suites));
4481
#ifdef WOLFSSL_DEBUG_TLS
4482
    {
4483
        int ii;
4484
        WOLFSSL_MSG("Refined Ciphers:");
4485
        for (ii = 0 ; ii < ssl->suites->suiteSz; ii += 2) {
4486
            WOLFSSL_MSG(GetCipherNameInternal(ssl->suites->suites[ii+0],
4487
                                              ssl->suites->suites[ii+1]));
4488
        }
4489
    }
4490
#endif
4491
}
4492
4493
4494
#ifndef NO_PSK
4495
/* Attempt to find the PSK (not session ticket) that matches.
4496
 *
4497
 * @param [in, out] ssl    The SSL/TLS object.
4498
 * @param [in]      psk    A pre-shared key from the extension.
4499
 * @param [out]     suite  Cipher suite to use with PSK.
4500
 * @param [out]     err    Error code.
4501
 *                         PSK_KEY_ERROR when key is too big or ticket age is
4502
 *                         invalid,
4503
 *                         UNSUPPORTED_SUITE on invalid suite.
4504
 *                         Other error when attempting to derive early secret.
4505
 * @return  1 when a match found - but check error code.
4506
 * @return  0 when no match found.
4507
 */
4508
static int FindPsk(WOLFSSL* ssl, PreSharedKey* psk, byte* suite, int* err)
4509
{
4510
    int         ret = 0;
4511
    int         found = 0;
4512
    const char* cipherName = NULL;
4513
    byte        cipherSuite0 = TLS13_BYTE;
4514
    byte        cipherSuite  = WOLFSSL_DEF_PSK_CIPHER;
4515
    Arrays*     sa = ssl->arrays;
4516
4517
    if (ssl->options.server_psk_tls13_cb != NULL) {
4518
         sa->psk_keySz = ssl->options.server_psk_tls13_cb(ssl,
4519
             sa->client_identity, sa->psk_key, MAX_PSK_KEY_LEN, &cipherName);
4520
         if (sa->psk_keySz != 0) {
4521
             int cipherSuiteFlags = WOLFSSL_CIPHER_SUITE_FLAG_NONE;
4522
             found = (GetCipherSuiteFromName(cipherName, &cipherSuite0,
4523
                 &cipherSuite, &cipherSuiteFlags) == 0);
4524
             (void)cipherSuiteFlags;
4525
         }
4526
    }
4527
    if (!found && (ssl->options.server_psk_cb != NULL)) {
4528
         sa->psk_keySz = ssl->options.server_psk_cb(ssl,
4529
                             sa->client_identity, sa->psk_key,
4530
                             MAX_PSK_KEY_LEN);
4531
         found = (sa->psk_keySz != 0);
4532
    }
4533
    if (found) {
4534
        if (sa->psk_keySz > MAX_PSK_KEY_LEN) {
4535
            ret = PSK_KEY_ERROR;
4536
            WOLFSSL_ERROR_VERBOSE(ret);
4537
        }
4538
        if (ret == 0) {
4539
        #ifndef WOLFSSL_PSK_ONE_ID
4540
            /* Check whether PSK ciphersuite is in SSL. */
4541
            found = (suite[0] == cipherSuite0) && (suite[1] == cipherSuite);
4542
        #else
4543
            /* Check whether PSK ciphersuite is in SSL. */
4544
            suite[0] = cipherSuite0;
4545
            suite[1] = cipherSuite;
4546
            found = FindSuiteSSL(ssl, suite);
4547
        #endif
4548
        }
4549
        if ((ret == 0) && found) {
4550
            /* Default to ciphersuite if cb doesn't specify. */
4551
            ssl->options.resuming = 0;
4552
            /* Don't send certificate request when using PSK. */
4553
            ssl->options.verifyPeer = 0;
4554
4555
            /* PSK age is always zero. */
4556
            if (psk->ticketAge != ssl->session->ticketAdd) {
4557
                ret = PSK_KEY_ERROR;
4558
                WOLFSSL_ERROR_VERBOSE(ret);
4559
            }
4560
        }
4561
        if ((ret == 0) && found) {
4562
            /* Set PSK ciphersuite into SSL. */
4563
            ssl->options.cipherSuite0 = suite[0];
4564
            ssl->options.cipherSuite  = suite[1];
4565
            ret = SetCipherSpecs(ssl);
4566
        }
4567
        if ((ret == 0) && found) {
4568
            /* Derive the early secret using the PSK. */
4569
            ret = DeriveEarlySecret(ssl);
4570
        }
4571
        if ((ret == 0) && found) {
4572
            /* PSK negotiation has succeeded */
4573
            ssl->options.isPSK = 1;
4574
            /* SERVER: using PSK for peer authentication. */
4575
            ssl->options.peerAuthGood = 1;
4576
        }
4577
    }
4578
4579
    *err = ret;
4580
    return found;
4581
}
4582
#endif
4583
4584
/* Handle any Pre-Shared Key (PSK) extension.
4585
 * Find a PSK that supports the cipher suite passed in.
4586
 *
4587
 * ssl         SSL/TLS object.
4588
 * suite       Cipher suite to find PSK for.
4589
 * usingPSK    1=Indicates handshake is using Pre-Shared Keys (2=Ephemeral)
4590
 * first       Set to 1 if first in extension
4591
 * returns 0 on success and otherwise failure.
4592
 */
4593
static int DoPreSharedKeys(WOLFSSL* ssl, const byte* input, word32 inputSz,
4594
    byte* suite, int* usingPSK, int* first)
4595
{
4596
    int           ret = 0;
4597
    TLSX*         ext;
4598
    PreSharedKey* current;
4599
    byte          binderKey[WC_MAX_DIGEST_SIZE];
4600
    byte          binder[WC_MAX_DIGEST_SIZE];
4601
    word32        binderLen;
4602
4603
    WOLFSSL_ENTER("DoPreSharedKeys");
4604
4605
    ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
4606
    if (ext == NULL) {
4607
        WOLFSSL_MSG("No pre shared extension keys found");
4608
        return BAD_FUNC_ARG;
4609
    }
4610
4611
    /* Look through all client's pre-shared keys for a match. */
4612
    current = (PreSharedKey*)ext->data;
4613
    while (current != NULL) {
4614
    #ifndef NO_PSK
4615
        if (current->identityLen > MAX_PSK_ID_LEN) {
4616
            return BUFFER_ERROR;
4617
        }
4618
        XMEMCPY(ssl->arrays->client_identity, current->identity,
4619
                current->identityLen);
4620
        ssl->arrays->client_identity[current->identityLen] = '\0';
4621
    #endif
4622
4623
    #ifdef HAVE_SESSION_TICKET
4624
        /* Decode the identity. */
4625
        ret = DoClientTicket(ssl, current->identity, current->identityLen);
4626
        #ifdef WOLFSSL_ASYNC_CRYPT
4627
        if (ret == WC_PENDING_E)
4628
            return ret;
4629
        #endif
4630
4631
        if (ret == WOLFSSL_TICKET_RET_OK) {
4632
            word32  now;
4633
            sword64 diff;
4634
4635
            now = TimeNowInMilliseconds();
4636
            if (now == (word32)GETTIME_ERROR)
4637
                return now;
4638
            /* Difference between now and time ticket constructed
4639
             * (from decrypted ticket). */
4640
            diff = now;
4641
            diff -= ssl->session->ticketSeen;
4642
            if (diff > (sword64)ssl->timeout * 1000 ||
4643
                diff > (sword64)TLS13_MAX_TICKET_AGE * 1000) {
4644
                current = current->next;
4645
                continue;
4646
            }
4647
            /* Subtract client's ticket age and unobfuscate. */
4648
            diff -= current->ticketAge;
4649
            diff += ssl->session->ticketAdd;
4650
            /* Check session and ticket age timeout.
4651
             * Allow +/- 1000 milliseconds on ticket age.
4652
             */
4653
            if (diff < -1000 || diff - MAX_TICKET_AGE_DIFF * 1000 > 1000) {
4654
                current = current->next;
4655
                continue;
4656
            }
4657
4658
        #ifndef WOLFSSL_PSK_ONE_ID
4659
            /* Check whether resumption is possible based on suites in SSL and
4660
             * ciphersuite in ticket.
4661
             */
4662
            if ((suite[0] != ssl->session->cipherSuite0) ||
4663
                                       (suite[1] != ssl->session->cipherSuite)) {
4664
                current = current->next;
4665
                continue;
4666
            }
4667
        #else
4668
            suite[0] = ssl->session->cipherSuite0;
4669
            suite[1] = ssl->session->cipherSuite;
4670
            if (!FindSuiteSSL(ssl, suite)) {
4671
                current = current->next;
4672
                continue;
4673
            }
4674
        #endif
4675
4676
            /* SERVER: using secret in session ticket for peer auth. */
4677
            ssl->options.peerAuthGood = 1;
4678
4679
        #ifdef WOLFSSL_EARLY_DATA
4680
            ssl->options.maxEarlyDataSz = ssl->session->maxEarlyDataSz;
4681
        #endif
4682
            /* Use the same cipher suite as before and set up for use. */
4683
            ssl->options.cipherSuite0   = ssl->session->cipherSuite0;
4684
            ssl->options.cipherSuite    = ssl->session->cipherSuite;
4685
            ret = SetCipherSpecs(ssl);
4686
            if (ret != 0)
4687
                return ret;
4688
4689
            /* Resumption PSK is resumption master secret. */
4690
            ssl->arrays->psk_keySz = ssl->specs.hash_size;
4691
            if ((ret = DeriveResumptionPSK(ssl, ssl->session->ticketNonce.data,
4692
                ssl->session->ticketNonce.len, ssl->arrays->psk_key)) != 0) {
4693
                return ret;
4694
            }
4695
4696
            /* Derive the early secret using the PSK. */
4697
            ret = DeriveEarlySecret(ssl);
4698
            if (ret != 0)
4699
                return ret;
4700
4701
            /* Hash data up to binders for deriving binders in PSK extension. */
4702
            ret = HashInput(ssl, input, inputSz);
4703
            if (ret < 0)
4704
                return ret;
4705
4706
            /* Derive the binder key to use with HMAC. */
4707
            ret = DeriveBinderKeyResume(ssl, binderKey);
4708
            if (ret != 0)
4709
                return ret;
4710
        }
4711
        else
4712
    #endif
4713
    #ifndef NO_PSK
4714
        if (FindPsk(ssl, current, suite, &ret)) {
4715
            if (ret != 0)
4716
                return ret;
4717
4718
            ret = HashInput(ssl, input, inputSz);
4719
            if (ret < 0)
4720
                return ret;
4721
4722
            /* Derive the binder key to use with HMAC. */
4723
            ret = DeriveBinderKey(ssl, binderKey);
4724
            if (ret != 0)
4725
                return ret;
4726
        }
4727
        else
4728
    #endif
4729
        {
4730
            current = current->next;
4731
            continue;
4732
        }
4733
4734
        ssl->options.sendVerify = 0;
4735
4736
        /* Derive the Finished message secret. */
4737
        ret = DeriveFinishedSecret(ssl, binderKey,
4738
                                             ssl->keys.client_write_MAC_secret);
4739
        if (ret != 0)
4740
            return ret;
4741
4742
        /* Derive the binder and compare with the one in the extension. */
4743
        ret = BuildTls13HandshakeHmac(ssl,
4744
                         ssl->keys.client_write_MAC_secret, binder, &binderLen);
4745
        if (ret != 0)
4746
            return ret;
4747
        if (binderLen != current->binderLen ||
4748
                             XMEMCMP(binder, current->binder, binderLen) != 0) {
4749
            WOLFSSL_ERROR_VERBOSE(BAD_BINDER);
4750
            return BAD_BINDER;
4751
        }
4752
4753
        /* This PSK works, no need to try any more. */
4754
        current->chosen = 1;
4755
        ext->resp = 1;
4756
        break;
4757
    }
4758
4759
    if (current == NULL) {
4760
#ifdef WOLFSSL_PSK_ID_PROTECTION
4761
    #ifndef NO_CERTS
4762
        if (ssl->buffers.certChainCnt != 0)
4763
            return 0;
4764
    #endif
4765
        WOLFSSL_ERROR_VERBOSE(BAD_BINDER);
4766
        return BAD_BINDER;
4767
#else
4768
        return 0;
4769
#endif
4770
    }
4771
4772
    *first = (current == ext->data);
4773
    *usingPSK = 1;
4774
4775
    WOLFSSL_LEAVE("DoPreSharedKeys", ret);
4776
4777
    return ret;
4778
}
4779
4780
/* Handle any Pre-Shared Key (PSK) extension.
4781
 * Must do this in ClientHello as it requires a hash of the truncated message.
4782
 * Don't know size of binders until Pre-Shared Key extension has been parsed.
4783
 *
4784
 * ssl         SSL/TLS object.
4785
 * input       ClientHello message.
4786
 * helloSz     Size of the ClientHello message (including binders if present).
4787
 * clSuites    Client's cipher suite list.
4788
 * usingPSK    Indicates handshake is using Pre-Shared Keys.
4789
 */
4790
static int CheckPreSharedKeys(WOLFSSL* ssl, const byte* input, word32 helloSz,
4791
                              Suites* clSuites, int* usingPSK)
4792
{
4793
    int    ret;
4794
    TLSX*  ext;
4795
    word16 bindersLen;
4796
    int    first = 0;
4797
#ifndef WOLFSSL_PSK_ONE_ID
4798
    int    i;
4799
    int    j;
4800
#else
4801
    byte   suite[2];
4802
#endif
4803
4804
    WOLFSSL_ENTER("CheckPreSharedKeys");
4805
4806
    ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
4807
    if (ext == NULL) {
4808
#ifdef WOLFSSL_EARLY_DATA
4809
        ssl->earlyData = no_early_data;
4810
#endif
4811
        if (usingPSK)
4812
            *usingPSK = 0;
4813
        /* Hash data up to binders for deriving binders in PSK extension. */
4814
        ret = HashInput(ssl, input,  helloSz);
4815
        return ret;
4816
    }
4817
4818
    /* Extensions pushed on stack/list and PSK must be last. */
4819
    if (ssl->extensions != ext) {
4820
        WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
4821
        return PSK_KEY_ERROR;
4822
    }
4823
4824
    /* Assume we are going to resume with a pre-shared key. */
4825
    ssl->options.resuming = 1;
4826
4827
    /* Find the pre-shared key extension and calculate hash of truncated
4828
     * ClientHello for binders.
4829
     */
4830
    ret = TLSX_PreSharedKey_GetSizeBinders((PreSharedKey*)ext->data,
4831
                                                     client_hello, &bindersLen);
4832
    if (ret < 0)
4833
        return ret;
4834
4835
    /* Refine list for PSK processing. */
4836
    RefineSuites(ssl, clSuites);
4837
4838
#ifndef WOLFSSL_PSK_ONE_ID
4839
    if (usingPSK == NULL)
4840
        return BAD_FUNC_ARG;
4841
4842
    if (!ssl->options.useClientOrder) {
4843
        /* Server order - server list has only common suites from refining. */
4844
        for (i = 0; !(*usingPSK) && i < ssl->suites->suiteSz; i += 2) {
4845
            ret = DoPreSharedKeys(ssl, input, helloSz - bindersLen,
4846
                ssl->suites->suites + i, usingPSK, &first);
4847
            if (ret != 0) {
4848
                return ret;
4849
            }
4850
        }
4851
    }
4852
    else {
4853
        /* Client order */
4854
        for (j = 0; !(*usingPSK) && j < clSuites->suiteSz; j += 2) {
4855
            for (i = 0; !(*usingPSK) && i < ssl->suites->suiteSz; i += 2) {
4856
            ret = DoPreSharedKeys(ssl, input, helloSz - bindersLen,
4857
                ssl->suites->suites + i, usingPSK, &first);
4858
                if (ret != 0)
4859
                    return ret;
4860
            }
4861
        }
4862
    }
4863
#else
4864
    ret = DoPreSharedKeys(ssl, input, helloSz - bindersLen, suite, usingPSK,
4865
        &first);
4866
    if (ret != 0)
4867
        return ret;
4868
#endif
4869
4870
    if (*usingPSK) {
4871
        /* While verifying the selected PSK, we updated the
4872
         * handshake hash up to the binder bytes in the PSK extensions.
4873
         * Continuing, we need the rest of the ClientHello hashed as well.
4874
         */
4875
        ret = HashRaw(ssl, input + helloSz - bindersLen, bindersLen);
4876
    }
4877
    else {
4878
        /* No suitable PSK found, Hash the complete ClientHello,
4879
         * as caller expect it after we return */
4880
        ret = HashInput(ssl, input,  helloSz);
4881
    }
4882
    if (ret != 0)
4883
        return ret;
4884
4885
    if (*usingPSK != 0) {
4886
        word16 modes;
4887
    #ifdef WOLFSSL_EARLY_DATA
4888
        TLSX*  extEarlyData;
4889
4890
        extEarlyData = TLSX_Find(ssl->extensions, TLSX_EARLY_DATA);
4891
        if (extEarlyData != NULL) {
4892
            /* Check if accepting early data and first PSK. */
4893
            if (ssl->earlyData != no_early_data && first) {
4894
                extEarlyData->resp = 1;
4895
4896
                /* Derive early data decryption key. */
4897
                ret = DeriveTls13Keys(ssl, early_data_key, DECRYPT_SIDE_ONLY,
4898
                                                                             1);
4899
                if (ret != 0)
4900
                    return ret;
4901
                if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0)
4902
                    return ret;
4903
4904
#ifdef WOLFSSL_DTLS13
4905
                if (ssl->options.dtls) {
4906
                    ret = Dtls13NewEpoch(ssl,
4907
                        w64From32(0x0, DTLS13_EPOCH_EARLYDATA),
4908
                        DECRYPT_SIDE_ONLY);
4909
                    if (ret != 0)
4910
                        return ret;
4911
                }
4912
#endif /* WOLFSSL_DTLS13 */
4913
4914
                ssl->earlyData = process_early_data;
4915
            }
4916
            else
4917
                extEarlyData->resp = 0;
4918
        }
4919
    #endif
4920
4921
        /* Get the PSK key exchange modes the client wants to negotiate. */
4922
        ext = TLSX_Find(ssl->extensions, TLSX_PSK_KEY_EXCHANGE_MODES);
4923
        if (ext == NULL) {
4924
            WOLFSSL_ERROR_VERBOSE(MISSING_HANDSHAKE_DATA);
4925
            return MISSING_HANDSHAKE_DATA;
4926
        }
4927
        modes = ext->val;
4928
4929
    #ifdef HAVE_SUPPORTED_CURVES
4930
        ext = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
4931
        /* Use (EC)DHE for forward-security if possible. */
4932
        if ((modes & (1 << PSK_DHE_KE)) != 0 && !ssl->options.noPskDheKe &&
4933
                                                                  ext != NULL) {
4934
            /* Only use named group used in last session. */
4935
            ssl->namedGroup = ssl->session->namedGroup;
4936
4937
            *usingPSK = 2; /* generate new ephemeral key */
4938
        }
4939
        else
4940
    #endif
4941
        {
4942
            if ((modes & (1 << PSK_KE)) == 0) {
4943
                WOLFSSL_MSG("psk_ke mode does not allow key share");
4944
                WOLFSSL_ERROR_VERBOSE(PSK_KEY_ERROR);
4945
                return PSK_KEY_ERROR;
4946
            }
4947
            ssl->options.noPskDheKe = 1;
4948
            ssl->arrays->preMasterSz = 0;
4949
4950
            *usingPSK = 1;
4951
        }
4952
    }
4953
#ifdef WOLFSSL_PSK_ID_PROTECTION
4954
    else {
4955
    #ifndef NO_CERTS
4956
        if (ssl->buffers.certChainCnt != 0)
4957
            return 0;
4958
    #endif
4959
        WOLFSSL_ERROR_VERBOSE(BAD_BINDER);
4960
        return BAD_BINDER;
4961
    }
4962
#endif
4963
4964
    WOLFSSL_LEAVE("CheckPreSharedKeys", ret);
4965
4966
    return 0;
4967
}
4968
#endif /* HAVE_SESSION_TICKET || !NO_PSK */
4969
4970
#if defined(WOLFSSL_SEND_HRR_COOKIE)
4971
/* Check that the Cookie data's integrity.
4972
 *
4973
 * ssl       SSL/TLS object.
4974
 * cookie    The cookie data - hash and MAC.
4975
 * cookieSz  The length of the cookie data in bytes.
4976
 * returns Length of the hash on success, otherwise failure.
4977
 */
4978
static int CheckCookie(WOLFSSL* ssl, byte* cookie, byte cookieSz)
4979
{
4980
    int  ret;
4981
    byte mac[WC_MAX_DIGEST_SIZE] = {0};
4982
    Hmac cookieHmac;
4983
    byte cookieType = 0;
4984
    byte macSz = 0;
4985
4986
#if !defined(NO_SHA) && defined(NO_SHA256)
4987
    cookieType = SHA;
4988
    macSz = WC_SHA_DIGEST_SIZE;
4989
#endif /* NO_SHA */
4990
#ifndef NO_SHA256
4991
    cookieType = WC_SHA256;
4992
    macSz = WC_SHA256_DIGEST_SIZE;
4993
#endif /* NO_SHA256 */
4994
4995
    if (cookieSz < ssl->specs.hash_size + macSz)
4996
        return HRR_COOKIE_ERROR;
4997
    cookieSz -= macSz;
4998
4999
    ret = wc_HmacInit(&cookieHmac, ssl->heap, INVALID_DEVID);
5000
    if (ret == 0) {
5001
        ret = wc_HmacSetKey(&cookieHmac, cookieType,
5002
                            ssl->buffers.tls13CookieSecret.buffer,
5003
                            ssl->buffers.tls13CookieSecret.length);
5004
    }
5005
    if (ret == 0)
5006
        ret = wc_HmacUpdate(&cookieHmac, cookie, cookieSz);
5007
#ifdef WOLFSSL_DTLS13
5008
    /* Tie cookie to peer address */
5009
    if (ret == 0) {
5010
        if (ssl->options.dtls && ssl->buffers.dtlsCtx.peer.sz > 0) {
5011
            ret = wc_HmacUpdate(&cookieHmac, ssl->buffers.dtlsCtx.peer.sa,
5012
                                ssl->buffers.dtlsCtx.peer.sz);
5013
        }
5014
    }
5015
#endif
5016
    if (ret == 0)
5017
        ret = wc_HmacFinal(&cookieHmac, mac);
5018
5019
    wc_HmacFree(&cookieHmac);
5020
    if (ret != 0)
5021
        return ret;
5022
5023
    if (ConstantCompare(cookie + cookieSz, mac, macSz) != 0) {
5024
        WOLFSSL_ERROR_VERBOSE(HRR_COOKIE_ERROR);
5025
        return HRR_COOKIE_ERROR;
5026
    }
5027
    return cookieSz;
5028
}
5029
5030
/* Length of the KeyShare Extension */
5031
#define HRR_KEY_SHARE_SZ   (OPAQUE16_LEN + OPAQUE16_LEN + OPAQUE16_LEN)
5032
/* Length of the Supported Versions Extension */
5033
#define HRR_VERSIONS_SZ    (OPAQUE16_LEN + OPAQUE16_LEN + OPAQUE16_LEN)
5034
/* Length of the Cookie Extension excluding cookie data */
5035
#define HRR_COOKIE_HDR_SZ  (OPAQUE16_LEN + OPAQUE16_LEN + OPAQUE16_LEN)
5036
/* PV | Random | Session Id | CipherSuite | Compression | Ext Len */
5037
#define HRR_BODY_SZ        (VERSION_SZ + RAN_LEN + ENUM_LEN + ID_LEN + \
5038
                            SUITE_LEN + COMP_LEN + OPAQUE16_LEN)
5039
/* HH | PV | CipherSuite | Ext Len | Key Share | Supported Version | Cookie */
5040
#define MAX_HRR_SZ   (HRR_MAX_HS_HEADER_SZ   + \
5041
                        HRR_BODY_SZ         + \
5042
                          HRR_KEY_SHARE_SZ  + \
5043
                          HRR_VERSIONS_SZ   + \
5044
                          HRR_COOKIE_HDR_SZ)
5045
5046
5047
/* Restart the handshake hash from the cookie value.
5048
 *
5049
 * ssl     SSL/TLS object.
5050
 * cookie  Cookie data from client.
5051
 * returns 0 on success, otherwise failure.
5052
 */
5053
static int RestartHandshakeHashWithCookie(WOLFSSL* ssl, Cookie* cookie)
5054
{
5055
    byte   header[HRR_MAX_HS_HEADER_SZ] = {0};
5056
    byte   hrr[MAX_HRR_SZ] = {0};
5057
    int    hrrIdx;
5058
    word32 idx;
5059
    byte   hashSz;
5060
    byte*  cookieData;
5061
    byte   cookieDataSz;
5062
    word16 length;
5063
    int    keyShareExt = 0;
5064
    int    ret;
5065
5066
    cookieDataSz = ret = CheckCookie(ssl, &cookie->data, cookie->len);
5067
    if (ret < 0)
5068
        return ret;
5069
    hashSz = cookie->data;
5070
    cookieData = &cookie->data;
5071
    idx = OPAQUE8_LEN;
5072
5073
    /* Restart handshake hash with synthetic message hash. */
5074
    AddTls13HandShakeHeader(header, hashSz, 0, 0, message_hash, ssl);
5075
5076
    if ((ret = InitHandshakeHashes(ssl)) != 0)
5077
        return ret;
5078
    if ((ret = HashRaw(ssl, header, sizeof(header))) != 0)
5079
        return ret;
5080
#ifdef WOLFSSL_DEBUG_TLS
5081
    WOLFSSL_MSG("Restart Hash from Cookie");
5082
    WOLFSSL_BUFFER(cookieData + idx, hashSz);
5083
#endif
5084
    if ((ret = HashRaw(ssl, cookieData + idx, hashSz)) != 0)
5085
        return ret;
5086
5087
    /* Reconstruct the HelloRetryMessage for handshake hash. */
5088
    length = HRR_BODY_SZ - ID_LEN + ssl->session->sessionIDSz +
5089
             HRR_COOKIE_HDR_SZ + cookie->len;
5090
    length += HRR_VERSIONS_SZ;
5091
    /* HashSz (1 byte) + Hash (HashSz bytes) + CipherSuite (2 bytes) */
5092
    if (cookieDataSz > OPAQUE8_LEN + hashSz + OPAQUE16_LEN) {
5093
        keyShareExt = 1;
5094
        length += HRR_KEY_SHARE_SZ;
5095
    }
5096
5097
    AddTls13HandShakeHeader(hrr, length, 0, 0, server_hello, ssl);
5098
5099
    idx += hashSz;
5100
    hrrIdx = HANDSHAKE_HEADER_SZ;
5101
5102
#ifdef WOLFSSL_DTLS13
5103
    if (ssl->options.dtls)
5104
        hrrIdx += DTLS_HANDSHAKE_EXTRA;
5105
#endif /* WOLFSSL_DTLS13 */
5106
5107
    /* The negotiated protocol version. */
5108
    hrr[hrrIdx++] = ssl->version.major;
5109
    hrr[hrrIdx++] = ssl->options.dtls ? DTLSv1_2_MINOR : TLSv1_2_MINOR;
5110
5111
    /* HelloRetryRequest message has fixed value for random. */
5112
    XMEMCPY(hrr + hrrIdx, helloRetryRequestRandom, RAN_LEN);
5113
    hrrIdx += RAN_LEN;
5114
5115
    hrr[hrrIdx++] = ssl->session->sessionIDSz;
5116
    if (ssl->session->sessionIDSz > 0) {
5117
        XMEMCPY(hrr + hrrIdx, ssl->session->sessionID, ssl->session->sessionIDSz);
5118
        hrrIdx += ssl->session->sessionIDSz;
5119
    }
5120
5121
    /* Cipher Suite */
5122
    hrr[hrrIdx++] = cookieData[idx++];
5123
    hrr[hrrIdx++] = cookieData[idx++];
5124
5125
    /* Compression not supported in TLS v1.3. */
5126
    hrr[hrrIdx++] = 0;
5127
5128
    /* Extensions' length */
5129
    length -= HRR_BODY_SZ - ID_LEN + ssl->session->sessionIDSz;
5130
    c16toa(length, hrr + hrrIdx);
5131
    hrrIdx += 2;
5132
5133
    /* Optional KeyShare Extension */
5134
    if (keyShareExt) {
5135
        c16toa(TLSX_KEY_SHARE, hrr + hrrIdx);
5136
        hrrIdx += 2;
5137
        c16toa(OPAQUE16_LEN, hrr + hrrIdx);
5138
        hrrIdx += 2;
5139
        hrr[hrrIdx++] = cookieData[idx++];
5140
        hrr[hrrIdx++] = cookieData[idx++];
5141
    }
5142
    c16toa(TLSX_SUPPORTED_VERSIONS, hrr + hrrIdx);
5143
    hrrIdx += 2;
5144
    c16toa(OPAQUE16_LEN, hrr + hrrIdx);
5145
    hrrIdx += 2;
5146
    #ifdef WOLFSSL_TLS13_DRAFT
5147
        hrr[hrrIdx++] = TLS_DRAFT_MAJOR;
5148
        hrr[hrrIdx++] = TLS_DRAFT_MINOR;
5149
    #else
5150
        hrr[hrrIdx++] = ssl->version.major;
5151
        hrr[hrrIdx++] = ssl->version.minor;
5152
    #endif
5153
5154
    /* Mandatory Cookie Extension */
5155
    c16toa(TLSX_COOKIE, hrr + hrrIdx);
5156
    hrrIdx += 2;
5157
    c16toa(cookie->len + OPAQUE16_LEN, hrr + hrrIdx);
5158
    hrrIdx += 2;
5159
    c16toa(cookie->len, hrr + hrrIdx);
5160
    hrrIdx += 2;
5161
5162
#ifdef WOLFSSL_DEBUG_TLS
5163
    WOLFSSL_MSG("Reconstructed HelloRetryRequest");
5164
    WOLFSSL_BUFFER(hrr, hrrIdx);
5165
    WOLFSSL_MSG("Cookie");
5166
    WOLFSSL_BUFFER(cookieData, cookie->len);
5167
#endif
5168
5169
#ifdef WOLFSSL_DTLS13
5170
    if (ssl->options.dtls) {
5171
        ret = Dtls13HashHandshake(ssl, hrr, hrrIdx);
5172
    }
5173
    else
5174
#endif /* WOLFSSL_DTLS13 */
5175
        {
5176
            ret = HashRaw(ssl, hrr, hrrIdx);
5177
        }
5178
5179
    if (ret != 0)
5180
        return ret;
5181
5182
    return HashRaw(ssl, cookieData, cookie->len);
5183
}
5184
#endif
5185
5186
/* Do SupportedVersion extension for TLS v1.3+ otherwise it is not.
5187
 *
5188
 * ssl       The SSL/TLS object.
5189
 * input     The message buffer.
5190
 * i         The index into the message buffer of ClientHello.
5191
 * helloSz   The length of the current handshake message.
5192
 * returns 0 on success and otherwise failure.
5193
 */
5194
static int DoTls13SupportedVersions(WOLFSSL* ssl, const byte* input, word32 i,
5195
                                    word32 helloSz, int* wantDowngrade)
5196
0
{
5197
0
    int    ret;
5198
0
    byte   b;
5199
0
    word16 suiteSz;
5200
0
    word16 totalExtSz;
5201
0
    int    foundVersion = 0;
5202
5203
    /* Client random */
5204
0
    i += RAN_LEN;
5205
    /* Session id - not used in TLS v1.3 */
5206
0
    b = input[i++];
5207
0
    if (i + b > helloSz) {
5208
0
        return BUFFER_ERROR;
5209
0
    }
5210
0
    i += b;
5211
#ifdef WOLFSSL_DTLS13
5212
    if (ssl->options.dtls) {
5213
        /* legacy_cookie - not used in DTLS v1.3 */
5214
        b = input[i++];
5215
        if (i + b > helloSz) {
5216
            return BUFFER_ERROR;
5217
        }
5218
        i += b;
5219
    }
5220
#endif /* WOLFSSL_DTLS13 */
5221
    /* Cipher suites */
5222
0
    if (i + OPAQUE16_LEN > helloSz)
5223
0
        return BUFFER_ERROR;
5224
0
    ato16(input + i, &suiteSz);
5225
0
    i += OPAQUE16_LEN;
5226
0
    if (i + suiteSz + 1 > helloSz)
5227
0
        return BUFFER_ERROR;
5228
0
    i += suiteSz;
5229
    /* Compression */
5230
0
    b = input[i++];
5231
0
    if (i + b > helloSz)
5232
0
        return BUFFER_ERROR;
5233
0
    i += b;
5234
5235
    /* TLS 1.3 must have extensions */
5236
0
    if (i < helloSz) {
5237
0
        if (i + OPAQUE16_LEN > helloSz)
5238
0
            return BUFFER_ERROR;
5239
0
        ato16(&input[i], &totalExtSz);
5240
0
        i += OPAQUE16_LEN;
5241
0
        if (totalExtSz != helloSz - i)
5242
0
            return BUFFER_ERROR;
5243
5244
        /* Need to negotiate version first. */
5245
0
        if ((ret = TLSX_ParseVersion(ssl, input + i, totalExtSz, client_hello,
5246
0
                                                              &foundVersion))) {
5247
0
            return ret;
5248
0
        }
5249
0
    }
5250
0
    *wantDowngrade = !foundVersion || !IsAtLeastTLSv1_3(ssl->version);
5251
5252
0
    return 0;
5253
0
}
5254
5255
/* Handle a ClientHello handshake message.
5256
 * If the protocol version in the message is not TLS v1.3 or higher, use
5257
 * DoClientHello()
5258
 * Only a server will receive this message.
5259
 *
5260
 * ssl       The SSL/TLS object.
5261
 * input     The message buffer.
5262
 * inOutIdx  On entry, the index into the message buffer of ClientHello.
5263
 *           On exit, the index of byte after the ClientHello message and
5264
 *           padding.
5265
 * helloSz   The length of the current handshake message.
5266
 * returns 0 on success and otherwise failure.
5267
 */
5268
5269
typedef struct Dch13Args {
5270
    ProtocolVersion pv;
5271
    Suites*         clSuites;
5272
    word32          idx;
5273
    word32          begin;
5274
    int             usingPSK;
5275
} Dch13Args;
5276
5277
static void FreeDch13Args(WOLFSSL* ssl, void* pArgs)
5278
0
{
5279
0
    Dch13Args* args = (Dch13Args*)pArgs;
5280
5281
0
    (void)ssl;
5282
5283
0
    if (args && args->clSuites) {
5284
0
        XFREE(args->clSuites, ssl->heap, DYNAMIC_TYPE_SUITES);
5285
0
        args->clSuites = NULL;
5286
0
    }
5287
0
}
5288
5289
int DoTls13ClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
5290
                       word32 helloSz)
5291
0
{
5292
0
    int ret;
5293
#ifdef WOLFSSL_ASYNC_CRYPT
5294
    Dch13Args* args = NULL;
5295
    WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
5296
#else
5297
0
    Dch13Args  args[1];
5298
0
#endif
5299
5300
0
    WOLFSSL_START(WC_FUNC_CLIENT_HELLO_DO);
5301
0
    WOLFSSL_ENTER("DoTls13ClientHello");
5302
5303
#ifdef WOLFSSL_ASYNC_CRYPT
5304
    if (ssl->async == NULL) {
5305
        ssl->async = (struct WOLFSSL_ASYNC*)
5306
                XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
5307
                        DYNAMIC_TYPE_ASYNC);
5308
        if (ssl->async == NULL)
5309
            ERROR_OUT(MEMORY_E, exit_dch);
5310
    }
5311
    args = (Dch13Args*)ssl->async->args;
5312
5313
    ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
5314
    if (ret != WC_NOT_PENDING_E) {
5315
        /* Check for error */
5316
        if (ret < 0) {
5317
            goto exit_dch;
5318
        }
5319
    }
5320
    else
5321
#endif
5322
0
    {
5323
        /* Reset state */
5324
0
        ret = VERSION_ERROR;
5325
0
        ssl->options.asyncState = TLS_ASYNC_BEGIN;
5326
0
        XMEMSET(args, 0, sizeof(Dch13Args));
5327
    #ifdef WOLFSSL_ASYNC_CRYPT
5328
        ssl->async->freeArgs = FreeDch13Args;
5329
    #endif
5330
0
    }
5331
5332
0
    switch (ssl->options.asyncState) {
5333
0
    case TLS_ASYNC_BEGIN:
5334
0
    {
5335
0
    byte b;
5336
0
    byte sessIdSz;
5337
0
    int wantDowngrade = 0;
5338
0
    word16 totalExtSz = 0;
5339
5340
#ifdef WOLFSSL_CALLBACKS
5341
    if (ssl->hsInfoOn) AddPacketName(ssl, "ClientHello");
5342
    if (ssl->toInfoOn) AddLateName("ClientHello", &ssl->timeoutInfo);
5343
#endif
5344
5345
0
    args->idx = *inOutIdx;
5346
0
    args->begin = args->idx;
5347
5348
    /* protocol version, random and session id length check */
5349
0
    if (OPAQUE16_LEN + RAN_LEN + OPAQUE8_LEN > helloSz) {
5350
0
        ERROR_OUT(BUFFER_ERROR, exit_dch);
5351
0
    }
5352
5353
    /* Protocol version */
5354
0
    XMEMCPY(&args->pv, input + args->idx, OPAQUE16_LEN);
5355
0
    ssl->chVersion = args->pv;   /* store */
5356
0
    args->idx += OPAQUE16_LEN;
5357
5358
5359
    /* this check pass for DTLS Major (0xff) */
5360
0
    if (args->pv.major < SSLv3_MAJOR) {
5361
0
        WOLFSSL_MSG("Legacy version field contains unsupported value");
5362
 #ifdef WOLFSSL_MYSQL_COMPATIBLE
5363
        SendAlert(ssl, alert_fatal, wc_protocol_version);
5364
 #else
5365
0
        SendAlert(ssl, alert_fatal, protocol_version);
5366
0
 #endif
5367
0
        ERROR_OUT(INVALID_PARAMETER, exit_dch);
5368
0
    }
5369
5370
#ifdef WOLFSSL_DTLS13
5371
    if (ssl->options.dtls &&
5372
        args->pv.major == DTLS_MAJOR && args->pv.minor > DTLSv1_2_MINOR) {
5373
        wantDowngrade = 1;
5374
        ssl->version.minor = args->pv.minor;
5375
    }
5376
#endif /* WOLFSSL_DTLS13 */
5377
5378
0
    if (!ssl->options.dtls) {
5379
        /* Legacy protocol version cannot negotiate TLS 1.3 or higher. */
5380
0
        if (args->pv.major > SSLv3_MAJOR || (args->pv.major == SSLv3_MAJOR &&
5381
0
                                             args->pv.minor >= TLSv1_3_MINOR)) {
5382
0
            args->pv.major = SSLv3_MAJOR;
5383
0
            args->pv.minor = TLSv1_2_MINOR;
5384
0
            wantDowngrade = 1;
5385
0
            ssl->version.minor = args->pv.minor;
5386
0
        }
5387
        /* Legacy version must be [ SSLv3_MAJOR, TLSv1_2_MINOR ] for TLS v1.3 */
5388
0
        else if (args->pv.major == SSLv3_MAJOR &&
5389
0
                 args->pv.minor < TLSv1_2_MINOR) {
5390
0
            wantDowngrade = 1;
5391
0
            ssl->version.minor = args->pv.minor;
5392
0
        }
5393
0
    }
5394
5395
0
    if (!wantDowngrade) {
5396
0
        ret = DoTls13SupportedVersions(ssl, input + args->begin,
5397
0
            args->idx - args->begin, helloSz, &wantDowngrade);
5398
0
        if (ret < 0)
5399
0
            goto exit_dch;
5400
0
    }
5401
5402
0
    if (wantDowngrade) {
5403
0
#ifndef WOLFSSL_NO_TLS12
5404
0
        if (!ssl->options.downgrade) {
5405
0
            WOLFSSL_MSG("Client trying to connect with lesser version than "
5406
0
                        "TLS v1.3");
5407
#if defined(WOLFSSL_EXTRA_ALERTS) ||  defined(OPENSSL_EXTRA)
5408
            SendAlert(ssl, alert_fatal, handshake_failure);
5409
#endif
5410
0
            ERROR_OUT(VERSION_ERROR, exit_dch);
5411
0
        }
5412
5413
0
        if ((!ssl->options.dtls
5414
0
                 && args->pv.minor < ssl->options.minDowngrade) ||
5415
0
            (ssl->options.dtls && args->pv.minor > ssl->options.minDowngrade)) {
5416
0
            WOLFSSL_MSG("\tversion below minimum allowed, fatal error");
5417
#if defined(WOLFSSL_EXTRA_ALERTS) ||  defined(OPENSSL_EXTRA)
5418
            SendAlert(ssl, alert_fatal, handshake_failure);
5419
#endif
5420
0
            ERROR_OUT(VERSION_ERROR, exit_dch);
5421
0
        }
5422
5423
0
        ret = HashInput(ssl, input + args->begin, helloSz);
5424
0
        if (ret == 0) {
5425
0
            ret = DoClientHello(ssl, input, inOutIdx, helloSz);
5426
0
        }
5427
0
        goto exit_dch;
5428
#else
5429
        WOLFSSL_MSG("Client trying to connect with lesser version than "
5430
                    "TLS v1.3");
5431
        ERROR_OUT(VERSION_ERROR, exit_dch);
5432
#endif
5433
0
    }
5434
5435
    /* From here on we are a TLS 1.3 ClientHello. */
5436
5437
    /* Client random */
5438
0
    XMEMCPY(ssl->arrays->clientRandom, input + args->idx, RAN_LEN);
5439
0
    args->idx += RAN_LEN;
5440
5441
#ifdef WOLFSSL_DEBUG_TLS
5442
    WOLFSSL_MSG("client random");
5443
    WOLFSSL_BUFFER(ssl->arrays->clientRandom, RAN_LEN);
5444
#endif
5445
5446
0
    sessIdSz = input[args->idx++];
5447
0
    if (sessIdSz != ID_LEN && sessIdSz != 0)
5448
0
        ERROR_OUT(INVALID_PARAMETER, exit_dch);
5449
5450
0
    if (sessIdSz + args->idx > helloSz) {
5451
0
        ERROR_OUT(BUFFER_ERROR, exit_dch);
5452
0
    }
5453
5454
0
    ssl->session->sessionIDSz = sessIdSz;
5455
0
    if (sessIdSz == ID_LEN) {
5456
0
        XMEMCPY(ssl->session->sessionID, input + args->idx, sessIdSz);
5457
0
        args->idx += ID_LEN;
5458
0
    }
5459
5460
#ifdef WOLFSSL_DTLS13
5461
    /* legacy_cookie */
5462
    if (ssl->options.dtls)
5463
        args->idx += OPAQUE8_LEN;
5464
#endif /* WOLFSSL_DTLS13 */
5465
5466
0
    args->clSuites = (Suites*)XMALLOC(sizeof(Suites), ssl->heap,
5467
0
        DYNAMIC_TYPE_SUITES);
5468
0
    if (args->clSuites == NULL) {
5469
0
        ERROR_OUT(MEMORY_E, exit_dch);
5470
0
    }
5471
5472
    /* Cipher suites */
5473
0
    if ((args->idx - args->begin) + OPAQUE16_LEN > helloSz)
5474
0
        ERROR_OUT(BUFFER_ERROR, exit_dch);
5475
0
    ato16(&input[args->idx], &args->clSuites->suiteSz);
5476
0
    args->idx += OPAQUE16_LEN;
5477
    /* suites and compression length check */
5478
0
    if ((args->idx - args->begin) + args->clSuites->suiteSz + OPAQUE8_LEN > helloSz)
5479
0
        ERROR_OUT(BUFFER_ERROR, exit_dch);
5480
0
    if (args->clSuites->suiteSz > WOLFSSL_MAX_SUITE_SZ)
5481
0
        ERROR_OUT(BUFFER_ERROR, exit_dch);
5482
0
    XMEMCPY(args->clSuites->suites, input + args->idx, args->clSuites->suiteSz);
5483
0
    args->idx += args->clSuites->suiteSz;
5484
0
    args->clSuites->hashSigAlgoSz = 0;
5485
5486
    /* Compression */
5487
0
    b = input[args->idx++];
5488
0
    if ((args->idx - args->begin) + b > helloSz)
5489
0
        ERROR_OUT(BUFFER_ERROR, exit_dch);
5490
0
    if (b != COMP_LEN) {
5491
0
        WOLFSSL_MSG("Must be one compression type in list");
5492
0
        ERROR_OUT(INVALID_PARAMETER, exit_dch);
5493
0
    }
5494
0
    b = input[args->idx++];
5495
0
    if (b != NO_COMPRESSION) {
5496
0
        WOLFSSL_MSG("Must be no compression type in list");
5497
0
        ERROR_OUT(INVALID_PARAMETER, exit_dch);
5498
0
    }
5499
5500
    /* Extensions */
5501
0
    if ((args->idx - args->begin) == helloSz)
5502
0
        ERROR_OUT(BUFFER_ERROR, exit_dch);
5503
0
    if ((args->idx - args->begin) + OPAQUE16_LEN > helloSz)
5504
0
        ERROR_OUT(BUFFER_ERROR, exit_dch);
5505
5506
0
    ato16(&input[args->idx], &totalExtSz);
5507
0
    args->idx += OPAQUE16_LEN;
5508
0
    if ((args->idx - args->begin) + totalExtSz > helloSz)
5509
0
        ERROR_OUT(BUFFER_ERROR, exit_dch);
5510
5511
    /* Auto populate extensions supported unless user defined. */
5512
0
    if ((ret = TLSX_PopulateExtensions(ssl, 1)) != 0)
5513
0
        goto exit_dch;
5514
5515
    /* Parse extensions */
5516
0
    if ((ret = TLSX_Parse(ssl, input + args->idx, totalExtSz, client_hello,
5517
0
                                                            args->clSuites))) {
5518
0
        goto exit_dch;
5519
0
    }
5520
5521
#ifdef WOLFSSL_DTLS_CID
5522
    if (ssl->options.useDtlsCID)
5523
        DtlsCIDOnExtensionsParsed(ssl);
5524
#endif /* WOLFSSL_DTLS_CID */
5525
5526
#ifdef HAVE_SNI
5527
        if ((ret = SNI_Callback(ssl)) != 0)
5528
            return ret;
5529
        ssl->options.side = WOLFSSL_SERVER_END;
5530
#endif
5531
5532
0
    args->idx += totalExtSz;
5533
0
    ssl->options.haveSessionId = 1;
5534
0
    ssl->options.sendVerify = SEND_CERT;
5535
5536
#if defined(WOLFSSL_SEND_HRR_COOKIE)
5537
    if (ssl->options.sendCookie &&
5538
            (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST_COMPLETE
5539
#ifdef WOLFSSL_DTLS13
5540
                    /* Always check for a valid cookie since we may have already
5541
                     * sent a HRR but we reset the state. */
5542
                    || ssl->options.dtls
5543
#endif
5544
                    )) {
5545
        TLSX* ext = TLSX_Find(ssl->extensions, TLSX_COOKIE);
5546
5547
        if (ext != NULL) {
5548
            /* Ensure the cookie came from client and isn't the one in the
5549
            * response - HelloRetryRequest.
5550
            */
5551
            if (ext->resp == 0) {
5552
                ret = RestartHandshakeHashWithCookie(ssl, (Cookie*)ext->data);
5553
#ifdef WOLFSSL_DTLS13
5554
                /* Send a new cookie request */
5555
                if (ret == HRR_COOKIE_ERROR && ssl->options.dtls)
5556
                    ssl->options.serverState = NULL_STATE;
5557
                else
5558
#endif
5559
                if (ret != 0)
5560
                    goto exit_dch;
5561
                ssl->options.serverState = SERVER_HELLO_COMPLETE;
5562
            }
5563
            else {
5564
#ifdef WOLFSSL_DTLS13
5565
                if (ssl->options.dtls)
5566
                    ssl->options.serverState = NULL_STATE;
5567
                else
5568
#endif
5569
                    ERROR_OUT(HRR_COOKIE_ERROR, exit_dch);
5570
            }
5571
        }
5572
        else
5573
#ifdef WOLFSSL_DTLS13
5574
            if (!ssl->options.dtls)
5575
#endif
5576
                ERROR_OUT(HRR_COOKIE_ERROR, exit_dch);
5577
    }
5578
#endif
5579
5580
#if (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)) && \
5581
                                                    defined(HAVE_TLS_EXTENSIONS)
5582
    ret = CheckPreSharedKeys(ssl, input + args->begin, helloSz, args->clSuites,
5583
        &args->usingPSK);
5584
    if (ret != 0)
5585
        goto exit_dch;
5586
#else
5587
0
    if ((ret = HashInput(ssl, input + args->begin, helloSz)) != 0)
5588
0
        goto exit_dch;
5589
0
#endif
5590
5591
#if (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)) && \
5592
                                                    defined(HAVE_TLS_EXTENSIONS)
5593
    if (!args->usingPSK)
5594
#endif
5595
0
    {
5596
        /* Not using PSK so don't require no KE. */
5597
0
        ssl->options.noPskDheKe = 0;
5598
5599
0
#ifndef NO_CERTS
5600
0
        if (TLSX_Find(ssl->extensions, TLSX_KEY_SHARE) == NULL) {
5601
0
            WOLFSSL_MSG("Client did not send a KeyShare extension");
5602
0
            SendAlert(ssl, alert_fatal, missing_extension);
5603
0
            ERROR_OUT(INCOMPLETE_DATA, exit_dch);
5604
0
        }
5605
0
        if (TLSX_Find(ssl->extensions, TLSX_SIGNATURE_ALGORITHMS) == NULL) {
5606
0
            WOLFSSL_MSG("Client did not send a SignatureAlgorithms extension");
5607
0
            SendAlert(ssl, alert_fatal, missing_extension);
5608
0
            ERROR_OUT(INCOMPLETE_DATA, exit_dch);
5609
0
        }
5610
#else
5611
        ERROR_OUT(INVALID_PARAMETER, exit_dch);
5612
#endif
5613
0
    }
5614
5615
    /* Advance state and proceed */
5616
0
    ssl->options.asyncState = TLS_ASYNC_BUILD;
5617
0
    } /* case TLS_ASYNC_BEGIN */
5618
0
    FALL_THROUGH;
5619
5620
0
    case TLS_ASYNC_BUILD:
5621
0
    case TLS_ASYNC_DO:
5622
0
    {
5623
0
#ifndef NO_CERTS
5624
0
    if (!args->usingPSK) {
5625
0
        if ((ret = MatchSuite(ssl, args->clSuites)) < 0) {
5626
        #ifdef WOLFSSL_ASYNC_CRYPT
5627
            if (ret == WC_PENDING_E)
5628
                goto exit_dch;
5629
        #endif
5630
0
            WOLFSSL_MSG("Unsupported cipher suite, ClientHello");
5631
0
            SendAlert(ssl, alert_fatal, handshake_failure);
5632
0
            goto exit_dch;
5633
0
        }
5634
0
    }
5635
0
    else
5636
0
#endif
5637
0
#ifdef HAVE_SUPPORTED_CURVES
5638
0
    if (args->usingPSK == 2) {
5639
        /* Pick key share and Generate a new key if not present. */
5640
0
        int doHelloRetry = 0;
5641
0
        ret = TLSX_KeyShare_Establish(ssl, &doHelloRetry);
5642
0
        if (doHelloRetry) {
5643
0
            ssl->options.serverState = SERVER_HELLO_RETRY_REQUEST_COMPLETE;
5644
0
            if (ret != WC_PENDING_E)
5645
0
                ret = 0; /* for hello_retry return 0 */
5646
0
        }
5647
0
        if (ret != 0)
5648
0
            goto exit_dch;
5649
0
    }
5650
0
#endif
5651
5652
    /* Advance state and proceed */
5653
0
    ssl->options.asyncState = TLS_ASYNC_FINALIZE;
5654
0
    } /* case TLS_ASYNC_BUILD || TLS_ASYNC_DO */
5655
0
    FALL_THROUGH;
5656
5657
0
    case TLS_ASYNC_FINALIZE:
5658
0
    {
5659
0
    *inOutIdx = args->idx;
5660
0
    ssl->options.clientState = CLIENT_HELLO_COMPLETE;
5661
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
5662
    ssl->options.pskNegotiated = (args->usingPSK != 0);
5663
#endif
5664
5665
0
    if (!args->usingPSK) {
5666
0
#ifndef NO_CERTS
5667
    #ifdef HAVE_NULL_CIPHER
5668
        if (ssl->options.cipherSuite0 == ECC_BYTE &&
5669
                              (ssl->options.cipherSuite == TLS_SHA256_SHA256 ||
5670
                               ssl->options.cipherSuite == TLS_SHA384_SHA384)) {
5671
            ;
5672
        }
5673
        else
5674
    #endif
5675
        /* Check that the negotiated ciphersuite matches protocol version. */
5676
0
        if (ssl->options.cipherSuite0 != TLS13_BYTE) {
5677
0
            WOLFSSL_MSG("Negotiated ciphersuite from lesser version than "
5678
0
                        "TLS v1.3");
5679
0
            SendAlert(ssl, alert_fatal, handshake_failure);
5680
0
            ERROR_OUT(VERSION_ERROR, exit_dch);
5681
0
        }
5682
5683
    #ifdef HAVE_SESSION_TICKET
5684
        if (ssl->options.resuming) {
5685
            ssl->options.resuming = 0;
5686
            XMEMSET(ssl->arrays->psk_key, 0, ssl->specs.hash_size);
5687
        }
5688
    #endif
5689
5690
        /* Derive early secret for handshake secret. */
5691
0
        if ((ret = DeriveEarlySecret(ssl)) != 0)
5692
0
            goto exit_dch;
5693
0
#endif /* !NO_CERTS */
5694
0
    }
5695
0
    break;
5696
0
    } /* case TLS_ASYNC_FINALIZE */
5697
0
    default:
5698
0
        ret = INPUT_CASE_ERROR;
5699
0
    } /* switch (ssl->options.asyncState) */
5700
5701
#if defined(WOLFSSL_DTLS13) && defined(WOLFSSL_SEND_HRR_COOKIE)
5702
    /* We are using DTLSv13 and set the HRR cookie secret, use the cookie to
5703
       perform a return-routability check. */
5704
    if (ret == 0 && ssl->options.dtls && ssl->options.sendCookie &&
5705
        ssl->options.serverState < SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
5706
5707
        /* ssl->options.serverState < SERVER_HELLO_RETRY_REQUEST_COMPLETE
5708
           so the client already provided a good KeyShareEntry. In this case
5709
           we don't add the KEY_SHARE extension to the HelloRetryRequest or
5710
           in the Cookie. The RFC8446 forbids to select a supported group
5711
           with KeyShare extension in HelloRetryRequest if the client
5712
           already provided a KeyShareEntry for that group. See rfc8446
5713
           section 4.1.4 */
5714
        TLSX_Remove(&ssl->extensions, TLSX_KEY_SHARE, ssl->heap);
5715
5716
        /* send an HRR (see wolfSSL_Accept_TLSv13()) */
5717
        ssl->options.serverState = SERVER_HELLO_RETRY_REQUEST_COMPLETE;
5718
    }
5719
#endif /* WOLFSSL_DTLS13 */
5720
5721
0
exit_dch:
5722
5723
0
    WOLFSSL_LEAVE("DoTls13ClientHello", ret);
5724
5725
#ifdef WOLFSSL_ASYNC_CRYPT
5726
    if (ret == WC_PENDING_E) {
5727
        ssl->msgsReceived.got_client_hello = 0;
5728
        return ret;
5729
    }
5730
#endif
5731
5732
0
    FreeDch13Args(ssl, args);
5733
#ifdef WOLFSSL_ASYNC_CRYPT
5734
    FreeAsyncCtx(ssl, 0);
5735
#endif
5736
0
    WOLFSSL_END(WC_FUNC_CLIENT_HELLO_DO);
5737
5738
0
    if (ret != 0) {
5739
0
        WOLFSSL_ERROR_VERBOSE(ret);
5740
0
    }
5741
5742
0
    return ret;
5743
0
}
5744
5745
/* Send TLS v1.3 ServerHello message to client.
5746
 * Only a server will send this message.
5747
 *
5748
 * ssl  The SSL/TLS object.
5749
 * returns 0 on success, otherwise failure.
5750
 */
5751
/* handle generation of TLS 1.3 server_hello (2) */
5752
int SendTls13ServerHello(WOLFSSL* ssl, byte extMsgType)
5753
0
{
5754
0
    int    ret;
5755
0
    byte*  output;
5756
0
    word16 length;
5757
0
    word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
5758
0
    int    sendSz;
5759
5760
0
    WOLFSSL_START(WC_FUNC_SERVER_HELLO_SEND);
5761
0
    WOLFSSL_ENTER("SendTls13ServerHello");
5762
5763
0
    if (extMsgType == hello_retry_request) {
5764
0
        WOLFSSL_MSG("wolfSSL Doing HelloRetryRequest");
5765
0
        if ((ret = RestartHandshakeHash(ssl)) < 0)
5766
0
            return ret;
5767
0
    }
5768
5769
0
    ssl->options.buildingMsg = 1;
5770
#ifdef WOLFSSL_DTLS13
5771
    if (ssl->options.dtls)
5772
        idx = DTLS_RECORD_HEADER_SZ + DTLS_HANDSHAKE_HEADER_SZ;
5773
#endif /* WOLFSSL_DTLS13 */
5774
5775
    /* Protocol version, server random, session id, cipher suite, compression
5776
     * and extensions.
5777
     */
5778
0
    length = VERSION_SZ + RAN_LEN + ENUM_LEN + ssl->session->sessionIDSz +
5779
0
             SUITE_LEN + COMP_LEN;
5780
0
    ret = TLSX_GetResponseSize(ssl, extMsgType, &length);
5781
0
    if (ret != 0)
5782
0
        return ret;
5783
0
    sendSz = idx + length;
5784
5785
    /* Check buffers are big enough and grow if needed. */
5786
0
    if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
5787
0
        return ret;
5788
5789
    /* Get position in output buffer to write new message to. */
5790
0
    output = ssl->buffers.outputBuffer.buffer +
5791
0
             ssl->buffers.outputBuffer.length;
5792
5793
    /* Put the record and handshake headers on. */
5794
0
    AddTls13Headers(output, length, server_hello, ssl);
5795
5796
    /* The protocol version must be TLS v1.2 for middleboxes. */
5797
0
    output[idx++] = ssl->version.major;
5798
0
    output[idx++] = ssl->options.dtls ? DTLSv1_2_MINOR : TLSv1_2_MINOR;
5799
5800
0
    if (extMsgType == server_hello) {
5801
        /* Generate server random. */
5802
0
        if ((ret = wc_RNG_GenerateBlock(ssl->rng, output + idx, RAN_LEN)) != 0)
5803
0
            return ret;
5804
0
    }
5805
0
    else {
5806
        /* HelloRetryRequest message has fixed value for random. */
5807
0
        XMEMCPY(output + idx, helloRetryRequestRandom, RAN_LEN);
5808
0
    }
5809
5810
    /* Store in SSL for debugging. */
5811
0
    XMEMCPY(ssl->arrays->serverRandom, output + idx, RAN_LEN);
5812
0
    idx += RAN_LEN;
5813
5814
#ifdef WOLFSSL_DEBUG_TLS
5815
    WOLFSSL_MSG("Server random");
5816
    WOLFSSL_BUFFER(ssl->arrays->serverRandom, RAN_LEN);
5817
#endif
5818
5819
0
    output[idx++] = ssl->session->sessionIDSz;
5820
0
    if (ssl->session->sessionIDSz > 0) {
5821
0
        XMEMCPY(output + idx, ssl->session->sessionID, ssl->session->sessionIDSz);
5822
0
        idx += ssl->session->sessionIDSz;
5823
0
    }
5824
5825
    /* Chosen cipher suite */
5826
0
    output[idx++] = ssl->options.cipherSuite0;
5827
0
    output[idx++] = ssl->options.cipherSuite;
5828
#ifdef WOLFSSL_DEBUG_TLS
5829
    WOLFSSL_MSG("Chosen cipher suite:");
5830
    WOLFSSL_MSG(GetCipherNameInternal(ssl->options.cipherSuite0,
5831
                                      ssl->options.cipherSuite));
5832
#endif
5833
5834
    /* Compression not supported in TLS v1.3. */
5835
0
    output[idx++] = 0;
5836
5837
    /* Extensions */
5838
0
    ret = TLSX_WriteResponse(ssl, output + idx, extMsgType, NULL);
5839
0
    if (ret != 0)
5840
0
        return ret;
5841
5842
#ifdef WOLFSSL_SEND_HRR_COOKIE
5843
    if (ssl->options.sendCookie && extMsgType == hello_retry_request) {
5844
        /* Reset the hashes from here. We will be able to restart the hashes
5845
         * from the cookie in RestartHandshakeHashWithCookie */
5846
        ret = InitHandshakeHashes(ssl);
5847
    }
5848
    else
5849
#endif
5850
0
    {
5851
#ifdef WOLFSSL_DTLS13
5852
        if (ssl->options.dtls) {
5853
            ret = Dtls13HashHandshake(ssl,
5854
                                      output + Dtls13GetRlHeaderLength(ssl, 0) ,
5855
                                      sendSz - Dtls13GetRlHeaderLength(ssl, 0));
5856
        }
5857
        else
5858
#endif /* WOLFSSL_DTLS13 */
5859
0
        {
5860
0
            ret = HashOutput(ssl, output, sendSz, 0);
5861
0
        }
5862
0
    }
5863
5864
0
    if (ret != 0)
5865
0
        return ret;
5866
5867
#if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
5868
    if (ssl->hsInfoOn)
5869
        AddPacketName(ssl, "ServerHello");
5870
    if (ssl->toInfoOn) {
5871
        AddPacketInfo(ssl, "ServerHello", handshake, output, sendSz,
5872
                      WRITE_PROTO, ssl->heap);
5873
    }
5874
    #endif
5875
5876
0
    if (extMsgType == server_hello)
5877
0
        ssl->options.serverState = SERVER_HELLO_COMPLETE;
5878
5879
0
    ssl->options.buildingMsg = 0;
5880
#ifdef WOLFSSL_DTLS13
5881
    if (ssl->options.dtls) {
5882
        ret = Dtls13HandshakeSend(ssl, output, sendSz, sendSz,
5883
            (enum HandShakeType)extMsgType, 0);
5884
5885
        WOLFSSL_LEAVE("SendTls13ServerHello", ret);
5886
        WOLFSSL_END(WC_FUNC_SERVER_HELLO_SEND);
5887
        return ret;
5888
    }
5889
#endif /* WOLFSSL_DTLS13 */
5890
5891
0
    ssl->buffers.outputBuffer.length += sendSz;
5892
5893
0
    if (!ssl->options.groupMessages || extMsgType != server_hello)
5894
0
        ret = SendBuffered(ssl);
5895
5896
0
    WOLFSSL_LEAVE("SendTls13ServerHello", ret);
5897
0
    WOLFSSL_END(WC_FUNC_SERVER_HELLO_SEND);
5898
5899
0
    return ret;
5900
0
}
5901
5902
/* handle generation of TLS 1.3 encrypted_extensions (8) */
5903
/* Send the rest of the extensions encrypted under the handshake key.
5904
 * This message is always encrypted in TLS v1.3.
5905
 * Only a server will send this message.
5906
 *
5907
 * ssl  The SSL/TLS object.
5908
 * returns 0 on success, otherwise failure.
5909
 */
5910
static int SendTls13EncryptedExtensions(WOLFSSL* ssl)
5911
0
{
5912
0
    int    ret;
5913
0
    byte*  output;
5914
0
    word16 length = 0;
5915
0
    word32 idx;
5916
0
    int    sendSz;
5917
5918
0
    WOLFSSL_START(WC_FUNC_ENCRYPTED_EXTENSIONS_SEND);
5919
0
    WOLFSSL_ENTER("SendTls13EncryptedExtensions");
5920
5921
0
    ssl->options.buildingMsg = 1;
5922
0
    ssl->keys.encryptionOn = 1;
5923
5924
#ifdef WOLFSSL_DTLS13
5925
    if (ssl->options.dtls) {
5926
        idx = Dtls13GetHeadersLength(ssl, encrypted_extensions);
5927
    }
5928
    else
5929
#endif /* WOLFSSL_DTLS13 */
5930
0
    {
5931
0
        idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
5932
0
    }
5933
5934
0
#if defined(HAVE_SUPPORTED_CURVES) && !defined(WOLFSSL_NO_SERVER_GROUPS_EXT)
5935
0
    if ((ret = TLSX_SupportedCurve_CheckPriority(ssl)) != 0)
5936
0
        return ret;
5937
0
#endif
5938
5939
    /* Derive the handshake secret now that we are at first message to be
5940
     * encrypted under the keys.
5941
     */
5942
0
    if ((ret = DeriveHandshakeSecret(ssl)) != 0)
5943
0
        return ret;
5944
0
    if ((ret = DeriveTls13Keys(ssl, handshake_key,
5945
0
                               ENCRYPT_AND_DECRYPT_SIDE, 1)) != 0)
5946
0
        return ret;
5947
5948
    /* Setup encrypt/decrypt keys for following messages. */
5949
#ifdef WOLFSSL_EARLY_DATA
5950
    if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
5951
        return ret;
5952
    if (ssl->earlyData != process_early_data) {
5953
        if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0)
5954
            return ret;
5955
    }
5956
#else
5957
0
    if ((ret = SetKeysSide(ssl, ENCRYPT_AND_DECRYPT_SIDE)) != 0)
5958
0
        return ret;
5959
0
#endif
5960
#ifdef WOLFSSL_QUIC
5961
    if (IsAtLeastTLSv1_3(ssl->version) && WOLFSSL_IS_QUIC(ssl)) {
5962
        ret = wolfSSL_quic_add_transport_extensions(ssl, encrypted_extensions);
5963
        if (ret != 0)
5964
            return ret;
5965
    }
5966
#endif
5967
5968
#ifdef WOLFSSL_DTLS13
5969
    if (ssl->options.dtls) {
5970
        w64wrapper epochHandshake = w64From32(0, DTLS13_EPOCH_HANDSHAKE);
5971
        ssl->dtls13Epoch = epochHandshake;
5972
5973
        ret = Dtls13NewEpoch(
5974
            ssl, epochHandshake, ENCRYPT_AND_DECRYPT_SIDE);
5975
        if (ret != 0)
5976
            return ret;
5977
5978
        ret = Dtls13SetEpochKeys(
5979
            ssl, epochHandshake, ENCRYPT_AND_DECRYPT_SIDE);
5980
        if (ret != 0)
5981
            return ret;
5982
5983
    }
5984
#endif /* WOLFSSL_DTLS13 */
5985
5986
0
    ret = TLSX_GetResponseSize(ssl, encrypted_extensions, &length);
5987
0
    if (ret != 0)
5988
0
        return ret;
5989
5990
0
    sendSz = idx + length;
5991
    /* Encryption always on. */
5992
0
    sendSz += MAX_MSG_EXTRA;
5993
5994
    /* Check buffers are big enough and grow if needed. */
5995
0
    ret = CheckAvailableSize(ssl, sendSz);
5996
0
    if (ret != 0)
5997
0
        return ret;
5998
5999
    /* Get position in output buffer to write new message to. */
6000
0
    output = ssl->buffers.outputBuffer.buffer +
6001
0
             ssl->buffers.outputBuffer.length;
6002
6003
    /* Put the record and handshake headers on. */
6004
0
    AddTls13Headers(output, length, encrypted_extensions, ssl);
6005
6006
0
    ret = TLSX_WriteResponse(ssl, output + idx, encrypted_extensions, NULL);
6007
0
    if (ret != 0)
6008
0
        return ret;
6009
0
    idx += length;
6010
6011
#if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
6012
    if (ssl->hsInfoOn)
6013
        AddPacketName(ssl, "EncryptedExtensions");
6014
    if (ssl->toInfoOn) {
6015
        AddPacketInfo(ssl, "EncryptedExtensions", handshake, output,
6016
                      sendSz, WRITE_PROTO, ssl->heap);
6017
    }
6018
#endif
6019
6020
#ifdef WOLFSSL_DTLS13
6021
    if (ssl->options.dtls) {
6022
        ssl->options.buildingMsg = 0;
6023
        ret = Dtls13HandshakeSend(ssl, output, sendSz, idx,
6024
                                  encrypted_extensions, 1);
6025
6026
        if (ret == 0)
6027
            ssl->options.serverState = SERVER_ENCRYPTED_EXTENSIONS_COMPLETE;
6028
6029
        WOLFSSL_LEAVE("SendTls13EncryptedExtensions", ret);
6030
        WOLFSSL_END(WC_FUNC_ENCRYPTED_EXTENSIONS_SEND);
6031
6032
        return ret;
6033
    }
6034
#endif /* WOLFSSL_DTLS13 */
6035
6036
    /* This handshake message is always encrypted. */
6037
0
    sendSz = BuildTls13Message(ssl, output, sendSz, output + RECORD_HEADER_SZ,
6038
0
                               idx - RECORD_HEADER_SZ, handshake, 1, 0, 0);
6039
0
    if (sendSz < 0)
6040
0
        return sendSz;
6041
6042
0
    ssl->buffers.outputBuffer.length += sendSz;
6043
0
    ssl->options.buildingMsg = 0;
6044
0
    ssl->options.serverState = SERVER_ENCRYPTED_EXTENSIONS_COMPLETE;
6045
6046
0
    if (!ssl->options.groupMessages)
6047
0
        ret = SendBuffered(ssl);
6048
6049
6050
0
    WOLFSSL_LEAVE("SendTls13EncryptedExtensions", ret);
6051
0
    WOLFSSL_END(WC_FUNC_ENCRYPTED_EXTENSIONS_SEND);
6052
6053
0
    return ret;
6054
0
}
6055
6056
#ifndef NO_CERTS
6057
/* handle generation TLS v1.3 certificate_request (13) */
6058
/* Send the TLS v1.3 CertificateRequest message.
6059
 * This message is always encrypted in TLS v1.3.
6060
 * Only a server will send this message.
6061
 *
6062
 * ssl        SSL/TLS object.
6063
 * reqCtx     Request context.
6064
 * reqCtxLen  Length of context. 0 when sending as part of handshake.
6065
 * returns 0 on success, otherwise failure.
6066
 */
6067
static int SendTls13CertificateRequest(WOLFSSL* ssl, byte* reqCtx,
6068
                                       int reqCtxLen)
6069
0
{
6070
0
    byte*   output;
6071
0
    int    ret;
6072
0
    int    sendSz;
6073
0
    word32 i;
6074
0
    word16 reqSz;
6075
0
    TLSX*  ext;
6076
6077
0
    WOLFSSL_START(WC_FUNC_CERTIFICATE_REQUEST_SEND);
6078
0
    WOLFSSL_ENTER("SendTls13CertificateRequest");
6079
6080
0
    ssl->options.buildingMsg = 1;
6081
6082
0
    if (ssl->options.side == WOLFSSL_SERVER_END)
6083
0
        InitSuitesHashSigAlgo(ssl->suites, 1, 1, 1, 1,
6084
0
                              0, 1, ssl->buffers.keySz);
6085
6086
0
    ext = TLSX_Find(ssl->extensions, TLSX_SIGNATURE_ALGORITHMS);
6087
0
    if (ext == NULL)
6088
0
        return EXT_MISSING;
6089
0
    ext->resp = 0;
6090
6091
0
    i = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
6092
#ifdef WOLFSSL_DTLS13
6093
    if (ssl->options.dtls)
6094
        i = Dtls13GetRlHeaderLength(ssl, 1) + DTLS_HANDSHAKE_HEADER_SZ;
6095
#endif /* WOLFSSL_DTLS13 */
6096
6097
0
    reqSz = (word16)(OPAQUE8_LEN + reqCtxLen);
6098
0
    ret = TLSX_GetRequestSize(ssl, certificate_request, &reqSz);
6099
0
    if (ret != 0)
6100
0
        return ret;
6101
6102
0
    sendSz = i + reqSz;
6103
    /* Always encrypted and make room for padding. */
6104
0
    sendSz += MAX_MSG_EXTRA;
6105
6106
    /* Check buffers are big enough and grow if needed. */
6107
0
    if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
6108
0
        return ret;
6109
6110
    /* Get position in output buffer to write new message to. */
6111
0
    output = ssl->buffers.outputBuffer.buffer +
6112
0
             ssl->buffers.outputBuffer.length;
6113
6114
    /* Put the record and handshake headers on. */
6115
0
    AddTls13Headers(output, reqSz, certificate_request, ssl);
6116
6117
    /* Certificate request context. */
6118
0
    output[i++] = (byte)reqCtxLen;
6119
0
    if (reqCtxLen != 0) {
6120
0
        XMEMCPY(output + i, reqCtx, reqCtxLen);
6121
0
        i += reqCtxLen;
6122
0
    }
6123
6124
    /* Certificate extensions. */
6125
0
    reqSz = 0;
6126
0
    ret = TLSX_WriteRequest(ssl, output + i, certificate_request, &reqSz);
6127
0
    if (ret != 0)
6128
0
        return ret;
6129
0
    i += reqSz;
6130
6131
#ifdef WOLFSSL_DTLS13
6132
    if (ssl->options.dtls) {
6133
        ssl->options.buildingMsg = 0;
6134
        ret =
6135
            Dtls13HandshakeSend(ssl, output, sendSz, i, certificate_request, 1);
6136
6137
        WOLFSSL_LEAVE("SendTls13CertificateRequest", ret);
6138
        WOLFSSL_END(WC_FUNC_CERTIFICATE_REQUEST_SEND);
6139
6140
        return ret;
6141
6142
    }
6143
#endif /* WOLFSSL_DTLS13 */
6144
6145
    /* Always encrypted. */
6146
0
    sendSz = BuildTls13Message(ssl, output, sendSz, output + RECORD_HEADER_SZ,
6147
0
                               i - RECORD_HEADER_SZ, handshake, 1, 0, 0);
6148
0
    if (sendSz < 0)
6149
0
        return sendSz;
6150
6151
    #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
6152
        if (ssl->hsInfoOn)
6153
            AddPacketName(ssl, "CertificateRequest");
6154
        if (ssl->toInfoOn) {
6155
            AddPacketInfo(ssl, "CertificateRequest", handshake, output,
6156
                          sendSz, WRITE_PROTO, ssl->heap);
6157
        }
6158
    #endif
6159
6160
0
    ssl->buffers.outputBuffer.length += sendSz;
6161
0
    ssl->options.buildingMsg = 0;
6162
0
    if (!ssl->options.groupMessages)
6163
0
        ret = SendBuffered(ssl);
6164
6165
0
    WOLFSSL_LEAVE("SendTls13CertificateRequest", ret);
6166
0
    WOLFSSL_END(WC_FUNC_CERTIFICATE_REQUEST_SEND);
6167
6168
0
    return ret;
6169
0
}
6170
#endif /* NO_CERTS */
6171
#endif /* NO_WOLFSSL_SERVER */
6172
6173
#ifndef NO_CERTS
6174
#if !defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
6175
    defined(HAVE_ED448) || defined(HAVE_PQC)
6176
/* Encode the signature algorithm into buffer.
6177
 *
6178
 * hashalgo  The hash algorithm.
6179
 * hsType   The signature type.
6180
 * output    The buffer to encode into.
6181
 */
6182
static WC_INLINE void EncodeSigAlg(byte hashAlgo, byte hsType, byte* output)
6183
0
{
6184
0
    switch (hsType) {
6185
0
#ifdef HAVE_ECC
6186
0
        case ecc_dsa_sa_algo:
6187
0
            output[0] = hashAlgo;
6188
0
            output[1] = ecc_dsa_sa_algo;
6189
0
            break;
6190
0
#endif
6191
0
#ifdef HAVE_ED25519
6192
        /* ED25519: 0x0807 */
6193
0
        case ed25519_sa_algo:
6194
0
            output[0] = ED25519_SA_MAJOR;
6195
0
            output[1] = ED25519_SA_MINOR;
6196
0
            (void)hashAlgo;
6197
0
            break;
6198
0
#endif
6199
0
#ifdef HAVE_ED448
6200
        /* ED448: 0x0808 */
6201
0
        case ed448_sa_algo:
6202
0
            output[0] = ED448_SA_MAJOR;
6203
0
            output[1] = ED448_SA_MINOR;
6204
0
            (void)hashAlgo;
6205
0
            break;
6206
0
#endif
6207
0
#ifndef NO_RSA
6208
        /* PSS signatures: 0x080[4-6] */
6209
0
        case rsa_pss_sa_algo:
6210
0
            output[0] = rsa_pss_sa_algo;
6211
0
            output[1] = hashAlgo;
6212
0
            break;
6213
0
#endif
6214
#ifdef HAVE_PQC
6215
        #ifdef HAVE_FALCON
6216
        case falcon_level1_sa_algo:
6217
            output[0] = FALCON_LEVEL1_SA_MAJOR;
6218
            output[1] = FALCON_LEVEL1_SA_MINOR;
6219
            break;
6220
        case falcon_level5_sa_algo:
6221
            output[0] = FALCON_LEVEL5_SA_MAJOR;
6222
            output[1] = FALCON_LEVEL5_SA_MINOR;
6223
            break;
6224
        #endif
6225
        #ifdef HAVE_DILITHIUM
6226
        case dilithium_level2_sa_algo:
6227
            output[0] = DILITHIUM_LEVEL2_SA_MAJOR;
6228
            output[1] = DILITHIUM_LEVEL2_SA_MINOR;
6229
            break;
6230
        case dilithium_level3_sa_algo:
6231
            output[0] = DILITHIUM_LEVEL3_SA_MAJOR;
6232
            output[1] = DILITHIUM_LEVEL3_SA_MINOR;
6233
            break;
6234
        case dilithium_level5_sa_algo:
6235
            output[0] = DILITHIUM_LEVEL5_SA_MAJOR;
6236
            output[1] = DILITHIUM_LEVEL5_SA_MINOR;
6237
            break;
6238
        case dilithium_aes_level2_sa_algo:
6239
            output[0] = DILITHIUM_AES_LEVEL2_SA_MAJOR;
6240
            output[1] = DILITHIUM_AES_LEVEL2_SA_MINOR;
6241
            break;
6242
        case dilithium_aes_level3_sa_algo:
6243
            output[0] = DILITHIUM_AES_LEVEL3_SA_MAJOR;
6244
            output[1] = DILITHIUM_AES_LEVEL3_SA_MINOR;
6245
            break;
6246
        case dilithium_aes_level5_sa_algo:
6247
            output[0] = DILITHIUM_AES_LEVEL5_SA_MAJOR;
6248
            output[1] = DILITHIUM_AES_LEVEL5_SA_MINOR;
6249
            break;
6250
        #endif
6251
#endif
6252
0
        default:
6253
0
            break;
6254
0
    }
6255
0
}
6256
6257
/* Decode the signature algorithm.
6258
 *
6259
 * input     The encoded signature algorithm.
6260
 * hashalgo  The hash algorithm.
6261
 * hsType    The signature type.
6262
 * returns INVALID_PARAMETER if not recognized and 0 otherwise.
6263
 */
6264
static WC_INLINE int DecodeTls13SigAlg(byte* input, byte* hashAlgo,
6265
                                       byte* hsType)
6266
0
{
6267
0
    int ret = 0;
6268
6269
0
    switch (input[0]) {
6270
0
        case NEW_SA_MAJOR:
6271
            /* PSS signatures: 0x080[4-6] */
6272
0
            if (input[1] >= sha256_mac && input[1] <= sha512_mac) {
6273
0
                *hsType   = input[0];
6274
0
                *hashAlgo = input[1];
6275
0
            }
6276
0
    #ifdef HAVE_ED25519
6277
            /* ED25519: 0x0807 */
6278
0
            else if (input[1] == ED25519_SA_MINOR) {
6279
0
                *hsType = ed25519_sa_algo;
6280
                /* Hash performed as part of sign/verify operation. */
6281
0
                *hashAlgo = sha512_mac;
6282
0
            }
6283
0
    #endif
6284
0
    #ifdef HAVE_ED448
6285
            /* ED448: 0x0808 */
6286
0
            else if (input[1] == ED448_SA_MINOR) {
6287
0
                *hsType = ed448_sa_algo;
6288
                /* Hash performed as part of sign/verify operation. */
6289
0
                *hashAlgo = sha512_mac;
6290
0
            }
6291
0
    #endif
6292
0
            else
6293
0
                ret = INVALID_PARAMETER;
6294
0
            break;
6295
#ifdef HAVE_PQC
6296
        case PQC_SA_MAJOR:
6297
#if defined(HAVE_FALCON)
6298
            if (input[1] == FALCON_LEVEL1_SA_MINOR) {
6299
                *hsType = falcon_level1_sa_algo;
6300
                /* Hash performed as part of sign/verify operation. */
6301
                *hashAlgo = sha512_mac;
6302
            } else if (input[1] == FALCON_LEVEL5_SA_MINOR) {
6303
                *hsType = falcon_level5_sa_algo;
6304
                /* Hash performed as part of sign/verify operation. */
6305
                *hashAlgo = sha512_mac;
6306
            }
6307
            else
6308
#endif /* HAVE_FALCON */
6309
#if defined(HAVE_DILITHIUM)
6310
            if (input[1] == DILITHIUM_LEVEL2_SA_MINOR) {
6311
                *hsType = dilithium_level2_sa_algo;
6312
                /* Hash performed as part of sign/verify operation. */
6313
                *hashAlgo = sha512_mac;
6314
            } else if (input[1] == DILITHIUM_LEVEL3_SA_MINOR) {
6315
                *hsType = dilithium_level3_sa_algo;
6316
                /* Hash performed as part of sign/verify operation. */
6317
                *hashAlgo = sha512_mac;
6318
            } else if (input[1] == DILITHIUM_LEVEL5_SA_MINOR) {
6319
                *hsType = dilithium_level5_sa_algo;
6320
                /* Hash performed as part of sign/verify operation. */
6321
                *hashAlgo = sha512_mac;
6322
            } else if (input[1] == DILITHIUM_AES_LEVEL2_SA_MINOR) {
6323
                *hsType = dilithium_aes_level2_sa_algo;
6324
                /* Hash performed as part of sign/verify operation. */
6325
                *hashAlgo = sha512_mac;
6326
            } else if (input[1] == DILITHIUM_AES_LEVEL3_SA_MINOR) {
6327
                *hsType = dilithium_aes_level3_sa_algo;
6328
                /* Hash performed as part of sign/verify operation. */
6329
                *hashAlgo = sha512_mac;
6330
            } else if (input[1] == DILITHIUM_AES_LEVEL5_SA_MINOR) {
6331
                *hsType = dilithium_aes_level5_sa_algo;
6332
                /* Hash performed as part of sign/verify operation. */
6333
                *hashAlgo = sha512_mac;
6334
            }
6335
            else
6336
#endif /* HAVE_DILITHIUM */
6337
            {
6338
                ret = INVALID_PARAMETER;
6339
            }
6340
            break;
6341
#endif
6342
0
        default:
6343
0
            *hashAlgo = input[0];
6344
0
            *hsType   = input[1];
6345
0
            break;
6346
0
    }
6347
6348
0
    return ret;
6349
0
}
6350
6351
/* Get the hash of the messages so far.
6352
 *
6353
 * ssl   The SSL/TLS object.
6354
 * hash  The buffer to write the hash to.
6355
 * returns the length of the hash.
6356
 */
6357
static WC_INLINE int GetMsgHash(WOLFSSL* ssl, byte* hash)
6358
0
{
6359
0
    int ret = 0;
6360
0
    switch (ssl->specs.mac_algorithm) {
6361
0
    #ifndef NO_SHA256
6362
0
        case sha256_mac:
6363
0
            ret = wc_Sha256GetHash(&ssl->hsHashes->hashSha256, hash);
6364
0
            if (ret == 0)
6365
0
                ret = WC_SHA256_DIGEST_SIZE;
6366
0
            break;
6367
0
    #endif /* !NO_SHA256 */
6368
0
    #ifdef WOLFSSL_SHA384
6369
0
        case sha384_mac:
6370
0
            ret = wc_Sha384GetHash(&ssl->hsHashes->hashSha384, hash);
6371
0
            if (ret == 0)
6372
0
                ret = WC_SHA384_DIGEST_SIZE;
6373
0
            break;
6374
0
    #endif /* WOLFSSL_SHA384 */
6375
    #ifdef WOLFSSL_TLS13_SHA512
6376
        case sha512_mac:
6377
            ret = wc_Sha512GetHash(&ssl->hsHashes->hashSha512, hash);
6378
            if (ret == 0)
6379
                ret = WC_SHA512_DIGEST_SIZE;
6380
            break;
6381
    #endif /* WOLFSSL_TLS13_SHA512 */
6382
0
        default:
6383
0
            break;
6384
0
    }
6385
0
    return ret;
6386
0
}
6387
6388
/* The length of the certificate verification label - client and server. */
6389
0
#define CERT_VFY_LABEL_SZ    34
6390
/* The server certificate verification label. */
6391
static const byte serverCertVfyLabel[CERT_VFY_LABEL_SZ] =
6392
    "TLS 1.3, server CertificateVerify";
6393
/* The client certificate verification label. */
6394
static const byte clientCertVfyLabel[CERT_VFY_LABEL_SZ] =
6395
    "TLS 1.3, client CertificateVerify";
6396
6397
/* The number of prefix bytes for signature data. */
6398
0
#define SIGNING_DATA_PREFIX_SZ     64
6399
/* The prefix byte in the signature data. */
6400
#define SIGNING_DATA_PREFIX_BYTE   0x20
6401
/* Maximum length of the signature data. */
6402
0
#define MAX_SIG_DATA_SZ            (SIGNING_DATA_PREFIX_SZ + \
6403
0
                                    CERT_VFY_LABEL_SZ      + \
6404
0
                                    WC_MAX_DIGEST_SIZE)
6405
6406
/* Create the signature data for TLS v1.3 certificate verification.
6407
 *
6408
 * ssl        The SSL/TLS object.
6409
 * sigData    The signature data.
6410
 * sigDataSz  The length of the signature data.
6411
 * check      Indicates this is a check not create.
6412
 */
6413
static int CreateSigData(WOLFSSL* ssl, byte* sigData, word16* sigDataSz,
6414
                          int check)
6415
0
{
6416
0
    word16 idx;
6417
0
    int side = ssl->options.side;
6418
0
    int ret;
6419
6420
    /* Signature Data = Prefix | Label | Handshake Hash */
6421
0
    XMEMSET(sigData, SIGNING_DATA_PREFIX_BYTE, SIGNING_DATA_PREFIX_SZ);
6422
0
    idx = SIGNING_DATA_PREFIX_SZ;
6423
6424
0
    if ((side == WOLFSSL_SERVER_END && check) ||
6425
0
        (side == WOLFSSL_CLIENT_END && !check)) {
6426
0
        XMEMCPY(&sigData[idx], clientCertVfyLabel, CERT_VFY_LABEL_SZ);
6427
0
    }
6428
0
    if ((side == WOLFSSL_CLIENT_END && check) ||
6429
0
        (side == WOLFSSL_SERVER_END && !check)) {
6430
0
        XMEMCPY(&sigData[idx], serverCertVfyLabel, CERT_VFY_LABEL_SZ);
6431
0
    }
6432
0
    idx += CERT_VFY_LABEL_SZ;
6433
6434
0
    ret = GetMsgHash(ssl, &sigData[idx]);
6435
0
    if (ret < 0)
6436
0
        return ret;
6437
6438
0
    *sigDataSz = (word16)(idx + ret);
6439
0
    ret = 0;
6440
6441
0
    return ret;
6442
0
}
6443
6444
#ifndef NO_RSA
6445
/* Encode the PKCS #1.5 RSA signature.
6446
 *
6447
 * sig        The buffer to place the encoded signature into.
6448
 * sigData    The data to be signed.
6449
 * sigDataSz  The size of the data to be signed.
6450
 * hashAlgo   The hash algorithm to use when signing.
6451
 * returns the length of the encoded signature or negative on error.
6452
 */
6453
static int CreateRSAEncodedSig(byte* sig, byte* sigData, int sigDataSz,
6454
                               int sigAlgo, int hashAlgo)
6455
0
{
6456
0
    Digest digest;
6457
0
    int    hashSz = 0;
6458
0
    int    ret = BAD_FUNC_ARG;
6459
0
    byte*  hash;
6460
6461
0
    (void)sigAlgo;
6462
6463
0
    hash = sig;
6464
6465
    /* Digest the signature data. */
6466
0
    switch (hashAlgo) {
6467
0
#ifndef NO_WOLFSSL_SHA256
6468
0
        case sha256_mac:
6469
0
            ret = wc_InitSha256(&digest.sha256);
6470
0
            if (ret == 0) {
6471
0
                ret = wc_Sha256Update(&digest.sha256, sigData, sigDataSz);
6472
0
                if (ret == 0)
6473
0
                    ret = wc_Sha256Final(&digest.sha256, hash);
6474
0
                wc_Sha256Free(&digest.sha256);
6475
0
            }
6476
0
            hashSz = WC_SHA256_DIGEST_SIZE;
6477
0
            break;
6478
0
#endif
6479
0
#ifdef WOLFSSL_SHA384
6480
0
        case sha384_mac:
6481
0
            ret = wc_InitSha384(&digest.sha384);
6482
0
            if (ret == 0) {
6483
0
                ret = wc_Sha384Update(&digest.sha384, sigData, sigDataSz);
6484
0
                if (ret == 0)
6485
0
                    ret = wc_Sha384Final(&digest.sha384, hash);
6486
0
                wc_Sha384Free(&digest.sha384);
6487
0
            }
6488
0
            hashSz = WC_SHA384_DIGEST_SIZE;
6489
0
            break;
6490
0
#endif
6491
0
#ifdef WOLFSSL_SHA512
6492
0
        case sha512_mac:
6493
0
            ret = wc_InitSha512(&digest.sha512);
6494
0
            if (ret == 0) {
6495
0
                ret = wc_Sha512Update(&digest.sha512, sigData, sigDataSz);
6496
0
                if (ret == 0)
6497
0
                    ret = wc_Sha512Final(&digest.sha512, hash);
6498
0
                wc_Sha512Free(&digest.sha512);
6499
0
            }
6500
0
            hashSz = WC_SHA512_DIGEST_SIZE;
6501
0
            break;
6502
0
#endif
6503
0
    }
6504
6505
0
    if (ret != 0)
6506
0
        return ret;
6507
6508
0
    return hashSz;
6509
0
}
6510
#endif /* !NO_RSA */
6511
6512
#ifdef HAVE_ECC
6513
/* Encode the ECC signature.
6514
 *
6515
 * sigData    The data to be signed.
6516
 * sigDataSz  The size of the data to be signed.
6517
 * hashAlgo   The hash algorithm to use when signing.
6518
 * returns the length of the encoded signature or negative on error.
6519
 */
6520
static int CreateECCEncodedSig(byte* sigData, int sigDataSz, int hashAlgo)
6521
0
{
6522
0
    Digest digest;
6523
0
    int    hashSz = 0;
6524
0
    int    ret = BAD_FUNC_ARG;
6525
6526
    /* Digest the signature data. */
6527
0
    switch (hashAlgo) {
6528
0
#ifndef NO_WOLFSSL_SHA256
6529
0
        case sha256_mac:
6530
0
            ret = wc_InitSha256(&digest.sha256);
6531
0
            if (ret == 0) {
6532
0
                ret = wc_Sha256Update(&digest.sha256, sigData, sigDataSz);
6533
0
                if (ret == 0)
6534
0
                    ret = wc_Sha256Final(&digest.sha256, sigData);
6535
0
                wc_Sha256Free(&digest.sha256);
6536
0
            }
6537
0
            hashSz = WC_SHA256_DIGEST_SIZE;
6538
0
            break;
6539
0
#endif
6540
0
#ifdef WOLFSSL_SHA384
6541
0
        case sha384_mac:
6542
0
            ret = wc_InitSha384(&digest.sha384);
6543
0
            if (ret == 0) {
6544
0
                ret = wc_Sha384Update(&digest.sha384, sigData, sigDataSz);
6545
0
                if (ret == 0)
6546
0
                    ret = wc_Sha384Final(&digest.sha384, sigData);
6547
0
                wc_Sha384Free(&digest.sha384);
6548
0
            }
6549
0
            hashSz = WC_SHA384_DIGEST_SIZE;
6550
0
            break;
6551
0
#endif
6552
0
#ifdef WOLFSSL_SHA512
6553
0
        case sha512_mac:
6554
0
            ret = wc_InitSha512(&digest.sha512);
6555
0
            if (ret == 0) {
6556
0
                ret = wc_Sha512Update(&digest.sha512, sigData, sigDataSz);
6557
0
                if (ret == 0)
6558
0
                    ret = wc_Sha512Final(&digest.sha512, sigData);
6559
0
                wc_Sha512Free(&digest.sha512);
6560
0
            }
6561
0
            hashSz = WC_SHA512_DIGEST_SIZE;
6562
0
            break;
6563
0
#endif
6564
0
        default:
6565
0
            break;
6566
0
    }
6567
6568
0
    if (ret != 0)
6569
0
        return ret;
6570
6571
0
    return hashSz;
6572
0
}
6573
#endif /* HAVE_ECC */
6574
6575
#if !defined(NO_RSA) && defined(WC_RSA_PSS)
6576
/* Check that the decrypted signature matches the encoded signature
6577
 * based on the digest of the signature data.
6578
 *
6579
 * ssl       The SSL/TLS object.
6580
 * sigAlgo   The signature algorithm used to generate signature.
6581
 * hashAlgo  The hash algorithm used to generate signature.
6582
 * decSig    The decrypted signature.
6583
 * decSigSz  The size of the decrypted signature.
6584
 * returns 0 on success, otherwise failure.
6585
 */
6586
static int CheckRSASignature(WOLFSSL* ssl, int sigAlgo, int hashAlgo,
6587
                             byte* decSig, word32 decSigSz)
6588
0
{
6589
0
    int    ret = 0;
6590
0
    byte   sigData[MAX_SIG_DATA_SZ];
6591
0
    word16 sigDataSz;
6592
0
    word32 sigSz;
6593
6594
0
    ret = CreateSigData(ssl, sigData, &sigDataSz, 1);
6595
0
    if (ret != 0)
6596
0
        return ret;
6597
6598
0
    if (sigAlgo == rsa_pss_sa_algo) {
6599
0
        enum wc_HashType hashType = WC_HASH_TYPE_NONE;
6600
6601
0
        ret = ConvertHashPss(hashAlgo, &hashType, NULL);
6602
0
        if (ret < 0)
6603
0
            return ret;
6604
6605
        /* PSS signature can be done in-place */
6606
0
        ret = CreateRSAEncodedSig(sigData, sigData, sigDataSz,
6607
0
                                  sigAlgo, hashAlgo);
6608
0
        if (ret < 0)
6609
0
            return ret;
6610
0
        sigSz = ret;
6611
6612
0
        ret = wc_RsaPSS_CheckPadding(sigData, sigSz, decSig, decSigSz,
6613
0
                                     hashType);
6614
0
    }
6615
6616
0
    return ret;
6617
0
}
6618
#endif /* !NO_RSA && WC_RSA_PSS */
6619
#endif /* !NO_RSA || HAVE_ECC */
6620
6621
#if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER)
6622
/* Get the next certificate from the list for writing into the TLS v1.3
6623
 * Certificate message.
6624
 *
6625
 * data    The certificate list.
6626
 * length  The length of the certificate data in the list.
6627
 * idx     The index of the next certificate.
6628
 * returns the length of the certificate data. 0 indicates no more certificates
6629
 * in the list.
6630
 */
6631
static word32 NextCert(byte* data, word32 length, word32* idx)
6632
0
{
6633
0
    word32 len;
6634
6635
    /* Is index at end of list. */
6636
0
    if (*idx == length)
6637
0
        return 0;
6638
6639
    /* Length of the current ASN.1 encoded certificate. */
6640
0
    c24to32(data + *idx, &len);
6641
    /* Include the length field. */
6642
0
    len += 3;
6643
6644
    /* Move index to next certificate and return the current certificate's
6645
     * length.
6646
     */
6647
0
    *idx += len;
6648
0
    return len;
6649
0
}
6650
6651
/* Add certificate data and empty extension to output up to the fragment size.
6652
 *
6653
 * ssl     SSL/TLS object.
6654
 * cert    The certificate data to write out.
6655
 * len     The length of the certificate data.
6656
 * extSz   Length of the extension data with the certificate.
6657
 * idx     The start of the certificate data to write out.
6658
 * fragSz  The maximum size of this fragment.
6659
 * output  The buffer to write to.
6660
 * returns the number of bytes written.
6661
 */
6662
static word32 AddCertExt(WOLFSSL* ssl, byte* cert, word32 len, word16 extSz,
6663
                         word32 idx, word32 fragSz, byte* output)
6664
0
{
6665
0
    word32 i = 0;
6666
0
    word32 copySz = min(len - idx, fragSz);
6667
6668
0
    if (idx < len) {
6669
0
        XMEMCPY(output, cert + idx, copySz);
6670
0
        i = copySz;
6671
0
        if (copySz == fragSz)
6672
0
            return i;
6673
0
    }
6674
0
    copySz = len + extSz - idx - i;
6675
6676
0
    if (extSz == OPAQUE16_LEN) {
6677
0
        if (copySz <= fragSz) {
6678
            /* Empty extension */
6679
0
            output[i++] = 0;
6680
0
            output[i++] = 0;
6681
0
        }
6682
0
    }
6683
0
    else {
6684
0
        byte* certExts = ssl->buffers.certExts->buffer + idx + i - len;
6685
        /* Put out as much of the extensions' data as will fit in fragment. */
6686
0
        if (copySz > fragSz - i)
6687
0
            copySz = fragSz - i;
6688
0
        XMEMCPY(output + i, certExts, copySz);
6689
0
        i += copySz;
6690
0
    }
6691
6692
0
    return i;
6693
0
}
6694
6695
/* handle generation TLS v1.3 certificate (11) */
6696
/* Send the certificate for this end and any CAs that help with validation.
6697
 * This message is always encrypted in TLS v1.3.
6698
 *
6699
 * ssl  The SSL/TLS object.
6700
 * returns 0 on success, otherwise failure.
6701
 */
6702
static int SendTls13Certificate(WOLFSSL* ssl)
6703
0
{
6704
0
    int    ret = 0;
6705
0
    word32 certSz, certChainSz, headerSz, listSz, payloadSz;
6706
0
    word16 extSz = 0;
6707
0
    word32 length, maxFragment;
6708
0
    word32 len = 0;
6709
0
    word32 idx = 0;
6710
0
    word32 offset = OPAQUE16_LEN;
6711
0
    byte*  p = NULL;
6712
0
    byte   certReqCtxLen = 0;
6713
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
6714
    byte*  certReqCtx = NULL;
6715
#endif
6716
6717
#ifdef OPENSSL_EXTRA
6718
    WOLFSSL_X509* x509 = NULL;
6719
    WOLFSSL_EVP_PKEY* pkey = NULL;
6720
#endif
6721
6722
0
    WOLFSSL_START(WC_FUNC_CERTIFICATE_SEND);
6723
0
    WOLFSSL_ENTER("SendTls13Certificate");
6724
6725
0
    ssl->options.buildingMsg = 1;
6726
6727
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
6728
    if (ssl->options.side == WOLFSSL_CLIENT_END && ssl->certReqCtx != NULL) {
6729
        certReqCtxLen = ssl->certReqCtx->len;
6730
        certReqCtx = &ssl->certReqCtx->ctx;
6731
    }
6732
#endif
6733
6734
#ifdef OPENSSL_EXTRA
6735
    /* call client cert callback if no cert has been loaded */
6736
    if ((ssl->ctx->CBClientCert != NULL) &&
6737
        (!ssl->buffers.certificate || !ssl->buffers.certificate->buffer)) {
6738
        ret = ssl->ctx->CBClientCert(ssl, &x509, &pkey);
6739
        if (ret == 1) {
6740
            if ((wolfSSL_CTX_use_certificate(ssl->ctx, x509) == WOLFSSL_SUCCESS) &&
6741
                (wolfSSL_CTX_use_PrivateKey(ssl->ctx, pkey) == WOLFSSL_SUCCESS)) {
6742
                ssl->options.sendVerify = SEND_CERT;
6743
            }
6744
            wolfSSL_X509_free(x509);
6745
            wolfSSL_EVP_PKEY_free(pkey);
6746
        }
6747
    }
6748
#endif
6749
6750
0
    if (ssl->options.sendVerify == SEND_BLANK_CERT) {
6751
0
        certSz = 0;
6752
0
        certChainSz = 0;
6753
0
        headerSz = OPAQUE8_LEN + certReqCtxLen + CERT_HEADER_SZ;
6754
0
        length = headerSz;
6755
0
        listSz = 0;
6756
0
    }
6757
0
    else {
6758
#ifdef OPENSSL_EXTRA
6759
        if ((ret = CertSetupCbWrapper(ssl)) != 0)
6760
            return ret;
6761
#endif
6762
6763
0
        if (!ssl->buffers.certificate) {
6764
0
            WOLFSSL_MSG("Send Cert missing certificate buffer");
6765
0
            return BUFFER_ERROR;
6766
0
        }
6767
        /* Certificate Data */
6768
0
        certSz = ssl->buffers.certificate->length;
6769
        /* Cert Req Ctx Len | Cert Req Ctx | Cert List Len | Cert Data Len */
6770
0
        headerSz = OPAQUE8_LEN + certReqCtxLen + CERT_HEADER_SZ +
6771
0
                   CERT_HEADER_SZ;
6772
6773
0
        ret = TLSX_GetResponseSize(ssl, certificate, &extSz);
6774
0
        if (ret < 0)
6775
0
            return ret;
6776
6777
        /* Create extensions' data if none already present. */
6778
0
        if (extSz > OPAQUE16_LEN && ssl->buffers.certExts == NULL) {
6779
0
            ret = AllocDer(&ssl->buffers.certExts, extSz, CERT_TYPE, ssl->heap);
6780
0
            if (ret < 0)
6781
0
                return ret;
6782
6783
0
            extSz = 0;
6784
0
            ret = TLSX_WriteResponse(ssl, ssl->buffers.certExts->buffer,
6785
0
                                                           certificate, &extSz);
6786
0
            if (ret < 0)
6787
0
                return ret;
6788
0
        }
6789
6790
        /* Length of message data with one certificate and extensions. */
6791
0
        length = headerSz + certSz + extSz;
6792
        /* Length of list data with one certificate and extensions. */
6793
0
        listSz = CERT_HEADER_SZ + certSz + extSz;
6794
6795
        /* Send rest of chain if sending cert (chain has leading size/s). */
6796
0
        if (certSz > 0 && ssl->buffers.certChainCnt > 0) {
6797
0
            p = ssl->buffers.certChain->buffer;
6798
            /* Chain length including extensions. */
6799
0
            certChainSz = ssl->buffers.certChain->length +
6800
0
                          OPAQUE16_LEN * ssl->buffers.certChainCnt;
6801
0
            length += certChainSz;
6802
0
            listSz += certChainSz;
6803
0
        }
6804
0
        else
6805
0
            certChainSz = 0;
6806
0
    }
6807
6808
0
    payloadSz = length;
6809
6810
0
    if (ssl->fragOffset != 0)
6811
0
        length -= (ssl->fragOffset + headerSz);
6812
6813
0
    maxFragment = wolfSSL_GetMaxFragSize(ssl, MAX_RECORD_SIZE);
6814
6815
0
    while (length > 0 && ret == 0) {
6816
0
        byte*  output = NULL;
6817
0
        word32 fragSz = 0;
6818
0
        word32 i = RECORD_HEADER_SZ;
6819
0
        int    sendSz = RECORD_HEADER_SZ;
6820
6821
#ifdef WOLFSSL_DTLS13
6822
        if (ssl->options.dtls) {
6823
            i = Dtls13GetRlHeaderLength(ssl, 1);
6824
            sendSz = (int)i;
6825
        }
6826
#endif /* WOLFSSL_DTLS13 */
6827
6828
0
        if (ssl->fragOffset == 0) {
6829
0
            if (headerSz + certSz + extSz + certChainSz <=
6830
0
                                            maxFragment - HANDSHAKE_HEADER_SZ) {
6831
0
                fragSz = headerSz + certSz + extSz + certChainSz;
6832
0
            }
6833
#ifdef WOLFSSL_DTLS13
6834
            else if (ssl->options.dtls){
6835
                /* short-circuit the fragmentation logic here. DTLS
6836
                   fragmentation will be done in dtls13HandshakeSend() */
6837
                fragSz = headerSz + certSz + extSz + certChainSz;
6838
            }
6839
#endif /* WOLFSSL_DTLS13 */
6840
0
            else {
6841
0
                fragSz = maxFragment - HANDSHAKE_HEADER_SZ;
6842
0
            }
6843
6844
0
            sendSz += fragSz + HANDSHAKE_HEADER_SZ;
6845
0
            i += HANDSHAKE_HEADER_SZ;
6846
#ifdef WOLFSSL_DTLS13
6847
            if (ssl->options.dtls) {
6848
                sendSz += DTLS_HANDSHAKE_EXTRA;
6849
                i += DTLS_HANDSHAKE_EXTRA;
6850
            }
6851
#endif /* WOLFSSL_DTLS13 */
6852
0
        }
6853
0
        else {
6854
0
            fragSz = min(length, maxFragment);
6855
0
            sendSz += fragSz;
6856
0
        }
6857
6858
0
        sendSz += MAX_MSG_EXTRA;
6859
6860
        /* Check buffers are big enough and grow if needed. */
6861
0
        if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
6862
0
            return ret;
6863
6864
        /* Get position in output buffer to write new message to. */
6865
0
        output = ssl->buffers.outputBuffer.buffer +
6866
0
                 ssl->buffers.outputBuffer.length;
6867
6868
0
        if (ssl->fragOffset == 0) {
6869
0
            AddTls13FragHeaders(output, fragSz, 0, payloadSz, certificate, ssl);
6870
6871
            /* Request context. */
6872
0
            output[i++] = certReqCtxLen;
6873
        #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
6874
            if (certReqCtxLen > 0) {
6875
                XMEMCPY(output + i, certReqCtx, certReqCtxLen);
6876
                i += certReqCtxLen;
6877
            }
6878
        #endif
6879
0
            length -= OPAQUE8_LEN + certReqCtxLen;
6880
0
            fragSz -= OPAQUE8_LEN + certReqCtxLen;
6881
            /* Certificate list length. */
6882
0
            c32to24(listSz, output + i);
6883
0
            i += CERT_HEADER_SZ;
6884
0
            length -= CERT_HEADER_SZ;
6885
0
            fragSz -= CERT_HEADER_SZ;
6886
            /* Leaf certificate data length. */
6887
0
            if (certSz > 0) {
6888
0
                c32to24(certSz, output + i);
6889
0
                i += CERT_HEADER_SZ;
6890
0
                length -= CERT_HEADER_SZ;
6891
0
                fragSz -= CERT_HEADER_SZ;
6892
0
            }
6893
0
        }
6894
0
        else
6895
0
            AddTls13RecordHeader(output, fragSz, handshake, ssl);
6896
6897
0
        if (certSz > 0 && ssl->fragOffset < certSz + extSz) {
6898
            /* Put in the leaf certificate with extensions. */
6899
0
            word32 copySz = AddCertExt(ssl, ssl->buffers.certificate->buffer,
6900
0
                            certSz, extSz, ssl->fragOffset, fragSz, output + i);
6901
0
            i += copySz;
6902
0
            ssl->fragOffset += copySz;
6903
0
            length -= copySz;
6904
0
            fragSz -= copySz;
6905
0
            if (ssl->fragOffset == certSz + extSz)
6906
0
                FreeDer(&ssl->buffers.certExts);
6907
0
        }
6908
0
        if (certChainSz > 0 && fragSz > 0) {
6909
            /* Put in the CA certificates with empty extensions. */
6910
0
            while (fragSz > 0) {
6911
0
                word32 l;
6912
6913
0
                if (offset == len + OPAQUE16_LEN) {
6914
                    /* Find next CA certificate to write out. */
6915
0
                    offset = 0;
6916
                    /* Point to the start of current cert in chain buffer. */
6917
0
                    p = ssl->buffers.certChain->buffer + idx;
6918
0
                    len = NextCert(ssl->buffers.certChain->buffer,
6919
0
                                   ssl->buffers.certChain->length, &idx);
6920
0
                    if (len == 0)
6921
0
                        break;
6922
0
                }
6923
6924
                /* Write out certificate and empty extension. */
6925
0
                l = AddCertExt(ssl, p, len, OPAQUE16_LEN, offset, fragSz,
6926
0
                                                                    output + i);
6927
0
                i += l;
6928
0
                ssl->fragOffset += l;
6929
0
                length -= l;
6930
0
                fragSz -= l;
6931
0
                offset += l;
6932
0
            }
6933
0
        }
6934
6935
0
        if ((int)i - RECORD_HEADER_SZ < 0) {
6936
0
            WOLFSSL_MSG("Send Cert bad inputSz");
6937
0
            return BUFFER_E;
6938
0
        }
6939
6940
#ifdef WOLFSSL_DTLS13
6941
        if (ssl->options.dtls) {
6942
            /* DTLS1.3 uses a separate variable and logic for fragments */
6943
            ssl->options.buildingMsg = 0;
6944
            ssl->fragOffset = 0;
6945
            ret = Dtls13HandshakeSend(ssl, output, sendSz, i, certificate, 1);
6946
        }
6947
        else
6948
#endif /* WOLFSSL_DTLS13 */
6949
0
        {
6950
            /* This message is always encrypted. */
6951
0
            sendSz = BuildTls13Message(ssl, output, sendSz,
6952
0
                output + RECORD_HEADER_SZ, i - RECORD_HEADER_SZ, handshake, 1,
6953
0
                0, 0);
6954
0
            if (sendSz < 0)
6955
0
                return sendSz;
6956
6957
#if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
6958
            if (ssl->hsInfoOn)
6959
                AddPacketName(ssl, "Certificate");
6960
            if (ssl->toInfoOn) {
6961
                AddPacketInfo(ssl, "Certificate", handshake, output,
6962
                              sendSz, WRITE_PROTO, ssl->heap);
6963
            }
6964
#endif
6965
6966
0
            ssl->buffers.outputBuffer.length += sendSz;
6967
0
            ssl->options.buildingMsg = 0;
6968
0
            if (!ssl->options.groupMessages)
6969
0
                ret = SendBuffered(ssl);
6970
0
        }
6971
0
    }
6972
6973
0
    if (ret != WANT_WRITE) {
6974
        /* Clean up the fragment offset. */
6975
0
        ssl->options.buildingMsg = 0;
6976
0
        ssl->fragOffset = 0;
6977
0
        if (ssl->options.side == WOLFSSL_SERVER_END)
6978
0
            ssl->options.serverState = SERVER_CERT_COMPLETE;
6979
0
    }
6980
6981
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
6982
    if (ssl->options.side == WOLFSSL_CLIENT_END && ssl->certReqCtx != NULL) {
6983
        CertReqCtx* ctx = ssl->certReqCtx;
6984
        ssl->certReqCtx = ssl->certReqCtx->next;
6985
        XFREE(ctx, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
6986
    }
6987
#endif
6988
6989
0
    WOLFSSL_LEAVE("SendTls13Certificate", ret);
6990
0
    WOLFSSL_END(WC_FUNC_CERTIFICATE_SEND);
6991
6992
0
    return ret;
6993
0
}
6994
6995
#if (!defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
6996
     defined(HAVE_ED448) || defined(HAVE_PQC)) && \
6997
    (!defined(NO_WOLFSSL_SERVER) || !defined(WOLFSSL_NO_CLIENT_AUTH))
6998
typedef struct Scv13Args {
6999
    byte*  output; /* not allocated */
7000
    byte*  verify; /* not allocated */
7001
    word32 idx;
7002
    word32 sigLen;
7003
    int    sendSz;
7004
    word16 length;
7005
7006
    byte   sigAlgo;
7007
    byte*  sigData;
7008
    word16 sigDataSz;
7009
} Scv13Args;
7010
7011
static void FreeScv13Args(WOLFSSL* ssl, void* pArgs)
7012
0
{
7013
0
    Scv13Args* args = (Scv13Args*)pArgs;
7014
7015
0
    (void)ssl;
7016
7017
0
    if (args && args->sigData) {
7018
0
        XFREE(args->sigData, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
7019
0
        args->sigData = NULL;
7020
0
    }
7021
0
}
7022
7023
/* handle generation TLS v1.3 certificate_verify (15) */
7024
/* Send the TLS v1.3 CertificateVerify message.
7025
 * A hash of all the message so far is used.
7026
 * The signed data is:
7027
 *     0x20 * 64 | context string | 0x00 | hash of messages
7028
 * This message is always encrypted in TLS v1.3.
7029
 *
7030
 * ssl  The SSL/TLS object.
7031
 * returns 0 on success, otherwise failure.
7032
 */
7033
static int SendTls13CertificateVerify(WOLFSSL* ssl)
7034
0
{
7035
0
    int ret = 0;
7036
0
    buffer* sig = &ssl->buffers.sig;
7037
#ifdef WOLFSSL_ASYNC_CRYPT
7038
    Scv13Args* args = NULL;
7039
    WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
7040
#else
7041
0
    Scv13Args  args[1];
7042
0
#endif
7043
7044
#ifdef WOLFSSL_DTLS13
7045
    int recordLayerHdrExtra;
7046
#endif /* WOLFSSL_DTLS13 */
7047
7048
0
    WOLFSSL_START(WC_FUNC_CERTIFICATE_VERIFY_SEND);
7049
0
    WOLFSSL_ENTER("SendTls13CertificateVerify");
7050
7051
0
    ssl->options.buildingMsg = 1;
7052
7053
#if defined(WOLFSSL_RENESAS_TSIP_TLS) && (WOLFSSL_RENESAS_TSIP_VER >= 115)
7054
    ret = tsip_Tls13SendCertVerify(ssl);
7055
    if (ret != CRYPTOCB_UNAVAILABLE) {
7056
        goto exit_scv;
7057
    }
7058
    ret = 0;
7059
#endif /* WOLFSSL_RENESAS_TSIP_TLS && WOLFSSL_RENESAS_TSIP_VER >= 115 */
7060
7061
#ifdef WOLFSSL_DTLS13
7062
    /* can be negative */
7063
    if (ssl->options.dtls)
7064
        recordLayerHdrExtra = Dtls13GetRlHeaderLength(ssl, 1) - RECORD_HEADER_SZ;
7065
    else
7066
        recordLayerHdrExtra = 0;
7067
7068
#endif /* WOLFSSL_DTLS13 */
7069
7070
#ifdef WOLFSSL_ASYNC_CRYPT
7071
    if (ssl->async == NULL) {
7072
        ssl->async = (struct WOLFSSL_ASYNC*)
7073
                XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
7074
                        DYNAMIC_TYPE_ASYNC);
7075
        if (ssl->async == NULL)
7076
            ERROR_OUT(MEMORY_E, exit_scv);
7077
    }
7078
    args = (Scv13Args*)ssl->async->args;
7079
7080
    ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
7081
    if (ret != WC_NOT_PENDING_E) {
7082
        /* Check for error */
7083
        if (ret < 0)
7084
            goto exit_scv;
7085
    }
7086
    else
7087
#endif
7088
0
    {
7089
        /* Reset state */
7090
0
        ret = 0;
7091
0
        ssl->options.asyncState = TLS_ASYNC_BEGIN;
7092
0
        XMEMSET(args, 0, sizeof(Scv13Args));
7093
    #ifdef WOLFSSL_ASYNC_CRYPT
7094
        ssl->async->freeArgs = FreeScv13Args;
7095
    #endif
7096
0
    }
7097
7098
0
    switch(ssl->options.asyncState)
7099
0
    {
7100
0
        case TLS_ASYNC_BEGIN:
7101
0
        {
7102
0
            if (ssl->options.sendVerify == SEND_BLANK_CERT) {
7103
0
                return 0;  /* sent blank cert, can't verify */
7104
0
            }
7105
7106
0
            args->sendSz = MAX_CERT_VERIFY_SZ + MAX_MSG_EXTRA;
7107
            /* Always encrypted.  */
7108
0
            args->sendSz += MAX_MSG_EXTRA;
7109
7110
            /* check for available size */
7111
0
            if ((ret = CheckAvailableSize(ssl, args->sendSz)) != 0) {
7112
0
                goto exit_scv;
7113
0
            }
7114
7115
            /* get output buffer */
7116
0
            args->output = ssl->buffers.outputBuffer.buffer +
7117
0
                           ssl->buffers.outputBuffer.length;
7118
7119
            /* Advance state and proceed */
7120
0
            ssl->options.asyncState = TLS_ASYNC_BUILD;
7121
0
        } /* case TLS_ASYNC_BEGIN */
7122
0
        FALL_THROUGH;
7123
7124
0
        case TLS_ASYNC_BUILD:
7125
0
        {
7126
0
            int rem = ssl->buffers.outputBuffer.bufferSize
7127
0
              - ssl->buffers.outputBuffer.length
7128
0
              - RECORD_HEADER_SZ - HANDSHAKE_HEADER_SZ;
7129
7130
            /* idx is used to track verify pointer offset to output */
7131
0
            args->idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
7132
0
            args->verify =
7133
0
                          &args->output[RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ];
7134
7135
#ifdef WOLFSSL_DTLS13
7136
            if (ssl->options.dtls) {
7137
                rem -= recordLayerHdrExtra + DTLS_HANDSHAKE_EXTRA;
7138
                args->idx += recordLayerHdrExtra + DTLS_HANDSHAKE_EXTRA;
7139
                args->verify += recordLayerHdrExtra + DTLS_HANDSHAKE_EXTRA;
7140
            }
7141
#endif /* WOLFSSL_DTLS13 */
7142
7143
0
            if (ssl->buffers.key == NULL) {
7144
            #ifdef HAVE_PK_CALLBACKS
7145
                if (wolfSSL_CTX_IsPrivatePkSet(ssl->ctx))
7146
                    args->length = GetPrivateKeySigSize(ssl);
7147
                else
7148
            #endif
7149
0
                    ERROR_OUT(NO_PRIVATE_KEY, exit_scv);
7150
0
            }
7151
0
            else {
7152
0
                ret = DecodePrivateKey(ssl, &args->length);
7153
0
                if (ret != 0)
7154
0
                    goto exit_scv;
7155
0
            }
7156
7157
0
            if (rem < 0 || args->length > rem) {
7158
0
                ERROR_OUT(BUFFER_E, exit_scv);
7159
0
            }
7160
7161
0
            if (args->length == 0) {
7162
0
                ERROR_OUT(NO_PRIVATE_KEY, exit_scv);
7163
0
            }
7164
7165
            /* Add signature algorithm. */
7166
0
            if (ssl->hsType == DYNAMIC_TYPE_RSA)
7167
0
                args->sigAlgo = rsa_pss_sa_algo;
7168
0
        #ifdef HAVE_ECC
7169
0
            else if (ssl->hsType == DYNAMIC_TYPE_ECC)
7170
0
                args->sigAlgo = ecc_dsa_sa_algo;
7171
0
        #endif
7172
0
        #ifdef HAVE_ED25519
7173
0
            else if (ssl->hsType == DYNAMIC_TYPE_ED25519)
7174
0
                args->sigAlgo = ed25519_sa_algo;
7175
0
        #endif
7176
0
        #ifdef HAVE_ED448
7177
0
            else if (ssl->hsType == DYNAMIC_TYPE_ED448)
7178
0
                args->sigAlgo = ed448_sa_algo;
7179
0
        #endif
7180
        #if defined(HAVE_PQC)
7181
            #if defined(HAVE_FALCON)
7182
            else if (ssl->hsType == DYNAMIC_TYPE_FALCON) {
7183
                falcon_key* fkey = (falcon_key*)ssl->hsKey;
7184
                byte level = 0;
7185
                if (wc_falcon_get_level(fkey, &level) != 0) {
7186
                    ERROR_OUT(ALGO_ID_E, exit_scv);
7187
                }
7188
                if (level == 1) {
7189
                    args->sigAlgo = falcon_level1_sa_algo;
7190
                }
7191
                else if (level == 5) {
7192
                    args->sigAlgo = falcon_level5_sa_algo;
7193
                }
7194
                else {
7195
                    ERROR_OUT(ALGO_ID_E, exit_scv);
7196
                }
7197
            }
7198
            #endif /* HAVE_FALCON */
7199
            #if defined(HAVE_DILITHIUM)
7200
            else if (ssl->hsType == DYNAMIC_TYPE_DILITHIUM) {
7201
                dilithium_key* fkey = (dilithium_key*)ssl->hsKey;
7202
                byte level = 0;
7203
                byte sym = 0;
7204
                if (wc_dilithium_get_level_and_sym(fkey, &level, &sym) != 0) {
7205
                    ERROR_OUT(ALGO_ID_E, exit_scv);
7206
                }
7207
                if ((level == 2) && (sym == SHAKE_VARIANT)) {
7208
                    args->sigAlgo = dilithium_level2_sa_algo;
7209
                }
7210
                else if ((level == 3) && (sym == SHAKE_VARIANT)) {
7211
                    args->sigAlgo = dilithium_level3_sa_algo;
7212
                }
7213
                else if ((level == 5) && (sym == SHAKE_VARIANT)) {
7214
                    args->sigAlgo = dilithium_level5_sa_algo;
7215
                }
7216
                else if ((level == 2) && (sym == AES_VARIANT)) {
7217
                    args->sigAlgo = dilithium_aes_level2_sa_algo;
7218
                }
7219
                else if ((level == 3) && (sym == AES_VARIANT)) {
7220
                    args->sigAlgo = dilithium_aes_level3_sa_algo;
7221
                }
7222
                else if ((level == 5) && (sym == AES_VARIANT)) {
7223
                    args->sigAlgo = dilithium_aes_level5_sa_algo;
7224
                }
7225
                else {
7226
                    ERROR_OUT(ALGO_ID_E, exit_scv);
7227
                }
7228
            }
7229
            #endif /* HAVE_DILITHIUM */
7230
        #endif /* HAVE_PQC */
7231
0
            else {
7232
0
                ERROR_OUT(ALGO_ID_E, exit_scv);
7233
0
            }
7234
0
            EncodeSigAlg(ssl->suites->hashAlgo, args->sigAlgo, args->verify);
7235
7236
0
            if (ssl->hsType == DYNAMIC_TYPE_RSA) {
7237
0
                int sigLen = MAX_SIG_DATA_SZ;
7238
0
                if (args->length > MAX_SIG_DATA_SZ)
7239
0
                    sigLen = args->length;
7240
0
                args->sigData = (byte*)XMALLOC(sigLen, ssl->heap,
7241
0
                                                        DYNAMIC_TYPE_SIGNATURE);
7242
0
            }
7243
0
            else {
7244
0
                args->sigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap,
7245
0
                                                        DYNAMIC_TYPE_SIGNATURE);
7246
0
            }
7247
0
            if (args->sigData == NULL) {
7248
0
                ERROR_OUT(MEMORY_E, exit_scv);
7249
0
            }
7250
7251
            /* Create the data to be signed. */
7252
0
            ret = CreateSigData(ssl, args->sigData, &args->sigDataSz, 0);
7253
0
            if (ret != 0)
7254
0
                goto exit_scv;
7255
7256
0
        #ifndef NO_RSA
7257
0
            if (ssl->hsType == DYNAMIC_TYPE_RSA) {
7258
                /* build encoded signature buffer */
7259
0
                sig->length = WC_MAX_DIGEST_SIZE;
7260
0
                sig->buffer = (byte*)XMALLOC(sig->length, ssl->heap,
7261
0
                                                        DYNAMIC_TYPE_SIGNATURE);
7262
0
                if (sig->buffer == NULL) {
7263
0
                    ERROR_OUT(MEMORY_E, exit_scv);
7264
0
                }
7265
7266
0
                ret = CreateRSAEncodedSig(sig->buffer, args->sigData,
7267
0
                    args->sigDataSz, args->sigAlgo, ssl->suites->hashAlgo);
7268
0
                if (ret < 0)
7269
0
                    goto exit_scv;
7270
0
                sig->length = ret;
7271
0
                ret = 0;
7272
7273
                /* Maximum size of RSA Signature. */
7274
0
                args->sigLen = args->length;
7275
0
            }
7276
0
        #endif /* !NO_RSA */
7277
0
        #ifdef HAVE_ECC
7278
0
            if (ssl->hsType == DYNAMIC_TYPE_ECC) {
7279
0
                sig->length = args->sendSz - args->idx - HASH_SIG_SIZE -
7280
0
                              VERIFY_HEADER;
7281
0
                ret = CreateECCEncodedSig(args->sigData,
7282
0
                    args->sigDataSz, ssl->suites->hashAlgo);
7283
0
                if (ret < 0)
7284
0
                    goto exit_scv;
7285
0
                args->sigDataSz = (word16)ret;
7286
0
                ret = 0;
7287
0
            }
7288
0
        #endif /* HAVE_ECC */
7289
0
        #ifdef HAVE_ED25519
7290
0
            if (ssl->hsType == DYNAMIC_TYPE_ED25519) {
7291
0
                ret = Ed25519CheckPubKey(ssl);
7292
0
                if (ret < 0) {
7293
0
                    ERROR_OUT(ret, exit_scv);
7294
0
                }
7295
0
                sig->length = ED25519_SIG_SIZE;
7296
0
            }
7297
0
        #endif /* HAVE_ED25519 */
7298
0
        #ifdef HAVE_ED448
7299
0
            if (ssl->hsType == DYNAMIC_TYPE_ED448) {
7300
0
                ret = Ed448CheckPubKey(ssl);
7301
0
                if (ret < 0) {
7302
0
                    ERROR_OUT(ret, exit_scv);
7303
0
                }
7304
0
                sig->length = ED448_SIG_SIZE;
7305
0
            }
7306
0
        #endif /* HAVE_ED448 */
7307
        #if defined(HAVE_PQC)
7308
            #if defined(HAVE_FALCON)
7309
            if (ssl->hsType == DYNAMIC_TYPE_FALCON) {
7310
                sig->length = FALCON_MAX_SIG_SIZE;
7311
            }
7312
            #endif
7313
            #if defined(HAVE_DILITHIUM)
7314
            if (ssl->hsType == DYNAMIC_TYPE_DILITHIUM) {
7315
                sig->length = DILITHIUM_MAX_SIG_SIZE;
7316
            }
7317
            #endif
7318
        #endif /* HAVE_PQC */
7319
7320
            /* Advance state and proceed */
7321
0
            ssl->options.asyncState = TLS_ASYNC_DO;
7322
0
        } /* case TLS_ASYNC_BUILD */
7323
0
        FALL_THROUGH;
7324
7325
0
        case TLS_ASYNC_DO:
7326
0
        {
7327
0
        #ifdef HAVE_ECC
7328
0
           if (ssl->hsType == DYNAMIC_TYPE_ECC) {
7329
7330
0
                ret = EccSign(ssl, args->sigData, args->sigDataSz,
7331
0
                    args->verify + HASH_SIG_SIZE + VERIFY_HEADER,
7332
0
                    (word32*)&sig->length, (ecc_key*)ssl->hsKey,
7333
            #ifdef HAVE_PK_CALLBACKS
7334
                    ssl->buffers.key
7335
            #else
7336
0
                    NULL
7337
0
            #endif
7338
0
                );
7339
0
                args->length = (word16)sig->length;
7340
0
            }
7341
0
        #endif /* HAVE_ECC */
7342
0
        #ifdef HAVE_ED25519
7343
0
            if (ssl->hsType == DYNAMIC_TYPE_ED25519) {
7344
0
                ret = Ed25519Sign(ssl, args->sigData, args->sigDataSz,
7345
0
                    args->verify + HASH_SIG_SIZE + VERIFY_HEADER,
7346
0
                    (word32*)&sig->length, (ed25519_key*)ssl->hsKey,
7347
            #ifdef HAVE_PK_CALLBACKS
7348
                    ssl->buffers.key
7349
            #else
7350
0
                    NULL
7351
0
            #endif
7352
0
                );
7353
0
                args->length = (word16)sig->length;
7354
0
            }
7355
0
        #endif
7356
0
        #ifdef HAVE_ED448
7357
0
            if (ssl->hsType == DYNAMIC_TYPE_ED448) {
7358
0
                ret = Ed448Sign(ssl, args->sigData, args->sigDataSz,
7359
0
                    args->verify + HASH_SIG_SIZE + VERIFY_HEADER,
7360
0
                    (word32*)&sig->length, (ed448_key*)ssl->hsKey,
7361
            #ifdef HAVE_PK_CALLBACKS
7362
                    ssl->buffers.key
7363
            #else
7364
0
                    NULL
7365
0
            #endif
7366
0
                );
7367
0
                args->length = (word16)sig->length;
7368
0
            }
7369
0
        #endif
7370
        #if defined(HAVE_PQC)
7371
            #if defined(HAVE_FALCON)
7372
            if (ssl->hsType == DYNAMIC_TYPE_FALCON) {
7373
                ret = wc_falcon_sign_msg(args->sigData, args->sigDataSz,
7374
                                         args->verify + HASH_SIG_SIZE +
7375
                                         VERIFY_HEADER, (word32*)&sig->length,
7376
                                         (falcon_key*)ssl->hsKey);
7377
                args->length = (word16)sig->length;
7378
            }
7379
            #endif
7380
            #if defined(HAVE_DILITHIUM)
7381
            if (ssl->hsType == DYNAMIC_TYPE_DILITHIUM) {
7382
                ret = wc_dilithium_sign_msg(args->sigData, args->sigDataSz,
7383
                                         args->verify + HASH_SIG_SIZE +
7384
                                         VERIFY_HEADER, (word32*)&sig->length,
7385
                                         (dilithium_key*)ssl->hsKey);
7386
                args->length = (word16)sig->length;
7387
            }
7388
            #endif
7389
        #endif /* HAVE_PQC */
7390
0
        #ifndef NO_RSA
7391
0
            if (ssl->hsType == DYNAMIC_TYPE_RSA) {
7392
0
                ret = RsaSign(ssl, sig->buffer, (word32)sig->length,
7393
0
                    args->verify + HASH_SIG_SIZE + VERIFY_HEADER, &args->sigLen,
7394
0
                    args->sigAlgo, ssl->suites->hashAlgo,
7395
0
                    (RsaKey*)ssl->hsKey,
7396
0
                    ssl->buffers.key
7397
0
                );
7398
0
                if (ret == 0) {
7399
0
                    args->length = (word16)args->sigLen;
7400
7401
0
                    XMEMCPY(args->sigData,
7402
0
                        args->verify + HASH_SIG_SIZE + VERIFY_HEADER,
7403
0
                        args->sigLen);
7404
0
                }
7405
0
            }
7406
0
        #endif /* !NO_RSA */
7407
7408
            /* Check for error */
7409
0
            if (ret != 0) {
7410
0
                goto exit_scv;
7411
0
            }
7412
7413
            /* Add signature length. */
7414
0
            c16toa(args->length, args->verify + HASH_SIG_SIZE);
7415
7416
            /* Advance state and proceed */
7417
0
            ssl->options.asyncState = TLS_ASYNC_VERIFY;
7418
0
        } /* case TLS_ASYNC_DO */
7419
0
        FALL_THROUGH;
7420
7421
0
        case TLS_ASYNC_VERIFY:
7422
0
        {
7423
0
        #ifndef NO_RSA
7424
0
            if (ssl->hsType == DYNAMIC_TYPE_RSA) {
7425
                /* check for signature faults */
7426
0
                ret = VerifyRsaSign(ssl, args->sigData, args->sigLen,
7427
0
                    sig->buffer, (word32)sig->length, args->sigAlgo,
7428
0
                    ssl->suites->hashAlgo, (RsaKey*)ssl->hsKey,
7429
0
                    ssl->buffers.key
7430
0
                );
7431
0
            }
7432
0
        #endif /* !NO_RSA */
7433
7434
            /* Check for error */
7435
0
            if (ret != 0) {
7436
0
                goto exit_scv;
7437
0
            }
7438
7439
            /* Advance state and proceed */
7440
0
            ssl->options.asyncState = TLS_ASYNC_FINALIZE;
7441
0
        } /* case TLS_ASYNC_VERIFY */
7442
0
        FALL_THROUGH;
7443
7444
0
        case TLS_ASYNC_FINALIZE:
7445
0
        {
7446
            /* Put the record and handshake headers on. */
7447
0
            AddTls13Headers(args->output, args->length + HASH_SIG_SIZE +
7448
0
                            VERIFY_HEADER, certificate_verify, ssl);
7449
7450
0
            args->sendSz = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ +
7451
0
                                   args->length + HASH_SIG_SIZE + VERIFY_HEADER;
7452
#ifdef WOLFSSL_DTLS13
7453
            if (ssl->options.dtls)
7454
                args->sendSz += recordLayerHdrExtra + DTLS_HANDSHAKE_EXTRA;
7455
7456
#endif /* WOLFSSL_DTLS13 */
7457
            /* Advance state and proceed */
7458
0
            ssl->options.asyncState = TLS_ASYNC_END;
7459
0
        } /* case TLS_ASYNC_FINALIZE */
7460
0
        FALL_THROUGH;
7461
7462
0
        case TLS_ASYNC_END:
7463
0
        {
7464
#ifdef WOLFSSL_DTLS13
7465
            if (ssl->options.dtls) {
7466
                ssl->options.buildingMsg = 0;
7467
                ret = Dtls13HandshakeSend(ssl, args->output,
7468
                    MAX_CERT_VERIFY_SZ + MAX_MSG_EXTRA + MAX_MSG_EXTRA,
7469
                    args->sendSz, certificate_verify, 1);
7470
                if (ret != 0)
7471
                    goto exit_scv;
7472
7473
                break;
7474
            }
7475
#endif /* WOLFSSL_DTLS13 */
7476
7477
            /* This message is always encrypted. */
7478
0
            ret = BuildTls13Message(ssl, args->output,
7479
0
                                    MAX_CERT_VERIFY_SZ + MAX_MSG_EXTRA,
7480
0
                                    args->output + RECORD_HEADER_SZ,
7481
0
                                    args->sendSz - RECORD_HEADER_SZ, handshake,
7482
0
                                    1, 0, 0);
7483
7484
0
            if (ret < 0) {
7485
0
                goto exit_scv;
7486
0
            }
7487
0
            else {
7488
0
                args->sendSz = ret;
7489
0
                ret = 0;
7490
0
            }
7491
7492
        #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
7493
            if (ssl->hsInfoOn)
7494
                AddPacketName(ssl, "CertificateVerify");
7495
            if (ssl->toInfoOn) {
7496
                AddPacketInfo(ssl, "CertificateVerify", handshake,
7497
                            args->output, args->sendSz, WRITE_PROTO, ssl->heap);
7498
            }
7499
        #endif
7500
7501
0
            ssl->buffers.outputBuffer.length += args->sendSz;
7502
0
            ssl->options.buildingMsg = 0;
7503
0
            if (!ssl->options.groupMessages)
7504
0
                ret = SendBuffered(ssl);
7505
0
            break;
7506
0
        }
7507
0
        default:
7508
0
            ret = INPUT_CASE_ERROR;
7509
0
    } /* switch(ssl->options.asyncState) */
7510
7511
0
exit_scv:
7512
7513
0
    WOLFSSL_LEAVE("SendTls13CertificateVerify", ret);
7514
0
    WOLFSSL_END(WC_FUNC_CERTIFICATE_VERIFY_SEND);
7515
7516
#ifdef WOLFSSL_ASYNC_CRYPT
7517
    /* Handle async operation */
7518
    if (ret == WC_PENDING_E) {
7519
        return ret;
7520
    }
7521
#endif /* WOLFSSL_ASYNC_CRYPT */
7522
7523
    /* Final cleanup */
7524
0
    FreeScv13Args(ssl, args);
7525
0
    FreeKeyExchange(ssl);
7526
0
#ifdef WOLFSSL_ASYNC_IO
7527
    /* Cleanup async */
7528
0
    FreeAsyncCtx(ssl, 0);
7529
0
#endif
7530
7531
0
    if (ret != 0) {
7532
0
        WOLFSSL_ERROR_VERBOSE(ret);
7533
0
    }
7534
7535
0
    return ret;
7536
0
}
7537
#endif
7538
#endif /* !NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER */
7539
7540
#if !defined(NO_WOLFSSL_CLIENT) || !defined(WOLFSSL_NO_CLIENT_AUTH)
7541
/* handle processing TLS v1.3 certificate (11) */
7542
/* Parse and handle a TLS v1.3 Certificate message.
7543
 *
7544
 * ssl       The SSL/TLS object.
7545
 * input     The message buffer.
7546
 * inOutIdx  On entry, the index into the message buffer of Certificate.
7547
 *           On exit, the index of byte after the Certificate message.
7548
 * totalSz   The length of the current handshake message.
7549
 * returns 0 on success and otherwise failure.
7550
 */
7551
static int DoTls13Certificate(WOLFSSL* ssl, byte* input, word32* inOutIdx,
7552
                              word32 totalSz)
7553
0
{
7554
0
    int ret = 0;
7555
7556
0
    WOLFSSL_START(WC_FUNC_CERTIFICATE_DO);
7557
0
    WOLFSSL_ENTER("DoTls13Certificate");
7558
7559
#ifdef WOLFSSL_DTLS13
7560
    if (ssl->options.dtls && ssl->options.handShakeDone) {
7561
        /* certificate needs some special care after the handshake */
7562
        ret = Dtls13RtxProcessingCertificate(
7563
            ssl, input + *inOutIdx, totalSz);
7564
    }
7565
#endif /* WOLFSSL_DTLS13 */
7566
7567
0
    if (ret == 0)
7568
0
        ret = ProcessPeerCerts(ssl, input, inOutIdx, totalSz);
7569
0
    if (ret == 0) {
7570
0
#if !defined(NO_WOLFSSL_CLIENT)
7571
0
        if (ssl->options.side == WOLFSSL_CLIENT_END)
7572
0
            ssl->options.serverState = SERVER_CERT_COMPLETE;
7573
0
#endif
7574
#if !defined(NO_WOLFSSL_SERVER) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
7575
        if (ssl->options.side == WOLFSSL_SERVER_END &&
7576
                                ssl->options.handShakeState == HANDSHAKE_DONE) {
7577
            /* reset handshake states */
7578
            ssl->options.serverState = SERVER_FINISHED_COMPLETE;
7579
            ssl->options.acceptState  = TICKET_SENT;
7580
            ssl->options.handShakeState = SERVER_FINISHED_COMPLETE;
7581
        }
7582
#endif
7583
0
    }
7584
7585
0
    WOLFSSL_LEAVE("DoTls13Certificate", ret);
7586
0
    WOLFSSL_END(WC_FUNC_CERTIFICATE_DO);
7587
7588
0
    return ret;
7589
0
}
7590
#endif
7591
7592
#if !defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
7593
                                                             defined(HAVE_ED448)
7594
7595
typedef struct Dcv13Args {
7596
    byte*  output; /* not allocated */
7597
    word32 sendSz;
7598
    word16 sz;
7599
    word32 sigSz;
7600
    word32 idx;
7601
    word32 begin;
7602
    byte   hashAlgo;
7603
    byte   sigAlgo;
7604
7605
    byte*  sigData;
7606
    word16 sigDataSz;
7607
} Dcv13Args;
7608
7609
static void FreeDcv13Args(WOLFSSL* ssl, void* pArgs)
7610
0
{
7611
0
    Dcv13Args* args = (Dcv13Args*)pArgs;
7612
7613
0
    if (args && args->sigData != NULL) {
7614
0
        XFREE(args->sigData, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
7615
0
        args->sigData = NULL;
7616
0
    }
7617
7618
0
    (void)ssl;
7619
0
}
7620
7621
/* handle processing TLS v1.3 certificate_verify (15) */
7622
/* Parse and handle a TLS v1.3 CertificateVerify message.
7623
 *
7624
 * ssl       The SSL/TLS object.
7625
 * input     The message buffer.
7626
 * inOutIdx  On entry, the index into the message buffer of
7627
 *           CertificateVerify.
7628
 *           On exit, the index of byte after the CertificateVerify message.
7629
 * totalSz   The length of the current handshake message.
7630
 * returns 0 on success and otherwise failure.
7631
 */
7632
static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input,
7633
                                    word32* inOutIdx, word32 totalSz)
7634
0
{
7635
0
    int         ret = 0;
7636
0
    buffer*     sig = &ssl->buffers.sig;
7637
#ifdef WOLFSSL_ASYNC_CRYPT
7638
    Dcv13Args* args = NULL;
7639
    WOLFSSL_ASSERT_SIZEOF_GE(ssl->async->args, *args);
7640
#else
7641
0
    Dcv13Args  args[1];
7642
0
#endif
7643
7644
0
    WOLFSSL_START(WC_FUNC_CERTIFICATE_VERIFY_DO);
7645
0
    WOLFSSL_ENTER("DoTls13CertificateVerify");
7646
7647
#if defined(WOLFSSL_RENESAS_TSIP_TLS) && (WOLFSSL_RENESAS_TSIP_VER >= 115)
7648
    ret = tsip_Tls13CertificateVerify(ssl, input, inOutIdx, totalSz);
7649
    if (ret != CRYPTOCB_UNAVAILABLE) {
7650
        goto exit_dcv;
7651
    }
7652
    ret = 0;
7653
#endif
7654
7655
#ifdef WOLFSSL_ASYNC_CRYPT
7656
    if (ssl->async == NULL) {
7657
        ssl->async = (struct WOLFSSL_ASYNC*)
7658
                XMALLOC(sizeof(struct WOLFSSL_ASYNC), ssl->heap,
7659
                        DYNAMIC_TYPE_ASYNC);
7660
        if (ssl->async == NULL)
7661
            ERROR_OUT(MEMORY_E, exit_dcv);
7662
    }
7663
    args = (Dcv13Args*)ssl->async->args;
7664
7665
    ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
7666
    if (ret != WC_NOT_PENDING_E) {
7667
        /* Check for error */
7668
        if (ret < 0)
7669
            goto exit_dcv;
7670
    }
7671
    else
7672
#endif
7673
0
    {
7674
        /* Reset state */
7675
0
        ret = 0;
7676
0
        ssl->options.asyncState = TLS_ASYNC_BEGIN;
7677
0
        XMEMSET(args, 0, sizeof(Dcv13Args));
7678
0
        args->hashAlgo = sha_mac;
7679
0
        args->sigAlgo = anonymous_sa_algo;
7680
0
        args->idx = *inOutIdx;
7681
0
        args->begin = *inOutIdx;
7682
    #ifdef WOLFSSL_ASYNC_CRYPT
7683
        ssl->async->freeArgs = FreeDcv13Args;
7684
    #endif
7685
0
    }
7686
7687
0
    switch(ssl->options.asyncState)
7688
0
    {
7689
0
        case TLS_ASYNC_BEGIN:
7690
0
        {
7691
        #ifdef WOLFSSL_CALLBACKS
7692
            if (ssl->hsInfoOn) AddPacketName(ssl, "CertificateVerify");
7693
            if (ssl->toInfoOn) AddLateName("CertificateVerify",
7694
                                           &ssl->timeoutInfo);
7695
        #endif
7696
7697
            /* Advance state and proceed */
7698
0
            ssl->options.asyncState = TLS_ASYNC_BUILD;
7699
0
        } /* case TLS_ASYNC_BEGIN */
7700
0
        FALL_THROUGH;
7701
7702
0
        case TLS_ASYNC_BUILD:
7703
0
        {
7704
0
            int validSigAlgo;
7705
7706
            /* Signature algorithm. */
7707
0
            if ((args->idx - args->begin) + ENUM_LEN + ENUM_LEN > totalSz) {
7708
0
                ERROR_OUT(BUFFER_ERROR, exit_dcv);
7709
0
            }
7710
0
            ret = DecodeTls13SigAlg(input + args->idx, &args->hashAlgo,
7711
0
                                                                &args->sigAlgo);
7712
0
            if (ret < 0)
7713
0
                goto exit_dcv;
7714
0
            args->idx += OPAQUE16_LEN;
7715
7716
            /* Signature length. */
7717
0
            if ((args->idx - args->begin) + OPAQUE16_LEN > totalSz) {
7718
0
                ERROR_OUT(BUFFER_ERROR, exit_dcv);
7719
0
            }
7720
0
            ato16(input + args->idx, &args->sz);
7721
0
            args->idx += OPAQUE16_LEN;
7722
7723
            /* Signature data. */
7724
0
            if ((args->idx - args->begin) + args->sz > totalSz ||
7725
0
                                                       args->sz > ENCRYPT_LEN) {
7726
0
                ERROR_OUT(BUFFER_ERROR, exit_dcv);
7727
0
            }
7728
7729
            /* Check for public key of required type. */
7730
            /* Assume invalid unless signature algo matches the key provided */
7731
0
            validSigAlgo = 0;
7732
0
        #ifdef HAVE_ED25519
7733
0
            if (args->sigAlgo == ed25519_sa_algo) {
7734
0
                WOLFSSL_MSG("Peer sent ED25519 sig");
7735
0
                validSigAlgo = (ssl->peerEd25519Key != NULL) &&
7736
0
                                                     ssl->peerEd25519KeyPresent;
7737
0
            }
7738
0
        #endif
7739
0
        #ifdef HAVE_ED448
7740
0
            if (args->sigAlgo == ed448_sa_algo) {
7741
0
                WOLFSSL_MSG("Peer sent ED448 sig");
7742
0
                validSigAlgo = (ssl->peerEd448Key != NULL) &&
7743
0
                                                       ssl->peerEd448KeyPresent;
7744
0
            }
7745
0
        #endif
7746
0
        #ifdef HAVE_ECC
7747
0
            if (args->sigAlgo == ecc_dsa_sa_algo) {
7748
0
                WOLFSSL_MSG("Peer sent ECC sig");
7749
0
                validSigAlgo = (ssl->peerEccDsaKey != NULL) &&
7750
0
                                                      ssl->peerEccDsaKeyPresent;
7751
0
            }
7752
0
        #endif
7753
        #ifdef HAVE_PQC
7754
            if (args->sigAlgo == falcon_level1_sa_algo) {
7755
                WOLFSSL_MSG("Peer sent Falcon Level 1 sig");
7756
                validSigAlgo = (ssl->peerFalconKey != NULL) &&
7757
                               ssl->peerFalconKeyPresent;
7758
            }
7759
            if (args->sigAlgo == falcon_level5_sa_algo) {
7760
                WOLFSSL_MSG("Peer sent Falcon Level 5 sig");
7761
                validSigAlgo = (ssl->peerFalconKey != NULL) &&
7762
                               ssl->peerFalconKeyPresent;
7763
            }
7764
            if (args->sigAlgo == dilithium_level2_sa_algo) {
7765
                WOLFSSL_MSG("Peer sent Dilithium Level 2 sig");
7766
                validSigAlgo = (ssl->peerDilithiumKey != NULL) &&
7767
                               ssl->peerDilithiumKeyPresent;
7768
            }
7769
            if (args->sigAlgo == dilithium_level3_sa_algo) {
7770
                WOLFSSL_MSG("Peer sent Dilithium Level 3 sig");
7771
                validSigAlgo = (ssl->peerDilithiumKey != NULL) &&
7772
                               ssl->peerDilithiumKeyPresent;
7773
            }
7774
            if (args->sigAlgo == dilithium_level5_sa_algo) {
7775
                WOLFSSL_MSG("Peer sent Dilithium Level 5 sig");
7776
                validSigAlgo = (ssl->peerDilithiumKey != NULL) &&
7777
                               ssl->peerDilithiumKeyPresent;
7778
            }
7779
            if (args->sigAlgo == dilithium_aes_level2_sa_algo) {
7780
                WOLFSSL_MSG("Peer sent Dilithium AES Level 2 sig");
7781
                validSigAlgo = (ssl->peerDilithiumKey != NULL) &&
7782
                               ssl->peerDilithiumKeyPresent;
7783
            }
7784
            if (args->sigAlgo == dilithium_aes_level3_sa_algo) {
7785
                WOLFSSL_MSG("Peer sent Dilithium AES Level 3 sig");
7786
                validSigAlgo = (ssl->peerDilithiumKey != NULL) &&
7787
                               ssl->peerDilithiumKeyPresent;
7788
            }
7789
            if (args->sigAlgo == dilithium_aes_level5_sa_algo) {
7790
                WOLFSSL_MSG("Peer sent Dilithium AES Level 5 sig");
7791
                validSigAlgo = (ssl->peerDilithiumKey != NULL) &&
7792
                               ssl->peerDilithiumKeyPresent;
7793
            }
7794
        #endif
7795
0
        #ifndef NO_RSA
7796
0
            if (args->sigAlgo == rsa_sa_algo) {
7797
0
                WOLFSSL_MSG("Peer sent PKCS#1.5 algo - not valid TLS 1.3");
7798
0
                ERROR_OUT(INVALID_PARAMETER, exit_dcv);
7799
0
            }
7800
0
            if (args->sigAlgo == rsa_pss_sa_algo) {
7801
0
                WOLFSSL_MSG("Peer sent RSA sig");
7802
0
                validSigAlgo = (ssl->peerRsaKey != NULL) &&
7803
0
                                                         ssl->peerRsaKeyPresent;
7804
0
            }
7805
0
        #endif
7806
0
            if (!validSigAlgo) {
7807
0
                WOLFSSL_MSG("Sig algo doesn't correspond to certficate");
7808
0
                ERROR_OUT(SIG_VERIFY_E, exit_dcv);
7809
0
            }
7810
7811
0
            sig->buffer = (byte*)XMALLOC(args->sz, ssl->heap,
7812
0
                                         DYNAMIC_TYPE_SIGNATURE);
7813
0
            if (sig->buffer == NULL) {
7814
0
                ERROR_OUT(MEMORY_E, exit_dcv);
7815
0
            }
7816
0
            sig->length = args->sz;
7817
0
            XMEMCPY(sig->buffer, input + args->idx, args->sz);
7818
7819
0
        #ifdef HAVE_ECC
7820
0
            if (ssl->peerEccDsaKeyPresent) {
7821
0
                WOLFSSL_MSG("Doing ECC peer cert verify");
7822
7823
0
                args->sigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap,
7824
0
                                                        DYNAMIC_TYPE_SIGNATURE);
7825
0
                if (args->sigData == NULL) {
7826
0
                    ERROR_OUT(MEMORY_E, exit_dcv);
7827
0
                }
7828
7829
0
                ret = CreateSigData(ssl, args->sigData, &args->sigDataSz, 1);
7830
0
                if (ret != 0)
7831
0
                    goto exit_dcv;
7832
0
                ret = CreateECCEncodedSig(args->sigData,
7833
0
                    args->sigDataSz, args->hashAlgo);
7834
0
                if (ret < 0)
7835
0
                    goto exit_dcv;
7836
0
                args->sigDataSz = (word16)ret;
7837
0
                ret = 0;
7838
0
            }
7839
0
        #endif
7840
0
        #ifdef HAVE_ED25519
7841
0
            if (ssl->peerEd25519KeyPresent) {
7842
0
                WOLFSSL_MSG("Doing ED25519 peer cert verify");
7843
7844
0
                args->sigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap,
7845
0
                                                        DYNAMIC_TYPE_SIGNATURE);
7846
0
                if (args->sigData == NULL) {
7847
0
                    ERROR_OUT(MEMORY_E, exit_dcv);
7848
0
                }
7849
7850
0
                CreateSigData(ssl, args->sigData, &args->sigDataSz, 1);
7851
0
                ret = 0;
7852
0
            }
7853
0
        #endif
7854
0
        #ifdef HAVE_ED448
7855
0
            if (ssl->peerEd448KeyPresent) {
7856
0
                WOLFSSL_MSG("Doing ED448 peer cert verify");
7857
7858
0
                args->sigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap,
7859
0
                                                        DYNAMIC_TYPE_SIGNATURE);
7860
0
                if (args->sigData == NULL) {
7861
0
                    ERROR_OUT(MEMORY_E, exit_dcv);
7862
0
                }
7863
7864
0
                CreateSigData(ssl, args->sigData, &args->sigDataSz, 1);
7865
0
                ret = 0;
7866
0
            }
7867
0
       #endif
7868
       #ifdef HAVE_PQC
7869
            if (ssl->peerFalconKeyPresent) {
7870
                WOLFSSL_MSG("Doing Falcon peer cert verify");
7871
7872
                args->sigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap,
7873
                                                        DYNAMIC_TYPE_SIGNATURE);
7874
                if (args->sigData == NULL) {
7875
                    ERROR_OUT(MEMORY_E, exit_dcv);
7876
                }
7877
7878
                CreateSigData(ssl, args->sigData, &args->sigDataSz, 1);
7879
                ret = 0;
7880
            }
7881
7882
            if (ssl->peerDilithiumKeyPresent) {
7883
                WOLFSSL_MSG("Doing Dilithium peer cert verify");
7884
7885
                args->sigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap,
7886
                                                        DYNAMIC_TYPE_SIGNATURE);
7887
                if (args->sigData == NULL) {
7888
                    ERROR_OUT(MEMORY_E, exit_dcv);
7889
                }
7890
7891
                CreateSigData(ssl, args->sigData, &args->sigDataSz, 1);
7892
                ret = 0;
7893
            }
7894
       #endif
7895
7896
            /* Advance state and proceed */
7897
0
            ssl->options.asyncState = TLS_ASYNC_DO;
7898
0
        } /* case TLS_ASYNC_BUILD */
7899
0
        FALL_THROUGH;
7900
7901
0
        case TLS_ASYNC_DO:
7902
0
        {
7903
0
        #ifndef NO_RSA
7904
0
            if (ssl->peerRsaKey != NULL && ssl->peerRsaKeyPresent != 0) {
7905
0
                ret = RsaVerify(ssl, sig->buffer, (word32)sig->length, &args->output,
7906
0
                    args->sigAlgo, args->hashAlgo, ssl->peerRsaKey,
7907
                #ifdef HAVE_PK_CALLBACKS
7908
                    &ssl->buffers.peerRsaKey
7909
                #else
7910
0
                    NULL
7911
0
                #endif
7912
0
                );
7913
0
                if (ret >= 0) {
7914
0
                    args->sendSz = ret;
7915
0
                    ret = 0;
7916
0
                }
7917
0
            }
7918
0
        #endif /* !NO_RSA */
7919
0
        #ifdef HAVE_ECC
7920
0
            if (ssl->peerEccDsaKeyPresent) {
7921
0
                ret = EccVerify(ssl, input + args->idx, args->sz,
7922
0
                    args->sigData, args->sigDataSz,
7923
0
                    ssl->peerEccDsaKey,
7924
                #ifdef HAVE_PK_CALLBACKS
7925
                    &ssl->buffers.peerEccDsaKey
7926
                #else
7927
0
                    NULL
7928
0
                #endif
7929
0
                );
7930
7931
0
                if (ret >= 0) {
7932
                    /* CLIENT/SERVER: data verified with public key from
7933
                     * certificate. */
7934
0
                    ssl->options.peerAuthGood = 1;
7935
0
                    FreeKey(ssl, DYNAMIC_TYPE_ECC, (void**)&ssl->peerEccDsaKey);
7936
0
                    ssl->peerEccDsaKeyPresent = 0;
7937
0
                }
7938
0
            }
7939
0
        #endif /* HAVE_ECC */
7940
0
        #ifdef HAVE_ED25519
7941
0
            if (ssl->peerEd25519KeyPresent) {
7942
0
                ret = Ed25519Verify(ssl, input + args->idx, args->sz,
7943
0
                    args->sigData, args->sigDataSz,
7944
0
                    ssl->peerEd25519Key,
7945
                #ifdef HAVE_PK_CALLBACKS
7946
                    &ssl->buffers.peerEd25519Key
7947
                #else
7948
0
                    NULL
7949
0
                #endif
7950
0
                );
7951
7952
0
                if (ret >= 0) {
7953
                    /* CLIENT/SERVER: data verified with public key from
7954
                     * certificate. */
7955
0
                    ssl->options.peerAuthGood = 1;
7956
0
                    FreeKey(ssl, DYNAMIC_TYPE_ED25519,
7957
0
                                                  (void**)&ssl->peerEd25519Key);
7958
0
                    ssl->peerEd25519KeyPresent = 0;
7959
0
                }
7960
0
            }
7961
0
        #endif
7962
0
        #ifdef HAVE_ED448
7963
0
            if (ssl->peerEd448KeyPresent) {
7964
0
                ret = Ed448Verify(ssl, input + args->idx, args->sz,
7965
0
                    args->sigData, args->sigDataSz,
7966
0
                    ssl->peerEd448Key,
7967
                #ifdef HAVE_PK_CALLBACKS
7968
                    &ssl->buffers.peerEd448Key
7969
                #else
7970
0
                    NULL
7971
0
                #endif
7972
0
                );
7973
7974
0
                if (ret >= 0) {
7975
                    /* CLIENT/SERVER: data verified with public key from
7976
                     * certificate. */
7977
0
                    ssl->options.peerAuthGood = 1;
7978
0
                    FreeKey(ssl, DYNAMIC_TYPE_ED448,
7979
0
                                                    (void**)&ssl->peerEd448Key);
7980
0
                    ssl->peerEd448KeyPresent = 0;
7981
0
                }
7982
0
            }
7983
0
        #endif
7984
        #if defined(HAVE_PQC) && defined(HAVE_FALCON)
7985
            if (ssl->peerFalconKeyPresent) {
7986
                int res = 0;
7987
                WOLFSSL_MSG("Doing Falcon peer cert verify");
7988
                ret = wc_falcon_verify_msg(input + args->idx, args->sz,
7989
                                    args->sigData, args->sigDataSz,
7990
                                    &res, ssl->peerFalconKey);
7991
7992
                if ((ret >= 0) && (res == 1)) {
7993
                    /* CLIENT/SERVER: data verified with public key from
7994
                     * certificate. */
7995
                    ssl->options.peerAuthGood = 1;
7996
                    FreeKey(ssl, DYNAMIC_TYPE_FALCON,
7997
                                                   (void**)&ssl->peerFalconKey);
7998
                    ssl->peerFalconKeyPresent = 0;
7999
                }
8000
            }
8001
        #endif /* HAVE_PQC && HAVE_FALCON */
8002
        #if defined(HAVE_PQC) && defined(HAVE_DILITHIUM)
8003
            if (ssl->peerDilithiumKeyPresent) {
8004
                int res = 0;
8005
                WOLFSSL_MSG("Doing Dilithium peer cert verify");
8006
                ret = wc_dilithium_verify_msg(input + args->idx, args->sz,
8007
                                              args->sigData, args->sigDataSz,
8008
                                              &res, ssl->peerDilithiumKey);
8009
8010
                if ((ret >= 0) && (res == 1)) {
8011
                    /* CLIENT/SERVER: data verified with public key from
8012
                     * certificate. */
8013
                    ssl->options.peerAuthGood = 1;
8014
                    FreeKey(ssl, DYNAMIC_TYPE_DILITHIUM,
8015
                            (void**)&ssl->peerDilithiumKey);
8016
                    ssl->peerDilithiumKeyPresent = 0;
8017
                }
8018
            }
8019
        #endif /* HAVE_PQC && HAVE_DILITHIUM */
8020
8021
            /* Check for error */
8022
0
            if (ret != 0) {
8023
0
                goto exit_dcv;
8024
0
            }
8025
8026
            /* Advance state and proceed */
8027
0
            ssl->options.asyncState = TLS_ASYNC_VERIFY;
8028
0
        } /* case TLS_ASYNC_DO */
8029
0
        FALL_THROUGH;
8030
8031
0
        case TLS_ASYNC_VERIFY:
8032
0
        {
8033
0
        #if !defined(NO_RSA) && defined(WC_RSA_PSS)
8034
0
            if (ssl->peerRsaKey != NULL && ssl->peerRsaKeyPresent != 0) {
8035
0
                ret = CheckRSASignature(ssl, args->sigAlgo, args->hashAlgo,
8036
0
                                        args->output, args->sendSz);
8037
0
                if (ret != 0)
8038
0
                    goto exit_dcv;
8039
8040
                /* CLIENT/SERVER: data verified with public key from
8041
                 * certificate. */
8042
0
                ssl->peerRsaKeyPresent = 0;
8043
0
                FreeKey(ssl, DYNAMIC_TYPE_RSA, (void**)&ssl->peerRsaKey);
8044
0
                ssl->options.peerAuthGood = 1;
8045
0
            }
8046
0
        #endif /* !NO_RSA && WC_RSA_PSS */
8047
8048
            /* Advance state and proceed */
8049
0
            ssl->options.asyncState = TLS_ASYNC_FINALIZE;
8050
0
        } /* case TLS_ASYNC_VERIFY */
8051
0
        FALL_THROUGH;
8052
8053
0
        case TLS_ASYNC_FINALIZE:
8054
0
        {
8055
0
            ssl->options.havePeerVerify = 1;
8056
8057
            /* Set final index */
8058
0
            args->idx += args->sz;
8059
0
            *inOutIdx = args->idx;
8060
8061
            /* Encryption is always on: add padding */
8062
0
            *inOutIdx += ssl->keys.padSz;
8063
8064
            /* Advance state and proceed */
8065
0
            ssl->options.asyncState = TLS_ASYNC_END;
8066
8067
0
        #if !defined(NO_WOLFSSL_CLIENT)
8068
0
            if (ssl->options.side == WOLFSSL_CLIENT_END)
8069
0
                ssl->options.serverState = SERVER_CERT_VERIFY_COMPLETE;
8070
0
        #endif
8071
0
        } /* case TLS_ASYNC_FINALIZE */
8072
0
        FALL_THROUGH;
8073
8074
0
        case TLS_ASYNC_END:
8075
0
        {
8076
0
            break;
8077
0
        }
8078
8079
0
        default:
8080
0
            ret = INPUT_CASE_ERROR;
8081
0
    } /* switch(ssl->options.asyncState) */
8082
8083
0
exit_dcv:
8084
8085
0
    WOLFSSL_LEAVE("DoTls13CertificateVerify", ret);
8086
0
    WOLFSSL_END(WC_FUNC_CERTIFICATE_VERIFY_DO);
8087
8088
#ifdef WOLFSSL_ASYNC_CRYPT
8089
    /* Handle async operation */
8090
    if (ret == WC_PENDING_E) {
8091
        /* Mark message as not received so it can process again */
8092
        ssl->msgsReceived.got_certificate_verify = 0;
8093
8094
        return ret;
8095
    }
8096
    else
8097
#endif /* WOLFSSL_ASYNC_CRYPT */
8098
0
    if (ret != 0) {
8099
0
        WOLFSSL_ERROR_VERBOSE(ret);
8100
8101
0
        if (ret != INVALID_PARAMETER) {
8102
0
            SendAlert(ssl, alert_fatal, decrypt_error);
8103
0
        }
8104
0
    }
8105
8106
    /* Final cleanup */
8107
0
    FreeDcv13Args(ssl, args);
8108
0
    FreeKeyExchange(ssl);
8109
0
#ifdef WOLFSSL_ASYNC_IO
8110
    /* Cleanup async */
8111
0
    FreeAsyncCtx(ssl, 0);
8112
0
#endif
8113
8114
0
    return ret;
8115
0
}
8116
#endif /* !NO_RSA || HAVE_ECC */
8117
#endif /* !NO_CERTS */
8118
8119
/* Parse and handle a TLS v1.3 Finished message.
8120
 *
8121
 * ssl       The SSL/TLS object.
8122
 * input     The message buffer.
8123
 * inOutIdx  On entry, the index into the message buffer of Finished.
8124
 *           On exit, the index of byte after the Finished message and padding.
8125
 * size      Length of message data.
8126
 * totalSz   Length of remaining data in the message buffer.
8127
 * sniff     Indicates whether we are sniffing packets.
8128
 * returns 0 on success and otherwise failure.
8129
 */
8130
int DoTls13Finished(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
8131
                           word32 size, word32 totalSz, int sniff)
8132
0
{
8133
0
    int    ret;
8134
0
    word32 finishedSz = 0;
8135
0
    byte*  secret;
8136
0
    byte   mac[WC_MAX_DIGEST_SIZE];
8137
8138
0
    WOLFSSL_START(WC_FUNC_FINISHED_DO);
8139
0
    WOLFSSL_ENTER("DoTls13Finished");
8140
8141
0
#if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CLIENT_AUTH)
8142
    /* verify the client sent certificate if required */
8143
0
    if (ssl->options.side == WOLFSSL_SERVER_END && !ssl->options.resuming &&
8144
0
            (ssl->options.mutualAuth || ssl->options.failNoCert)) {
8145
#ifdef OPENSSL_COMPATIBLE_DEFAULTS
8146
        if (ssl->options.isPSK) {
8147
            WOLFSSL_MSG("TLS v1.3 client used PSK but cert required. Allowing "
8148
                        "for OpenSSL compatibility");
8149
        }
8150
        else
8151
#endif
8152
0
        if (!ssl->options.havePeerCert || !ssl->options.havePeerVerify) {
8153
0
            ret = NO_PEER_CERT; /* NO_PEER_VERIFY */
8154
0
            WOLFSSL_MSG("TLS v1.3 client did not present peer cert");
8155
0
            DoCertFatalAlert(ssl, ret);
8156
0
            return ret;
8157
0
        }
8158
0
    }
8159
0
#endif
8160
8161
    /* check against totalSz */
8162
0
    if (*inOutIdx + size > totalSz)
8163
0
        return BUFFER_E;
8164
8165
#if defined(WOLFSSL_RENESAS_TSIP_TLS) && (WOLFSSL_RENESAS_TSIP_VER >= 115)
8166
    ret = tsip_Tls13HandleFinished(ssl, input, inOutIdx, size, totalSz);
8167
    if (ret == 0) {
8168
        ssl->options.serverState = SERVER_FINISHED_COMPLETE;
8169
        return ret;
8170
    }
8171
    if (ret == VERIFY_FINISHED_ERROR) {
8172
        SendAlert(ssl, alert_fatal, decrypt_error);
8173
        return ret;
8174
    }
8175
    if (ret != CRYPTOCB_UNAVAILABLE) {
8176
        /* other errors */
8177
        return ret;
8178
    }
8179
    ret = 0;
8180
#endif /* WOLFSSL_RENESAS_TSIP_TLS &&  WOLFSSL_RENESAS_TSIP_VER >= 115 */
8181
8182
0
    if (ssl->options.handShakeDone) {
8183
0
        ret = DeriveFinishedSecret(ssl, ssl->clientSecret,
8184
0
                                   ssl->keys.client_write_MAC_secret);
8185
0
        if (ret != 0)
8186
0
            return ret;
8187
8188
0
        secret = ssl->keys.client_write_MAC_secret;
8189
0
    }
8190
0
    else if (ssl->options.side == WOLFSSL_CLIENT_END) {
8191
        /* All the handshake messages have been received to calculate
8192
         * client and server finished keys.
8193
         */
8194
0
        ret = DeriveFinishedSecret(ssl, ssl->clientSecret,
8195
0
                                   ssl->keys.client_write_MAC_secret);
8196
0
        if (ret != 0)
8197
0
            return ret;
8198
8199
0
        ret = DeriveFinishedSecret(ssl, ssl->serverSecret,
8200
0
                                   ssl->keys.server_write_MAC_secret);
8201
0
        if (ret != 0)
8202
0
            return ret;
8203
8204
0
        secret = ssl->keys.server_write_MAC_secret;
8205
0
    }
8206
0
    else {
8207
0
        secret = ssl->keys.client_write_MAC_secret;
8208
0
    }
8209
8210
0
    if (sniff == NO_SNIFF) {
8211
0
        ret = BuildTls13HandshakeHmac(ssl, secret, mac, &finishedSz);
8212
    #ifdef WOLFSSL_HAVE_TLS_UNIQUE
8213
        if (ssl->options.side == WOLFSSL_CLIENT_END) {
8214
            XMEMCPY(ssl->serverFinished, mac, finishedSz);
8215
            ssl->serverFinished_len = finishedSz;
8216
        }
8217
        else {
8218
            XMEMCPY(ssl->clientFinished, mac, finishedSz);
8219
            ssl->clientFinished_len = finishedSz;
8220
        }
8221
    #endif /* WOLFSSL_HAVE_TLS_UNIQUE */
8222
0
        if (ret != 0)
8223
0
            return ret;
8224
0
        if (size != finishedSz)
8225
0
            return BUFFER_ERROR;
8226
0
    }
8227
8228
#ifdef WOLFSSL_CALLBACKS
8229
    if (ssl->hsInfoOn) AddPacketName(ssl, "Finished");
8230
    if (ssl->toInfoOn) AddLateName("Finished", &ssl->timeoutInfo);
8231
#endif
8232
8233
0
    if (sniff == NO_SNIFF) {
8234
        /* Actually check verify data. */
8235
0
        if (XMEMCMP(input + *inOutIdx, mac, size) != 0){
8236
0
            WOLFSSL_MSG("Verify finished error on hashes");
8237
0
            SendAlert(ssl, alert_fatal, decrypt_error);
8238
0
            WOLFSSL_ERROR_VERBOSE(VERIFY_FINISHED_ERROR);
8239
0
            return VERIFY_FINISHED_ERROR;
8240
0
        }
8241
0
    }
8242
8243
    /* Force input exhaustion at ProcessReply by consuming padSz. */
8244
0
    *inOutIdx += size + ssl->keys.padSz;
8245
8246
0
    if (ssl->options.side == WOLFSSL_SERVER_END &&
8247
0
                                                  !ssl->options.handShakeDone) {
8248
#ifdef WOLFSSL_EARLY_DATA
8249
        if (ssl->earlyData != no_early_data) {
8250
            if ((ret = DeriveTls13Keys(ssl, no_key, DECRYPT_SIDE_ONLY, 1)) != 0)
8251
                return ret;
8252
        }
8253
#endif
8254
        /* Setup keys for application data messages from client. */
8255
0
        if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0)
8256
0
            return ret;
8257
0
    }
8258
8259
0
#ifndef NO_WOLFSSL_CLIENT
8260
0
    if (ssl->options.side == WOLFSSL_CLIENT_END)
8261
0
        ssl->options.serverState = SERVER_FINISHED_COMPLETE;
8262
0
#endif
8263
0
#ifndef NO_WOLFSSL_SERVER
8264
0
    if (ssl->options.side == WOLFSSL_SERVER_END) {
8265
0
        ssl->options.clientState = CLIENT_FINISHED_COMPLETE;
8266
0
        ssl->options.handShakeState = HANDSHAKE_DONE;
8267
0
        ssl->options.handShakeDone  = 1;
8268
0
    }
8269
0
#endif
8270
8271
#if defined(WOLFSSL_DTLS13) && defined(WOLFSSL_EARLY_DATA)
8272
    if (ssl->options.dtls && ssl->earlyData > early_data_ext) {
8273
        /* DTLSv1.3 has no EndOfearlydata messages. We stop processing EarlyData
8274
           as soon we receive the client's finished message */
8275
        ssl->earlyData = done_early_data;
8276
    }
8277
#endif /* WOLFSSL_DTLS13 && WOLFSSL_EARLY_DATA */
8278
#if defined(WOLFSSL_QUIC) && defined(WOLFSSL_EARLY_DATA)
8279
    if (WOLFSSL_IS_QUIC(ssl) && ssl->earlyData > early_data_ext) {
8280
        /* QUIC has no EndOfEarlyData messages. We stop processing EarlyData
8281
           as soon we receive the client's finished message */
8282
        ssl->earlyData = done_early_data;
8283
    }
8284
#endif /* WOLFSSL_QUIC && WOLFSSL_EARLY_DATA */
8285
8286
0
    WOLFSSL_LEAVE("DoTls13Finished", 0);
8287
0
    WOLFSSL_END(WC_FUNC_FINISHED_DO);
8288
8289
0
    return 0;
8290
0
}
8291
8292
#if !defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER)
8293
/* Send the TLS v1.3 Finished message.
8294
 *
8295
 * ssl  The SSL/TLS object.
8296
 * returns 0 on success, otherwise failure.
8297
 */
8298
static int SendTls13Finished(WOLFSSL* ssl)
8299
0
{
8300
0
    int   sendSz;
8301
0
    int   finishedSz = ssl->specs.hash_size;
8302
0
    byte* input;
8303
0
    byte* output;
8304
0
    int   ret;
8305
0
    int   headerSz = HANDSHAKE_HEADER_SZ;
8306
0
    int   outputSz;
8307
0
    byte* secret;
8308
8309
#ifdef WOLFSSL_DTLS13
8310
    int dtlsRet = 0, isDtls = 0;
8311
#endif /* WOLFSSL_DTLS13 */
8312
8313
0
    WOLFSSL_START(WC_FUNC_FINISHED_SEND);
8314
0
    WOLFSSL_ENTER("SendTls13Finished");
8315
8316
0
    ssl->options.buildingMsg = 1;
8317
#ifdef WOLFSSL_DTLS13
8318
    if (ssl->options.dtls) {
8319
        headerSz = DTLS_HANDSHAKE_HEADER_SZ;
8320
        /* using isDtls instead of ssl->options.dtls will abide clang static
8321
           analyzer on unsing an uninitialized value */
8322
        isDtls = 1;
8323
    }
8324
#endif /* WOLFSSL_DTLS13 */
8325
8326
0
    outputSz = WC_MAX_DIGEST_SIZE + DTLS_HANDSHAKE_HEADER_SZ + MAX_MSG_EXTRA;
8327
    /* Check buffers are big enough and grow if needed. */
8328
0
    if ((ret = CheckAvailableSize(ssl, outputSz)) != 0)
8329
0
        return ret;
8330
8331
    /* get output buffer */
8332
0
    output = ssl->buffers.outputBuffer.buffer +
8333
0
             ssl->buffers.outputBuffer.length;
8334
0
    input = output + RECORD_HEADER_SZ;
8335
8336
#ifdef WOLFSSL_DTLS13
8337
    if (isDtls)
8338
        input = output + Dtls13GetRlHeaderLength(ssl, 1);
8339
#endif /* WOLFSSL_DTLS13 */
8340
8341
0
    AddTls13HandShakeHeader(input, finishedSz, 0, finishedSz, finished, ssl);
8342
8343
#if defined(WOLFSSL_RENESAS_TSIP_TLS) && (WOLFSSL_RENESAS_TSIP_VER >= 115)
8344
    if (ssl->options.side == WOLFSSL_CLIENT_END) {
8345
        ret = tsip_Tls13SendFinished(ssl, output, outputSz, input, 1);
8346
        if (ret != CRYPTOCB_UNAVAILABLE) {
8347
            return ret;
8348
        }
8349
        ret = 0;
8350
    }
8351
#endif /* WOLFSSL_RENESAS_TSIP_TLS &&  WOLFSSL_RENESAS_TSIP_VER >= 115 */
8352
8353
    /* make finished hashes */
8354
0
    if (ssl->options.handShakeDone) {
8355
0
        ret = DeriveFinishedSecret(ssl, ssl->clientSecret,
8356
0
                                   ssl->keys.client_write_MAC_secret);
8357
0
        if (ret != 0)
8358
0
            return ret;
8359
8360
0
        secret = ssl->keys.client_write_MAC_secret;
8361
0
    }
8362
0
    else if (ssl->options.side == WOLFSSL_CLIENT_END)
8363
0
        secret = ssl->keys.client_write_MAC_secret;
8364
0
    else {
8365
        /* All the handshake messages have been done to calculate client and
8366
         * server finished keys.
8367
         */
8368
0
        ret = DeriveFinishedSecret(ssl, ssl->clientSecret,
8369
0
                                   ssl->keys.client_write_MAC_secret);
8370
0
        if (ret != 0)
8371
0
            return ret;
8372
8373
0
        ret = DeriveFinishedSecret(ssl, ssl->serverSecret,
8374
0
                                   ssl->keys.server_write_MAC_secret);
8375
0
        if (ret != 0)
8376
0
            return ret;
8377
8378
0
        secret = ssl->keys.server_write_MAC_secret;
8379
0
    }
8380
0
    ret = BuildTls13HandshakeHmac(ssl, secret, &input[headerSz], NULL);
8381
0
    if (ret != 0)
8382
0
        return ret;
8383
    #ifdef WOLFSSL_HAVE_TLS_UNIQUE
8384
        if (ssl->options.side == WOLFSSL_CLIENT_END) {
8385
            XMEMCPY(ssl->clientFinished, &input[headerSz], finishedSz);
8386
            ssl->clientFinished_len = finishedSz;
8387
        }
8388
        else {
8389
            XMEMCPY(ssl->serverFinished, &input[headerSz], finishedSz);
8390
            ssl->serverFinished_len = finishedSz;
8391
        }
8392
    #endif /* WOLFSSL_HAVE_TLS_UNIQUE */
8393
8394
#ifdef WOLFSSL_DTLS13
8395
    if (isDtls) {
8396
        dtlsRet = Dtls13HandshakeSend(ssl, output, outputSz,
8397
            Dtls13GetRlHeaderLength(ssl, 1) + headerSz + finishedSz, finished,
8398
            1);
8399
        if (dtlsRet != 0 && dtlsRet != WANT_WRITE)
8400
            return ret;
8401
8402
    } else
8403
#endif /* WOLFSSL_DTLS13 */
8404
0
    {
8405
    /* This message is always encrypted. */
8406
0
    sendSz = BuildTls13Message(ssl, output, outputSz, input,
8407
0
                               headerSz + finishedSz, handshake, 1, 0, 0);
8408
0
    if (sendSz < 0) {
8409
0
        WOLFSSL_ERROR_VERBOSE(BUILD_MSG_ERROR);
8410
0
        return BUILD_MSG_ERROR;
8411
0
    }
8412
8413
    #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
8414
        if (ssl->hsInfoOn) AddPacketName(ssl, "Finished");
8415
        if (ssl->toInfoOn) {
8416
            AddPacketInfo(ssl, "Finished", handshake, output, sendSz,
8417
                          WRITE_PROTO, ssl->heap);
8418
        }
8419
    #endif
8420
8421
0
    ssl->buffers.outputBuffer.length += sendSz;
8422
0
    ssl->options.buildingMsg = 0;
8423
0
    }
8424
8425
0
    if (ssl->options.side == WOLFSSL_SERVER_END) {
8426
#ifdef WOLFSSL_EARLY_DATA
8427
        byte storeTrafficDecKeys = ssl->earlyData == no_early_data;
8428
#endif
8429
        /* Can send application data now. */
8430
0
        if ((ret = DeriveMasterSecret(ssl)) != 0)
8431
0
            return ret;
8432
        /* Last use of preMasterSecret - zeroize as soon as possible. */
8433
0
        ForceZero(ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz);
8434
#ifdef WOLFSSL_EARLY_DATA
8435
8436
#ifdef WOLFSSL_DTLS13
8437
        /* DTLS13 dynamically change keys and it needs all
8438
           the keys in ssl->keys to save the keying material */
8439
        if (isDtls)
8440
            storeTrafficDecKeys = 1;
8441
#endif /* WOLFSSL_DTLS13 */
8442
8443
        if ((ret = DeriveTls13Keys(ssl, traffic_key, ENCRYPT_SIDE_ONLY, 1))
8444
                                                                         != 0) {
8445
            return ret;
8446
        }
8447
        if ((ret = DeriveTls13Keys(ssl, traffic_key, DECRYPT_SIDE_ONLY,
8448
                                       storeTrafficDecKeys)) != 0) {
8449
            return ret;
8450
        }
8451
#else
8452
0
        if ((ret = DeriveTls13Keys(ssl, traffic_key, ENCRYPT_AND_DECRYPT_SIDE,
8453
0
                                                                     1)) != 0) {
8454
0
            return ret;
8455
0
        }
8456
0
#endif
8457
0
        if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
8458
0
            return ret;
8459
8460
#ifdef WOLFSSL_DTLS13
8461
        if (isDtls) {
8462
            w64wrapper epochTraffic0;
8463
            epochTraffic0 = w64From32(0, DTLS13_EPOCH_TRAFFIC0);
8464
            ssl->dtls13Epoch = epochTraffic0;
8465
            ssl->dtls13PeerEpoch = epochTraffic0;
8466
8467
            ret = Dtls13NewEpoch(
8468
                ssl, epochTraffic0, ENCRYPT_AND_DECRYPT_SIDE);
8469
            if (ret != 0)
8470
                return ret;
8471
8472
            ret = Dtls13SetEpochKeys(
8473
                ssl, epochTraffic0, ENCRYPT_AND_DECRYPT_SIDE);
8474
            if (ret != 0)
8475
                return ret;
8476
8477
        }
8478
#endif /* WOLFSSL_DTLS13 */
8479
8480
0
    }
8481
8482
0
    if (ssl->options.side == WOLFSSL_CLIENT_END &&
8483
0
                                                  !ssl->options.handShakeDone) {
8484
#ifdef WOLFSSL_EARLY_DATA
8485
        if (ssl->earlyData != no_early_data) {
8486
            if ((ret = DeriveTls13Keys(ssl, no_key, ENCRYPT_AND_DECRYPT_SIDE,
8487
                                                                     1)) != 0) {
8488
                    return ret;
8489
            }
8490
        }
8491
#endif
8492
        /* Setup keys for application data messages. */
8493
0
        if ((ret = SetKeysSide(ssl, ENCRYPT_AND_DECRYPT_SIDE)) != 0)
8494
0
            return ret;
8495
8496
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
8497
        ret = DeriveResumptionSecret(ssl, ssl->session->masterSecret);
8498
        if (ret != 0)
8499
            return ret;
8500
#endif
8501
8502
#ifdef WOLFSSL_DTLS13
8503
        if (isDtls) {
8504
            w64wrapper epochTraffic0;
8505
            epochTraffic0 = w64From32(0, DTLS13_EPOCH_TRAFFIC0);
8506
            ssl->dtls13Epoch = epochTraffic0;
8507
            ssl->dtls13PeerEpoch = epochTraffic0;
8508
8509
            ret = Dtls13NewEpoch(
8510
                ssl, epochTraffic0, ENCRYPT_AND_DECRYPT_SIDE);
8511
            if (ret != 0)
8512
                return ret;
8513
8514
            ret = Dtls13SetEpochKeys(
8515
                ssl, epochTraffic0, ENCRYPT_AND_DECRYPT_SIDE);
8516
            if (ret != 0)
8517
                return ret;
8518
8519
        }
8520
#endif /* WOLFSSL_DTLS13 */
8521
0
    }
8522
8523
0
#ifndef NO_WOLFSSL_CLIENT
8524
0
    if (ssl->options.side == WOLFSSL_CLIENT_END) {
8525
0
        ssl->options.clientState = CLIENT_FINISHED_COMPLETE;
8526
0
        ssl->options.handShakeState = HANDSHAKE_DONE;
8527
0
        ssl->options.handShakeDone  = 1;
8528
0
    }
8529
0
#endif
8530
0
#ifndef NO_WOLFSSL_SERVER
8531
0
    if (ssl->options.side == WOLFSSL_SERVER_END) {
8532
0
        ssl->options.serverState = SERVER_FINISHED_COMPLETE;
8533
0
    }
8534
0
#endif
8535
8536
#ifdef WOLFSSL_DTLS13
8537
    if (isDtls) {
8538
        WOLFSSL_LEAVE("SendTls13Finished", ret);
8539
        WOLFSSL_END(WC_FUNC_FINISHED_SEND);
8540
8541
        return dtlsRet;
8542
    }
8543
#endif /* WOLFSSL_DTLS13 */
8544
8545
0
    if ((ret = SendBuffered(ssl)) != 0)
8546
0
        return ret;
8547
8548
0
    WOLFSSL_LEAVE("SendTls13Finished", ret);
8549
0
    WOLFSSL_END(WC_FUNC_FINISHED_SEND);
8550
8551
0
    return ret;
8552
0
}
8553
#endif /* !NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER */
8554
8555
/* handle generation TLS v1.3 key_update (24) */
8556
/* Send the TLS v1.3 KeyUpdate message.
8557
 *
8558
 * ssl  The SSL/TLS object.
8559
 * returns 0 on success, otherwise failure.
8560
 */
8561
static int SendTls13KeyUpdate(WOLFSSL* ssl)
8562
0
{
8563
0
    int    sendSz;
8564
0
    byte*  input;
8565
0
    byte*  output;
8566
0
    int    ret;
8567
0
    int    headerSz = HANDSHAKE_HEADER_SZ;
8568
0
    int    outputSz;
8569
0
    word32 i = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
8570
8571
0
    WOLFSSL_START(WC_FUNC_KEY_UPDATE_SEND);
8572
0
    WOLFSSL_ENTER("SendTls13KeyUpdate");
8573
8574
#ifdef WOLFSSL_DTLS13
8575
    if (ssl->options.dtls)
8576
        i = Dtls13GetRlHeaderLength(ssl, 1) + DTLS_HANDSHAKE_HEADER_SZ;
8577
#endif /* WOLFSSL_DTLS13 */
8578
8579
0
    outputSz = OPAQUE8_LEN + MAX_MSG_EXTRA;
8580
    /* Check buffers are big enough and grow if needed. */
8581
0
    if ((ret = CheckAvailableSize(ssl, outputSz)) != 0)
8582
0
        return ret;
8583
8584
    /* get output buffer */
8585
0
    output = ssl->buffers.outputBuffer.buffer +
8586
0
             ssl->buffers.outputBuffer.length;
8587
0
    input = output + RECORD_HEADER_SZ;
8588
8589
#ifdef WOLFSSL_DTLS13
8590
    if (ssl->options.dtls)
8591
        input = output + Dtls13GetRlHeaderLength(ssl, 1);
8592
#endif /* WOLFSSL_DTLS13 */
8593
8594
0
    AddTls13Headers(output, OPAQUE8_LEN, key_update, ssl);
8595
8596
    /* If:
8597
     *   1. I haven't sent a KeyUpdate requesting a response and
8598
     *   2. This isn't responding to peer KeyUpdate requiring a response then,
8599
     * I want a response.
8600
     */
8601
0
    ssl->keys.updateResponseReq = output[i++] =
8602
0
         !ssl->keys.updateResponseReq && !ssl->keys.keyUpdateRespond;
8603
    /* Sent response, no longer need to respond. */
8604
0
    ssl->keys.keyUpdateRespond = 0;
8605
8606
#ifdef WOLFSSL_DTLS13
8607
    if (ssl->options.dtls) {
8608
        ret = Dtls13HandshakeSend(ssl, output, outputSz,
8609
            OPAQUE8_LEN + Dtls13GetRlHeaderLength(ssl, 1) +
8610
                DTLS_HANDSHAKE_HEADER_SZ,
8611
            key_update, 0);
8612
    }
8613
    else
8614
#endif /* WOLFSSL_DTLS13 */
8615
0
    {
8616
        /* This message is always encrypted. */
8617
0
        sendSz = BuildTls13Message(ssl, output, outputSz, input,
8618
0
                                   headerSz + OPAQUE8_LEN, handshake, 0, 0, 0);
8619
0
        if (sendSz < 0)
8620
0
            return BUILD_MSG_ERROR;
8621
8622
        #if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
8623
            if (ssl->hsInfoOn) AddPacketName(ssl, "KeyUpdate");
8624
            if (ssl->toInfoOn) {
8625
                AddPacketInfo(ssl, "KeyUpdate", handshake, output, sendSz,
8626
                              WRITE_PROTO, ssl->heap);
8627
            }
8628
        #endif
8629
8630
0
        ssl->buffers.outputBuffer.length += sendSz;
8631
8632
0
        ret = SendBuffered(ssl);
8633
8634
8635
0
        if (ret != 0 && ret != WANT_WRITE)
8636
0
            return ret;
8637
0
    }
8638
8639
    /* In DTLS we must wait for the ack before setting up the new keys */
8640
0
    if (!ssl->options.dtls) {
8641
8642
        /* Future traffic uses new encryption keys. */
8643
0
        if ((ret = DeriveTls13Keys(
8644
0
                       ssl, update_traffic_key, ENCRYPT_SIDE_ONLY, 1))
8645
0
            != 0)
8646
0
            return ret;
8647
0
        if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
8648
0
            return ret;
8649
0
    }
8650
8651
8652
0
    WOLFSSL_LEAVE("SendTls13KeyUpdate", ret);
8653
0
    WOLFSSL_END(WC_FUNC_KEY_UPDATE_SEND);
8654
8655
0
    return ret;
8656
0
}
8657
8658
/* handle processing TLS v1.3 key_update (24) */
8659
/* Parse and handle a TLS v1.3 KeyUpdate message.
8660
 *
8661
 * ssl       The SSL/TLS object.
8662
 * input     The message buffer.
8663
 * inOutIdx  On entry, the index into the message buffer of Finished.
8664
 *           On exit, the index of byte after the Finished message and padding.
8665
 * totalSz   The length of the current handshake message.
8666
 * returns 0 on success and otherwise failure.
8667
 */
8668
static int DoTls13KeyUpdate(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
8669
                            word32 totalSz)
8670
0
{
8671
0
    int    ret;
8672
0
    word32 i = *inOutIdx;
8673
8674
0
    WOLFSSL_START(WC_FUNC_KEY_UPDATE_DO);
8675
0
    WOLFSSL_ENTER("DoTls13KeyUpdate");
8676
8677
    /* check against totalSz */
8678
0
    if (OPAQUE8_LEN != totalSz)
8679
0
        return BUFFER_E;
8680
8681
0
    switch (input[i]) {
8682
0
        case update_not_requested:
8683
            /* This message in response to any outstanding request. */
8684
0
            ssl->keys.keyUpdateRespond = 0;
8685
0
            ssl->keys.updateResponseReq = 0;
8686
0
            break;
8687
0
        case update_requested:
8688
            /* New key update requiring a response. */
8689
0
            ssl->keys.keyUpdateRespond = 1;
8690
0
            break;
8691
0
        default:
8692
0
            WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
8693
0
            return INVALID_PARAMETER;
8694
0
    }
8695
8696
    /* Move index to byte after message. */
8697
0
    *inOutIdx += totalSz;
8698
    /* Always encrypted. */
8699
0
    *inOutIdx += ssl->keys.padSz;
8700
8701
    /* Future traffic uses new decryption keys. */
8702
0
    if ((ret = DeriveTls13Keys(ssl, update_traffic_key, DECRYPT_SIDE_ONLY, 1))
8703
0
                                                                         != 0) {
8704
0
        return ret;
8705
0
    }
8706
0
    if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0)
8707
0
        return ret;
8708
8709
#ifdef WOLFSSL_DTLS13
8710
    if (ssl->options.dtls) {
8711
        w64Increment(&ssl->dtls13PeerEpoch);
8712
8713
        ret = Dtls13NewEpoch(ssl, ssl->dtls13PeerEpoch, DECRYPT_SIDE_ONLY);
8714
        if (ret != 0)
8715
            return ret;
8716
8717
        ret = Dtls13SetEpochKeys(ssl, ssl->dtls13PeerEpoch, DECRYPT_SIDE_ONLY);
8718
        if (ret != 0)
8719
            return ret;
8720
    }
8721
#endif /* WOLFSSL_DTLS13 */
8722
8723
0
    if (ssl->keys.keyUpdateRespond) {
8724
8725
#ifdef WOLFSSL_DTLS13
8726
        /* we already sent a keyUpdate (either in response to a previous
8727
           KeyUpdate or initiated by the application) and we are waiting for the
8728
           ack. We can't send a new KeyUpdate right away but to honor the RFC we
8729
           should send another KeyUpdate after the one in-flight is acked. We
8730
           don't do that as it looks redundant, it will make the code more
8731
           complex and I don't see a good use case for that. */
8732
        if (ssl->options.dtls && ssl->dtls13WaitKeyUpdateAck) {
8733
            ssl->keys.keyUpdateRespond = 0;
8734
            return 0;
8735
        }
8736
#endif /* WOLFSSL_DTLS13 */
8737
8738
0
        return SendTls13KeyUpdate(ssl);
8739
0
    }
8740
8741
0
    WOLFSSL_LEAVE("DoTls13KeyUpdate", ret);
8742
0
    WOLFSSL_END(WC_FUNC_KEY_UPDATE_DO);
8743
8744
0
    return 0;
8745
0
}
8746
8747
#ifdef WOLFSSL_EARLY_DATA
8748
#ifndef NO_WOLFSSL_CLIENT
8749
/* Send the TLS v1.3 EndOfEarlyData message to indicate that there will be no
8750
 * more early application data.
8751
 * The encryption key now changes to the pre-calculated handshake key.
8752
 *
8753
 * ssl  The SSL/TLS object.
8754
 * returns 0 on success and otherwise failure.
8755
 */
8756
static int SendTls13EndOfEarlyData(WOLFSSL* ssl)
8757
{
8758
    byte*  output;
8759
    int    ret;
8760
    int    sendSz;
8761
    word32 length;
8762
    word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
8763
8764
    WOLFSSL_START(WC_FUNC_END_OF_EARLY_DATA_SEND);
8765
    WOLFSSL_ENTER("SendTls13EndOfEarlyData");
8766
8767
    length = 0;
8768
    sendSz = idx + length + MAX_MSG_EXTRA;
8769
    ssl->options.buildingMsg = 1;
8770
8771
    /* Check buffers are big enough and grow if needed. */
8772
    if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
8773
        return ret;
8774
8775
    /* Get position in output buffer to write new message to. */
8776
    output = ssl->buffers.outputBuffer.buffer +
8777
             ssl->buffers.outputBuffer.length;
8778
8779
    /* Put the record and handshake headers on. */
8780
    AddTls13Headers(output, length, end_of_early_data, ssl);
8781
8782
    /* This message is always encrypted. */
8783
    sendSz = BuildTls13Message(ssl, output, sendSz, output + RECORD_HEADER_SZ,
8784
                               idx - RECORD_HEADER_SZ, handshake, 1, 0, 0);
8785
    if (sendSz < 0)
8786
        return sendSz;
8787
8788
    ssl->buffers.outputBuffer.length += sendSz;
8789
8790
    if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
8791
        return ret;
8792
8793
    ssl->options.buildingMsg = 0;
8794
    if (!ssl->options.groupMessages)
8795
        ret = SendBuffered(ssl);
8796
8797
    WOLFSSL_LEAVE("SendTls13EndOfEarlyData", ret);
8798
    WOLFSSL_END(WC_FUNC_END_OF_EARLY_DATA_SEND);
8799
8800
    return ret;
8801
}
8802
#endif /* !NO_WOLFSSL_CLIENT */
8803
8804
#ifndef NO_WOLFSSL_SERVER
8805
/* handle processing of TLS 1.3 end_of_early_data (5) */
8806
/* Parse the TLS v1.3 EndOfEarlyData message that indicates that there will be
8807
 * no more early application data.
8808
 * The decryption key now changes to the pre-calculated handshake key.
8809
 *
8810
 * ssl  The SSL/TLS object.
8811
 * returns 0 on success and otherwise failure.
8812
 */
8813
static int DoTls13EndOfEarlyData(WOLFSSL* ssl, const byte* input,
8814
                                 word32* inOutIdx, word32 size)
8815
{
8816
    int    ret;
8817
    word32 begin = *inOutIdx;
8818
8819
    (void)input;
8820
8821
    WOLFSSL_START(WC_FUNC_END_OF_EARLY_DATA_DO);
8822
    WOLFSSL_ENTER("DoTls13EndOfEarlyData");
8823
8824
    if ((*inOutIdx - begin) != size)
8825
        return BUFFER_ERROR;
8826
8827
    if (ssl->earlyData == no_early_data) {
8828
        WOLFSSL_MSG("EndOfEarlyData received unexpectedly");
8829
        SendAlert(ssl, alert_fatal, unexpected_message);
8830
        WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
8831
        return OUT_OF_ORDER_E;
8832
    }
8833
8834
    ssl->earlyData = done_early_data;
8835
8836
    /* Always encrypted. */
8837
    *inOutIdx += ssl->keys.padSz;
8838
8839
    ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY);
8840
8841
    WOLFSSL_LEAVE("DoTls13EndOfEarlyData", ret);
8842
    WOLFSSL_END(WC_FUNC_END_OF_EARLY_DATA_DO);
8843
8844
    return ret;
8845
}
8846
#endif /* !NO_WOLFSSL_SERVER */
8847
#endif /* WOLFSSL_EARLY_DATA */
8848
8849
#ifndef NO_WOLFSSL_CLIENT
8850
/* Handle a New Session Ticket handshake message.
8851
 * Message contains the information required to perform resumption.
8852
 *
8853
 * ssl       The SSL/TLS object.
8854
 * input     The message buffer.
8855
 * inOutIdx  On entry, the index into the message buffer of Finished.
8856
 *           On exit, the index of byte after the Finished message and padding.
8857
 * size      The length of the current handshake message.
8858
 * returns 0 on success, otherwise failure.
8859
 */
8860
static int DoTls13NewSessionTicket(WOLFSSL* ssl, const byte* input,
8861
                                   word32* inOutIdx, word32 size)
8862
0
{
8863
#ifdef HAVE_SESSION_TICKET
8864
    int    ret;
8865
    word32 begin = *inOutIdx;
8866
    word32 lifetime;
8867
    word32 ageAdd;
8868
    word16 length;
8869
    word32 now;
8870
    const byte* nonce;
8871
    byte        nonceLength;
8872
8873
    WOLFSSL_START(WC_FUNC_NEW_SESSION_TICKET_DO);
8874
    WOLFSSL_ENTER("DoTls13NewSessionTicket");
8875
8876
    /* Lifetime hint. */
8877
    if ((*inOutIdx - begin) + SESSION_HINT_SZ > size)
8878
        return BUFFER_ERROR;
8879
    ato32(input + *inOutIdx, &lifetime);
8880
    *inOutIdx += SESSION_HINT_SZ;
8881
    if (lifetime > MAX_LIFETIME) {
8882
        WOLFSSL_ERROR_VERBOSE(SERVER_HINT_ERROR);
8883
        return SERVER_HINT_ERROR;
8884
    }
8885
8886
    /* Age add. */
8887
    if ((*inOutIdx - begin) + SESSION_ADD_SZ > size)
8888
        return BUFFER_ERROR;
8889
    ato32(input + *inOutIdx, &ageAdd);
8890
    *inOutIdx += SESSION_ADD_SZ;
8891
8892
    /* Ticket nonce. */
8893
    if ((*inOutIdx - begin) + 1 > size)
8894
        return BUFFER_ERROR;
8895
    nonceLength = input[*inOutIdx];
8896
    if (nonceLength > MAX_TICKET_NONCE_SZ) {
8897
        WOLFSSL_MSG("Nonce length not supported");
8898
        WOLFSSL_ERROR_VERBOSE(INVALID_PARAMETER);
8899
        return INVALID_PARAMETER;
8900
    }
8901
    *inOutIdx += 1;
8902
    if ((*inOutIdx - begin) + nonceLength > size)
8903
        return BUFFER_ERROR;
8904
    nonce = input + *inOutIdx;
8905
    *inOutIdx += nonceLength;
8906
8907
    /* Ticket length. */
8908
    if ((*inOutIdx - begin) + LENGTH_SZ > size)
8909
        return BUFFER_ERROR;
8910
    ato16(input + *inOutIdx, &length);
8911
    *inOutIdx += LENGTH_SZ;
8912
    if ((*inOutIdx - begin) + length > size)
8913
        return BUFFER_ERROR;
8914
8915
    if ((ret = SetTicket(ssl, input + *inOutIdx, length)) != 0)
8916
        return ret;
8917
    *inOutIdx += length;
8918
8919
    now = TimeNowInMilliseconds();
8920
    if (now == (word32)GETTIME_ERROR)
8921
        return now;
8922
    /* Copy in ticket data (server identity). */
8923
    ssl->timeout                = lifetime;
8924
    ssl->session->timeout        = lifetime;
8925
    ssl->session->cipherSuite0   = ssl->options.cipherSuite0;
8926
    ssl->session->cipherSuite    = ssl->options.cipherSuite;
8927
    ssl->session->ticketSeen     = now;
8928
    ssl->session->ticketAdd      = ageAdd;
8929
    #ifdef WOLFSSL_EARLY_DATA
8930
    ssl->session->maxEarlyDataSz = ssl->options.maxEarlyDataSz;
8931
    #endif
8932
    ssl->session->ticketNonce.len = nonceLength;
8933
    if (nonceLength > 0)
8934
        XMEMCPY(&ssl->session->ticketNonce.data, nonce, nonceLength);
8935
    ssl->session->namedGroup     = ssl->namedGroup;
8936
8937
    if ((*inOutIdx - begin) + EXTS_SZ > size)
8938
        return BUFFER_ERROR;
8939
    ato16(input + *inOutIdx, &length);
8940
    *inOutIdx += EXTS_SZ;
8941
    if ((*inOutIdx - begin) + length != size)
8942
        return BUFFER_ERROR;
8943
    #ifdef WOLFSSL_EARLY_DATA
8944
    ret = TLSX_Parse(ssl, (byte *)input + (*inOutIdx), length, session_ticket,
8945
                     NULL);
8946
    if (ret != 0)
8947
        return ret;
8948
    #endif
8949
    *inOutIdx += length;
8950
8951
    #ifndef NO_SESSION_CACHE
8952
    AddSession(ssl);
8953
    #endif
8954
8955
    /* Always encrypted. */
8956
    *inOutIdx += ssl->keys.padSz;
8957
8958
    ssl->expect_session_ticket = 0;
8959
#else
8960
0
    (void)ssl;
8961
0
    (void)input;
8962
8963
0
    WOLFSSL_ENTER("DoTls13NewSessionTicket");
8964
8965
0
    *inOutIdx += size + ssl->keys.padSz;
8966
0
#endif /* HAVE_SESSION_TICKET */
8967
8968
0
    WOLFSSL_LEAVE("DoTls13NewSessionTicket", 0);
8969
0
    WOLFSSL_END(WC_FUNC_NEW_SESSION_TICKET_DO);
8970
8971
0
    return 0;
8972
0
}
8973
#endif /* NO_WOLFSSL_CLIENT */
8974
8975
#ifndef NO_WOLFSSL_SERVER
8976
    #ifdef HAVE_SESSION_TICKET
8977
8978
#ifdef WOLFSSL_TLS13_TICKET_BEFORE_FINISHED
8979
/* Offset of the MAC size in the finished message. */
8980
#define FINISHED_MSG_SIZE_OFFSET    3
8981
8982
/* Calculate the resumption secret which includes the unseen client finished
8983
 * message.
8984
 *
8985
 * ssl  The SSL/TLS object.
8986
 * returns 0 on success, otherwise failure.
8987
 */
8988
static int ExpectedResumptionSecret(WOLFSSL* ssl)
8989
{
8990
    int         ret;
8991
    word32      finishedSz = 0;
8992
    byte        mac[WC_MAX_DIGEST_SIZE];
8993
    Digest      digest;
8994
    static byte header[] = { 0x14, 0x00, 0x00, 0x00 };
8995
8996
    /* Copy the running hash so we can restore it after. */
8997
    switch (ssl->specs.mac_algorithm) {
8998
    #ifndef NO_SHA256
8999
        case sha256_mac:
9000
            ret = wc_Sha256Copy(&ssl->hsHashes->hashSha256, &digest.sha256);
9001
            if (ret != 0)
9002
                return ret;
9003
            break;
9004
    #endif
9005
    #ifdef WOLFSSL_SHA384
9006
        case sha384_mac:
9007
            ret = wc_Sha384Copy(&ssl->hsHashes->hashSha384, &digest.sha384);
9008
            if (ret != 0)
9009
                return ret;
9010
            break;
9011
    #endif
9012
    #ifdef WOLFSSL_TLS13_SHA512
9013
        case sha512_mac:
9014
            ret = wc_Sha512Copy(&ssl->hsHashes->hashSha512, &digest.sha512);
9015
            if (ret != 0)
9016
                return ret;
9017
            break;
9018
    #endif
9019
    }
9020
9021
    /* Generate the Client's Finished message and hash it. */
9022
    ret = BuildTls13HandshakeHmac(ssl, ssl->keys.client_write_MAC_secret, mac,
9023
                                  &finishedSz);
9024
    if (ret != 0)
9025
        return ret;
9026
    header[FINISHED_MSG_SIZE_OFFSET] = finishedSz;
9027
#ifdef WOLFSSL_EARLY_DATA
9028
    if (ssl->earlyData != no_early_data) {
9029
        static byte endOfEarlyData[] = { 0x05, 0x00, 0x00, 0x00 };
9030
        ret = HashRaw(ssl, endOfEarlyData, sizeof(endOfEarlyData));
9031
        if (ret != 0)
9032
            return ret;
9033
    }
9034
#endif
9035
    if ((ret = HashRaw(ssl, header, sizeof(header))) != 0)
9036
        return ret;
9037
    if ((ret = HashRaw(ssl, mac, finishedSz)) != 0)
9038
        return ret;
9039
9040
    if ((ret = DeriveResumptionSecret(ssl, ssl->session->masterSecret)) != 0)
9041
        return ret;
9042
9043
    /* Restore the hash inline with currently seen messages. */
9044
    switch (ssl->specs.mac_algorithm) {
9045
    #ifndef NO_SHA256
9046
        case sha256_mac:
9047
            wc_Sha256Free(&ssl->hsHashes->hashSha256);
9048
            ret = wc_Sha256Copy(&digest.sha256, &ssl->hsHashes->hashSha256);
9049
            wc_Sha256Free(&digest.sha256);
9050
            if (ret != 0)
9051
                return ret;
9052
            break;
9053
    #endif
9054
    #ifdef WOLFSSL_SHA384
9055
        case sha384_mac:
9056
            wc_Sha384Free(&ssl->hsHashes->hashSha384);
9057
            ret = wc_Sha384Copy(&digest.sha384, &ssl->hsHashes->hashSha384);
9058
            wc_Sha384Free(&digest.sha384);
9059
            if (ret != 0)
9060
                return ret;
9061
            break;
9062
    #endif
9063
    #ifdef WOLFSSL_TLS13_SHA512
9064
        case sha512_mac:
9065
            wc_Sha512Free(&ssl->hsHashes->hashSha512);
9066
            ret = wc_Sha512Copy(&digest.sha512, &ssl->hsHashes->hashSha512);
9067
            wc_Sha512Free(&digest.sha512);
9068
            if (ret != 0)
9069
                return ret;
9070
            break;
9071
    #endif
9072
    }
9073
9074
    return ret;
9075
}
9076
#endif
9077
9078
/* Send New Session Ticket handshake message.
9079
 * Message contains the information required to perform resumption.
9080
 *
9081
 * ssl  The SSL/TLS object.
9082
 * returns 0 on success, otherwise failure.
9083
 */
9084
static int SendTls13NewSessionTicket(WOLFSSL* ssl)
9085
{
9086
    byte*  output;
9087
    int    ret;
9088
    int    sendSz;
9089
    word16 extSz;
9090
    word32 length;
9091
    word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
9092
9093
    WOLFSSL_START(WC_FUNC_NEW_SESSION_TICKET_SEND);
9094
    WOLFSSL_ENTER("SendTls13NewSessionTicket");
9095
9096
#ifdef WOLFSSL_DTLS13
9097
    if (ssl->options.dtls)
9098
        idx = Dtls13GetRlHeaderLength(ssl, 1) + DTLS_HANDSHAKE_HEADER_SZ;
9099
#endif /* WOLFSSL_DTLS13 */
9100
9101
#ifdef WOLFSSL_TLS13_TICKET_BEFORE_FINISHED
9102
    if (!ssl->msgsReceived.got_finished) {
9103
        if ((ret = ExpectedResumptionSecret(ssl)) != 0)
9104
            return ret;
9105
    }
9106
#endif
9107
9108
    /* Start ticket nonce at 0 and go up to 255. */
9109
    if (ssl->session->ticketNonce.len == 0) {
9110
        ssl->session->ticketNonce.len = DEF_TICKET_NONCE_SZ;
9111
        ssl->session->ticketNonce.data[0] = 0;
9112
    }
9113
    else
9114
        ssl->session->ticketNonce.data[0]++;
9115
9116
    if (!ssl->options.noTicketTls13) {
9117
        if ((ret = CreateTicket(ssl)) != 0)
9118
            return ret;
9119
    }
9120
9121
#ifdef WOLFSSL_EARLY_DATA
9122
    ssl->session->maxEarlyDataSz = ssl->options.maxEarlyDataSz;
9123
    if (ssl->session->maxEarlyDataSz > 0)
9124
        TLSX_EarlyData_Use(ssl, ssl->session->maxEarlyDataSz, 1);
9125
    extSz = 0;
9126
    ret = TLSX_GetResponseSize(ssl, session_ticket, &extSz);
9127
    if (ret != 0)
9128
        return ret;
9129
#else
9130
    extSz = EXTS_SZ;
9131
#endif
9132
9133
    /* Lifetime | Age Add | Ticket | Extensions */
9134
    length = SESSION_HINT_SZ + SESSION_ADD_SZ + LENGTH_SZ +
9135
             ssl->session->ticketLen + extSz;
9136
    /* Nonce */
9137
    length += TICKET_NONCE_LEN_SZ + DEF_TICKET_NONCE_SZ;
9138
    sendSz = idx + length + MAX_MSG_EXTRA;
9139
9140
    /* Check buffers are big enough and grow if needed. */
9141
    if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
9142
        return ret;
9143
9144
    /* Get position in output buffer to write new message to. */
9145
    output = ssl->buffers.outputBuffer.buffer +
9146
             ssl->buffers.outputBuffer.length;
9147
9148
    /* Put the record and handshake headers on. */
9149
    AddTls13Headers(output, length, session_ticket, ssl);
9150
9151
    /* Lifetime hint */
9152
    c32toa(ssl->ctx->ticketHint, output + idx);
9153
    idx += SESSION_HINT_SZ;
9154
    /* Age add - obfuscator */
9155
    c32toa(ssl->session->ticketAdd, output + idx);
9156
    idx += SESSION_ADD_SZ;
9157
9158
    output[idx++] = ssl->session->ticketNonce.len;
9159
    output[idx++] = ssl->session->ticketNonce.data[0];
9160
9161
    /* length */
9162
    c16toa(ssl->session->ticketLen, output + idx);
9163
    idx += LENGTH_SZ;
9164
    /* ticket */
9165
    XMEMCPY(output + idx, ssl->session->ticket, ssl->session->ticketLen);
9166
    idx += ssl->session->ticketLen;
9167
9168
#ifdef WOLFSSL_EARLY_DATA
9169
    extSz = 0;
9170
    ret = TLSX_WriteResponse(ssl, output + idx, session_ticket, &extSz);
9171
    if (ret != 0)
9172
        return ret;
9173
    idx += extSz;
9174
#else
9175
    /* No extension support - empty extensions. */
9176
    c16toa(0, output + idx);
9177
    idx += EXTS_SZ;
9178
#endif
9179
9180
    ssl->options.haveSessionId = 1;
9181
9182
#ifndef NO_SESSION_CACHE
9183
    AddSession(ssl);
9184
#endif
9185
9186
#ifdef WOLFSSL_DTLS13
9187
    if (ssl->options.dtls)
9188
        return Dtls13HandshakeSend(ssl, output, sendSz, idx, session_ticket, 0);
9189
#endif /* WOLFSSL_DTLS13 */
9190
9191
    /* This message is always encrypted. */
9192
    sendSz = BuildTls13Message(ssl, output, sendSz, output + RECORD_HEADER_SZ,
9193
                               idx - RECORD_HEADER_SZ, handshake, 0, 0, 0);
9194
    if (sendSz < 0)
9195
        return sendSz;
9196
9197
    ssl->buffers.outputBuffer.length += sendSz;
9198
9199
    /* Always send as this is either directly after server's Finished or only
9200
     * message after client's Finished.
9201
     */
9202
    ret = SendBuffered(ssl);
9203
9204
    WOLFSSL_LEAVE("SendTls13NewSessionTicket", 0);
9205
    WOLFSSL_END(WC_FUNC_NEW_SESSION_TICKET_SEND);
9206
9207
    return ret;
9208
}
9209
    #endif /* HAVE_SESSION_TICKET */
9210
#endif /* NO_WOLFSSL_SERVER */
9211
9212
/* Make sure no duplicates, no fast forward, or other problems
9213
 *
9214
 * ssl   The SSL/TLS object.
9215
 * type  Type of handshake message received.
9216
 * returns 0 on success, otherwise failure.
9217
 */
9218
static int SanityCheckTls13MsgReceived(WOLFSSL* ssl, byte type)
9219
0
{
9220
    /* verify not a duplicate, mark received, check state */
9221
0
    switch (type) {
9222
9223
0
#ifndef NO_WOLFSSL_SERVER
9224
0
        case client_hello:
9225
0
        #ifndef NO_WOLFSSL_CLIENT
9226
            /* Only valid when received on SERVER side. */
9227
0
            if (ssl->options.side == WOLFSSL_CLIENT_END) {
9228
0
                WOLFSSL_MSG("ClientHello received by client");
9229
0
                WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
9230
0
                return SIDE_ERROR;
9231
0
            }
9232
0
        #endif
9233
            /* Check state. */
9234
0
            if (ssl->options.clientState >= CLIENT_HELLO_COMPLETE) {
9235
0
                WOLFSSL_MSG("ClientHello received out of order");
9236
0
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
9237
0
                return OUT_OF_ORDER_E;
9238
0
            }
9239
            /* Check previously seen. */
9240
            /* Initial and after HelloRetryRequest - no more than 2. */
9241
0
            if (ssl->msgsReceived.got_client_hello == 2) {
9242
0
                WOLFSSL_MSG("Too many ClientHello received");
9243
0
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
9244
0
                return DUPLICATE_MSG_E;
9245
0
            }
9246
            /* Second only after HelloRetryRequest seen. */
9247
0
            if (ssl->msgsReceived.got_client_hello == 1 &&
9248
0
                ssl->options.serverState !=
9249
0
                                          SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
9250
0
                WOLFSSL_MSG("Duplicate ClientHello received");
9251
0
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
9252
0
                return DUPLICATE_MSG_E;
9253
0
            }
9254
0
            ssl->msgsReceived.got_client_hello++;
9255
9256
0
            break;
9257
0
#endif
9258
9259
0
#ifndef NO_WOLFSSL_CLIENT
9260
0
        case server_hello:
9261
0
        #ifndef NO_WOLFSSL_SERVER
9262
            /* Only valid when received on CLIENT side. */
9263
0
            if (ssl->options.side == WOLFSSL_SERVER_END) {
9264
0
                WOLFSSL_MSG("ServerHello received by server");
9265
0
                WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
9266
0
                return SIDE_ERROR;
9267
0
            }
9268
0
        #endif
9269
            /* Check state. */
9270
0
            if (ssl->options.serverState >= SERVER_HELLO_COMPLETE) {
9271
0
                WOLFSSL_MSG("ServerHello received out of order");
9272
0
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
9273
0
                return OUT_OF_ORDER_E;
9274
0
            }
9275
            /* Check previously seen. */
9276
            /* Only once after ClientHello.
9277
             * HelloRetryRequest has ServerHello type but count fixed up later
9278
             * - see DoTls13ServerHello().
9279
             */
9280
0
            if (ssl->msgsReceived.got_server_hello) {
9281
0
                WOLFSSL_MSG("Duplicate ServerHello received");
9282
0
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
9283
0
                return DUPLICATE_MSG_E;
9284
0
            }
9285
0
            ssl->msgsReceived.got_server_hello = 1;
9286
9287
0
            break;
9288
0
#endif
9289
9290
0
#ifndef NO_WOLFSSL_CLIENT
9291
0
        case session_ticket:
9292
0
        #ifndef NO_WOLFSSL_SERVER
9293
            /* Only valid when received on CLIENT side. */
9294
0
            if (ssl->options.side == WOLFSSL_SERVER_END) {
9295
0
                WOLFSSL_MSG("NewSessionTicket received by server");
9296
0
                WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
9297
0
                return SIDE_ERROR;
9298
0
            }
9299
0
        #endif
9300
            /* Check state. */
9301
        #ifdef WOLFSSL_TLS13_TICKET_BEFORE_FINISHED
9302
            /* Only allowed after server's Finished message. */
9303
            if (ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
9304
                WOLFSSL_MSG("NewSessionTicket received out of order");
9305
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
9306
                return OUT_OF_ORDER_E;
9307
            }
9308
        #else
9309
            /* Only allowed after client's Finished message. */
9310
0
            if (ssl->options.clientState < CLIENT_FINISHED_COMPLETE) {
9311
0
                WOLFSSL_MSG("NewSessionTicket received out of order");
9312
0
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
9313
0
                return OUT_OF_ORDER_E;
9314
0
            }
9315
0
        #endif
9316
            /* Many SessionTickets can be sent. */
9317
0
            ssl->msgsReceived.got_session_ticket = 1;
9318
9319
0
            break;
9320
0
#endif
9321
9322
0
#ifndef NO_WOLFSSL_SERVER
9323
    #ifdef WOLFSSL_EARLY_DATA
9324
        case end_of_early_data:
9325
        #ifndef NO_WOLFSSL_CLIENT
9326
            /* Only valid when received on SERVER side. */
9327
            if (ssl->options.side == WOLFSSL_CLIENT_END) {
9328
                WOLFSSL_MSG("EndOfEarlyData received by client");
9329
                WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
9330
                return SIDE_ERROR;
9331
            }
9332
        #endif
9333
            /* Check state. */
9334
            /* Only after server's Finished and before client's Finished. */
9335
            if (ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
9336
                WOLFSSL_MSG("EndOfEarlyData received out of order");
9337
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
9338
                return OUT_OF_ORDER_E;
9339
            }
9340
            if (ssl->options.clientState >= CLIENT_FINISHED_COMPLETE) {
9341
                WOLFSSL_MSG("EndOfEarlyData received out of order");
9342
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
9343
                return OUT_OF_ORDER_E;
9344
            }
9345
            /* Check previously seen. */
9346
            if (ssl->msgsReceived.got_end_of_early_data) {
9347
                WOLFSSL_MSG("Too many EndOfEarlyData received");
9348
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
9349
                return DUPLICATE_MSG_E;
9350
            }
9351
            ssl->msgsReceived.got_end_of_early_data = 1;
9352
9353
            break;
9354
    #endif
9355
0
#endif
9356
9357
0
#ifndef NO_WOLFSSL_CLIENT
9358
0
        case encrypted_extensions:
9359
0
        #ifndef NO_WOLFSSL_SERVER
9360
            /* Only valid when received on CLIENT side. */
9361
0
            if (ssl->options.side == WOLFSSL_SERVER_END) {
9362
0
                WOLFSSL_MSG("EncryptedExtensions received by server");
9363
0
                WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
9364
0
                return SIDE_ERROR;
9365
0
            }
9366
0
        #endif
9367
            /* Check state. */
9368
            /* Must be received directly after ServerHello.
9369
             * DoTls13EncryptedExtensions() changes state to:
9370
             *   SERVER_ENCRYPTED_EXTENSIONS_COMPLETE.
9371
             */
9372
0
            if (ssl->options.serverState != SERVER_HELLO_COMPLETE) {
9373
0
                WOLFSSL_MSG("EncryptedExtensions received out of order");
9374
0
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
9375
0
                return OUT_OF_ORDER_E;
9376
0
            }
9377
            /* Check previously seen. */
9378
0
            if (ssl->msgsReceived.got_encrypted_extensions) {
9379
0
                WOLFSSL_MSG("Duplicate EncryptedExtensions received");
9380
0
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
9381
0
                return DUPLICATE_MSG_E;
9382
0
            }
9383
0
            ssl->msgsReceived.got_encrypted_extensions = 1;
9384
9385
0
            break;
9386
0
#endif
9387
9388
0
        case certificate:
9389
            /* Valid on both sides. */
9390
0
    #ifndef NO_WOLFSSL_CLIENT
9391
            /* Check state. */
9392
            /* On client, seen after EncryptedExtension and CertificateRequest
9393
             * (if sent) and before CertificateVerify and Finished.
9394
             * DoTls13Certificate() sets serverState to SERVER_CERT_COMPLETE.
9395
             */
9396
0
            if (ssl->options.side == WOLFSSL_CLIENT_END &&
9397
0
                ssl->options.serverState !=
9398
0
                                         SERVER_ENCRYPTED_EXTENSIONS_COMPLETE) {
9399
0
                WOLFSSL_MSG("Certificate received out of order - Client");
9400
0
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
9401
0
                return OUT_OF_ORDER_E;
9402
0
            }
9403
        #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
9404
            /* Server's authenticating with PSK must not send this. */
9405
            if (ssl->options.side == WOLFSSL_CLIENT_END &&
9406
                             ssl->options.serverState == SERVER_CERT_COMPLETE &&
9407
                             ssl->options.pskNegotiated) {
9408
                WOLFSSL_MSG("Certificate received while using PSK");
9409
                WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
9410
                return SANITY_MSG_E;
9411
            }
9412
        #endif
9413
0
    #endif
9414
0
    #ifndef NO_WOLFSSL_SERVER
9415
            /* Check state. */
9416
            /* On Server, valid after ClientHello received and ServerFinished
9417
             * sent. */
9418
0
            if (ssl->options.side == WOLFSSL_SERVER_END &&
9419
0
                ssl->options.clientState != CLIENT_HELLO_COMPLETE &&
9420
0
                ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
9421
0
                WOLFSSL_MSG("Certificate received out of order - Server");
9422
0
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
9423
0
                return OUT_OF_ORDER_E;
9424
0
            }
9425
0
    #endif
9426
            /* Check previously seen. */
9427
0
            if (ssl->msgsReceived.got_certificate) {
9428
0
                WOLFSSL_MSG("Duplicate Certificate received");
9429
0
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
9430
0
                return DUPLICATE_MSG_E;
9431
0
            }
9432
0
            ssl->msgsReceived.got_certificate = 1;
9433
9434
0
            break;
9435
9436
0
#ifndef NO_WOLFSSL_CLIENT
9437
0
        case certificate_request:
9438
0
        #ifndef NO_WOLFSSL_SERVER
9439
            /* Only valid when received on CLIENT side. */
9440
0
            if (ssl->options.side == WOLFSSL_SERVER_END) {
9441
0
                WOLFSSL_MSG("CertificateRequest received by server");
9442
0
                WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
9443
0
                return SIDE_ERROR;
9444
0
            }
9445
0
        #endif
9446
            /* Check state. */
9447
0
        #ifndef WOLFSSL_POST_HANDSHAKE_AUTH
9448
            /* Only valid when sent after EncryptedExtensions and before
9449
             * Certificate. */
9450
0
            if (ssl->options.serverState !=
9451
0
                                         SERVER_ENCRYPTED_EXTENSIONS_COMPLETE) {
9452
0
                WOLFSSL_MSG("CertificateRequest received out of order");
9453
0
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
9454
0
                return OUT_OF_ORDER_E;
9455
0
            }
9456
        #else
9457
            /* Valid when sent after EncryptedExtensions and before Certificate
9458
             * and after both client and server have sent Finished (Post
9459
             * Handshake Authentication). */
9460
            if (ssl->options.serverState !=
9461
                                         SERVER_ENCRYPTED_EXTENSIONS_COMPLETE &&
9462
                       (ssl->options.serverState < SERVER_FINISHED_COMPLETE ||
9463
                        ssl->options.clientState != CLIENT_FINISHED_COMPLETE)) {
9464
                WOLFSSL_MSG("CertificateRequest received out of order");
9465
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
9466
                return OUT_OF_ORDER_E;
9467
            }
9468
        #endif
9469
        #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
9470
            /* Server's authenticating with PSK must not send this. */
9471
            if (ssl->options.pskNegotiated) {
9472
                WOLFSSL_MSG("CertificateRequest received while using PSK");
9473
                WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
9474
                return SANITY_MSG_E;
9475
            }
9476
        #endif
9477
            /* Check previously seen. */
9478
0
        #ifndef WOLFSSL_POST_HANDSHAKE_AUTH
9479
            /* Only once during handshake. */
9480
0
            if (ssl->msgsReceived.got_certificate_request) {
9481
0
                WOLFSSL_MSG("Duplicate CertificateRequest received");
9482
0
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
9483
0
                return DUPLICATE_MSG_E;
9484
0
            }
9485
        #else
9486
            /* Only once during handshake. */
9487
            if (ssl->msgsReceived.got_certificate_request &&
9488
                ssl->options.clientState != CLIENT_FINISHED_COMPLETE) {
9489
                WOLFSSL_MSG("Duplicate CertificateRequest received");
9490
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
9491
                return DUPLICATE_MSG_E;
9492
            }
9493
        #endif
9494
0
            ssl->msgsReceived.got_certificate_request = 1;
9495
9496
0
            break;
9497
0
#endif
9498
9499
0
        case certificate_verify:
9500
            /* Valid on both sides. */
9501
0
    #ifndef NO_WOLFSSL_CLIENT
9502
            /* Check state on client.
9503
             * Valid only directly after a Certificate message. */
9504
0
            if (ssl->options.side == WOLFSSL_CLIENT_END) {
9505
0
                if (ssl->options.serverState != SERVER_CERT_COMPLETE) {
9506
0
                    WOLFSSL_MSG("No Cert before CertVerify");
9507
0
                    WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
9508
0
                    return OUT_OF_ORDER_E;
9509
0
                }
9510
            #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
9511
                /* Server's authenticating with PSK must not send this. */
9512
                if (ssl->options.pskNegotiated) {
9513
                    WOLFSSL_MSG("CertificateVerify received while using PSK");
9514
                    WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
9515
                    return SANITY_MSG_E;
9516
                }
9517
            #endif
9518
0
            }
9519
0
    #endif
9520
0
    #ifndef NO_WOLFSSL_SERVER
9521
            /* Check state on server. */
9522
0
            if (ssl->options.side == WOLFSSL_SERVER_END) {
9523
                /* Server must have sent Finished message. */
9524
0
                if (ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
9525
0
                    WOLFSSL_MSG("CertificateVerify received out of order");
9526
0
                    WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
9527
0
                    return OUT_OF_ORDER_E;
9528
0
                }
9529
                /* Valid only directly after a Certificate message. */
9530
0
                if (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
9531
0
                    WOLFSSL_MSG("CertificateVerify before ClientHello done");
9532
0
                    WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
9533
0
                    return OUT_OF_ORDER_E;
9534
0
                }
9535
0
                if (!ssl->msgsReceived.got_certificate) {
9536
0
                    WOLFSSL_MSG("No Cert before CertificateVerify");
9537
0
                    WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
9538
0
                    return OUT_OF_ORDER_E;
9539
0
                }
9540
0
            }
9541
0
    #endif
9542
            /* Check previously seen. */
9543
0
            if (ssl->msgsReceived.got_certificate_verify) {
9544
0
                WOLFSSL_MSG("Duplicate CertificateVerify received");
9545
0
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
9546
0
                return DUPLICATE_MSG_E;
9547
0
            }
9548
0
            ssl->msgsReceived.got_certificate_verify = 1;
9549
9550
0
            break;
9551
9552
0
        case finished:
9553
            /* Valid on both sides. */
9554
0
        #ifndef NO_WOLFSSL_CLIENT
9555
            /* Check state on client. */
9556
0
            if (ssl->options.side == WOLFSSL_CLIENT_END) {
9557
                /* After sending ClientHello */
9558
0
                if (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
9559
0
                    WOLFSSL_MSG("Finished received out of order - clientState");
9560
0
                    WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
9561
0
                    return OUT_OF_ORDER_E;
9562
0
                }
9563
                /* Must have seen certificate and verify from server except when
9564
                 * using PSK. */
9565
            #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
9566
                if (ssl->options.pskNegotiated) {
9567
                    if (ssl->options.serverState !=
9568
                                         SERVER_ENCRYPTED_EXTENSIONS_COMPLETE) {
9569
                        WOLFSSL_MSG("Finished received out of order - PSK");
9570
                        WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
9571
                        return OUT_OF_ORDER_E;
9572
                    }
9573
                }
9574
                else
9575
            #endif
9576
0
                if (ssl->options.serverState != SERVER_CERT_VERIFY_COMPLETE) {
9577
0
                    WOLFSSL_MSG("Finished received out of order - serverState");
9578
0
                    WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
9579
0
                    return OUT_OF_ORDER_E;
9580
0
                }
9581
0
            }
9582
0
        #endif
9583
0
        #ifndef NO_WOLFSSL_SERVER
9584
            /* Check state on server. */
9585
0
            if (ssl->options.side == WOLFSSL_SERVER_END) {
9586
0
                if (ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
9587
0
                    WOLFSSL_MSG("Finished received out of order - serverState");
9588
0
                    WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
9589
0
                    return OUT_OF_ORDER_E;
9590
0
                }
9591
0
                if (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
9592
0
                    WOLFSSL_MSG("Finished received out of order - clientState");
9593
0
                    WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
9594
0
                    return OUT_OF_ORDER_E;
9595
0
                }
9596
            #ifdef WOLFSSL_EARLY_DATA
9597
                if (ssl->earlyData == process_early_data &&
9598
                    /* early data may be lost when using DTLS */
9599
                    !ssl->options.dtls
9600
                    /* QUIC does not use EndOfEarlyData records */
9601
                    && !WOLFSSL_IS_QUIC(ssl)) {
9602
                    WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
9603
                    return OUT_OF_ORDER_E;
9604
                }
9605
            #endif
9606
0
            }
9607
0
        #endif
9608
        #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
9609
            if (!ssl->options.pskNegotiated)
9610
        #endif
9611
0
            {
9612
                /* Must have received a Certificate message from client if
9613
                 * verifying the peer. Empty certificate message indicates
9614
                 * no certificate available.
9615
                 */
9616
0
                if (ssl->options.verifyPeer &&
9617
0
                                           !ssl->msgsReceived.got_certificate) {
9618
0
                    WOLFSSL_MSG("Finished received out of order - "
9619
0
                                "missing Certificate message");
9620
0
                    WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
9621
0
                    return OUT_OF_ORDER_E;
9622
0
                }
9623
                /* Mutual authentication on server requires a certificate from
9624
                 * peer. Verify peer set on client side requires a certificate
9625
                 * from peer as not doing PSK.
9626
                 */
9627
0
                if ((ssl->options.mutualAuth ||
9628
0
                    (ssl->options.side == WOLFSSL_CLIENT_END &&
9629
0
                     ssl->options.verifyPeer)) && !ssl->options.havePeerCert) {
9630
0
                    WOLFSSL_MSG("Finished received out of order - "
9631
0
                                "no valid certificate");
9632
0
                    WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
9633
0
                    return OUT_OF_ORDER_E;
9634
0
                }
9635
                /* Must have received a valid CertificateVerify if verifying
9636
                 * peer and got a peer certificate.
9637
                 */
9638
0
                if ((ssl->options.mutualAuth || ssl->options.verifyPeer) &&
9639
0
                    ssl->options.havePeerCert && !ssl->options.havePeerVerify) {
9640
0
                    WOLFSSL_MSG("Finished received out of order - "
9641
0
                                "Certificate message but no CertificateVerify");
9642
0
                    WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
9643
0
                    return OUT_OF_ORDER_E;
9644
0
                }
9645
0
            }
9646
            /* Check previously seen. */
9647
0
            if (ssl->msgsReceived.got_finished) {
9648
0
                WOLFSSL_MSG("Duplicate Finished received");
9649
0
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
9650
0
                return DUPLICATE_MSG_E;
9651
0
            }
9652
0
            ssl->msgsReceived.got_finished = 1;
9653
9654
0
            break;
9655
9656
0
        case key_update:
9657
            /* Valid on both sides. */
9658
            /* Check state.
9659
             * Client and server must have received finished message from other
9660
             * side.
9661
             */
9662
0
            if (!ssl->msgsReceived.got_finished) {
9663
0
                WOLFSSL_MSG("No KeyUpdate before Finished");
9664
0
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
9665
0
                return OUT_OF_ORDER_E;
9666
0
            }
9667
            /* Multiple KeyUpdates can be sent. */
9668
0
            break;
9669
#if defined(WOLFSSL_DTLS13) && !defined(WOLFSSL_NO_TLS12)
9670
        case hello_verify_request:
9671
            if (!ssl->options.dtls) {
9672
                WOLFSSL_MSG("HelloVerifyRequest when not in DTLS");
9673
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
9674
                return OUT_OF_ORDER_E;
9675
            }
9676
            if (ssl->msgsReceived.got_hello_verify_request) {
9677
                WOLFSSL_MSG("Duplicate HelloVerifyRequest received");
9678
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
9679
                return DUPLICATE_MSG_E;
9680
            }
9681
            ssl->msgsReceived.got_hello_verify_request = 1;
9682
            if (ssl->msgsReceived.got_hello_retry_request) {
9683
                WOLFSSL_MSG(
9684
                    "Both HelloVerifyRequest and HelloRetryRequest received");
9685
                WOLFSSL_ERROR_VERBOSE(DUPLICATE_MSG_E);
9686
                return DUPLICATE_MSG_E;
9687
            }
9688
            if (ssl->options.serverState >=
9689
                    SERVER_HELLO_RETRY_REQUEST_COMPLETE ||
9690
                ssl->options.connectState != CLIENT_HELLO_SENT) {
9691
                WOLFSSL_MSG("HelloVerifyRequest received out of order");
9692
                WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
9693
                return OUT_OF_ORDER_E;
9694
            }
9695
            if (ssl->options.side == WOLFSSL_SERVER_END) {
9696
                WOLFSSL_MSG("HelloVerifyRequest recevied on the server");
9697
                WOLFSSL_ERROR_VERBOSE(SIDE_ERROR);
9698
                return SIDE_ERROR;
9699
            }
9700
            if (!ssl->options.downgrade ||
9701
                ssl->options.minDowngrade < DTLSv1_2_MINOR) {
9702
                WOLFSSL_MSG(
9703
                    "HelloVerifyRequest recevied but not DTLSv1.2 allowed");
9704
                WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
9705
                return VERSION_ERROR;
9706
            }
9707
            break;
9708
#endif /* WOLFSSL_DTLS13 && !WOLFSSL_NO_TLS12*/
9709
9710
0
        default:
9711
0
            WOLFSSL_MSG("Unknown message type");
9712
0
            WOLFSSL_ERROR_VERBOSE(SANITY_MSG_E);
9713
0
            return SANITY_MSG_E;
9714
0
    }
9715
9716
0
    return 0;
9717
0
}
9718
9719
/* Handle a type of handshake message that has been received.
9720
 *
9721
 * ssl       The SSL/TLS object.
9722
 * input     The message buffer.
9723
 * inOutIdx  On entry, the index into the buffer of the current message.
9724
 *           On exit, the index into the buffer of the next message.
9725
 * size      The length of the current handshake message.
9726
 * totalSz   Length of remaining data in the message buffer.
9727
 * returns 0 on success and otherwise failure.
9728
 */
9729
int DoTls13HandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx,
9730
                            byte type, word32 size, word32 totalSz)
9731
0
{
9732
0
    int ret = 0;
9733
0
    word32 inIdx = *inOutIdx;
9734
9735
0
    (void)totalSz;
9736
9737
0
    WOLFSSL_ENTER("DoTls13HandShakeMsgType");
9738
9739
    /* make sure we can read the message */
9740
0
    if (*inOutIdx + size > totalSz)
9741
0
        return INCOMPLETE_DATA;
9742
9743
    /* sanity check msg received */
9744
0
    if ((ret = SanityCheckTls13MsgReceived(ssl, type)) != 0) {
9745
0
        WOLFSSL_MSG("Sanity Check on handshake message type received failed");
9746
0
        SendAlert(ssl, alert_fatal, unexpected_message);
9747
0
        return ret;
9748
0
    }
9749
9750
#if defined(WOLFSSL_CALLBACKS)
9751
    /* add name later, add on record and handshake header part back on */
9752
    if (ssl->toInfoOn) {
9753
        int add = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
9754
        AddPacketInfo(ssl, 0, handshake, input + *inOutIdx - add,
9755
                      size + add, READ_PROTO, ssl->heap);
9756
        AddLateRecordHeader(&ssl->curRL, &ssl->timeoutInfo);
9757
    }
9758
#endif
9759
9760
0
    if (ssl->options.handShakeState == HANDSHAKE_DONE &&
9761
0
            type != session_ticket && type != certificate_request &&
9762
0
            type != certificate && type != key_update && type != finished) {
9763
0
        WOLFSSL_MSG("HandShake message after handshake complete");
9764
0
        SendAlert(ssl, alert_fatal, unexpected_message);
9765
0
        WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
9766
0
        return OUT_OF_ORDER_E;
9767
0
    }
9768
9769
0
    if (ssl->options.side == WOLFSSL_CLIENT_END &&
9770
0
               ssl->options.serverState == NULL_STATE &&
9771
0
               type != server_hello && type != hello_retry_request
9772
#if defined(WOLFSSL_DTLS13) && !defined(WOLFSSL_NO_TLS12)
9773
        && (!ssl->options.dtls || type != hello_verify_request)
9774
#endif /* defined(WOLFSSL_DTLS13) && !defined(WOLFSSL_NO_TLS12) */
9775
0
        ) {
9776
0
        WOLFSSL_MSG("First server message not server hello");
9777
0
        SendAlert(ssl, alert_fatal, unexpected_message);
9778
0
        WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
9779
0
        return OUT_OF_ORDER_E;
9780
0
    }
9781
9782
0
    if (ssl->options.side == WOLFSSL_SERVER_END &&
9783
0
               ssl->options.clientState == NULL_STATE && type != client_hello) {
9784
0
        WOLFSSL_MSG("First client message not client hello");
9785
0
        SendAlert(ssl, alert_fatal, unexpected_message);
9786
0
        WOLFSSL_ERROR_VERBOSE(OUT_OF_ORDER_E);
9787
0
        return OUT_OF_ORDER_E;
9788
0
    }
9789
9790
    /* above checks handshake state */
9791
0
    switch (type) {
9792
0
#ifndef NO_WOLFSSL_CLIENT
9793
    /* Messages only received by client. */
9794
0
    case server_hello:
9795
0
        WOLFSSL_MSG("processing server hello");
9796
0
        ret = DoTls13ServerHello(ssl, input, inOutIdx, size, &type);
9797
0
    #if !defined(WOLFSSL_NO_CLIENT_AUTH) && \
9798
0
               ((defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)) || \
9799
0
                (defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)))
9800
0
        if (ssl->options.resuming || !IsAtLeastTLSv1_2(ssl) ||
9801
0
                                               IsAtLeastTLSv1_3(ssl->version)) {
9802
0
            ssl->options.cacheMessages = 0;
9803
0
            if ((ssl->hsHashes != NULL) && (ssl->hsHashes->messages != NULL)) {
9804
0
                ForceZero(ssl->hsHashes->messages, ssl->hsHashes->length);
9805
0
                XFREE(ssl->hsHashes->messages, ssl->heap, DYNAMIC_TYPE_HASHES);
9806
0
                ssl->hsHashes->messages = NULL;
9807
0
            }
9808
0
        }
9809
0
    #endif
9810
0
        break;
9811
9812
0
    case encrypted_extensions:
9813
0
        WOLFSSL_MSG("processing encrypted extensions");
9814
0
        ret = DoTls13EncryptedExtensions(ssl, input, inOutIdx, size);
9815
0
        break;
9816
9817
0
    #ifndef NO_CERTS
9818
0
    case certificate_request:
9819
0
        WOLFSSL_MSG("processing certificate request");
9820
0
        ret = DoTls13CertificateRequest(ssl, input, inOutIdx, size);
9821
0
        break;
9822
0
    #endif
9823
9824
0
    case session_ticket:
9825
0
        WOLFSSL_MSG("processing new session ticket");
9826
0
        ret = DoTls13NewSessionTicket(ssl, input, inOutIdx, size);
9827
0
        break;
9828
0
#endif /* !NO_WOLFSSL_CLIENT */
9829
9830
0
#ifndef NO_WOLFSSL_SERVER
9831
    /* Messages only received by server. */
9832
0
    case client_hello:
9833
0
        WOLFSSL_MSG("processing client hello");
9834
0
        ret = DoTls13ClientHello(ssl, input, inOutIdx, size);
9835
0
        break;
9836
9837
    #ifdef WOLFSSL_EARLY_DATA
9838
    case end_of_early_data:
9839
        WOLFSSL_MSG("processing end of early data");
9840
        ret = DoTls13EndOfEarlyData(ssl, input, inOutIdx, size);
9841
        break;
9842
    #endif
9843
0
#endif /* !NO_WOLFSSL_SERVER */
9844
9845
    /* Messages received by both client and server. */
9846
0
#if !defined(NO_CERTS) && (!defined(NO_WOLFSSL_CLIENT) || \
9847
0
                           !defined(WOLFSSL_NO_CLIENT_AUTH))
9848
0
    case certificate:
9849
0
        WOLFSSL_MSG("processing certificate");
9850
0
        ret = DoTls13Certificate(ssl, input, inOutIdx, size);
9851
0
        break;
9852
0
#endif
9853
9854
0
#if !defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519) || \
9855
0
    defined(HAVE_ED448) || defined(HAVE_PQC)
9856
0
    case certificate_verify:
9857
0
        WOLFSSL_MSG("processing certificate verify");
9858
0
        ret = DoTls13CertificateVerify(ssl, input, inOutIdx, size);
9859
0
        break;
9860
0
#endif
9861
0
    case finished:
9862
0
        WOLFSSL_MSG("processing finished");
9863
0
        ret = DoTls13Finished(ssl, input, inOutIdx, size, totalSz, NO_SNIFF);
9864
0
        break;
9865
9866
0
    case key_update:
9867
0
        WOLFSSL_MSG("processing key update");
9868
0
        ret = DoTls13KeyUpdate(ssl, input, inOutIdx, size);
9869
0
        break;
9870
9871
#if defined(WOLFSSL_DTLS13) && !defined(WOLFSSL_NO_TLS12)
9872
    case hello_verify_request:
9873
        WOLFSSL_MSG("processing hello verify request");
9874
        ret = DoHelloVerifyRequest(ssl, input, inOutIdx, size);
9875
        break;
9876
#endif
9877
0
    default:
9878
0
        WOLFSSL_MSG("Unknown handshake message type");
9879
0
        ret = UNKNOWN_HANDSHAKE_TYPE;
9880
0
        break;
9881
0
    }
9882
9883
0
#if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_ASYNC_IO)
9884
    /* if async, offset index so this msg will be processed again */
9885
    /* NOTE: check this now before other calls can overwrite ret */
9886
0
    if ((ret == WC_PENDING_E || ret == OCSP_WANT_READ) && *inOutIdx > 0) {
9887
        /* DTLS always stores a message in a buffer when async is enable, so we
9888
         * don't need to adjust for the extra bytes here (*inOutIdx is always
9889
         * == 0) */
9890
0
        *inOutIdx -= HANDSHAKE_HEADER_SZ;
9891
0
    }
9892
0
#endif
9893
9894
    /* reset error */
9895
0
    if (ret == 0 && ssl->error == WC_PENDING_E)
9896
0
        ssl->error = 0;
9897
9898
0
    if (ret == 0 && type != client_hello && type != session_ticket &&
9899
0
                                                           type != key_update) {
9900
0
        ret = HashInput(ssl, input + inIdx, size);
9901
0
    }
9902
9903
0
    if (ret == BUFFER_ERROR || ret == MISSING_HANDSHAKE_DATA)
9904
0
        SendAlert(ssl, alert_fatal, decode_error);
9905
0
    else if (ret == EXT_NOT_ALLOWED || ret == PEER_KEY_ERROR ||
9906
0
                        ret == ECC_PEERKEY_ERROR || ret == BAD_KEY_SHARE_DATA ||
9907
0
                        ret == PSK_KEY_ERROR || ret == INVALID_PARAMETER) {
9908
0
        SendAlert(ssl, alert_fatal, illegal_parameter);
9909
0
    }
9910
9911
0
    if (ret == 0 && ssl->options.tls1_3) {
9912
        /* Need to hash input message before deriving secrets. */
9913
0
    #ifndef NO_WOLFSSL_CLIENT
9914
0
        if (ssl->options.side == WOLFSSL_CLIENT_END) {
9915
0
            if (type == server_hello) {
9916
0
                if ((ret = DeriveEarlySecret(ssl)) != 0)
9917
0
                    return ret;
9918
0
                if ((ret = DeriveHandshakeSecret(ssl)) != 0)
9919
0
                    return ret;
9920
9921
0
                if ((ret = DeriveTls13Keys(ssl, handshake_key,
9922
0
                                        ENCRYPT_AND_DECRYPT_SIDE, 1)) != 0) {
9923
0
                    return ret;
9924
0
                }
9925
        #ifdef WOLFSSL_EARLY_DATA
9926
                if (ssl->earlyData != no_early_data) {
9927
                    if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0)
9928
                        return ret;
9929
                }
9930
                else
9931
        #endif
9932
0
                if ((ret = SetKeysSide(ssl, ENCRYPT_AND_DECRYPT_SIDE)) != 0)
9933
0
                    return ret;
9934
9935
#ifdef WOLFSSL_DTLS13
9936
                if (ssl->options.dtls) {
9937
                    w64wrapper epochHandshake;
9938
                    epochHandshake = w64From32(0, DTLS13_EPOCH_HANDSHAKE);
9939
                    ssl->dtls13Epoch = epochHandshake;
9940
                    ssl->dtls13PeerEpoch = epochHandshake;
9941
9942
                    ret = Dtls13NewEpoch(
9943
                        ssl, epochHandshake, ENCRYPT_AND_DECRYPT_SIDE);
9944
                    if (ret != 0)
9945
                        return ret;
9946
9947
                    ret = Dtls13SetEpochKeys(
9948
                        ssl, epochHandshake, ENCRYPT_AND_DECRYPT_SIDE);
9949
                    if (ret != 0)
9950
                        return ret;
9951
9952
                }
9953
#endif /* WOLFSSL_DTLS13 */
9954
0
            }
9955
9956
0
            if (type == finished) {
9957
0
                if ((ret = DeriveMasterSecret(ssl)) != 0)
9958
0
                    return ret;
9959
                /* Last use of preMasterSecret - zeroize as soon as possible. */
9960
0
                ForceZero(ssl->arrays->preMasterSecret,
9961
0
                    ssl->arrays->preMasterSz);
9962
        #ifdef WOLFSSL_EARLY_DATA
9963
        #ifdef WOLFSSL_QUIC
9964
                if (WOLFSSL_IS_QUIC(ssl) && ssl->earlyData != no_early_data) {
9965
                    /* QUIC never sends/receives EndOfEarlyData, but having
9966
                     * early data means the last encrpytion keys had not been
9967
                     * set yet. */
9968
                    if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
9969
                        return ret;
9970
                }
9971
        #endif
9972
                if ((ret = DeriveTls13Keys(ssl, traffic_key,
9973
                                    ENCRYPT_AND_DECRYPT_SIDE,
9974
                                    ssl->earlyData == no_early_data)) != 0) {
9975
                    return ret;
9976
                }
9977
        #else
9978
0
                if ((ret = DeriveTls13Keys(ssl, traffic_key,
9979
0
                                        ENCRYPT_AND_DECRYPT_SIDE, 1)) != 0) {
9980
0
                    return ret;
9981
0
                }
9982
0
        #endif
9983
0
            }
9984
        #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
9985
            if (type == certificate_request &&
9986
                                ssl->options.handShakeState == HANDSHAKE_DONE) {
9987
                /* reset handshake states */
9988
                ssl->options.clientState = CLIENT_HELLO_COMPLETE;
9989
                ssl->options.connectState  = FIRST_REPLY_DONE;
9990
                ssl->options.handShakeState = CLIENT_HELLO_COMPLETE;
9991
                ssl->options.processReply = 0; /* doProcessInit */
9992
9993
                /*
9994
                   DTLSv1.3 note: We can't reset serverState to
9995
                   SERVER_FINISHED_COMPLETE with the goal that this connect
9996
                   blocks until the cert/cert_verify/finished flight gets ACKed
9997
                   by the server. The problem is that we will invoke
9998
                   ProcessReplyEx() in that case, but we came here from
9999
                   ProcessReplyEx() and it is not re-entrant safe (the input
10000
                   buffer would still have the certificate_request message). */
10001
10002
                if (wolfSSL_connect_TLSv13(ssl) != WOLFSSL_SUCCESS) {
10003
                    ret = ssl->error;
10004
                    if (ret != WC_PENDING_E)
10005
                        ret = POST_HAND_AUTH_ERROR;
10006
                }
10007
            }
10008
        #endif
10009
0
        }
10010
0
    #endif /* NO_WOLFSSL_CLIENT */
10011
10012
0
#ifndef NO_WOLFSSL_SERVER
10013
    #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
10014
        if (ssl->options.side == WOLFSSL_SERVER_END && type == finished) {
10015
            ret = DeriveResumptionSecret(ssl, ssl->session->masterSecret);
10016
            if (ret != 0)
10017
                return ret;
10018
        }
10019
    #endif
10020
0
#endif /* NO_WOLFSSL_SERVER */
10021
0
    }
10022
10023
0
    WOLFSSL_LEAVE("DoTls13HandShakeMsgType()", ret);
10024
0
    return ret;
10025
0
}
10026
10027
10028
/* Handle a handshake message that has been received.
10029
 *
10030
 * ssl       The SSL/TLS object.
10031
 * input     The message buffer.
10032
 * inOutIdx  On entry, the index into the buffer of the current message.
10033
 *           On exit, the index into the buffer of the next message.
10034
 * totalSz   Length of remaining data in the message buffer.
10035
 * returns 0 on success and otherwise failure.
10036
 */
10037
int DoTls13HandShakeMsg(WOLFSSL* ssl, byte* input, word32* inOutIdx,
10038
                        word32 totalSz)
10039
0
{
10040
0
    int    ret = 0;
10041
0
    word32 inputLength;
10042
0
    byte   type;
10043
0
    word32 size = 0;
10044
10045
0
    WOLFSSL_ENTER("DoTls13HandShakeMsg()");
10046
10047
0
    if (ssl->arrays == NULL) {
10048
10049
10050
0
        if (GetHandshakeHeader(ssl, input, inOutIdx, &type, &size,
10051
0
                                                                totalSz) != 0) {
10052
0
            SendAlert(ssl, alert_fatal, unexpected_message);
10053
0
            WOLFSSL_ERROR_VERBOSE(PARSE_ERROR);
10054
0
            return PARSE_ERROR;
10055
0
        }
10056
10057
0
        return DoTls13HandShakeMsgType(ssl, input, inOutIdx, type, size,
10058
0
                                       totalSz);
10059
0
    }
10060
10061
0
    inputLength = ssl->buffers.inputBuffer.length - *inOutIdx - ssl->keys.padSz;
10062
10063
    /* If there is a pending fragmented handshake message,
10064
     * pending message size will be non-zero. */
10065
0
    if (ssl->arrays->pendingMsgSz == 0) {
10066
10067
0
        if (GetHandshakeHeader(ssl, input, inOutIdx, &type, &size,
10068
0
                               totalSz) != 0) {
10069
0
            WOLFSSL_ERROR_VERBOSE(PARSE_ERROR);
10070
0
            return PARSE_ERROR;
10071
0
        }
10072
10073
        /* Cap the maximum size of a handshake message to something reasonable.
10074
         * By default is the maximum size of a certificate message assuming
10075
         * nine 2048-bit RSA certificates in the chain. */
10076
0
        if (size > MAX_HANDSHAKE_SZ) {
10077
0
            WOLFSSL_MSG("Handshake message too large");
10078
0
            WOLFSSL_ERROR_VERBOSE(HANDSHAKE_SIZE_ERROR);
10079
0
            return HANDSHAKE_SIZE_ERROR;
10080
0
        }
10081
10082
        /* size is the size of the certificate message payload */
10083
0
        if (inputLength - HANDSHAKE_HEADER_SZ < size) {
10084
0
            ssl->arrays->pendingMsgType = type;
10085
0
            ssl->arrays->pendingMsgSz = size + HANDSHAKE_HEADER_SZ;
10086
0
            ssl->arrays->pendingMsg = (byte*)XMALLOC(size + HANDSHAKE_HEADER_SZ,
10087
0
                                                     ssl->heap,
10088
0
                                                     DYNAMIC_TYPE_ARRAYS);
10089
0
            if (ssl->arrays->pendingMsg == NULL)
10090
0
                return MEMORY_E;
10091
0
            XMEMCPY(ssl->arrays->pendingMsg,
10092
0
                    input + *inOutIdx - HANDSHAKE_HEADER_SZ,
10093
0
                    inputLength);
10094
0
            ssl->arrays->pendingMsgOffset = inputLength;
10095
0
            *inOutIdx += inputLength + ssl->keys.padSz - HANDSHAKE_HEADER_SZ;
10096
0
            return 0;
10097
0
        }
10098
10099
0
        ret = DoTls13HandShakeMsgType(ssl, input, inOutIdx, type, size,
10100
0
                                      totalSz);
10101
0
    }
10102
0
    else {
10103
0
        if (inputLength + ssl->arrays->pendingMsgOffset >
10104
0
                                                    ssl->arrays->pendingMsgSz) {
10105
0
            inputLength = ssl->arrays->pendingMsgSz -
10106
0
                                                  ssl->arrays->pendingMsgOffset;
10107
0
        }
10108
0
        XMEMCPY(ssl->arrays->pendingMsg + ssl->arrays->pendingMsgOffset,
10109
0
                input + *inOutIdx, inputLength);
10110
0
        ssl->arrays->pendingMsgOffset += inputLength;
10111
0
        *inOutIdx += inputLength + ssl->keys.padSz;
10112
10113
0
        if (ssl->arrays->pendingMsgOffset == ssl->arrays->pendingMsgSz)
10114
0
        {
10115
0
            word32 idx = 0;
10116
0
            ret = DoTls13HandShakeMsgType(ssl,
10117
0
                                ssl->arrays->pendingMsg + HANDSHAKE_HEADER_SZ,
10118
0
                                &idx, ssl->arrays->pendingMsgType,
10119
0
                                ssl->arrays->pendingMsgSz - HANDSHAKE_HEADER_SZ,
10120
0
                                ssl->arrays->pendingMsgSz);
10121
        #ifdef WOLFSSL_ASYNC_CRYPT
10122
            if (ret == WC_PENDING_E) {
10123
                /* setup to process fragment again */
10124
                ssl->arrays->pendingMsgOffset -= inputLength;
10125
                *inOutIdx -= inputLength + ssl->keys.padSz;
10126
            }
10127
            else
10128
        #endif
10129
0
            {
10130
0
                XFREE(ssl->arrays->pendingMsg, ssl->heap, DYNAMIC_TYPE_ARRAYS);
10131
0
                ssl->arrays->pendingMsg = NULL;
10132
0
                ssl->arrays->pendingMsgSz = 0;
10133
0
            }
10134
0
        }
10135
0
    }
10136
10137
0
    WOLFSSL_LEAVE("DoTls13HandShakeMsg()", ret);
10138
0
    return ret;
10139
0
}
10140
10141
#ifndef NO_WOLFSSL_CLIENT
10142
10143
/* The client connecting to the server.
10144
 * The protocol version is expecting to be TLS v1.3.
10145
 * If the server downgrades, and older versions of the protocol are compiled
10146
 * in, the client will fallback to wolfSSL_connect().
10147
 * Please see note at top of README if you get an error from connect.
10148
 *
10149
 * ssl  The SSL/TLS object.
10150
 * returns WOLFSSL_SUCCESS on successful handshake, WOLFSSL_FATAL_ERROR when
10151
 * unrecoverable error occurs and 0 otherwise.
10152
 * For more error information use wolfSSL_get_error().
10153
 */
10154
int wolfSSL_connect_TLSv13(WOLFSSL* ssl)
10155
0
{
10156
0
    int advanceState;
10157
0
    int ret = 0;
10158
10159
0
    WOLFSSL_ENTER("wolfSSL_connect_TLSv13()");
10160
10161
0
#ifdef HAVE_ERRNO_H
10162
0
    errno = 0;
10163
0
#endif
10164
10165
0
    if (ssl == NULL)
10166
0
        return BAD_FUNC_ARG;
10167
10168
0
    if (ssl->options.side != WOLFSSL_CLIENT_END) {
10169
0
        ssl->error = SIDE_ERROR;
10170
0
        WOLFSSL_ERROR(ssl->error);
10171
0
        return WOLFSSL_FATAL_ERROR;
10172
0
    }
10173
10174
    /* make sure this wolfSSL object has arrays and rng setup. Protects
10175
     * case where the WOLFSSL object is re-used via wolfSSL_clear() */
10176
0
    if ((ret = ReinitSSL(ssl, ssl->ctx, 0)) != 0) {
10177
0
        return ret;
10178
0
    }
10179
10180
#ifdef WOLFSSL_WOLFSENTRY_HOOKS
10181
    if ((ssl->ConnectFilter != NULL) &&
10182
        (ssl->options.connectState == CONNECT_BEGIN))
10183
    {
10184
        wolfSSL_netfilter_decision_t res;
10185
        if ((ssl->ConnectFilter(ssl, ssl->ConnectFilter_arg, &res) ==
10186
             WOLFSSL_SUCCESS) &&
10187
            (res == WOLFSSL_NETFILTER_REJECT)) {
10188
            ssl->error = SOCKET_FILTERED_E;
10189
            WOLFSSL_ERROR(ssl->error);
10190
            return WOLFSSL_FATAL_ERROR;
10191
        }
10192
    }
10193
#endif /* WOLFSSL_WOLFSENTRY_HOOKS */
10194
10195
    /* fragOffset is non-zero when sending fragments. On the last
10196
     * fragment, fragOffset is zero again, and the state can be
10197
     * advanced. Also, only advance from states in which we send data */
10198
0
    advanceState = (ssl->options.connectState == CONNECT_BEGIN ||
10199
0
            ssl->options.connectState == HELLO_AGAIN ||
10200
0
            (ssl->options.connectState >= FIRST_REPLY_DONE &&
10201
0
             ssl->options.connectState <= FIRST_REPLY_FOURTH));
10202
10203
#ifdef WOLFSSL_DTLS13
10204
    if (ssl->options.dtls)
10205
        advanceState = advanceState && !ssl->dtls13SendingFragments
10206
            && !ssl->dtls13SendingAckOrRtx;
10207
#endif /* WOLFSSL_DTLS13 */
10208
10209
0
    if (ssl->buffers.outputBuffer.length > 0
10210
    #ifdef WOLFSSL_ASYNC_CRYPT
10211
        /* do not send buffered or advance state if last error was an
10212
            async pending operation */
10213
        && ssl->error != WC_PENDING_E
10214
    #endif
10215
0
    ) {
10216
0
        if ((ssl->error = SendBuffered(ssl)) == 0) {
10217
0
            if (ssl->fragOffset == 0 && !ssl->options.buildingMsg) {
10218
0
                if (advanceState) {
10219
#ifdef WOLFSSL_DTLS13
10220
                    if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version) &&
10221
                        ssl->options.connectState == FIRST_REPLY_FOURTH) {
10222
                    /* WAIT_FINISHED_ACK is a state added afterwards, but it
10223
                       can't follow FIRST_REPLY_FOURTH in the enum order. Indeed
10224
                       the value of the enum ConnectState is stored in
10225
                       serialized session. This would make importing serialized
10226
                       session from other wolfSSL version incompatible */
10227
                        ssl->options.connectState = WAIT_FINISHED_ACK;
10228
                    }
10229
                    else
10230
#endif /* WOLFSSL_DTLS13 */
10231
0
                    {
10232
0
                        ssl->options.connectState++;
10233
0
                    }
10234
0
                    WOLFSSL_MSG("connect state: "
10235
0
                                "Advanced from last buffered fragment send");
10236
0
#ifdef WOLFSSL_ASYNC_IO
10237
0
                    FreeAsyncCtx(ssl, 0);
10238
0
#endif
10239
10240
0
                }
10241
0
            }
10242
0
            else {
10243
0
                WOLFSSL_MSG("connect state: "
10244
0
                            "Not advanced, more fragments to send");
10245
0
            }
10246
#ifdef WOLFSSL_DTLS13
10247
            if (ssl->options.dtls)
10248
                ssl->dtls13SendingAckOrRtx =0;
10249
#endif /* WOLFSSL_DTLS13 */
10250
10251
0
        }
10252
0
        else {
10253
0
            ssl->error = ret;
10254
0
            WOLFSSL_ERROR(ssl->error);
10255
0
            return WOLFSSL_FATAL_ERROR;
10256
0
        }
10257
0
    }
10258
10259
0
    ret = RetrySendAlert(ssl);
10260
0
    if (ret != 0) {
10261
0
        ssl->error = ret;
10262
0
        WOLFSSL_ERROR(ssl->error);
10263
0
        return WOLFSSL_FATAL_ERROR;
10264
0
    }
10265
10266
#ifdef WOLFSSL_DTLS13
10267
    if (ssl->options.dtls && ssl->dtls13SendingFragments) {
10268
        if ((ssl->error = Dtls13FragmentsContinue(ssl)) != 0) {
10269
                WOLFSSL_ERROR(ssl->error);
10270
                return WOLFSSL_FATAL_ERROR;
10271
        }
10272
10273
        /* we sent all the fragments. Advance state. */
10274
        ssl->options.connectState++;
10275
    }
10276
#endif /* WOLFSSL_DTLS13 */
10277
10278
0
    switch (ssl->options.connectState) {
10279
10280
0
        case CONNECT_BEGIN:
10281
            /* Always send client hello first. */
10282
0
            if ((ssl->error = SendTls13ClientHello(ssl)) != 0) {
10283
0
                WOLFSSL_ERROR(ssl->error);
10284
0
                return WOLFSSL_FATAL_ERROR;
10285
0
            }
10286
10287
0
            ssl->options.connectState = CLIENT_HELLO_SENT;
10288
0
            WOLFSSL_MSG("connect state: CLIENT_HELLO_SENT");
10289
    #ifdef WOLFSSL_EARLY_DATA
10290
            if (ssl->earlyData != no_early_data) {
10291
        #if defined(WOLFSSL_TLS13_MIDDLEBOX_COMPAT)
10292
                if (!ssl->options.dtls && ssl->options.tls13MiddleBoxCompat) {
10293
                    if ((ssl->error = SendChangeCipher(ssl)) != 0) {
10294
                        WOLFSSL_ERROR(ssl->error);
10295
                        return WOLFSSL_FATAL_ERROR;
10296
                    }
10297
                    ssl->options.sentChangeCipher = 1;
10298
                }
10299
        #endif
10300
            ssl->options.handShakeState = CLIENT_HELLO_COMPLETE;
10301
            return WOLFSSL_SUCCESS;
10302
            }
10303
    #endif
10304
0
            FALL_THROUGH;
10305
10306
0
        case CLIENT_HELLO_SENT:
10307
            /* Get the response/s from the server. */
10308
0
            while (ssl->options.serverState <
10309
0
                                          SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
10310
0
                if ((ssl->error = ProcessReply(ssl)) < 0) {
10311
0
                        WOLFSSL_ERROR(ssl->error);
10312
0
                        return WOLFSSL_FATAL_ERROR;
10313
0
                }
10314
10315
#ifdef WOLFSSL_DTLS13
10316
                if (ssl->options.dtls) {
10317
                    if ((ssl->error = Dtls13DoScheduledWork(ssl)) < 0) {
10318
                        WOLFSSL_ERROR(ssl->error);
10319
                        return WOLFSSL_FATAL_ERROR;
10320
                    }
10321
                }
10322
#endif /* WOLFSSL_DTLS13 */
10323
0
            }
10324
10325
0
            if (!ssl->options.tls1_3) {
10326
0
    #ifndef WOLFSSL_NO_TLS12
10327
0
                if (ssl->options.downgrade)
10328
0
                    return wolfSSL_connect(ssl);
10329
0
    #endif
10330
0
                WOLFSSL_MSG("Client using higher version, fatal error");
10331
0
                WOLFSSL_ERROR_VERBOSE(VERSION_ERROR);
10332
0
                return VERSION_ERROR;
10333
0
            }
10334
10335
0
            ssl->options.connectState = HELLO_AGAIN;
10336
0
            WOLFSSL_MSG("connect state: HELLO_AGAIN");
10337
0
            FALL_THROUGH;
10338
10339
0
        case HELLO_AGAIN:
10340
0
            if (ssl->options.certOnly)
10341
0
                return WOLFSSL_SUCCESS;
10342
10343
0
            if (ssl->options.serverState ==
10344
0
                                          SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
10345
        #if defined(WOLFSSL_TLS13_MIDDLEBOX_COMPAT)
10346
                if (!ssl->options.dtls && !ssl->options.sentChangeCipher
10347
                    && ssl->options.tls13MiddleBoxCompat) {
10348
                    if ((ssl->error = SendChangeCipher(ssl)) != 0) {
10349
                        WOLFSSL_ERROR(ssl->error);
10350
                        return WOLFSSL_FATAL_ERROR;
10351
                    }
10352
                    ssl->options.sentChangeCipher = 1;
10353
                }
10354
        #endif
10355
                /* Try again with different security parameters. */
10356
0
                if ((ssl->error = SendTls13ClientHello(ssl)) != 0) {
10357
0
                    WOLFSSL_ERROR(ssl->error);
10358
0
                    return WOLFSSL_FATAL_ERROR;
10359
0
                }
10360
0
            }
10361
10362
0
            ssl->options.connectState = HELLO_AGAIN_REPLY;
10363
0
            WOLFSSL_MSG("connect state: HELLO_AGAIN_REPLY");
10364
0
            FALL_THROUGH;
10365
10366
0
        case HELLO_AGAIN_REPLY:
10367
            /* Get the response/s from the server. */
10368
0
            while (ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
10369
0
                if ((ssl->error = ProcessReply(ssl)) < 0) {
10370
0
                        WOLFSSL_ERROR(ssl->error);
10371
0
                        return WOLFSSL_FATAL_ERROR;
10372
0
                }
10373
10374
#ifdef WOLFSSL_DTLS13
10375
                if (ssl->options.dtls) {
10376
                    if ((ssl->error = Dtls13DoScheduledWork(ssl)) < 0) {
10377
                        WOLFSSL_ERROR(ssl->error);
10378
                        return WOLFSSL_FATAL_ERROR;
10379
                    }
10380
                }
10381
#endif /* WOLFSSL_DTLS13 */
10382
0
            }
10383
10384
0
            ssl->options.connectState = FIRST_REPLY_DONE;
10385
0
            WOLFSSL_MSG("connect state: FIRST_REPLY_DONE");
10386
0
            FALL_THROUGH;
10387
10388
0
        case FIRST_REPLY_DONE:
10389
        #ifdef WOLFSSL_EARLY_DATA
10390
            if (!ssl->options.dtls && ssl->earlyData != no_early_data
10391
                && !WOLFSSL_IS_QUIC(ssl)) {
10392
                if ((ssl->error = SendTls13EndOfEarlyData(ssl)) != 0) {
10393
                    WOLFSSL_ERROR(ssl->error);
10394
                    return WOLFSSL_FATAL_ERROR;
10395
                }
10396
                WOLFSSL_MSG("sent: end_of_early_data");
10397
            }
10398
        #endif
10399
10400
0
            ssl->options.connectState = FIRST_REPLY_FIRST;
10401
0
            WOLFSSL_MSG("connect state: FIRST_REPLY_FIRST");
10402
0
            FALL_THROUGH;
10403
10404
0
        case FIRST_REPLY_FIRST:
10405
        #if defined(WOLFSSL_TLS13_MIDDLEBOX_COMPAT)
10406
            if (!ssl->options.sentChangeCipher && !ssl->options.dtls
10407
                && ssl->options.tls13MiddleBoxCompat) {
10408
                if ((ssl->error = SendChangeCipher(ssl)) != 0) {
10409
                    WOLFSSL_ERROR(ssl->error);
10410
                    return WOLFSSL_FATAL_ERROR;
10411
                }
10412
                ssl->options.sentChangeCipher = 1;
10413
            }
10414
        #endif
10415
10416
0
            ssl->options.connectState = FIRST_REPLY_SECOND;
10417
0
            WOLFSSL_MSG("connect state: FIRST_REPLY_SECOND");
10418
0
            FALL_THROUGH;
10419
10420
0
        case FIRST_REPLY_SECOND:
10421
            /* CLIENT: check peer authentication. */
10422
0
            if (!ssl->options.peerAuthGood) {
10423
0
                WOLFSSL_MSG("Server authentication did not happen");
10424
0
                WOLFSSL_ERROR_VERBOSE(WOLFSSL_FATAL_ERROR);
10425
0
                return WOLFSSL_FATAL_ERROR;
10426
0
            }
10427
0
        #ifndef NO_CERTS
10428
0
            if (!ssl->options.resuming && ssl->options.sendVerify) {
10429
0
                ssl->error = SendTls13Certificate(ssl);
10430
0
                if (ssl->error != 0) {
10431
                #ifdef WOLFSSL_CHECK_ALERT_ON_ERR
10432
                    ProcessReplyEx(ssl, 1); /* See if an alert was sent. */
10433
                #endif
10434
0
                    WOLFSSL_ERROR(ssl->error);
10435
0
                    return WOLFSSL_FATAL_ERROR;
10436
0
                }
10437
0
                WOLFSSL_MSG("sent: certificate");
10438
0
            }
10439
0
        #endif
10440
10441
0
            ssl->options.connectState = FIRST_REPLY_THIRD;
10442
0
            WOLFSSL_MSG("connect state: FIRST_REPLY_THIRD");
10443
0
            FALL_THROUGH;
10444
10445
0
        case FIRST_REPLY_THIRD:
10446
0
        #if (!defined(NO_CERTS) && (!defined(NO_RSA) || defined(HAVE_ECC) || \
10447
0
             defined(HAVE_ED25519) || defined(HAVE_ED448) || \
10448
0
             defined(HAVE_PQC))) && (!defined(NO_WOLFSSL_SERVER) || \
10449
0
             !defined(WOLFSSL_NO_CLIENT_AUTH))
10450
0
            if (!ssl->options.resuming && ssl->options.sendVerify) {
10451
0
                ssl->error = SendTls13CertificateVerify(ssl);
10452
0
                if (ssl->error != 0) {
10453
                #ifdef WOLFSSL_CHECK_ALERT_ON_ERR
10454
                    ProcessReplyEx(ssl, 1); /* See if an alert was sent. */
10455
                #endif
10456
0
                    WOLFSSL_ERROR(ssl->error);
10457
0
                    return WOLFSSL_FATAL_ERROR;
10458
0
                }
10459
0
                WOLFSSL_MSG("sent: certificate verify");
10460
0
            }
10461
0
        #endif
10462
10463
0
            ssl->options.connectState = FIRST_REPLY_FOURTH;
10464
0
            WOLFSSL_MSG("connect state: FIRST_REPLY_FOURTH");
10465
0
            FALL_THROUGH;
10466
10467
0
        case FIRST_REPLY_FOURTH:
10468
0
            if ((ssl->error = SendTls13Finished(ssl)) != 0) {
10469
            #ifdef WOLFSSL_CHECK_ALERT_ON_ERR
10470
                ProcessReplyEx(ssl, 1); /* See if an alert was sent. */
10471
            #endif
10472
0
                WOLFSSL_ERROR(ssl->error);
10473
0
                return WOLFSSL_FATAL_ERROR;
10474
0
            }
10475
0
            WOLFSSL_MSG("sent: finished");
10476
10477
#ifdef WOLFSSL_DTLS13
10478
            ssl->options.connectState = WAIT_FINISHED_ACK;
10479
            WOLFSSL_MSG("connect state: WAIT_FINISHED_ACK");
10480
            FALL_THROUGH;
10481
10482
        case WAIT_FINISHED_ACK:
10483
            if (ssl->options.dtls) {
10484
                while (ssl->options.serverState != SERVER_FINISHED_ACKED) {
10485
                    if ((ssl->error = ProcessReply(ssl)) < 0) {
10486
                        WOLFSSL_ERROR(ssl->error);
10487
                        return WOLFSSL_FATAL_ERROR;
10488
                    }
10489
10490
                    if ((ssl->error = Dtls13DoScheduledWork(ssl)) < 0) {
10491
                        WOLFSSL_ERROR(ssl->error);
10492
                        return WOLFSSL_FATAL_ERROR;
10493
                    }
10494
                }
10495
            }
10496
#endif /* WOLFSSL_DTLS13 */
10497
0
            ssl->options.connectState = FINISHED_DONE;
10498
0
            WOLFSSL_MSG("connect state: FINISHED_DONE");
10499
0
            FALL_THROUGH;
10500
10501
0
        case FINISHED_DONE:
10502
0
        #ifndef NO_HANDSHAKE_DONE_CB
10503
0
            if (ssl->hsDoneCb != NULL) {
10504
0
                int cbret = ssl->hsDoneCb(ssl, ssl->hsDoneCtx);
10505
0
                if (cbret < 0) {
10506
0
                    ssl->error = cbret;
10507
0
                    WOLFSSL_ERROR_VERBOSE(ssl->error);
10508
0
                    WOLFSSL_MSG("HandShake Done Cb don't continue error");
10509
0
                    return WOLFSSL_FATAL_ERROR;
10510
0
                }
10511
0
            }
10512
0
        #endif /* NO_HANDSHAKE_DONE_CB */
10513
10514
0
            if (!ssl->options.keepResources) {
10515
0
                FreeHandshakeResources(ssl);
10516
0
            }
10517
0
        #if defined(WOLFSSL_ASYNC_IO) && !defined(WOLFSSL_ASYNC_CRYPT)
10518
            /* Free the remaining async context if not using it for crypto */
10519
0
            FreeAsyncCtx(ssl, 1);
10520
0
        #endif
10521
10522
0
            ssl->error = 0; /* clear the error */
10523
10524
0
            WOLFSSL_LEAVE("wolfSSL_connect_TLSv13()", WOLFSSL_SUCCESS);
10525
0
            return WOLFSSL_SUCCESS;
10526
10527
0
        default:
10528
0
            WOLFSSL_MSG("Unknown connect state ERROR");
10529
0
            return WOLFSSL_FATAL_ERROR; /* unknown connect state */
10530
0
    }
10531
0
}
10532
#endif
10533
10534
#if defined(WOLFSSL_SEND_HRR_COOKIE)
10535
/* Send a cookie with the HelloRetryRequest to avoid storing state.
10536
 *
10537
 * ssl       SSL/TLS object.
10538
 * secret    Secret to use when generating integrity check for cookie.
10539
 *           A value of NULL indicates to generate a new random secret.
10540
 * secretSz  Size of secret data in bytes.
10541
 *           Use a value of 0 to indicate use of default size.
10542
 * returns BAD_FUNC_ARG when ssl is NULL or not using TLS v1.3, SIDE_ERROR when
10543
 * called on a client; WOLFSSL_SUCCESS on success and otherwise failure.
10544
 */
10545
int wolfSSL_send_hrr_cookie(WOLFSSL* ssl, const unsigned char* secret,
10546
                            unsigned int secretSz)
10547
{
10548
    int ret;
10549
10550
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
10551
        return BAD_FUNC_ARG;
10552
 #ifndef NO_WOLFSSL_SERVER
10553
    if (ssl->options.side == WOLFSSL_CLIENT_END)
10554
        return SIDE_ERROR;
10555
10556
    if (secretSz == 0) {
10557
    #if !defined(NO_SHA) && defined(NO_SHA256)
10558
        secretSz = WC_SHA_DIGEST_SIZE;
10559
    #endif /* NO_SHA */
10560
    #ifndef NO_SHA256
10561
        secretSz = WC_SHA256_DIGEST_SIZE;
10562
    #endif /* NO_SHA256 */
10563
    }
10564
10565
    if (secretSz != ssl->buffers.tls13CookieSecret.length) {
10566
        byte* newSecret;
10567
10568
        if (ssl->buffers.tls13CookieSecret.buffer != NULL) {
10569
            ForceZero(ssl->buffers.tls13CookieSecret.buffer,
10570
                      ssl->buffers.tls13CookieSecret.length);
10571
            XFREE(ssl->buffers.tls13CookieSecret.buffer,
10572
                  ssl->heap, DYNAMIC_TYPE_COOKIE_PWD);
10573
        }
10574
10575
        newSecret = (byte*)XMALLOC(secretSz, ssl->heap,
10576
                                   DYNAMIC_TYPE_COOKIE_PWD);
10577
        if (newSecret == NULL) {
10578
            ssl->buffers.tls13CookieSecret.buffer = NULL;
10579
            ssl->buffers.tls13CookieSecret.length = 0;
10580
            WOLFSSL_MSG("couldn't allocate new cookie secret");
10581
            return MEMORY_ERROR;
10582
        }
10583
        ssl->buffers.tls13CookieSecret.buffer = newSecret;
10584
        ssl->buffers.tls13CookieSecret.length = secretSz;
10585
    #ifdef WOLFSSL_CHECK_MEM_ZERO
10586
        wc_MemZero_Add("wolfSSL_send_hrr_cookie secret",
10587
            ssl->buffers.tls13CookieSecret.buffer,
10588
            ssl->buffers.tls13CookieSecret.length);
10589
    #endif
10590
    }
10591
10592
    /* If the supplied secret is NULL, randomly generate a new secret. */
10593
    if (secret == NULL) {
10594
        ret = wc_RNG_GenerateBlock(ssl->rng,
10595
                               ssl->buffers.tls13CookieSecret.buffer, secretSz);
10596
        if (ret < 0)
10597
            return ret;
10598
    }
10599
    else
10600
        XMEMCPY(ssl->buffers.tls13CookieSecret.buffer, secret, secretSz);
10601
10602
    ssl->options.sendCookie = 1;
10603
10604
    ret = WOLFSSL_SUCCESS;
10605
#else
10606
    (void)secret;
10607
    (void)secretSz;
10608
10609
    ret = SIDE_ERROR;
10610
#endif
10611
10612
    return ret;
10613
}
10614
#endif
10615
10616
#ifdef HAVE_SUPPORTED_CURVES
10617
/* Create a key share entry from group.
10618
 * Generates a key pair.
10619
 *
10620
 * ssl    The SSL/TLS object.
10621
 * group  The named group.
10622
 * returns 0 on success, otherwise failure.
10623
 *   for async can return WC_PENDING_E and should be called again
10624
 */
10625
int wolfSSL_UseKeyShare(WOLFSSL* ssl, word16 group)
10626
0
{
10627
0
    int ret;
10628
10629
0
    if (ssl == NULL)
10630
0
        return BAD_FUNC_ARG;
10631
10632
#ifdef WOLFSSL_ASYNC_CRYPT
10633
    ret = wolfSSL_AsyncPop(ssl, NULL);
10634
    if (ret != WC_NOT_PENDING_E) {
10635
        /* Check for error */
10636
        if (ret < 0)
10637
            return ret;
10638
    }
10639
#endif
10640
10641
#ifdef HAVE_PQC
10642
    if (WOLFSSL_NAMED_GROUP_IS_PQC(group)) {
10643
10644
        if (ssl->ctx != NULL && ssl->ctx->method != NULL &&
10645
            ssl->ctx->method->version.minor != TLSv1_3_MINOR) {
10646
            return BAD_FUNC_ARG;
10647
        }
10648
10649
        if (ssl->options.side == WOLFSSL_SERVER_END) {
10650
            /* If I am the server of a KEM connection, do not do keygen because I'm
10651
             * going to encapsulate with the client's public key. Note that I might
10652
             * be the client and ssl->option.side has not been properly set yet. In
10653
             * that case the KeyGen operation will be deferred to connection time. */
10654
            return WOLFSSL_SUCCESS;
10655
        }
10656
    }
10657
#endif
10658
#if defined(NO_TLS)
10659
    (void)ret;
10660
    (void)group;
10661
#else
10662
0
    ret = TLSX_KeyShare_Use(ssl, group, 0, NULL, NULL);
10663
0
    if (ret != 0)
10664
0
        return ret;
10665
0
#endif /* NO_TLS */
10666
0
    return WOLFSSL_SUCCESS;
10667
0
}
10668
10669
/* Send no key share entries - use HelloRetryRequest to negotiate shared group.
10670
 *
10671
 * ssl    The SSL/TLS object.
10672
 * returns 0 on success, otherwise failure.
10673
 */
10674
int wolfSSL_NoKeyShares(WOLFSSL* ssl)
10675
0
{
10676
0
    int ret;
10677
10678
0
    if (ssl == NULL)
10679
0
        return BAD_FUNC_ARG;
10680
0
    if (ssl->options.side == WOLFSSL_SERVER_END)
10681
0
        return SIDE_ERROR;
10682
#if defined(NO_TLS)
10683
    (void)ret;
10684
#else
10685
0
    ret = TLSX_KeyShare_Empty(ssl);
10686
0
    if (ret != 0)
10687
0
        return ret;
10688
0
#endif /* NO_TLS */
10689
0
    return WOLFSSL_SUCCESS;
10690
0
}
10691
#endif
10692
10693
/* Do not send a ticket after TLS v1.3 handshake for resumption.
10694
 *
10695
 * ctx  The SSL/TLS CTX object.
10696
 * returns BAD_FUNC_ARG when ctx is NULL and 0 on success.
10697
 */
10698
int wolfSSL_CTX_no_ticket_TLSv13(WOLFSSL_CTX* ctx)
10699
0
{
10700
0
    if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
10701
0
        return BAD_FUNC_ARG;
10702
0
    if (ctx->method->side == WOLFSSL_CLIENT_END)
10703
0
        return SIDE_ERROR;
10704
10705
#ifdef HAVE_SESSION_TICKET
10706
    ctx->noTicketTls13 = 1;
10707
#endif
10708
10709
0
    return 0;
10710
0
}
10711
10712
/* Do not send a ticket after TLS v1.3 handshake for resumption.
10713
 *
10714
 * ssl  The SSL/TLS object.
10715
 * returns BAD_FUNC_ARG when ssl is NULL, not using TLS v1.3, or called on
10716
 * a client and 0 on success.
10717
 */
10718
int wolfSSL_no_ticket_TLSv13(WOLFSSL* ssl)
10719
0
{
10720
0
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
10721
0
        return BAD_FUNC_ARG;
10722
0
    if (ssl->options.side == WOLFSSL_CLIENT_END)
10723
0
        return SIDE_ERROR;
10724
10725
#ifdef HAVE_SESSION_TICKET
10726
    ssl->options.noTicketTls13 = 1;
10727
#endif
10728
10729
0
    return 0;
10730
0
}
10731
10732
/* Disallow (EC)DHE key exchange when using pre-shared keys.
10733
 *
10734
 * ctx  The SSL/TLS CTX object.
10735
 * returns BAD_FUNC_ARG when ctx is NULL and 0 on success.
10736
 */
10737
int wolfSSL_CTX_no_dhe_psk(WOLFSSL_CTX* ctx)
10738
0
{
10739
0
    if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
10740
0
        return BAD_FUNC_ARG;
10741
10742
0
    ctx->noPskDheKe = 1;
10743
10744
0
    return 0;
10745
0
}
10746
10747
/* Disallow (EC)DHE key exchange when using pre-shared keys.
10748
 *
10749
 * ssl  The SSL/TLS object.
10750
 * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3 and 0 on
10751
 * success.
10752
 */
10753
int wolfSSL_no_dhe_psk(WOLFSSL* ssl)
10754
0
{
10755
0
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
10756
0
        return BAD_FUNC_ARG;
10757
10758
0
    ssl->options.noPskDheKe = 1;
10759
10760
0
    return 0;
10761
0
}
10762
10763
/* Update the keys for encryption and decryption.
10764
 * If using non-blocking I/O and WOLFSSL_ERROR_WANT_WRITE is returned then
10765
 * calling wolfSSL_write() will have the message sent when ready.
10766
 *
10767
 * ssl  The SSL/TLS object.
10768
 * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3,
10769
 * WOLFSSL_ERROR_WANT_WRITE when non-blocking I/O is not ready to write,
10770
 * WOLFSSL_SUCCESS on success and otherwise failure.
10771
 */
10772
int wolfSSL_update_keys(WOLFSSL* ssl)
10773
0
{
10774
0
    int ret;
10775
10776
0
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
10777
0
        return BAD_FUNC_ARG;
10778
10779
#ifdef WOLFSSL_DTLS13
10780
    /* we are already waiting for the ack of a sent key update message. We can't
10781
       send another one before receiving its ack. Either wolfSSL_update_keys()
10782
       was invoked multiple times over a short period of time or we replied to a
10783
       KeyUpdate with update request. We'll just ignore sending this
10784
       KeyUpdate. */
10785
    /* TODO: add WOLFSSL_ERROR_ALREADY_IN_PROGRESS type of error here */
10786
    if (ssl->options.dtls && ssl->dtls13WaitKeyUpdateAck)
10787
            return WOLFSSL_SUCCESS;
10788
#endif /* WOLFSSL_DTLS13 */
10789
10790
0
    ret = SendTls13KeyUpdate(ssl);
10791
0
    if (ret == WANT_WRITE)
10792
0
        ret = WOLFSSL_ERROR_WANT_WRITE;
10793
0
    else if (ret == 0)
10794
0
        ret = WOLFSSL_SUCCESS;
10795
0
    return ret;
10796
0
}
10797
10798
/* Whether a response is waiting for key update request.
10799
 *
10800
 * ssl        The SSL/TLS object.
10801
 * required   0 when no key update response required.
10802
 *            1 when no key update response required.
10803
 * return  0 on success.
10804
 * return  BAD_FUNC_ARG when ssl is NULL or not using TLS v1.3
10805
 */
10806
int wolfSSL_key_update_response(WOLFSSL* ssl, int* required)
10807
0
{
10808
0
    if (required == NULL || ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
10809
0
        return BAD_FUNC_ARG;
10810
10811
0
    *required = ssl->keys.updateResponseReq;
10812
10813
0
    return 0;
10814
0
}
10815
10816
#if !defined(NO_CERTS) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
10817
/* Allow post-handshake authentication in TLS v1.3 connections.
10818
 *
10819
 * ctx  The SSL/TLS CTX object.
10820
 * returns BAD_FUNC_ARG when ctx is NULL, SIDE_ERROR when not a client and
10821
 * 0 on success.
10822
 */
10823
int wolfSSL_CTX_allow_post_handshake_auth(WOLFSSL_CTX* ctx)
10824
{
10825
    if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
10826
        return BAD_FUNC_ARG;
10827
    if (ctx->method->side == WOLFSSL_SERVER_END)
10828
        return SIDE_ERROR;
10829
10830
    ctx->postHandshakeAuth = 1;
10831
10832
    return 0;
10833
}
10834
10835
/* Allow post-handshake authentication in TLS v1.3 connection.
10836
 *
10837
 * ssl  The SSL/TLS object.
10838
 * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3,
10839
 * SIDE_ERROR when not a client and 0 on success.
10840
 */
10841
int wolfSSL_allow_post_handshake_auth(WOLFSSL* ssl)
10842
{
10843
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
10844
        return BAD_FUNC_ARG;
10845
    if (ssl->options.side == WOLFSSL_SERVER_END)
10846
        return SIDE_ERROR;
10847
10848
    ssl->options.postHandshakeAuth = 1;
10849
10850
    return 0;
10851
}
10852
10853
/* Request a certificate of the client.
10854
 * Can be called any time after handshake completion.
10855
 * A maximum of 256 requests can be sent on a connection.
10856
 *
10857
 * ssl  SSL/TLS object.
10858
 */
10859
int wolfSSL_request_certificate(WOLFSSL* ssl)
10860
{
10861
    int         ret;
10862
#ifndef NO_WOLFSSL_SERVER
10863
    CertReqCtx* certReqCtx;
10864
#endif
10865
10866
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
10867
        return BAD_FUNC_ARG;
10868
#ifndef NO_WOLFSSL_SERVER
10869
    if (ssl->options.side == WOLFSSL_CLIENT_END)
10870
        return SIDE_ERROR;
10871
    if (ssl->options.handShakeState != HANDSHAKE_DONE)
10872
        return NOT_READY_ERROR;
10873
    if (!ssl->options.postHandshakeAuth)
10874
        return POST_HAND_AUTH_ERROR;
10875
10876
    certReqCtx = (CertReqCtx*)XMALLOC(sizeof(CertReqCtx), ssl->heap,
10877
                                                       DYNAMIC_TYPE_TMP_BUFFER);
10878
    if (certReqCtx == NULL)
10879
        return MEMORY_E;
10880
    XMEMSET(certReqCtx, 0, sizeof(CertReqCtx));
10881
    certReqCtx->next = ssl->certReqCtx;
10882
    certReqCtx->len = 1;
10883
    if (certReqCtx->next != NULL)
10884
        certReqCtx->ctx = certReqCtx->next->ctx + 1;
10885
    ssl->certReqCtx = certReqCtx;
10886
10887
    ssl->msgsReceived.got_certificate = 0;
10888
    ssl->msgsReceived.got_certificate_verify = 0;
10889
    ssl->msgsReceived.got_finished = 0;
10890
10891
    ret = SendTls13CertificateRequest(ssl, &certReqCtx->ctx, certReqCtx->len);
10892
    if (ret == WANT_WRITE)
10893
        ret = WOLFSSL_ERROR_WANT_WRITE;
10894
    else if (ret == 0)
10895
        ret = WOLFSSL_SUCCESS;
10896
#else
10897
    ret = SIDE_ERROR;
10898
#endif
10899
10900
    return ret;
10901
}
10902
#endif /* !NO_CERTS && WOLFSSL_POST_HANDSHAKE_AUTH */
10903
10904
#if !defined(WOLFSSL_NO_SERVER_GROUPS_EXT)
10905
/* Get the preferred key exchange group.
10906
 *
10907
 * ssl  The SSL/TLS object.
10908
 * returns BAD_FUNC_ARG when ssl is NULL or not using TLS v1.3,
10909
 * SIDE_ERROR when not a client, NOT_READY_ERROR when handshake not complete
10910
 * and group number on success.
10911
 */
10912
int wolfSSL_preferred_group(WOLFSSL* ssl)
10913
0
{
10914
0
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
10915
0
        return BAD_FUNC_ARG;
10916
0
#ifndef NO_WOLFSSL_CLIENT
10917
0
    if (ssl->options.side == WOLFSSL_SERVER_END)
10918
0
        return SIDE_ERROR;
10919
0
    if (ssl->options.handShakeState != HANDSHAKE_DONE)
10920
0
        return NOT_READY_ERROR;
10921
10922
0
#ifdef HAVE_SUPPORTED_CURVES
10923
    /* Return supported groups only. */
10924
0
    return TLSX_SupportedCurve_Preferred(ssl, 1);
10925
#else
10926
    return 0;
10927
#endif
10928
#else
10929
    return SIDE_ERROR;
10930
#endif
10931
0
}
10932
#endif
10933
10934
#if defined(HAVE_SUPPORTED_CURVES)
10935
/* Sets the key exchange groups in rank order on a context.
10936
 *
10937
 * ctx     SSL/TLS context object.
10938
 * groups  Array of groups.
10939
 * count   Number of groups in array.
10940
 * returns BAD_FUNC_ARG when ctx or groups is NULL, not using TLS v1.3 or
10941
 * count is greater than WOLFSSL_MAX_GROUP_COUNT and WOLFSSL_SUCCESS on success.
10942
 */
10943
int wolfSSL_CTX_set_groups(WOLFSSL_CTX* ctx, int* groups, int count)
10944
0
{
10945
0
    int ret, i;
10946
10947
0
    WOLFSSL_ENTER("wolfSSL_CTX_set_groups");
10948
0
    if (ctx == NULL || groups == NULL || count > WOLFSSL_MAX_GROUP_COUNT)
10949
0
        return BAD_FUNC_ARG;
10950
0
    if (!IsAtLeastTLSv1_3(ctx->method->version))
10951
0
        return BAD_FUNC_ARG;
10952
10953
0
    ctx->numGroups = 0;
10954
0
    #if !defined(NO_TLS)
10955
0
    TLSX_Remove(&ctx->extensions, TLSX_SUPPORTED_GROUPS, ctx->heap);
10956
0
    #endif /* !NO_TLS */
10957
0
    for (i = 0; i < count; i++) {
10958
        /* Call to wolfSSL_CTX_UseSupportedCurve also checks if input groups
10959
         * are valid */
10960
0
        if ((ret = wolfSSL_CTX_UseSupportedCurve(ctx, (word16)groups[i]))
10961
0
                != WOLFSSL_SUCCESS) {
10962
0
    #if !defined(NO_TLS)
10963
0
            TLSX_Remove(&ctx->extensions, TLSX_SUPPORTED_GROUPS, ctx->heap);
10964
0
    #endif /* !NO_TLS */
10965
0
            return ret;
10966
0
        }
10967
0
        ctx->group[i] = (word16)groups[i];
10968
0
    }
10969
0
    ctx->numGroups = (byte)count;
10970
10971
0
    return WOLFSSL_SUCCESS;
10972
0
}
10973
10974
/* Sets the key exchange groups in rank order.
10975
 *
10976
 * ssl     SSL/TLS object.
10977
 * groups  Array of groups.
10978
 * count   Number of groups in array.
10979
 * returns BAD_FUNC_ARG when ssl or groups is NULL, not using TLS v1.3 or
10980
 * count is greater than WOLFSSL_MAX_GROUP_COUNT and WOLFSSL_SUCCESS on success.
10981
 */
10982
int wolfSSL_set_groups(WOLFSSL* ssl, int* groups, int count)
10983
0
{
10984
0
    int ret, i;
10985
10986
0
    WOLFSSL_ENTER("wolfSSL_set_groups");
10987
0
    if (ssl == NULL || groups == NULL || count > WOLFSSL_MAX_GROUP_COUNT)
10988
0
        return BAD_FUNC_ARG;
10989
0
    if (!IsAtLeastTLSv1_3(ssl->version))
10990
0
        return BAD_FUNC_ARG;
10991
10992
0
    ssl->numGroups = 0;
10993
0
    #if !defined(NO_TLS)
10994
0
    TLSX_Remove(&ssl->extensions, TLSX_SUPPORTED_GROUPS, ssl->heap);
10995
0
    #endif /* !NO_TLS */
10996
0
    for (i = 0; i < count; i++) {
10997
        /* Call to wolfSSL_UseSupportedCurve also checks if input groups
10998
                 * are valid */
10999
0
        if ((ret = wolfSSL_UseSupportedCurve(ssl, (word16)groups[i]))
11000
0
                != WOLFSSL_SUCCESS) {
11001
0
    #if !defined(NO_TLS)
11002
0
            TLSX_Remove(&ssl->extensions, TLSX_SUPPORTED_GROUPS, ssl->heap);
11003
0
    #endif /* !NO_TLS */
11004
0
            return ret;
11005
0
        }
11006
0
        ssl->group[i] = (word16)groups[i];
11007
0
    }
11008
0
    ssl->numGroups = (byte)count;
11009
11010
0
    return WOLFSSL_SUCCESS;
11011
0
}
11012
#endif /* HAVE_SUPPORTED_CURVES */
11013
11014
#ifndef NO_PSK
11015
/* Set the PSK callback, that is passed the cipher suite, for a client to use
11016
 * against context object.
11017
 *
11018
 * @param [in, out] ctx  SSL/TLS context object.
11019
 * @param [in]      cb   Client PSK callback passed a cipher suite.
11020
 */
11021
void wolfSSL_CTX_set_psk_client_cs_callback(WOLFSSL_CTX* ctx,
11022
                                            wc_psk_client_cs_callback cb)
11023
{
11024
    WOLFSSL_ENTER("SSL_CTX_set_psk_client_cs_callback");
11025
11026
    if (ctx == NULL)
11027
        return;
11028
11029
    ctx->havePSK = 1;
11030
    ctx->client_psk_cs_cb = cb;
11031
}
11032
11033
/* Set the PSK callback, that is passed the cipher suite, for a client to use
11034
 * against SSL object.
11035
 *
11036
 * @param [in, out] ssl  SSL/TLS object.
11037
 * @param [in]      cb   Client PSK callback passed a cipher suite.
11038
 */
11039
void wolfSSL_set_psk_client_cs_callback(WOLFSSL* ssl,
11040
                                        wc_psk_client_cs_callback cb)
11041
{
11042
    byte haveRSA = 1;
11043
    int  keySz   = 0;
11044
11045
    WOLFSSL_ENTER("SSL_set_psk_client_cs_callback");
11046
11047
    if (ssl == NULL)
11048
        return;
11049
11050
    ssl->options.havePSK = 1;
11051
    ssl->options.client_psk_cs_cb = cb;
11052
11053
    #ifdef NO_RSA
11054
        haveRSA = 0;
11055
    #endif
11056
    #ifndef NO_CERTS
11057
        keySz = ssl->buffers.keySz;
11058
    #endif
11059
    InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE,
11060
               ssl->options.haveDH, ssl->options.haveECDSAsig,
11061
               ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
11062
               ssl->options.haveFalconSig, ssl->options.haveDilithiumSig,
11063
               ssl->options.haveAnon, TRUE, ssl->options.side);
11064
}
11065
11066
/* Set the PSK callback that returns the cipher suite for a client to use
11067
 * against context object.
11068
 *
11069
 * @param [in, out] ctx  SSL/TLS context object.
11070
 * @param [in]      cb   Client PSK callback returning cipher suite.
11071
 */
11072
void wolfSSL_CTX_set_psk_client_tls13_callback(WOLFSSL_CTX* ctx,
11073
                                               wc_psk_client_tls13_callback cb)
11074
{
11075
    WOLFSSL_ENTER("SSL_CTX_set_psk_client_tls13_callback");
11076
11077
    if (ctx == NULL)
11078
        return;
11079
11080
    ctx->havePSK = 1;
11081
    ctx->client_psk_tls13_cb = cb;
11082
}
11083
11084
/* Set the PSK callback that returns the cipher suite for a client to use
11085
 * against SSL object.
11086
 *
11087
 * @param [in, out] ssl  SSL/TLS object.
11088
 * @param [in]      cb   Client PSK callback returning cipher suite.
11089
 */
11090
void wolfSSL_set_psk_client_tls13_callback(WOLFSSL* ssl,
11091
                                           wc_psk_client_tls13_callback cb)
11092
{
11093
    byte haveRSA = 1;
11094
    int  keySz   = 0;
11095
11096
    WOLFSSL_ENTER("SSL_set_psk_client_tls13_callback");
11097
11098
    if (ssl == NULL)
11099
        return;
11100
11101
    ssl->options.havePSK = 1;
11102
    ssl->options.client_psk_tls13_cb = cb;
11103
11104
    #ifdef NO_RSA
11105
        haveRSA = 0;
11106
    #endif
11107
    #ifndef NO_CERTS
11108
        keySz = ssl->buffers.keySz;
11109
    #endif
11110
    InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE,
11111
               ssl->options.haveDH, ssl->options.haveECDSAsig,
11112
               ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
11113
               ssl->options.haveFalconSig, ssl->options.haveDilithiumSig,
11114
               ssl->options.haveAnon, TRUE, ssl->options.side);
11115
}
11116
11117
/* Set the PSK callback that returns the cipher suite for a server to use
11118
 * against context object.
11119
 *
11120
 * @param [in, out] ctx  SSL/TLS context object.
11121
 * @param [in]      cb   Server PSK callback returning cipher suite.
11122
 */
11123
void wolfSSL_CTX_set_psk_server_tls13_callback(WOLFSSL_CTX* ctx,
11124
                                               wc_psk_server_tls13_callback cb)
11125
{
11126
    WOLFSSL_ENTER("SSL_CTX_set_psk_server_tls13_callback");
11127
    if (ctx == NULL)
11128
        return;
11129
    ctx->havePSK = 1;
11130
    ctx->server_psk_tls13_cb = cb;
11131
}
11132
11133
/* Set the PSK callback that returns the cipher suite for a server to use
11134
 * against SSL object.
11135
 *
11136
 * @param [in, out] ssl  SSL/TLS object.
11137
 * @param [in]      cb   Server PSK callback returning cipher suite.
11138
 */
11139
void wolfSSL_set_psk_server_tls13_callback(WOLFSSL* ssl,
11140
                                           wc_psk_server_tls13_callback cb)
11141
{
11142
    byte haveRSA = 1;
11143
    int  keySz   = 0;
11144
11145
    WOLFSSL_ENTER("SSL_set_psk_server_tls13_callback");
11146
    if (ssl == NULL)
11147
        return;
11148
11149
    ssl->options.havePSK = 1;
11150
    ssl->options.server_psk_tls13_cb = cb;
11151
11152
    #ifdef NO_RSA
11153
        haveRSA = 0;
11154
    #endif
11155
    #ifndef NO_CERTS
11156
        keySz = ssl->buffers.keySz;
11157
    #endif
11158
    InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE,
11159
               ssl->options.haveDH, ssl->options.haveECDSAsig,
11160
               ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
11161
               ssl->options.haveFalconSig, ssl->options.haveDilithiumSig,
11162
               ssl->options.haveAnon, TRUE, ssl->options.side);
11163
}
11164
11165
/* Get name of first supported cipher suite that uses the hash indicated.
11166
 *
11167
 * @param [in] ssl   SSL/TLS object.
11168
 * @param [in] hash  Name of hash algorithm. e.g. "SHA256", "SHA384"
11169
 * @return  Name of cipher suite.
11170
 * @return  NULL on failure.
11171
 */
11172
const char* wolfSSL_get_cipher_name_by_hash(WOLFSSL* ssl, const char* hash)
11173
{
11174
    const char* name = NULL;
11175
    byte mac = no_mac;
11176
    int i;
11177
11178
    if (XSTRCMP(hash, "SHA256") == 0) {
11179
        mac = sha256_mac;
11180
    }
11181
    else if (XSTRCMP(hash, "SHA384") == 0) {
11182
        mac = sha384_mac;
11183
    }
11184
    if (mac != no_mac) {
11185
        for (i = 0; i < ssl->suites->suiteSz; i += 2) {
11186
            if (SuiteMac(ssl->suites->suites + i) == mac) {
11187
                name = GetCipherNameInternal(ssl->suites->suites[i + 0],
11188
                                             ssl->suites->suites[i + 1]);
11189
                break;
11190
            }
11191
        }
11192
    }
11193
    return name;
11194
}
11195
#endif /* !NO_PSK */
11196
11197
11198
#ifndef NO_WOLFSSL_SERVER
11199
/* The server accepting a connection from a client.
11200
 * The protocol version is expecting to be TLS v1.3.
11201
 * If the client downgrades, and older versions of the protocol are compiled
11202
 * in, the server will fallback to wolfSSL_accept().
11203
 * Please see note at top of README if you get an error from accept.
11204
 *
11205
 * ssl  The SSL/TLS object.
11206
 * returns WOLFSSL_SUCCESS on successful handshake, WOLFSSL_FATAL_ERROR when
11207
 * unrecoverable error occurs and 0 otherwise.
11208
 * For more error information use wolfSSL_get_error().
11209
 */
11210
int wolfSSL_accept_TLSv13(WOLFSSL* ssl)
11211
0
{
11212
#if !defined(NO_CERTS) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
11213
    word16 havePSK = 0;
11214
#endif
11215
0
    int advanceState;
11216
0
    int ret = 0;
11217
11218
0
    WOLFSSL_ENTER("SSL_accept_TLSv13()");
11219
11220
0
#ifdef HAVE_ERRNO_H
11221
0
    errno = 0;
11222
0
#endif
11223
11224
0
    if (ssl == NULL)
11225
0
        return WOLFSSL_FATAL_ERROR;
11226
11227
#if !defined(NO_CERTS) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
11228
    havePSK = ssl->options.havePSK;
11229
#endif
11230
11231
0
    if (ssl->options.side != WOLFSSL_SERVER_END) {
11232
0
        ssl->error = SIDE_ERROR;
11233
0
        WOLFSSL_ERROR(ssl->error);
11234
0
        return WOLFSSL_FATAL_ERROR;
11235
0
    }
11236
11237
    /* make sure this wolfSSL object has arrays and rng setup. Protects
11238
     * case where the WOLFSSL object is re-used via wolfSSL_clear() */
11239
0
    if ((ret = ReinitSSL(ssl, ssl->ctx, 0)) != 0) {
11240
0
        return ret;
11241
0
    }
11242
11243
#ifdef WOLFSSL_WOLFSENTRY_HOOKS
11244
    if ((ssl->AcceptFilter != NULL) &&
11245
            ((ssl->options.acceptState == TLS13_ACCEPT_BEGIN)
11246
#ifdef HAVE_SECURE_RENEGOTIATION
11247
             || (ssl->options.acceptState == TLS13_ACCEPT_BEGIN_RENEG)
11248
#endif
11249
                ))
11250
    {
11251
        wolfSSL_netfilter_decision_t res;
11252
        if ((ssl->AcceptFilter(ssl, ssl->AcceptFilter_arg, &res) ==
11253
             WOLFSSL_SUCCESS) &&
11254
            (res == WOLFSSL_NETFILTER_REJECT)) {
11255
            ssl->error = SOCKET_FILTERED_E;
11256
            WOLFSSL_ERROR(ssl->error);
11257
            return WOLFSSL_FATAL_ERROR;
11258
        }
11259
    }
11260
#endif /* WOLFSSL_WOLFSENTRY_HOOKS */
11261
11262
0
#ifndef NO_CERTS
11263
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
11264
    if (!havePSK)
11265
#endif
11266
0
    {
11267
    #if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) || \
11268
        defined(WOLFSSL_NGINX) || defined (WOLFSSL_HAPROXY)
11269
        if (ssl->ctx->certSetupCb != NULL) {
11270
            WOLFSSL_MSG("CertSetupCb set. server cert and "
11271
                        "key not checked");
11272
        }
11273
        else
11274
    #endif
11275
0
        {
11276
0
            if (!ssl->buffers.certificate ||
11277
0
                !ssl->buffers.certificate->buffer) {
11278
11279
0
                WOLFSSL_MSG("accept error: server cert required");
11280
0
                ssl->error = NO_PRIVATE_KEY;
11281
0
                WOLFSSL_ERROR(ssl->error);
11282
0
                return WOLFSSL_FATAL_ERROR;
11283
0
            }
11284
11285
0
            if (!ssl->buffers.key || !ssl->buffers.key->buffer) {
11286
                /* allow no private key if using existing key */
11287
0
            #ifdef WOLF_PRIVATE_KEY_ID
11288
0
                if (ssl->devId != INVALID_DEVID
11289
                #ifdef HAVE_PK_CALLBACKS
11290
                    || wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)
11291
                #endif
11292
0
                ) {
11293
0
                    WOLFSSL_MSG("Allowing no server private key (external)");
11294
0
                }
11295
0
                else
11296
0
            #endif
11297
0
                {
11298
0
                    WOLFSSL_MSG("accept error: server key required");
11299
0
                    ssl->error = NO_PRIVATE_KEY;
11300
0
                    WOLFSSL_ERROR(ssl->error);
11301
0
                    return WOLFSSL_FATAL_ERROR;
11302
0
                }
11303
0
            }
11304
0
        }
11305
0
    }
11306
0
#endif /* NO_CERTS */
11307
11308
0
    if (ssl->buffers.outputBuffer.length > 0
11309
    #ifdef WOLFSSL_ASYNC_CRYPT
11310
        /* do not send buffered or advance state if last error was an
11311
            async pending operation */
11312
        && ssl->error != WC_PENDING_E
11313
    #endif
11314
0
    ) {
11315
11316
        /* fragOffset is non-zero when sending fragments. On the last
11317
         * fragment, fragOffset is zero again, and the state can be
11318
         * advanced. */
11319
0
        advanceState =
11320
0
            (ssl->options.acceptState == TLS13_ACCEPT_CLIENT_HELLO_DONE ||
11321
0
                ssl->options.acceptState ==
11322
0
                    TLS13_ACCEPT_HELLO_RETRY_REQUEST_DONE ||
11323
0
                ssl->options.acceptState == TLS13_ACCEPT_SECOND_REPLY_DONE ||
11324
0
                ssl->options.acceptState == TLS13_SERVER_HELLO_SENT ||
11325
0
                ssl->options.acceptState == TLS13_ACCEPT_THIRD_REPLY_DONE ||
11326
0
                ssl->options.acceptState == TLS13_SERVER_EXTENSIONS_SENT ||
11327
0
                ssl->options.acceptState == TLS13_CERT_REQ_SENT ||
11328
0
                ssl->options.acceptState == TLS13_CERT_SENT ||
11329
0
                ssl->options.acceptState == TLS13_CERT_VERIFY_SENT ||
11330
0
                ssl->options.acceptState == TLS13_ACCEPT_FINISHED_SENT ||
11331
0
                ssl->options.acceptState == TLS13_ACCEPT_FINISHED_DONE);
11332
11333
#ifdef WOLFSSL_DTLS13
11334
        if (ssl->options.dtls)
11335
            advanceState = advanceState && !ssl->dtls13SendingFragments
11336
                && !ssl->dtls13SendingAckOrRtx;
11337
#endif /* WOLFSSL_DTLS13 */
11338
11339
0
        if ((ssl->error = SendBuffered(ssl)) == 0) {
11340
0
            if (ssl->fragOffset == 0 && !ssl->options.buildingMsg) {
11341
0
                if (advanceState) {
11342
0
                    ssl->options.acceptState++;
11343
0
                    WOLFSSL_MSG("accept state: "
11344
0
                                "Advanced from last buffered fragment send");
11345
0
#ifdef WOLFSSL_ASYNC_IO
11346
0
                    FreeAsyncCtx(ssl, 0);
11347
0
#endif
11348
0
                }
11349
0
            }
11350
0
            else {
11351
0
                WOLFSSL_MSG("accept state: "
11352
0
                            "Not advanced, more fragments to send");
11353
0
            }
11354
11355
#ifdef WOLFSSL_DTLS13
11356
            if (ssl->options.dtls)
11357
                ssl->dtls13SendingAckOrRtx = 0;
11358
#endif /* WOLFSSL_DTLS13 */
11359
11360
0
        }
11361
0
        else {
11362
0
            ssl->error = ret;
11363
0
            WOLFSSL_ERROR(ssl->error);
11364
0
            return WOLFSSL_FATAL_ERROR;
11365
0
        }
11366
0
    }
11367
11368
0
    ret = RetrySendAlert(ssl);
11369
0
    if (ret != 0) {
11370
0
        ssl->error = ret;
11371
0
        WOLFSSL_ERROR(ssl->error);
11372
0
        return WOLFSSL_FATAL_ERROR;
11373
0
    }
11374
#ifdef WOLFSSL_DTLS13
11375
    if (ssl->options.dtls && ssl->dtls13SendingFragments) {
11376
        if ((ssl->error = Dtls13FragmentsContinue(ssl)) != 0) {
11377
                WOLFSSL_ERROR(ssl->error);
11378
                return WOLFSSL_FATAL_ERROR;
11379
        }
11380
11381
        /* we sent all the fragments. Advance state. */
11382
        ssl->options.acceptState++;
11383
    }
11384
#endif /* WOLFSSL_DTLS13 */
11385
11386
0
    switch (ssl->options.acceptState) {
11387
11388
#ifdef HAVE_SECURE_RENEGOTIATION
11389
        case TLS13_ACCEPT_BEGIN_RENEG:
11390
#endif
11391
0
        case TLS13_ACCEPT_BEGIN :
11392
            /* get client_hello */
11393
0
            while (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
11394
0
                if ((ssl->error = ProcessReply(ssl)) < 0) {
11395
0
                    WOLFSSL_ERROR(ssl->error);
11396
0
                    return WOLFSSL_FATAL_ERROR;
11397
0
                }
11398
11399
#ifdef WOLFSSL_DTLS13
11400
                if (ssl->options.dtls) {
11401
                    if ((ssl->error = Dtls13DoScheduledWork(ssl)) < 0) {
11402
                        WOLFSSL_ERROR(ssl->error);
11403
                        return WOLFSSL_FATAL_ERROR;
11404
                    }
11405
                }
11406
#endif /* WOLFSSL_DTLS13 */
11407
11408
0
            }
11409
11410
0
            ssl->options.acceptState = TLS13_ACCEPT_CLIENT_HELLO_DONE;
11411
0
            WOLFSSL_MSG("accept state ACCEPT_CLIENT_HELLO_DONE");
11412
0
            if (!IsAtLeastTLSv1_3(ssl->version))
11413
0
                return wolfSSL_accept(ssl);
11414
0
            FALL_THROUGH;
11415
11416
0
        case TLS13_ACCEPT_CLIENT_HELLO_DONE :
11417
0
            if (ssl->options.serverState ==
11418
0
                                          SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
11419
0
                if ((ssl->error = SendTls13ServerHello(ssl,
11420
0
                                                   hello_retry_request)) != 0) {
11421
0
                    WOLFSSL_ERROR(ssl->error);
11422
0
                    return WOLFSSL_FATAL_ERROR;
11423
0
                }
11424
#ifdef WOLFSSL_DTLS13
11425
                if (ssl->options.dtls && wolfSSL_dtls_get_using_nonblock(ssl)) {
11426
                    /* Reset the state so that we can statelessly await the
11427
                     * ClientHello that contains the cookie. Return a WANT_READ
11428
                     * to the user so that we don't drop UDP messages in the
11429
                     * network callbacks. */
11430
11431
                    /* Reset DTLS window */
11432
                    w64Zero(&ssl->dtls13Epochs[0].nextSeqNumber);
11433
                    w64Zero(&ssl->dtls13Epochs[0].nextPeerSeqNumber);
11434
                    XMEMSET(ssl->dtls13Epochs[0].window, 0,
11435
                            sizeof(ssl->dtls13Epochs[0].window));
11436
11437
                    ssl->keys.dtls_expected_peer_handshake_number = 0;
11438
                    ssl->keys.dtls_handshake_number = 0;
11439
11440
                    ssl->msgsReceived.got_client_hello = 0;
11441
#ifdef WOLFSSL_SEND_HRR_COOKIE
11442
                    /* Remove cookie so that it will get computed again */
11443
                    TLSX_Remove(&ssl->extensions, TLSX_COOKIE, ssl->heap);
11444
#endif
11445
11446
                    /* Reset states */
11447
                    ssl->options.serverState = NULL_STATE;
11448
                    ssl->options.clientState = NULL_STATE;
11449
                    ssl->options.connectState = CONNECT_BEGIN;
11450
                    ssl->options.acceptState  = ACCEPT_BEGIN;
11451
                    ssl->options.handShakeState  = NULL_STATE;
11452
11453
                    ssl->error = WANT_READ;
11454
                    WOLFSSL_ERROR(ssl->error);
11455
                    return WOLFSSL_FATAL_ERROR;
11456
                }
11457
#endif /* WOLFSSL_DTLS13 */
11458
0
            }
11459
11460
0
            ssl->options.acceptState = TLS13_ACCEPT_HELLO_RETRY_REQUEST_DONE;
11461
0
            WOLFSSL_MSG("accept state ACCEPT_HELLO_RETRY_REQUEST_DONE");
11462
0
            FALL_THROUGH;
11463
11464
0
        case TLS13_ACCEPT_HELLO_RETRY_REQUEST_DONE :
11465
    #ifdef WOLFSSL_TLS13_MIDDLEBOX_COMPAT
11466
            if (!ssl->options.dtls && ssl->options.tls13MiddleBoxCompat
11467
                && ssl->options.serverState ==
11468
                                          SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
11469
                if ((ssl->error = SendChangeCipher(ssl)) != 0) {
11470
                    WOLFSSL_ERROR(ssl->error);
11471
                    return WOLFSSL_FATAL_ERROR;
11472
                }
11473
                ssl->options.sentChangeCipher = 1;
11474
                ssl->options.serverState = SERVER_HELLO_RETRY_REQUEST_COMPLETE;
11475
            }
11476
    #endif
11477
0
            ssl->options.acceptState = TLS13_ACCEPT_FIRST_REPLY_DONE;
11478
0
            WOLFSSL_MSG("accept state ACCEPT_FIRST_REPLY_DONE");
11479
0
            FALL_THROUGH;
11480
11481
0
        case TLS13_ACCEPT_FIRST_REPLY_DONE :
11482
0
            if (ssl->options.serverState ==
11483
0
                                          SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
11484
0
                ssl->options.clientState = CLIENT_HELLO_RETRY;
11485
0
                while (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
11486
0
                    if ((ssl->error = ProcessReply(ssl)) < 0) {
11487
0
                        WOLFSSL_ERROR(ssl->error);
11488
0
                        return WOLFSSL_FATAL_ERROR;
11489
0
                    }
11490
11491
#ifdef WOLFSSL_DTLS13
11492
                if (ssl->options.dtls) {
11493
                    if ((ssl->error = Dtls13DoScheduledWork(ssl)) < 0) {
11494
                        WOLFSSL_ERROR(ssl->error);
11495
                        return WOLFSSL_FATAL_ERROR;
11496
                    }
11497
                }
11498
#endif /* WOLFSSL_DTLS13 */
11499
11500
0
                }
11501
0
            }
11502
11503
#ifdef WOLFSSL_DTLS
11504
            if (ssl->chGoodCb != NULL) {
11505
                int cbret = ssl->chGoodCb(ssl, ssl->chGoodCtx);
11506
                if (cbret < 0) {
11507
                    ssl->error = cbret;
11508
                    WOLFSSL_MSG("ClientHello Good Cb don't continue error");
11509
                    return WOLFSSL_FATAL_ERROR;
11510
                }
11511
            }
11512
#endif
11513
11514
0
            ssl->options.acceptState = TLS13_ACCEPT_SECOND_REPLY_DONE;
11515
0
            WOLFSSL_MSG("accept state ACCEPT_SECOND_REPLY_DONE");
11516
0
            FALL_THROUGH;
11517
11518
0
        case TLS13_ACCEPT_SECOND_REPLY_DONE :
11519
0
            if ((ssl->error = SendTls13ServerHello(ssl, server_hello)) != 0) {
11520
0
                WOLFSSL_ERROR(ssl->error);
11521
0
                return WOLFSSL_FATAL_ERROR;
11522
0
            }
11523
0
            ssl->options.acceptState = TLS13_SERVER_HELLO_SENT;
11524
0
            WOLFSSL_MSG("accept state SERVER_HELLO_SENT");
11525
0
            FALL_THROUGH;
11526
11527
0
        case TLS13_SERVER_HELLO_SENT :
11528
    #if defined(WOLFSSL_TLS13_MIDDLEBOX_COMPAT)
11529
            if (!ssl->options.dtls && ssl->options.tls13MiddleBoxCompat
11530
                          && !ssl->options.sentChangeCipher && !ssl->options.dtls) {
11531
                if ((ssl->error = SendChangeCipher(ssl)) != 0) {
11532
                    WOLFSSL_ERROR(ssl->error);
11533
                    return WOLFSSL_FATAL_ERROR;
11534
                }
11535
                ssl->options.sentChangeCipher = 1;
11536
            }
11537
    #endif
11538
11539
0
            ssl->options.acceptState = TLS13_ACCEPT_THIRD_REPLY_DONE;
11540
0
            WOLFSSL_MSG("accept state ACCEPT_THIRD_REPLY_DONE");
11541
0
            FALL_THROUGH;
11542
11543
0
        case TLS13_ACCEPT_THIRD_REPLY_DONE :
11544
0
#ifdef HAVE_SUPPORTED_CURVES
11545
0
            if (!ssl->options.noPskDheKe) {
11546
0
                ssl->error = TLSX_KeyShare_DeriveSecret(ssl);
11547
0
                if (ssl->error != 0)
11548
0
                    return WOLFSSL_FATAL_ERROR;
11549
0
            }
11550
0
#endif
11551
11552
0
            if ((ssl->error = SendTls13EncryptedExtensions(ssl)) != 0) {
11553
0
                WOLFSSL_ERROR(ssl->error);
11554
0
                return WOLFSSL_FATAL_ERROR;
11555
0
            }
11556
0
            ssl->options.acceptState = TLS13_SERVER_EXTENSIONS_SENT;
11557
0
            WOLFSSL_MSG("accept state SERVER_EXTENSIONS_SENT");
11558
0
            FALL_THROUGH;
11559
11560
0
        case TLS13_SERVER_EXTENSIONS_SENT :
11561
0
#ifndef NO_CERTS
11562
0
            if (!ssl->options.resuming) {
11563
0
                if (ssl->options.verifyPeer
11564
    #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
11565
                    && !ssl->options.verifyPostHandshake
11566
    #endif
11567
0
                   ) {
11568
0
                    ssl->error = SendTls13CertificateRequest(ssl, NULL, 0);
11569
0
                    if (ssl->error != 0) {
11570
0
                        WOLFSSL_ERROR(ssl->error);
11571
0
                        return WOLFSSL_FATAL_ERROR;
11572
0
                    }
11573
0
                }
11574
0
                else {
11575
                    /* SERVER: Peer auth good if not verifying client. */
11576
0
                    ssl->options.peerAuthGood = 1;
11577
0
                }
11578
0
            }
11579
0
#endif
11580
0
            ssl->options.acceptState = TLS13_CERT_REQ_SENT;
11581
0
            WOLFSSL_MSG("accept state CERT_REQ_SENT");
11582
0
            FALL_THROUGH;
11583
11584
0
        case TLS13_CERT_REQ_SENT :
11585
0
#ifndef NO_CERTS
11586
0
            if (!ssl->options.resuming && ssl->options.sendVerify) {
11587
0
                if ((ssl->error = SendTls13Certificate(ssl)) != 0) {
11588
0
                    WOLFSSL_ERROR(ssl->error);
11589
0
                    return WOLFSSL_FATAL_ERROR;
11590
0
                }
11591
0
            }
11592
0
#endif
11593
0
            ssl->options.acceptState = TLS13_CERT_SENT;
11594
0
            WOLFSSL_MSG("accept state CERT_SENT");
11595
0
            FALL_THROUGH;
11596
11597
0
        case TLS13_CERT_SENT :
11598
0
#if !defined(NO_CERTS) && (!defined(NO_RSA) || defined(HAVE_ECC) || \
11599
0
     defined(HAVE_ED25519) || defined(HAVE_ED448) || defined(HAVE_PQC))
11600
0
            if (!ssl->options.resuming && ssl->options.sendVerify) {
11601
0
                if ((ssl->error = SendTls13CertificateVerify(ssl)) != 0) {
11602
0
                    WOLFSSL_ERROR(ssl->error);
11603
0
                    return WOLFSSL_FATAL_ERROR;
11604
0
                }
11605
0
            }
11606
0
#endif
11607
0
            ssl->options.acceptState = TLS13_CERT_VERIFY_SENT;
11608
0
            WOLFSSL_MSG("accept state CERT_VERIFY_SENT");
11609
0
            FALL_THROUGH;
11610
11611
0
        case TLS13_CERT_VERIFY_SENT :
11612
0
            if ((ssl->error = SendTls13Finished(ssl)) != 0) {
11613
0
                WOLFSSL_ERROR(ssl->error);
11614
0
                return WOLFSSL_FATAL_ERROR;
11615
0
            }
11616
11617
0
            ssl->options.acceptState = TLS13_ACCEPT_FINISHED_SENT;
11618
0
            WOLFSSL_MSG("accept state ACCEPT_FINISHED_SENT");
11619
#ifdef WOLFSSL_EARLY_DATA
11620
            if (ssl->earlyData != no_early_data) {
11621
                ssl->options.handShakeState = SERVER_FINISHED_COMPLETE;
11622
                return WOLFSSL_SUCCESS;
11623
            }
11624
#endif
11625
0
            FALL_THROUGH;
11626
11627
0
        case TLS13_ACCEPT_FINISHED_SENT :
11628
#ifdef HAVE_SESSION_TICKET
11629
    #ifdef WOLFSSL_TLS13_TICKET_BEFORE_FINISHED
11630
            if (!ssl->options.verifyPeer && !ssl->options.noTicketTls13 &&
11631
                                                ssl->ctx->ticketEncCb != NULL) {
11632
                if ((ssl->error = SendTls13NewSessionTicket(ssl)) != 0) {
11633
                    WOLFSSL_ERROR(ssl->error);
11634
                    return WOLFSSL_FATAL_ERROR;
11635
                }
11636
                ssl->options.ticketsSent = 1;
11637
            }
11638
    #endif
11639
#endif /* HAVE_SESSION_TICKET */
11640
0
            ssl->options.acceptState = TLS13_PRE_TICKET_SENT;
11641
0
            WOLFSSL_MSG("accept state  TICKET_SENT");
11642
0
            FALL_THROUGH;
11643
11644
0
        case TLS13_PRE_TICKET_SENT :
11645
0
            while (ssl->options.clientState < CLIENT_FINISHED_COMPLETE) {
11646
0
                if ( (ssl->error = ProcessReply(ssl)) < 0) {
11647
0
                        WOLFSSL_ERROR(ssl->error);
11648
0
                        return WOLFSSL_FATAL_ERROR;
11649
0
                    }
11650
11651
#ifdef WOLFSSL_DTLS13
11652
                if (ssl->options.dtls) {
11653
                    if ((ssl->error = Dtls13DoScheduledWork(ssl)) < 0) {
11654
                        WOLFSSL_ERROR(ssl->error);
11655
                        return WOLFSSL_FATAL_ERROR;
11656
                    }
11657
                }
11658
#endif /* WOLFSSL_DTLS13 */
11659
0
            }
11660
11661
0
            ssl->options.acceptState = TLS13_ACCEPT_FINISHED_DONE;
11662
0
            WOLFSSL_MSG("accept state ACCEPT_FINISHED_DONE");
11663
0
            FALL_THROUGH;
11664
11665
0
        case TLS13_ACCEPT_FINISHED_DONE :
11666
            /* SERVER: When not resuming and verifying peer but no certificate
11667
             * received and not failing when not received then peer auth good.
11668
             */
11669
0
            if (!ssl->options.resuming && ssl->options.verifyPeer &&
11670
        #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
11671
                !ssl->options.verifyPostHandshake &&
11672
        #endif
11673
0
                !ssl->options.havePeerCert && !ssl->options.failNoCert) {
11674
0
                ssl->options.peerAuthGood = 1;
11675
0
            }
11676
            /* SERVER: check peer authentication. */
11677
0
            if (!ssl->options.peerAuthGood) {
11678
0
                WOLFSSL_MSG("Client authentication did not happen");
11679
0
                return WOLFSSL_FATAL_ERROR;
11680
0
            }
11681
#ifdef HAVE_SESSION_TICKET
11682
            while (ssl->options.ticketsSent < ssl->options.maxTicketTls13) {
11683
                if (!ssl->options.noTicketTls13 && ssl->ctx->ticketEncCb
11684
                        != NULL) {
11685
                    if ((ssl->error = SendTls13NewSessionTicket(ssl)) != 0) {
11686
                        WOLFSSL_ERROR(ssl->error);
11687
                        return WOLFSSL_FATAL_ERROR;
11688
                    }
11689
                }
11690
                ssl->options.ticketsSent++;
11691
11692
                /* only one session ticket is sent on session resumption */
11693
                if (ssl->options.resuming) {
11694
                    break;
11695
                }
11696
            }
11697
#endif /* HAVE_SESSION_TICKET */
11698
0
            ssl->options.acceptState = TLS13_TICKET_SENT;
11699
0
            WOLFSSL_MSG("accept state TICKET_SENT");
11700
0
            FALL_THROUGH;
11701
11702
0
        case TLS13_TICKET_SENT :
11703
0
#ifndef NO_HANDSHAKE_DONE_CB
11704
0
            if (ssl->hsDoneCb) {
11705
0
                int cbret = ssl->hsDoneCb(ssl, ssl->hsDoneCtx);
11706
0
                if (cbret < 0) {
11707
0
                    ssl->error = cbret;
11708
0
                    WOLFSSL_MSG("HandShake Done Cb don't continue error");
11709
0
                    return WOLFSSL_FATAL_ERROR;
11710
0
                }
11711
0
            }
11712
0
#endif /* NO_HANDSHAKE_DONE_CB */
11713
11714
0
            if (!ssl->options.keepResources) {
11715
0
                FreeHandshakeResources(ssl);
11716
0
            }
11717
11718
0
#if defined(WOLFSSL_ASYNC_IO) && !defined(WOLFSSL_ASYNC_CRYPT)
11719
            /* Free the remaining async context if not using it for crypto */
11720
0
            FreeAsyncCtx(ssl, 1);
11721
0
#endif
11722
11723
0
            ssl->error = 0; /* clear the error */
11724
11725
0
            WOLFSSL_LEAVE("SSL_accept()", WOLFSSL_SUCCESS);
11726
0
            return WOLFSSL_SUCCESS;
11727
11728
0
        default :
11729
0
            WOLFSSL_MSG("Unknown accept state ERROR");
11730
0
            return WOLFSSL_FATAL_ERROR;
11731
0
    }
11732
0
}
11733
#endif
11734
11735
#if !defined(NO_WOLFSSL_SERVER) && defined(HAVE_SESSION_TICKET)
11736
/* Server sends a session ticket to the peer.
11737
 *
11738
 * RFC 8446, section 4.6.1, para 1.
11739
 *
11740
 * ssl  The SSL/TLS object.
11741
 * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3,
11742
 *         SIDE_ERROR when not a server,
11743
 *         NOT_READY_ERROR when handshake not complete,
11744
 *         WOLFSSL_FATAL_ERROR when creating or sending message fails, and
11745
 *         WOLFSSL_SUCCESS on success.
11746
 */
11747
int wolfSSL_send_SessionTicket(WOLFSSL* ssl)
11748
{
11749
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
11750
        return BAD_FUNC_ARG;
11751
    if (ssl->options.side == WOLFSSL_CLIENT_END)
11752
        return SIDE_ERROR;
11753
    if (ssl->options.handShakeState != HANDSHAKE_DONE)
11754
        return NOT_READY_ERROR;
11755
11756
    if ((ssl->error = SendTls13NewSessionTicket(ssl)) != 0) {
11757
        WOLFSSL_ERROR(ssl->error);
11758
        return WOLFSSL_FATAL_ERROR;
11759
    }
11760
    ssl->options.ticketsSent++;
11761
11762
    return WOLFSSL_SUCCESS;
11763
}
11764
#endif
11765
11766
#ifdef WOLFSSL_EARLY_DATA
11767
/* Sets the maximum amount of early data that can be seen by server when using
11768
 * session tickets for resumption.
11769
 * A value of zero indicates no early data is to be sent by client using session
11770
 * tickets.
11771
 *
11772
 * ctx  The SSL/TLS CTX object.
11773
 * sz   Maximum size of the early data.
11774
 * returns BAD_FUNC_ARG when ctx is NULL, SIDE_ERROR when not a server and
11775
 * 0 on success.
11776
 */
11777
int wolfSSL_CTX_set_max_early_data(WOLFSSL_CTX* ctx, unsigned int sz)
11778
{
11779
    if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
11780
        return BAD_FUNC_ARG;
11781
    if (ctx->method->side == WOLFSSL_CLIENT_END)
11782
        return SIDE_ERROR;
11783
11784
    ctx->maxEarlyDataSz = sz;
11785
11786
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_ERROR_CODE_OPENSSL)
11787
    /* 1 on success in OpenSSL*/
11788
    return WOLFSSL_SUCCESS;
11789
#else
11790
    return 0;
11791
#endif
11792
}
11793
11794
/* Sets the maximum amount of early data that can be seen by server when using
11795
 * session tickets for resumption.
11796
 * A value of zero indicates no early data is to be sent by client using session
11797
 * tickets.
11798
 *
11799
 * ssl  The SSL/TLS object.
11800
 * sz   Maximum size of the early data.
11801
 * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3,
11802
 * SIDE_ERROR when not a server and 0 on success.
11803
 */
11804
int wolfSSL_set_max_early_data(WOLFSSL* ssl, unsigned int sz)
11805
{
11806
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
11807
        return BAD_FUNC_ARG;
11808
    if (ssl->options.side == WOLFSSL_CLIENT_END)
11809
        return SIDE_ERROR;
11810
11811
    ssl->options.maxEarlyDataSz = sz;
11812
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_ERROR_CODE_OPENSSL)
11813
    /* 1 on success in OpenSSL*/
11814
    return WOLFSSL_SUCCESS;
11815
#else
11816
    return 0;
11817
#endif
11818
}
11819
11820
/* Gets the maximum amount of early data that can be seen by server when using
11821
 * session tickets for resumption.
11822
 * A value of zero indicates no early data is to be sent by client using session
11823
 * tickets.
11824
 *
11825
 * ctx  The SSL/TLS CTX object.
11826
 * returns BAD_FUNC_ARG when ctx is NULL, SIDE_ERROR when not a server and
11827
 * returns the maximum amount of early data to be set
11828
 */
11829
int wolfSSL_CTX_get_max_early_data(WOLFSSL_CTX* ctx)
11830
{
11831
    if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
11832
        return BAD_FUNC_ARG;
11833
    if (ctx->method->side == WOLFSSL_CLIENT_END)
11834
        return SIDE_ERROR;
11835
11836
    return ctx->maxEarlyDataSz;
11837
}
11838
11839
/* Gets the maximum amount of early data that can be seen by server when using
11840
 * session tickets for resumption.
11841
 * A value of zero indicates no early data is to be sent by client using session
11842
 * tickets.
11843
 *
11844
 * ssl  The SSL/TLS object.
11845
 * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3,
11846
 * SIDE_ERROR when not a server and
11847
 * returns the maximum amount of early data to be set
11848
 */
11849
int wolfSSL_get_max_early_data(WOLFSSL* ssl)
11850
{
11851
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
11852
        return BAD_FUNC_ARG;
11853
    if (ssl->options.side == WOLFSSL_CLIENT_END)
11854
        return SIDE_ERROR;
11855
11856
    return ssl->options.maxEarlyDataSz;
11857
}
11858
11859
/* Write early data to the server.
11860
 *
11861
 * ssl    The SSL/TLS object.
11862
 * data   Early data to write
11863
 * sz     The size of the early data in bytes.
11864
 * outSz  The number of early data bytes written.
11865
 * returns BAD_FUNC_ARG when: ssl, data or outSz is NULL; sz is negative;
11866
 * or not using TLS v1.3. SIDE ERROR when not a server. Otherwise the number of
11867
 * early data bytes written.
11868
 */
11869
int wolfSSL_write_early_data(WOLFSSL* ssl, const void* data, int sz, int* outSz)
11870
{
11871
    int ret = 0;
11872
11873
    WOLFSSL_ENTER("SSL_write_early_data()");
11874
11875
    if (ssl == NULL || data == NULL || sz < 0 || outSz == NULL)
11876
        return BAD_FUNC_ARG;
11877
    if (!IsAtLeastTLSv1_3(ssl->version))
11878
        return BAD_FUNC_ARG;
11879
11880
#ifndef NO_WOLFSSL_CLIENT
11881
    if (ssl->options.side == WOLFSSL_SERVER_END)
11882
        return SIDE_ERROR;
11883
11884
    if (ssl->options.handShakeState == NULL_STATE) {
11885
        if (ssl->error != WC_PENDING_E)
11886
            ssl->earlyData = expecting_early_data;
11887
        ret = wolfSSL_connect_TLSv13(ssl);
11888
        if (ret != WOLFSSL_SUCCESS)
11889
            return WOLFSSL_FATAL_ERROR;
11890
        /* on client side, status is set to rejected        */
11891
        /* until sever accepts the early data extension.    */
11892
        ssl->earlyDataStatus = WOLFSSL_EARLY_DATA_REJECTED;
11893
    }
11894
    if (ssl->options.handShakeState == CLIENT_HELLO_COMPLETE) {
11895
#ifdef OPENSSL_EXTRA
11896
        /* when processed early data exceeds max size */
11897
        if (ssl->session->maxEarlyDataSz > 0 &&
11898
            (ssl->earlyDataSz + sz > ssl->session->maxEarlyDataSz)) {
11899
            ssl->error = TOO_MUCH_EARLY_DATA;
11900
            return WOLFSSL_FATAL_ERROR;
11901
        }
11902
#endif
11903
        ret = SendData(ssl, data, sz);
11904
        if (ret > 0) {
11905
            *outSz = ret;
11906
            /* store amount of processed early data from client */
11907
            ssl->earlyDataSz += ret;
11908
        }
11909
    }
11910
#else
11911
    return SIDE_ERROR;
11912
#endif
11913
11914
    WOLFSSL_LEAVE("SSL_write_early_data()", ret);
11915
11916
    if (ret < 0)
11917
        ret = WOLFSSL_FATAL_ERROR;
11918
    return ret;
11919
}
11920
11921
/* Read the any early data from the client.
11922
 *
11923
 * ssl    The SSL/TLS object.
11924
 * data   Buffer to put the early data into.
11925
 * sz     The size of the buffer in bytes.
11926
 * outSz  The number of early data bytes read.
11927
 * returns BAD_FUNC_ARG when: ssl, data or outSz is NULL; sz is negative;
11928
 * or not using TLS v1.3. SIDE ERROR when not a server. Otherwise the number of
11929
 * early data bytes read.
11930
 */
11931
int wolfSSL_read_early_data(WOLFSSL* ssl, void* data, int sz, int* outSz)
11932
{
11933
    int ret = 0;
11934
11935
    WOLFSSL_ENTER("wolfSSL_read_early_data()");
11936
11937
11938
    if (ssl == NULL || data == NULL || sz < 0 || outSz == NULL)
11939
        return BAD_FUNC_ARG;
11940
    if (!IsAtLeastTLSv1_3(ssl->version))
11941
        return BAD_FUNC_ARG;
11942
11943
#ifndef NO_WOLFSSL_SERVER
11944
    if (ssl->options.side == WOLFSSL_CLIENT_END)
11945
        return SIDE_ERROR;
11946
11947
    if (ssl->options.handShakeState == NULL_STATE) {
11948
        if (ssl->error != WC_PENDING_E)
11949
            ssl->earlyData = expecting_early_data;
11950
        ret = wolfSSL_accept_TLSv13(ssl);
11951
        if (ret <= 0)
11952
            return WOLFSSL_FATAL_ERROR;
11953
    }
11954
    if (ssl->options.handShakeState == SERVER_FINISHED_COMPLETE) {
11955
        ret = ReceiveData(ssl, (byte*)data, sz, FALSE);
11956
        if (ret > 0)
11957
            *outSz = ret;
11958
        if (ssl->error == ZERO_RETURN) {
11959
            ssl->error = WOLFSSL_ERROR_NONE;
11960
#ifdef WOLFSSL_DTLS13
11961
            if (ssl->options.dtls) {
11962
                ret = Dtls13DoScheduledWork(ssl);
11963
                if (ret  < 0) {
11964
                    ssl->error = ret;
11965
                    WOLFSSL_ERROR(ssl->error);
11966
                    return WOLFSSL_FATAL_ERROR;
11967
                }
11968
            }
11969
#endif /* WOLFSSL_DTLS13 */
11970
        }
11971
    }
11972
    else
11973
        ret = 0;
11974
#else
11975
    return SIDE_ERROR;
11976
#endif
11977
11978
    WOLFSSL_LEAVE("wolfSSL_read_early_data()", ret);
11979
11980
    if (ret < 0)
11981
        ret = WOLFSSL_FATAL_ERROR;
11982
    return ret;
11983
}
11984
11985
/* Returns early data status
11986
 *
11987
 * ssl    The SSL/TLS object.
11988
 * returns WOLFSSL_EARLY_DATA_ACCEPTED if the data was accepted
11989
 *         WOLFSSL_EARLY_DATA_REJECTED if the data was rejected
11990
 *         WOLFSSL_EARLY_DATA_NOT_SENT if no early data was sent
11991
 */
11992
int wolfSSL_get_early_data_status(const WOLFSSL* ssl)
11993
{
11994
    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
11995
        return BAD_FUNC_ARG;
11996
11997
    return ssl->earlyDataStatus;
11998
}
11999
#endif
12000
12001
#ifdef HAVE_SECRET_CALLBACK
12002
int wolfSSL_set_tls13_secret_cb(WOLFSSL* ssl, Tls13SecretCb cb, void* ctx)
12003
{
12004
    WOLFSSL_ENTER("wolfSSL_set_tls13_secret_cb");
12005
    if (ssl == NULL)
12006
        return WOLFSSL_FATAL_ERROR;
12007
12008
    ssl->tls13SecretCb = cb;
12009
    ssl->tls13SecretCtx = ctx;
12010
12011
    return WOLFSSL_SUCCESS;
12012
}
12013
#endif
12014
12015
#undef ERROR_OUT
12016
12017
#endif /* !WOLFCRYPT_ONLY */
12018
12019
#endif /* WOLFSSL_TLS13 */