Coverage Report

Created: 2026-11-12 06:59

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/wolfssl-sp-math-all-8bit/wolfssl/internal.h
Line
Count
Source
1
/* internal.h
2
 *
3
 * Copyright (C) 2006-2026 wolfSSL Inc.
4
 *
5
 * This file is part of wolfSSL.
6
 *
7
 * wolfSSL is free software; you can redistribute it and/or modify
8
 * it under the terms of the GNU General Public License as published by
9
 * the Free Software Foundation; either version 3 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * wolfSSL is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License
18
 * along with this program; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
20
 */
21
22
23
24
#ifndef WOLFSSL_INT_H
25
#define WOLFSSL_INT_H
26
27
#include <wolfssl/wolfcrypt/types.h>
28
#include <wolfssl/ssl.h>
29
#include <wolfssl/wolfio.h>
30
#ifdef HAVE_CRL
31
    #include <wolfssl/crl.h>
32
#endif
33
#include <wolfssl/wolfcrypt/random.h>
34
#ifndef NO_DES3
35
    #include <wolfssl/wolfcrypt/des3.h>
36
#endif
37
#ifdef HAVE_CHACHA
38
    #include <wolfssl/wolfcrypt/chacha.h>
39
#endif
40
#ifndef NO_ASN
41
    #include <wolfssl/wolfcrypt/asn.h>
42
    #include <wolfssl/wolfcrypt/pkcs12.h>
43
#endif
44
#ifndef NO_MD5
45
    #include <wolfssl/wolfcrypt/md5.h>
46
#endif
47
#ifndef NO_SHA
48
    #include <wolfssl/wolfcrypt/sha.h>
49
#endif
50
#ifndef NO_AES
51
    #include <wolfssl/wolfcrypt/aes.h>
52
#endif
53
#ifdef HAVE_POLY1305
54
    #include <wolfssl/wolfcrypt/poly1305.h>
55
#endif
56
#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
57
    /* Not OPENSSL_EXTRA-only: the TLS record layer calls the persistent-key
58
     * helpers wc_ChaCha20Poly1305_{Encrypt,Decrypt}_ex(), so this header has
59
     * to be visible whenever the ChaCha20-Poly1305 suites are built. */
60
    #include <wolfssl/wolfcrypt/chacha20_poly1305.h>
61
#endif
62
#ifdef HAVE_ARIA
63
    #include <wolfssl/wolfcrypt/port/aria/aria-crypt.h>
64
#endif
65
#ifdef HAVE_CAMELLIA
66
    #include <wolfssl/wolfcrypt/camellia.h>
67
#endif
68
#ifdef WOLFSSL_SM4
69
    #include <wolfssl/wolfcrypt/sm4.h>
70
#endif
71
#include <wolfssl/wolfcrypt/logging.h>
72
#ifndef NO_HMAC
73
    #include <wolfssl/wolfcrypt/hmac.h>
74
#endif
75
#ifndef NO_RC4
76
    #include <wolfssl/wolfcrypt/arc4.h>
77
#endif
78
#ifndef NO_SHA256
79
    #include <wolfssl/wolfcrypt/sha256.h>
80
#endif
81
#if defined(WOLFSSL_SHA384)
82
    #include <wolfssl/wolfcrypt/sha512.h>
83
#endif
84
#ifdef HAVE_OCSP
85
    #include <wolfssl/ocsp.h>
86
#endif
87
#ifdef WOLFSSL_QUIC
88
    #include <wolfssl/quic.h>
89
#endif
90
#ifdef WOLFSSL_SHA384
91
    #include <wolfssl/wolfcrypt/sha512.h>
92
#endif
93
#ifdef WOLFSSL_SHA512
94
    #include <wolfssl/wolfcrypt/sha512.h>
95
#endif
96
#ifdef WOLFSSL_SM3
97
    #include <wolfssl/wolfcrypt/sm3.h>
98
#endif
99
#ifdef HAVE_AESGCM
100
    #include <wolfssl/wolfcrypt/sha512.h>
101
#endif
102
#ifdef WOLFSSL_RIPEMD
103
    #include <wolfssl/wolfcrypt/ripemd.h>
104
#endif
105
#ifndef NO_RSA
106
    #include <wolfssl/wolfcrypt/rsa.h>
107
#endif
108
#ifdef HAVE_ECC
109
    #include <wolfssl/wolfcrypt/ecc.h>
110
#endif
111
#ifdef WOLFSSL_SM2
112
    #include <wolfssl/wolfcrypt/sm2.h>
113
#endif
114
#ifndef NO_DH
115
    #include <wolfssl/wolfcrypt/dh.h>
116
#endif
117
#ifdef HAVE_ED25519
118
    #include <wolfssl/wolfcrypt/ed25519.h>
119
#endif
120
#ifdef HAVE_CURVE25519
121
    #include <wolfssl/wolfcrypt/curve25519.h>
122
#endif
123
#ifdef HAVE_ED448
124
    #include <wolfssl/wolfcrypt/ed448.h>
125
#endif
126
#ifdef HAVE_CURVE448
127
    #include <wolfssl/wolfcrypt/curve448.h>
128
#endif
129
#ifdef HAVE_FALCON
130
    #include <wolfssl/wolfcrypt/falcon.h>
131
#endif
132
#ifdef WOLFSSL_HAVE_MLDSA
133
    #include <wolfssl/wolfcrypt/wc_mldsa.h>
134
#endif
135
#ifdef WOLFSSL_HAVE_SLHDSA
136
    #include <wolfssl/wolfcrypt/wc_slhdsa.h>
137
#endif
138
#ifdef HAVE_HKDF
139
    #include <wolfssl/wolfcrypt/kdf.h>
140
#endif
141
#ifndef WOLFSSL_NO_DEF_TICKET_ENC_CB
142
    #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) && \
143
        !defined(WOLFSSL_TICKET_ENC_AES128_GCM) && \
144
        !defined(WOLFSSL_TICKET_ENC_AES256_GCM)
145
        #include <wolfssl/wolfcrypt/chacha20_poly1305.h>
146
    #else
147
        #include <wolfssl/wolfcrypt/aes.h>
148
    #endif
149
#endif
150
151
#include <wolfssl/wolfcrypt/wc_encrypt.h>
152
#include <wolfssl/wolfcrypt/hash.h>
153
154
#if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
155
    #include <wolfssl/callbacks.h>
156
#endif
157
#ifdef WOLFSSL_CALLBACKS
158
    #include <signal.h>
159
#endif
160
161
#if !defined(WOLFCRYPT_ONLY) && !defined(INT_MAX)
162
    /* Needed for TLS/DTLS limit checking (Added in 91aad90c59 Jan 24, 2025) */
163
    #include <limits.h>
164
#endif
165
166
167
#ifdef HAVE_LIBZ
168
    #include "zlib.h"
169
#endif
170
171
#ifdef WOLFSSL_ASYNC_CRYPT
172
    #include <wolfssl/wolfcrypt/async.h>
173
#endif
174
175
#ifdef OPENSSL_EXTRA
176
    #ifdef WOLFCRYPT_HAVE_SRP
177
        #include <wolfssl/wolfcrypt/srp.h>
178
    #endif
179
#endif
180
181
#ifdef _MSC_VER
182
    /* 4996 warning to use MS extensions e.g., strcpy_s instead of strncpy */
183
    #pragma warning(disable: 4996)
184
#endif
185
186
#ifdef NO_SHA
187
    #define WC_SHA_DIGEST_SIZE 20
188
#endif
189
190
#ifdef NO_SHA256
191
    #define WC_SHA256_DIGEST_SIZE 32
192
#endif
193
194
#ifdef NO_MD5
195
    #define WC_MD5_DIGEST_SIZE 16
196
#endif
197
198
#ifdef WOLFSSL_IOTSAFE
199
    #include <wolfssl/wolfcrypt/port/iotsafe/iotsafe.h>
200
#endif
201
202
#if defined(WOLFSSL_RENESAS_TSIP_TLS)
203
    #include <wolfssl/wolfcrypt/port/Renesas/renesas_tsip_internal.h>
204
#endif
205
206
#include <wolfssl/wolfcrypt/hpke.h>
207
208
#if defined(WOLFSSL_SNIFFER) && defined(WOLFSSL_SNIFFER_KEYLOGFILE)
209
#include <wolfssl/sniffer.h>
210
#endif /* WOLFSSL_SNIFFER && WOLFSSL_SNIFFER_KEYLOGFILE */
211
212
#ifdef WOLFSSL_TEST_APPLE_NATIVE_CERT_VALIDATION
213
    #include <CoreFoundation/CoreFoundation.h>
214
#endif /* WOLFSSL_TEST_APPLE_NATIVE_CERT_VALIDATION */
215
216
#ifdef __cplusplus
217
    extern "C" {
218
#endif
219
220
/* ML-KEM client support requires generating a key pair (encapsulation key) and
221
 * decapsulating the server's ciphertext. */
222
#if defined(WOLFSSL_HAVE_MLKEM) && !defined(WOLFSSL_MLKEM_NO_MAKE_KEY) && \
223
     !defined(WOLFSSL_MLKEM_NO_DECAPSULATE)
224
    #define WOLFSSL_HAVE_MLKEM_CLIENT_SUPPORT
225
#endif
226
/* ML-KEM server support requires encapsulating to the client's key. */
227
#if defined(WOLFSSL_HAVE_MLKEM) && !defined(WOLFSSL_MLKEM_NO_ENCAPSULATE)
228
    #define WOLFSSL_HAVE_MLKEM_SERVER_SUPPORT
229
#endif
230
231
/* Define or comment out the cipher suites you'd like to be compiled in
232
   make sure to use at least one BUILD_SSL_xxx or BUILD_TLS_xxx is defined
233
234
   When adding cipher suites, add name to cipher_names, idx to cipher_name_idx
235
236
   Now that there is a maximum strength crypto build, the following BUILD_XXX
237
   flags need to be divided into two groups selected by WOLFSSL_MAX_STRENGTH.
238
   Those that do not use Perfect Forward Security and do not use AEAD ciphers
239
   need to be switched off. Allowed suites use (EC)DHE, AES-GCM|CCM, or
240
   CHACHA-POLY.
241
*/
242
243
/* Check that if WOLFSSL_MAX_STRENGTH is set that all the required options are
244
 * not turned off. */
245
#if defined(WOLFSSL_MAX_STRENGTH) && \
246
    ((!defined(HAVE_ECC) && (defined(NO_DH) || defined(NO_RSA))) || \
247
     (!defined(HAVE_AESGCM) && !defined(HAVE_AESCCM) && \
248
      (!defined(HAVE_POLY1305) || !defined(HAVE_CHACHA))) || \
249
     (defined(NO_SHA256) && !defined(WOLFSSL_SHA384)) || \
250
     !defined(NO_OLD_TLS))
251
252
    #error "You are trying to build max strength with requirements disabled."
253
#endif
254
255
#ifndef WOLFSSL_NO_TLS12
256
257
#ifndef WOLFSSL_MAX_STRENGTH
258
259
#ifdef WOLFSSL_AEAD_ONLY
260
    /* AES CBC ciphers are not allowed in AEAD only mode */
261
    #undef HAVE_AES_CBC
262
#endif
263
264
/* When adding new ciphersuites, make sure that they have appropriate
265
 * guards for WOLFSSL_HARDEN_TLS. */
266
#if defined(WOLFSSL_HARDEN_TLS) && \
267
    !defined(WOLFSSL_HARDEN_TLS_ALLOW_ALL_CIPHERSUITES)
268
/* Use a separate define (undef'ed later) to simplify macro logic. */
269
#define WSSL_HARDEN_TLS WOLFSSL_HARDEN_TLS
270
#define NO_TLS_DH
271
#endif
272
273
#ifndef WOLFSSL_AEAD_ONLY
274
    #if !defined(NO_RSA) && !defined(NO_RC4) && !defined(WSSL_HARDEN_TLS)
275
        /* MUST NOT negotiate RC4 cipher suites
276
         * https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */
277
        #if defined(WOLFSSL_STATIC_RSA)
278
            #if !defined(NO_SHA)
279
                #define BUILD_SSL_RSA_WITH_RC4_128_SHA
280
            #endif
281
            #if !defined(NO_MD5)
282
                #define BUILD_SSL_RSA_WITH_RC4_128_MD5
283
            #endif
284
        #endif
285
    #endif
286
287
    #if !defined(NO_RSA) && !defined(NO_DES3) && !defined(NO_DES3_TLS_SUITES)
288
        #if !defined(NO_SHA)
289
            #if defined(WOLFSSL_STATIC_RSA)
290
                #define BUILD_SSL_RSA_WITH_3DES_EDE_CBC_SHA
291
            #endif
292
        #endif
293
    #endif
294
#endif /* !WOLFSSL_AEAD_ONLY */
295
296
    #if !defined(NO_RSA) && !defined(NO_AES) && !defined(NO_TLS)
297
        #if !defined(NO_SHA) && defined(HAVE_AES_CBC)
298
            #if defined(WOLFSSL_STATIC_RSA)
299
                #ifdef WOLFSSL_AES_128
300
                    #define BUILD_TLS_RSA_WITH_AES_128_CBC_SHA
301
                #endif
302
                #ifdef WOLFSSL_AES_256
303
                    #define BUILD_TLS_RSA_WITH_AES_256_CBC_SHA
304
                #endif
305
            #endif
306
        #endif
307
        #if defined(WOLFSSL_STATIC_RSA)
308
            #if !defined (NO_SHA256) && defined(HAVE_AES_CBC)
309
                #ifdef WOLFSSL_AES_128
310
                    #define BUILD_TLS_RSA_WITH_AES_128_CBC_SHA256
311
                #endif
312
                #ifdef WOLFSSL_AES_256
313
                    #define BUILD_TLS_RSA_WITH_AES_256_CBC_SHA256
314
                #endif
315
            #endif
316
            #if defined (HAVE_AESGCM)
317
                #ifdef WOLFSSL_AES_128
318
                    #define BUILD_TLS_RSA_WITH_AES_128_GCM_SHA256
319
                #endif
320
                #if defined (WOLFSSL_SHA384) && defined(WOLFSSL_AES_256)
321
                    #define BUILD_TLS_RSA_WITH_AES_256_GCM_SHA384
322
                #endif
323
            #endif
324
            #if defined (HAVE_AESCCM)
325
                #ifdef WOLFSSL_AES_128
326
                    #define BUILD_TLS_RSA_WITH_AES_128_CCM_8
327
                #endif
328
                #ifdef WOLFSSL_AES_256
329
                    #define BUILD_TLS_RSA_WITH_AES_256_CCM_8
330
                #endif
331
            #endif
332
        #endif
333
    #endif
334
335
    #if defined(HAVE_CAMELLIA) && !defined(NO_TLS) && !defined(NO_CAMELLIA_CBC)
336
        #ifndef NO_RSA
337
          #if defined(WOLFSSL_STATIC_RSA)
338
            #if !defined(NO_SHA)
339
                #define BUILD_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA
340
                #define BUILD_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA
341
            #endif
342
            #ifndef NO_SHA256
343
                #define BUILD_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256
344
                #define BUILD_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256
345
            #endif
346
          #endif
347
            #if !defined(NO_DH) && !defined(NO_TLS_DH)
348
              /* SHOULD NOT negotiate cipher suites based on ephemeral
349
               * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*"
350
               * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */
351
              #if !defined(NO_SHA)
352
                #define BUILD_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA
353
                #define BUILD_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA
354
              #endif
355
                #ifndef NO_SHA256
356
                    #define BUILD_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256
357
                    #define BUILD_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256
358
                #endif
359
            #endif
360
        #endif
361
    #endif
362
363
#if defined(WOLFSSL_STATIC_PSK)
364
    #if !defined(NO_PSK) && !defined(NO_AES) && !defined(NO_TLS)
365
        #if !defined(NO_SHA)
366
            #ifdef WOLFSSL_AES_128
367
                #define BUILD_TLS_PSK_WITH_AES_128_CBC_SHA
368
            #endif
369
            #ifdef WOLFSSL_AES_256
370
                #define BUILD_TLS_PSK_WITH_AES_256_CBC_SHA
371
            #endif
372
        #endif
373
        #ifndef NO_SHA256
374
            #ifdef WOLFSSL_AES_128
375
                #ifdef HAVE_AES_CBC
376
                    #define BUILD_TLS_PSK_WITH_AES_128_CBC_SHA256
377
                #endif
378
                #ifdef HAVE_AESGCM
379
                    #define BUILD_TLS_PSK_WITH_AES_128_GCM_SHA256
380
                #endif
381
            #endif /* WOLFSSL_AES_128 */
382
            #ifdef HAVE_AESCCM
383
                #ifdef WOLFSSL_AES_128
384
                    #define BUILD_TLS_PSK_WITH_AES_128_CCM_8
385
                    #define BUILD_TLS_PSK_WITH_AES_128_CCM
386
                #endif
387
                #ifdef WOLFSSL_AES_256
388
                    #define BUILD_TLS_PSK_WITH_AES_256_CCM_8
389
                    #define BUILD_TLS_PSK_WITH_AES_256_CCM
390
                #endif
391
            #endif
392
        #endif
393
        #if defined(WOLFSSL_SHA384) && defined(WOLFSSL_AES_256)
394
            #ifdef HAVE_AES_CBC
395
                #define BUILD_TLS_PSK_WITH_AES_256_CBC_SHA384
396
            #endif
397
            #ifdef HAVE_AESGCM
398
                #define BUILD_TLS_PSK_WITH_AES_256_GCM_SHA384
399
            #endif
400
        #endif
401
    #endif
402
#endif
403
404
    #if !defined(NO_TLS) && defined(HAVE_NULL_CIPHER)
405
        #if !defined(NO_RSA)
406
            #if defined(WOLFSSL_STATIC_RSA)
407
                #ifndef NO_MD5
408
                    #define BUILD_TLS_RSA_WITH_NULL_MD5
409
                #endif
410
                #if !defined(NO_SHA)
411
                    #define BUILD_TLS_RSA_WITH_NULL_SHA
412
                #endif
413
                #ifndef NO_SHA256
414
                    #define BUILD_TLS_RSA_WITH_NULL_SHA256
415
                #endif
416
            #endif
417
        #endif
418
        #if !defined(NO_PSK) && defined(WOLFSSL_STATIC_PSK)
419
            #if !defined(NO_SHA)
420
                #define BUILD_TLS_PSK_WITH_NULL_SHA
421
            #endif
422
            #ifndef NO_SHA256
423
                #define BUILD_TLS_PSK_WITH_NULL_SHA256
424
            #endif
425
            #ifdef WOLFSSL_SHA384
426
                #define BUILD_TLS_PSK_WITH_NULL_SHA384
427
            #endif
428
        #endif
429
    #endif
430
431
    #if !defined(NO_DH) && !defined(NO_AES) && !defined(NO_TLS) && \
432
        !defined(NO_RSA) && !defined(NO_TLS_DH)
433
        /* SHOULD NOT negotiate cipher suites based on ephemeral
434
         * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*"
435
         * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */
436
437
        #if !defined(NO_SHA)
438
            #if defined(WOLFSSL_AES_128) && defined(HAVE_AES_CBC)
439
                #define BUILD_TLS_DHE_RSA_WITH_AES_128_CBC_SHA
440
            #endif
441
            #if defined(WOLFSSL_AES_256) && defined(HAVE_AES_CBC)
442
                #define BUILD_TLS_DHE_RSA_WITH_AES_256_CBC_SHA
443
            #endif
444
            #if !defined(NO_DES3) && !defined(NO_DES3_TLS_SUITES)
445
                #define BUILD_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA
446
            #endif
447
        #endif
448
        #if !defined(NO_SHA256) && defined(HAVE_AES_CBC)
449
            #ifdef WOLFSSL_AES_128
450
                #define BUILD_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
451
            #endif
452
            #ifdef WOLFSSL_AES_256
453
                #define BUILD_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256
454
            #endif
455
        #endif
456
    #endif
457
458
    #if defined(HAVE_ANON) && !defined(NO_TLS) && !defined(NO_DH) && \
459
        !defined(NO_AES)
460
        #if !defined(NO_SHA) && defined(HAVE_AES_CBC) && \
461
                defined(WOLFSSL_AES_128)
462
            #define BUILD_TLS_DH_anon_WITH_AES_128_CBC_SHA
463
        #endif
464
        #if defined(WOLFSSL_SHA384) && defined(HAVE_AESGCM) && \
465
                defined(WOLFSSL_AES_256)
466
            #define BUILD_TLS_DH_anon_WITH_AES_256_GCM_SHA384
467
        #endif
468
    #endif
469
470
    #if !defined(NO_DH) && !defined(NO_PSK) && !defined(NO_TLS) && \
471
        !defined(NO_TLS_DH)
472
        /* SHOULD NOT negotiate cipher suites based on ephemeral
473
         * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*"
474
         * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */
475
        #ifndef NO_SHA256
476
            #if !defined(NO_AES) && defined(WOLFSSL_AES_128) && \
477
                                                           defined(HAVE_AES_CBC)
478
                #define BUILD_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256
479
            #endif
480
            #ifdef HAVE_NULL_CIPHER
481
                #define BUILD_TLS_DHE_PSK_WITH_NULL_SHA256
482
            #endif
483
        #endif
484
        #ifdef WOLFSSL_SHA384
485
            #if !defined(NO_AES) && defined(WOLFSSL_AES_256) && \
486
                                                           defined(HAVE_AES_CBC)
487
                #define BUILD_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384
488
            #endif
489
            #ifdef HAVE_NULL_CIPHER
490
                #define BUILD_TLS_DHE_PSK_WITH_NULL_SHA384
491
            #endif
492
        #endif
493
    #endif
494
495
    #if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
496
                                     defined(HAVE_CURVE448)) && !defined(NO_TLS)
497
        #if !defined(NO_AES)
498
            #if !defined(NO_SHA) && defined(HAVE_AES_CBC)
499
                #if !defined(NO_RSA)
500
                    #ifdef WOLFSSL_AES_128
501
                        #define BUILD_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
502
                    #endif
503
                    #ifdef WOLFSSL_AES_256
504
                        #define BUILD_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
505
                    #endif
506
                    #if defined(WOLFSSL_STATIC_DH) && defined(HAVE_ECC)
507
                        #ifdef WOLFSSL_AES_128
508
                            #define BUILD_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA
509
                        #endif
510
                        #ifdef WOLFSSL_AES_256
511
                            #define BUILD_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA
512
                        #endif
513
                    #endif
514
                #endif
515
516
                #if defined(HAVE_ECC) || \
517
                        (defined(HAVE_CURVE25519) && defined(HAVE_ED25519)) || \
518
                        (defined(HAVE_CURVE448) && defined(HAVE_ED448))
519
                    #ifdef WOLFSSL_AES_128
520
                        #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
521
                    #endif
522
                    #ifdef WOLFSSL_AES_256
523
                        #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
524
                    #endif
525
                #endif
526
527
                #if defined(WOLFSSL_STATIC_DH) && defined(HAVE_ECC)
528
                    #ifdef WOLFSSL_AES_128
529
                        #define BUILD_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA
530
                    #endif
531
                    #ifdef WOLFSSL_AES_256
532
                        #define BUILD_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA
533
                    #endif
534
                #endif
535
            #endif /* NO_SHA */
536
            #if !defined(NO_SHA256) && defined(WOLFSSL_AES_128) && \
537
                                                           defined(HAVE_AES_CBC)
538
                #if !defined(NO_RSA)
539
                    #define BUILD_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
540
                    #if defined(WOLFSSL_STATIC_DH) && defined(HAVE_ECC)
541
                        #define BUILD_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256
542
                    #endif
543
                #endif
544
                #if defined(HAVE_ECC) || \
545
                        (defined(HAVE_CURVE25519) && defined(HAVE_ED25519)) || \
546
                        (defined(HAVE_CURVE448) && defined(HAVE_ED448))
547
                    #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
548
                #endif
549
                #if defined(WOLFSSL_STATIC_DH) && defined(HAVE_ECC)
550
                    #define BUILD_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256
551
                #endif
552
            #endif
553
554
            #if defined(WOLFSSL_SHA384) && defined(WOLFSSL_AES_256) && \
555
                                                           defined(HAVE_AES_CBC)
556
                #if !defined(NO_RSA)
557
                    #define BUILD_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
558
                    #if defined(WOLFSSL_STATIC_DH) && defined(HAVE_ECC)
559
                        #define BUILD_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384
560
                    #endif
561
                #endif
562
                #if defined(HAVE_ECC) || \
563
                        (defined(HAVE_CURVE25519) && defined(HAVE_ED25519)) || \
564
                        (defined(HAVE_CURVE448) && defined(HAVE_ED448))
565
                    #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384
566
                #endif
567
                #if defined(WOLFSSL_STATIC_DH) && defined(HAVE_ECC)
568
                    #define BUILD_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384
569
                #endif
570
            #endif
571
572
            #if defined (HAVE_AESGCM)
573
                #if !defined(NO_RSA)
574
                    #if defined(WOLFSSL_STATIC_DH) && defined(HAVE_ECC)
575
                        #ifdef WOLFSSL_AES_128
576
                            #define BUILD_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256
577
                        #endif
578
                    #endif
579
                    #if defined(WOLFSSL_SHA384)
580
                        #if defined(WOLFSSL_STATIC_DH) && defined(HAVE_ECC)
581
                            #ifdef WOLFSSL_AES_256
582
                                #define BUILD_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384
583
                            #endif
584
                        #endif
585
                    #endif
586
                #endif
587
588
                #if defined(WOLFSSL_STATIC_DH) && defined(WOLFSSL_AES_128) && \
589
                                                               defined(HAVE_ECC)
590
                    #define BUILD_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256
591
                #endif
592
593
                #if defined(WOLFSSL_SHA384)
594
                    #if defined(WOLFSSL_STATIC_DH) && \
595
                                   defined(WOLFSSL_AES_256) && defined(HAVE_ECC)
596
                        #define BUILD_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384
597
                    #endif
598
                #endif
599
            #endif
600
        #endif /* NO_AES */
601
        #ifdef HAVE_ARIA
602
            #define BUILD_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256
603
            #define BUILD_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384
604
        #endif /* HAVE_ARIA */
605
        #if !defined(NO_RC4) && !defined(WSSL_HARDEN_TLS)
606
            /* MUST NOT negotiate RC4 cipher suites
607
             * https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */
608
            #if !defined(NO_SHA)
609
                #if !defined(NO_RSA)
610
                    #ifndef WOLFSSL_AEAD_ONLY
611
                        #define BUILD_TLS_ECDHE_RSA_WITH_RC4_128_SHA
612
                    #endif
613
                    #if defined(WOLFSSL_STATIC_DH) && defined(HAVE_ECC)
614
                        #define BUILD_TLS_ECDH_RSA_WITH_RC4_128_SHA
615
                    #endif
616
                #endif
617
618
                #if defined(HAVE_ECC) || \
619
                        (defined(HAVE_CURVE25519) && defined(HAVE_ED25519)) || \
620
                        (defined(HAVE_CURVE448) && defined(HAVE_ED448))
621
                    #ifndef WOLFSSL_AEAD_ONLY
622
                        #define BUILD_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA
623
                    #endif
624
                #endif
625
                #if defined(WOLFSSL_STATIC_DH) && defined(HAVE_ECC)
626
                    #define BUILD_TLS_ECDH_ECDSA_WITH_RC4_128_SHA
627
                #endif
628
            #endif
629
        #endif
630
        #if !defined(NO_DES3) && !(defined(WSSL_HARDEN_TLS) && \
631
                                           WSSL_HARDEN_TLS > 112) && \
632
            !defined(NO_DES3_TLS_SUITES)
633
            /* 3DES offers only 112 bits of security.
634
             * Using guidance from section 5.6.1
635
             * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf */
636
            #ifndef NO_SHA
637
                #if !defined(NO_RSA)
638
                    #define BUILD_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
639
                    #if defined(WOLFSSL_STATIC_DH) && defined(HAVE_ECC)
640
                        #define BUILD_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA
641
                    #endif
642
                #endif
643
644
                #if defined(HAVE_ECC) || \
645
                        (defined(HAVE_CURVE25519) && defined(HAVE_ED25519)) || \
646
                        (defined(HAVE_CURVE448) && defined(HAVE_ED448))
647
                    #define BUILD_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA
648
                #endif
649
                #if defined(WOLFSSL_STATIC_DH) && defined(HAVE_ECC)
650
                    #define BUILD_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA
651
                #endif
652
            #endif /* NO_SHA */
653
        #endif
654
        #if defined(HAVE_NULL_CIPHER)
655
            #if !defined(NO_SHA)
656
                #if defined(HAVE_ECC) || \
657
                        (defined(HAVE_CURVE25519) && defined(HAVE_ED25519)) || \
658
                        (defined(HAVE_CURVE448) && defined(HAVE_ED448))
659
                    #define BUILD_TLS_ECDHE_ECDSA_WITH_NULL_SHA
660
                #endif
661
            #endif
662
            #if !defined(NO_PSK) && !defined(NO_SHA256)
663
                #define BUILD_TLS_ECDHE_PSK_WITH_NULL_SHA256
664
            #endif
665
        #endif
666
        #if !defined(NO_PSK) && !defined(NO_SHA256) && !defined(NO_AES) && \
667
            defined(WOLFSSL_AES_128) && defined(HAVE_AES_CBC)
668
            #define BUILD_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256
669
        #endif
670
        #if !defined(NO_PSK) && !defined(NO_SHA256) && !defined(NO_AES) && \
671
            defined(WOLFSSL_AES_128) && defined(HAVE_AESGCM)
672
            #define BUILD_TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256
673
        #endif
674
    #endif
675
    #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) && !defined(NO_SHA256)
676
        #if !defined(NO_OLD_POLY1305)
677
        #if defined(HAVE_ECC) || \
678
                        (defined(HAVE_CURVE25519) && defined(HAVE_ED25519)) || \
679
                        (defined(HAVE_CURVE448) && defined(HAVE_ED448))
680
            #define BUILD_TLS_ECDHE_ECDSA_WITH_CHACHA20_OLD_POLY1305_SHA256
681
        #endif
682
        #if !defined(NO_RSA) && defined(HAVE_ECC)
683
            #define BUILD_TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256
684
        #endif
685
        #if !defined(NO_DH) && !defined(NO_RSA) && !defined(NO_TLS_DH)
686
            /* SHOULD NOT negotiate cipher suites based on ephemeral
687
             * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*"
688
             * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */
689
            #define BUILD_TLS_DHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256
690
        #endif
691
        #endif /* NO_OLD_POLY1305 */
692
        #if !defined(NO_PSK)
693
            #define BUILD_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256
694
            #if defined(HAVE_ECC) || defined(HAVE_ED25519) || \
695
                                                             defined(HAVE_ED448)
696
                #define BUILD_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256
697
            #endif
698
            #if !defined(NO_DH) && !defined(NO_TLS_DH)
699
                /* SHOULD NOT negotiate cipher suites based on ephemeral
700
                 * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*"
701
                 * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */
702
                #define BUILD_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256
703
            #endif
704
        #endif /* !NO_PSK */
705
    #endif
706
707
#endif /* !WOLFSSL_MAX_STRENGTH */
708
709
#if !defined(NO_DH) && !defined(NO_AES) && !defined(NO_TLS) && \
710
    !defined(NO_RSA) && defined(HAVE_AESGCM) && !defined(NO_TLS_DH)
711
    /* SHOULD NOT negotiate cipher suites based on ephemeral
712
     * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*"
713
     * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */
714
715
    #if !defined(NO_SHA256) && defined(WOLFSSL_AES_128)
716
        #define BUILD_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
717
    #endif
718
719
    #if defined(WOLFSSL_SHA384) && defined(WOLFSSL_AES_256)
720
        #define BUILD_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384
721
    #endif
722
#endif
723
724
#if !defined(NO_DH) && !defined(NO_PSK) && !defined(NO_TLS) && \
725
    !defined(NO_TLS_DH)
726
    /* SHOULD NOT negotiate cipher suites based on ephemeral
727
     * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*"
728
     * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */
729
    #ifndef NO_SHA256
730
        #if defined(HAVE_AESGCM) && defined(WOLFSSL_AES_128)
731
            #define BUILD_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256
732
        #endif
733
        #ifdef HAVE_AESCCM
734
            #ifdef WOLFSSL_AES_128
735
                #define BUILD_TLS_DHE_PSK_WITH_AES_128_CCM
736
            #endif
737
            #ifdef WOLFSSL_AES_256
738
                #define BUILD_TLS_DHE_PSK_WITH_AES_256_CCM
739
            #endif
740
        #endif
741
    #endif
742
    #if defined(WOLFSSL_SHA384) && defined(HAVE_AESGCM) && \
743
        defined(WOLFSSL_AES_256)
744
        #define BUILD_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384
745
    #endif
746
#endif
747
748
#if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)) \
749
                                         && !defined(NO_TLS) && !defined(NO_AES)
750
    #ifdef HAVE_AESGCM
751
        #if !defined(NO_SHA256) && defined(WOLFSSL_AES_128)
752
            #if defined(HAVE_ECC) || \
753
                        (defined(HAVE_CURVE25519) && defined(HAVE_ED25519)) || \
754
                        (defined(HAVE_CURVE448) && defined(HAVE_ED448))
755
                #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
756
            #endif
757
            #ifndef NO_RSA
758
                #define BUILD_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
759
            #endif
760
        #endif
761
        #if defined(WOLFSSL_SHA384) && defined(WOLFSSL_AES_256)
762
            #if defined(HAVE_ECC) || \
763
                        (defined(HAVE_CURVE25519) && defined(HAVE_ED25519)) || \
764
                        (defined(HAVE_CURVE448) && defined(HAVE_ED448))
765
                #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
766
            #endif
767
            #ifndef NO_RSA
768
                #define BUILD_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
769
            #endif
770
        #endif
771
    #endif
772
    #if defined(HAVE_AESCCM) && !defined(NO_SHA256)
773
        #if defined(HAVE_ECC) || \
774
                        (defined(HAVE_CURVE25519) && defined(HAVE_ED25519)) || \
775
                        (defined(HAVE_CURVE448) && defined(HAVE_ED448))
776
            #ifdef WOLFSSL_AES_128
777
                #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CCM
778
                #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8
779
            #endif
780
            #ifdef WOLFSSL_AES_256
781
                #define BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8
782
            #endif
783
        #endif
784
    #endif
785
#endif
786
787
#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) && !defined(NO_SHA256)
788
    #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
789
        #if defined(HAVE_ECC) || \
790
                        (defined(HAVE_CURVE25519) && defined(HAVE_ED25519)) || \
791
                        (defined(HAVE_CURVE448) && defined(HAVE_ED448))
792
            #define BUILD_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
793
        #endif
794
        #ifndef NO_RSA
795
            #define BUILD_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
796
        #endif
797
    #endif
798
    #if !defined(NO_DH) && !defined(NO_RSA) && !defined(NO_TLS_DH)
799
        /* SHOULD NOT negotiate cipher suites based on ephemeral
800
         * finite-field Diffie-Hellman key agreement (i.e., "TLS_DHE_*"
801
         * suites). https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */
802
        #define BUILD_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256
803
    #endif
804
#endif
805
806
    #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
807
        #ifdef WOLFSSL_SM4_CBC
808
            #define BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3
809
        #endif
810
        #ifdef WOLFSSL_SM4_GCM
811
            #define BUILD_TLS_ECDHE_ECDSA_WITH_SM4_GCM_SM3
812
        #endif
813
        #ifdef WOLFSSL_SM4_CCM
814
            #define BUILD_TLS_ECDHE_ECDSA_WITH_SM4_CCM_SM3
815
        #endif
816
    #endif
817
#endif
818
819
#if defined(WOLFSSL_TLS13)
820
    #ifdef HAVE_AESGCM
821
        #if !defined(NO_SHA256) && defined(WOLFSSL_AES_128)
822
            #define BUILD_TLS_AES_128_GCM_SHA256
823
        #endif
824
        #if defined(WOLFSSL_SHA384) && defined(WOLFSSL_AES_256)
825
            #define BUILD_TLS_AES_256_GCM_SHA384
826
        #endif
827
    #endif
828
829
    #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
830
        #ifndef NO_SHA256
831
            #define BUILD_TLS_CHACHA20_POLY1305_SHA256
832
        #endif
833
    #endif
834
835
    #ifdef HAVE_AESCCM
836
        #if !defined(NO_SHA256) && defined(WOLFSSL_AES_128)
837
            #define BUILD_TLS_AES_128_CCM_SHA256
838
            #define BUILD_TLS_AES_128_CCM_8_SHA256
839
        #endif
840
    #endif
841
    #ifdef HAVE_NULL_CIPHER
842
        #ifndef NO_SHA256
843
            #define BUILD_TLS_SHA256_SHA256
844
        #endif
845
        #ifdef WOLFSSL_SHA384
846
            #define BUILD_TLS_SHA384_SHA384
847
        #endif
848
    #endif
849
850
    #ifdef WOLFSSL_SM3
851
        #ifdef WOLFSSL_SM4_GCM
852
            #define BUILD_TLS_SM4_GCM_SM3
853
        #endif
854
855
        #ifdef WOLFSSL_SM4_CCM
856
            #define BUILD_TLS_SM4_CCM_SM3
857
        #endif
858
    #endif
859
#endif
860
861
#if !defined(WOLFCRYPT_ONLY) && defined(NO_PSK) && \
862
    (defined(NO_DH) || !defined(HAVE_ANON)) && \
863
    defined(NO_RSA) && !defined(HAVE_ECC) && \
864
    !defined(HAVE_ED25519) && !defined(HAVE_ED448) && \
865
    (!defined(WOLFSSL_TLS13) || \
866
     (!defined(HAVE_FALCON) && !defined(WOLFSSL_HAVE_MLDSA) && \
867
      !defined(WOLFSSL_HAVE_SLHDSA)))
868
   #error "No cipher suites available with this build"
869
#endif
870
871
#ifdef WOLFSSL_MULTICAST
872
    #if defined(HAVE_NULL_CIPHER) && !defined(NO_SHA256)
873
        #define BUILD_WDM_WITH_NULL_SHA256
874
    #endif
875
#endif
876
877
#if defined(BUILD_SSL_RSA_WITH_RC4_128_SHA) || \
878
    defined(BUILD_SSL_RSA_WITH_RC4_128_MD5)
879
    #define BUILD_ARC4
880
#endif
881
882
#if defined(BUILD_SSL_RSA_WITH_3DES_EDE_CBC_SHA)
883
    #define BUILD_DES3
884
#endif
885
886
#if defined(BUILD_TLS_RSA_WITH_AES_128_CBC_SHA) || \
887
    defined(BUILD_TLS_RSA_WITH_AES_256_CBC_SHA) || \
888
    defined(BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256) || \
889
    defined(BUILD_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256)
890
    #undef  BUILD_AES
891
    #define BUILD_AES
892
#endif
893
894
#if defined(BUILD_TLS_RSA_WITH_AES_128_GCM_SHA256) || \
895
    defined(BUILD_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256) || \
896
    defined(BUILD_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256) || \
897
    defined(BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256) || \
898
    defined(BUILD_TLS_PSK_WITH_AES_128_GCM_SHA256) || \
899
    defined(BUILD_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256) || \
900
    defined(BUILD_TLS_RSA_WITH_AES_256_GCM_SHA384) || \
901
    defined(BUILD_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384) || \
902
    defined(BUILD_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) || \
903
    defined(BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384) || \
904
    defined(BUILD_TLS_PSK_WITH_AES_256_GCM_SHA384) || \
905
    defined(BUILD_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384) || \
906
    defined(BUILD_TLS_AES_128_GCM_SHA256) || \
907
    defined(BUILD_TLS_AES_256_GCM_SHA384)
908
    #define BUILD_AESGCM
909
#else
910
    /* No AES-GCM cipher suites available with build */
911
    #define NO_AESGCM_AEAD
912
#endif
913
914
#if defined(BUILD_TLS_RSA_WITH_AES_128_CCM_8) || \
915
    defined(BUILD_TLS_RSA_WITH_AES_256_CCM_8) || \
916
    defined(BUILD_TLS_PSK_WITH_AES_128_CCM_8) || \
917
    defined(BUILD_TLS_PSK_WITH_AES_128_CCM) || \
918
    defined(BUILD_TLS_PSK_WITH_AES_256_CCM_8) || \
919
    defined(BUILD_TLS_PSK_WITH_AES_256_CCM) || \
920
    defined(BUILD_TLS_DHE_PSK_WITH_AES_128_CCM) || \
921
    defined(BUILD_TLS_DHE_PSK_WITH_AES_256_CCM) || \
922
    defined(BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CCM) || \
923
    defined(BUILD_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8) || \
924
    defined(BUILD_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8) || \
925
    defined(BUILD_TLS_AES_128_CCM_SHA256) || \
926
    defined(BUILD_TLS_AES_128_CCM_8_SHA256)
927
    #define BUILD_AESCCM
928
#else
929
    /* No AES-CCM cipher suites available with build */
930
    #define NO_AESCCM_AEAD
931
#endif
932
933
#if defined(BUILD_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256) || \
934
    defined(BUILD_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384)
935
    #define BUILD_ARIA
936
#endif
937
938
#if defined(BUILD_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256) || \
939
    defined(BUILD_TLS_DHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256) || \
940
    defined(BUILD_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256) || \
941
    defined(BUILD_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256) || \
942
    defined(BUILD_TLS_ECDHE_ECDSA_WITH_CHACHA20_OLD_POLY1305_SHA256) || \
943
    defined(BUILD_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256) || \
944
    defined(BUILD_TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256) || \
945
    defined(BUILD_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256) || \
946
    defined(BUILD_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256) || \
947
    defined(BUILD_TLS_CHACHA20_POLY1305_SHA256)
948
    /* Have an available ChaCha Poly cipher suite */
949
#else
950
    /* No ChaCha Poly cipher suites available with build */
951
    #define NO_CHAPOL_AEAD
952
#endif
953
954
#ifdef NO_DES3
955
    #define DES_BLOCK_SIZE 8
956
#else
957
    #undef  BUILD_DES3
958
    #define BUILD_DES3
959
#endif
960
961
#if defined(NO_AES) || !defined(HAVE_AES_DECRYPT)
962
    #undef WC_AES_BLOCK_SIZE
963
    #define WC_AES_BLOCK_SIZE 16
964
    #undef  BUILD_AES
965
#else
966
    #undef  BUILD_AES
967
    #define BUILD_AES
968
#endif
969
970
#if !defined(NO_RC4) && !defined(WSSL_HARDEN_TLS)
971
    /* MUST NOT negotiate RC4 cipher suites
972
     * https://www.rfc-editor.org/rfc/rfc9325#section-4.1 */
973
    #undef  BUILD_ARC4
974
    #define BUILD_ARC4
975
#endif
976
977
#ifdef HAVE_CHACHA
978
0
    #define CHACHA20_BLOCK_SIZE 16
979
#endif
980
981
#if defined(WOLFSSL_MAX_STRENGTH) || \
982
    (defined(HAVE_AESGCM) && !defined(NO_AESGCM_AEAD)) || \
983
     defined(HAVE_AESCCM) || \
984
     defined(HAVE_ARIA) || \
985
    (defined(HAVE_CHACHA) && defined(HAVE_POLY1305) && \
986
     !defined(NO_CHAPOL_AEAD)) || \
987
    defined(WOLFSSL_SM4_GCM) || defined(WOLFSSL_SM4_CCM) || \
988
    (defined(WOLFSSL_TLS13) && defined(HAVE_NULL_CIPHER))
989
990
    #define HAVE_AEAD
991
#endif
992
993
#if defined(WOLFSSL_MAX_STRENGTH) || \
994
    defined(HAVE_ECC) || !defined(NO_DH)
995
996
    #define HAVE_PFS
997
#endif
998
999
#ifdef WSSL_HARDEN_TLS
1000
    #ifdef HAVE_NULL_CIPHER
1001
        #error "NULL ciphers not allowed https://www.rfc-editor.org/rfc/rfc9325#section-4.1"
1002
    #endif
1003
    #ifdef WOLFSSL_STATIC_RSA
1004
        #error "Static RSA ciphers not allowed https://www.rfc-editor.org/rfc/rfc9325#section-4.1"
1005
    #endif
1006
    #ifdef WOLFSSL_STATIC_DH
1007
        #error "Static DH ciphers not allowed https://www.rfc-editor.org/rfc/rfc9325#section-4.1"
1008
    #endif
1009
    #ifdef HAVE_ANON
1010
        #error "At least the server side has to be authenticated"
1011
    #endif
1012
#endif
1013
1014
#undef WSSL_HARDEN_TLS
1015
1016
/* CA Names feature (TLS 1.3 certificate_authorities extension, RFC 8446).
1017
 * Enabled by default; opt out with WOLFSSL_NO_CA_NAMES. The OpenSSL
1018
 * stack-of-X509_NAME API is wired in when OPENSSL_EXTRA is also defined. */
1019
#ifndef WOLFSSL_NO_CA_NAMES
1020
    #ifdef OPENSSL_EXTRA
1021
        #define SSL_CLIENT_CA_NAMES(ssl) ((ssl)->client_ca_names != NULL ? \
1022
            (ssl)->client_ca_names : \
1023
            (ssl)->ctx->client_ca_names)
1024
        #define SSL_CA_NAMES(ssl) ((ssl)->ca_names != NULL ? \
1025
            (ssl)->ca_names : \
1026
            (ssl)->ctx->ca_names)
1027
        /* On the server, client_ca_names has priority over ca_names if both
1028
         * are set. This mimics OpenSSL's API:
1029
         * https://docs.openssl.org/3.6/man3/SSL_CTX_set0_CA_list/ */
1030
        #define SSL_PRIORITY_CA_NAMES(ssl) \
1031
            (((ssl)->options.side == WOLFSSL_SERVER_END && \
1032
            SSL_CLIENT_CA_NAMES(ssl) != NULL) ? \
1033
                SSL_CLIENT_CA_NAMES(ssl) : \
1034
                SSL_CA_NAMES(ssl))
1035
    #endif
1036
    #ifdef WOLFSSL_TLS13
1037
    /* wolfSSL native CA list: SSL override, else CTX. */
1038
    #define WS_CA_NAMES(ssl) ((ssl)->ws_ca_names != NULL ? \
1039
        (ssl)->ws_ca_names : \
1040
        ((ssl)->ctx != NULL ? (ssl)->ctx->ws_ca_names : NULL))
1041
    #endif
1042
#endif
1043
1044
1045
/* actual cipher values, 2nd byte */
1046
enum {
1047
    TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA = 0x16,
1048
    TLS_DHE_RSA_WITH_AES_256_CBC_SHA  = 0x39,
1049
    TLS_DHE_RSA_WITH_AES_128_CBC_SHA  = 0x33,
1050
    TLS_DH_anon_WITH_AES_128_CBC_SHA  = 0x34,
1051
    TLS_RSA_WITH_AES_256_CBC_SHA      = 0x35,
1052
    TLS_RSA_WITH_AES_128_CBC_SHA      = 0x2F,
1053
    TLS_RSA_WITH_NULL_MD5             = 0x01,
1054
    TLS_RSA_WITH_NULL_SHA             = 0x02,
1055
    TLS_PSK_WITH_AES_256_CBC_SHA      = 0x8d,
1056
    TLS_PSK_WITH_AES_128_CBC_SHA256   = 0xae,
1057
    TLS_PSK_WITH_AES_256_CBC_SHA384   = 0xaf,
1058
    TLS_PSK_WITH_AES_128_CBC_SHA      = 0x8c,
1059
    TLS_PSK_WITH_NULL_SHA256          = 0xb0,
1060
    TLS_PSK_WITH_NULL_SHA384          = 0xb1,
1061
    TLS_PSK_WITH_NULL_SHA             = 0x2c,
1062
    SSL_RSA_WITH_RC4_128_SHA          = 0x05,
1063
    SSL_RSA_WITH_RC4_128_MD5          = 0x04,
1064
    SSL_RSA_WITH_3DES_EDE_CBC_SHA     = 0x0A,
1065
1066
    /* ECC suites, first byte is 0xC0 (ECC_BYTE) */
1067
    TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA    = 0x14,
1068
    TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA    = 0x13,
1069
    TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA  = 0x0A,
1070
    TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA  = 0x09,
1071
    TLS_ECDHE_RSA_WITH_RC4_128_SHA        = 0x11,
1072
    TLS_ECDHE_ECDSA_WITH_RC4_128_SHA      = 0x07,
1073
    TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA   = 0x12,
1074
    TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA = 0x08,
1075
    TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256   = 0x27,
1076
    TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 = 0x23,
1077
    TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384   = 0x28,
1078
    TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 = 0x24,
1079
    TLS_ECDHE_ECDSA_WITH_NULL_SHA           = 0x06,
1080
    TLS_ECDHE_PSK_WITH_NULL_SHA256          = 0x3a,
1081
    TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256   = 0x37,
1082
1083
    /* static ECDH, first byte is 0xC0 (ECC_BYTE) */
1084
    TLS_ECDH_RSA_WITH_AES_256_CBC_SHA    = 0x0F,
1085
    TLS_ECDH_RSA_WITH_AES_128_CBC_SHA    = 0x0E,
1086
    TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA  = 0x05,
1087
    TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA  = 0x04,
1088
    TLS_ECDH_RSA_WITH_RC4_128_SHA        = 0x0C,
1089
    TLS_ECDH_ECDSA_WITH_RC4_128_SHA      = 0x02,
1090
    TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA   = 0x0D,
1091
    TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA = 0x03,
1092
    TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256   = 0x29,
1093
    TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 = 0x25,
1094
    TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384   = 0x2A,
1095
    TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 = 0x26,
1096
1097
    WDM_WITH_NULL_SHA256          = 0xFE, /* wolfSSL DTLS Multicast */
1098
1099
    /* SHA256 */
1100
    TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 = 0x6b,
1101
    TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 = 0x67,
1102
    TLS_RSA_WITH_AES_256_CBC_SHA256     = 0x3d,
1103
    TLS_RSA_WITH_AES_128_CBC_SHA256     = 0x3c,
1104
    TLS_RSA_WITH_NULL_SHA256            = 0x3b,
1105
    TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 = 0xb2,
1106
    TLS_DHE_PSK_WITH_NULL_SHA256        = 0xb4,
1107
1108
    /* SHA384 */
1109
    TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 = 0xb3,
1110
    TLS_DHE_PSK_WITH_NULL_SHA384        = 0xb5,
1111
1112
    /* AES-GCM */
1113
    TLS_RSA_WITH_AES_128_GCM_SHA256          = 0x9c,
1114
    TLS_RSA_WITH_AES_256_GCM_SHA384          = 0x9d,
1115
    TLS_DHE_RSA_WITH_AES_128_GCM_SHA256      = 0x9e,
1116
    TLS_DHE_RSA_WITH_AES_256_GCM_SHA384      = 0x9f,
1117
    TLS_DH_anon_WITH_AES_256_GCM_SHA384      = 0xa7,
1118
    TLS_PSK_WITH_AES_128_GCM_SHA256          = 0xa8,
1119
    TLS_PSK_WITH_AES_256_GCM_SHA384          = 0xa9,
1120
    TLS_DHE_PSK_WITH_AES_128_GCM_SHA256      = 0xaa,
1121
    TLS_DHE_PSK_WITH_AES_256_GCM_SHA384      = 0xab,
1122
1123
    /* ECC AES-GCM, first byte is 0xC0 (ECC_BYTE) */
1124
    TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256  = 0x2b,
1125
    TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384  = 0x2c,
1126
    TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256   = 0x2d,
1127
    TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384   = 0x2e,
1128
    TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256    = 0x2f,
1129
    TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384    = 0x30,
1130
    TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256     = 0x31,
1131
    TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384     = 0x32,
1132
1133
    /* AES-CCM, first byte is 0xC0 but isn't ECC,
1134
     * also, in some of the other AES-CCM suites
1135
     * there will be second byte number conflicts
1136
     * with non-ECC AES-GCM */
1137
    TLS_RSA_WITH_AES_128_CCM_8         = 0xa0,
1138
    TLS_RSA_WITH_AES_256_CCM_8         = 0xa1,
1139
    TLS_ECDHE_ECDSA_WITH_AES_128_CCM   = 0xac,
1140
    TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 = 0xae,
1141
    TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 = 0xaf,
1142
    TLS_PSK_WITH_AES_128_CCM           = 0xa4,
1143
    TLS_PSK_WITH_AES_256_CCM           = 0xa5,
1144
    TLS_PSK_WITH_AES_128_CCM_8         = 0xa8,
1145
    TLS_PSK_WITH_AES_256_CCM_8         = 0xa9,
1146
    TLS_DHE_PSK_WITH_AES_128_CCM       = 0xa6,
1147
    TLS_DHE_PSK_WITH_AES_256_CCM       = 0xa7,
1148
1149
    /* Camellia */
1150
    TLS_RSA_WITH_CAMELLIA_128_CBC_SHA        = 0x41,
1151
    TLS_RSA_WITH_CAMELLIA_256_CBC_SHA        = 0x84,
1152
    TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256     = 0xba,
1153
    TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256     = 0xc0,
1154
    TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA    = 0x45,
1155
    TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA    = 0x88,
1156
    TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 = 0xbe,
1157
    TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 = 0xc4,
1158
1159
    /* chacha20-poly1305 suites first byte is 0xCC (CHACHA_BYTE) */
1160
    TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256   = 0xa8,
1161
    TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 = 0xa9,
1162
    TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256     = 0xaa,
1163
    TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256   = 0xac,
1164
    TLS_PSK_WITH_CHACHA20_POLY1305_SHA256         = 0xab,
1165
    TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256     = 0xad,
1166
1167
    /* chacha20-poly1305 earlier version of nonce and padding (CHACHA_BYTE) */
1168
    TLS_ECDHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256   = 0x13,
1169
    TLS_ECDHE_ECDSA_WITH_CHACHA20_OLD_POLY1305_SHA256 = 0x14,
1170
    TLS_DHE_RSA_WITH_CHACHA20_OLD_POLY1305_SHA256     = 0x15,
1171
1172
    /* ECDHE_PSK RFC8442, first byte is 0xD0 (EDHE_PSK_BYTE) */
1173
    TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256    = 0x01,
1174
1175
    /* TLS v1.3 cipher suites */
1176
    TLS_AES_128_GCM_SHA256       = 0x01,
1177
    TLS_AES_256_GCM_SHA384       = 0x02,
1178
    TLS_CHACHA20_POLY1305_SHA256 = 0x03,
1179
    TLS_AES_128_CCM_SHA256       = 0x04,
1180
    TLS_AES_128_CCM_8_SHA256     = 0x05,
1181
1182
    /* TLS v1.3 Integrity only cipher suites - 0xC0 (ECC) first byte */
1183
    TLS_SHA256_SHA256            = 0xB4,
1184
    TLS_SHA384_SHA384            = 0xB5,
1185
1186
    /* ARIA-GCM, first byte is 0xC0 (ECC_BYTE)
1187
    * See: https://www.rfc-editor.org/rfc/rfc6209.html#section-5
1188
    */
1189
    TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256   = 0x5c,
1190
    TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384   = 0x5d,
1191
1192
    /* TLS v1.3 SM cipher suites - 0x00 (CIPHER_BYTE) is first byte */
1193
    TLS_SM4_GCM_SM3              = 0xC6,
1194
    TLS_SM4_CCM_SM3              = 0xC7,
1195
1196
    /* TLS v1.2 SM cipher suites - 0xE0 (SM_BYTE) is first byte */
1197
    TLS_ECDHE_ECDSA_WITH_SM4_CBC_SM3 = 0x11,
1198
    TLS_ECDHE_ECDSA_WITH_SM4_GCM_SM3 = 0x51,
1199
    TLS_ECDHE_ECDSA_WITH_SM4_CCM_SM3 = 0x52,
1200
1201
    /* Fallback SCSV (Signaling Cipher Suite Value) */
1202
    TLS_FALLBACK_SCSV                        = 0x56,
1203
    /* Renegotiation Indication Extension Special Suite */
1204
    TLS_EMPTY_RENEGOTIATION_INFO_SCSV        = 0xff
1205
};
1206
1207
1208
#ifndef WOLFSSL_SESSION_TIMEOUT
1209
6.41k
    #define WOLFSSL_SESSION_TIMEOUT 500
1210
    /* default session resumption cache timeout in seconds */
1211
#endif
1212
1213
1214
#ifndef WOLFSSL_DTLS_WINDOW_WORDS
1215
    #define WOLFSSL_DTLS_WINDOW_WORDS 2
1216
#endif /* WOLFSSL_DTLS_WINDOW_WORDS */
1217
#define DTLS_WORD_BITS (sizeof(word32) * CHAR_BIT)
1218
#define DTLS_SEQ_BITS  (WOLFSSL_DTLS_WINDOW_WORDS * DTLS_WORD_BITS)
1219
#define DTLS_SEQ_SZ    (sizeof(word32) * WOLFSSL_DTLS_WINDOW_WORDS)
1220
1221
#ifndef WOLFSSL_MULTICAST
1222
    #define WOLFSSL_DTLS_PEERSEQ_SZ 1
1223
#else
1224
    #ifndef WOLFSSL_MULTICAST_PEERS
1225
        /* max allowed multicast group peers */
1226
        #define WOLFSSL_MULTICAST_PEERS 100
1227
    #endif
1228
    #define WOLFSSL_DTLS_PEERSEQ_SZ WOLFSSL_MULTICAST_PEERS
1229
#endif /* WOLFSSL_MULTICAST */
1230
1231
#ifndef WOLFSSL_MAX_MTU
1232
    /* 1500 - 100 bytes to account for UDP and IP headers */
1233
    #define WOLFSSL_MAX_MTU 1400
1234
#endif /* WOLFSSL_MAX_MTU */
1235
1236
#ifndef WOLFSSL_DTLS_MTU_ADDITIONAL_READ_BUFFER
1237
    #define WOLFSSL_DTLS_MTU_ADDITIONAL_READ_BUFFER 500
1238
#endif /* WOLFSSL_DTLS_MTU_ADDITIONAL_READ_BUFFER */
1239
1240
#ifndef WOLFSSL_DTLS_FRAG_POOL_SZ
1241
    #define WOLFSSL_DTLS_FRAG_POOL_SZ 10
1242
#endif
1243
#if WOLFSSL_DTLS_FRAG_POOL_SZ > 255
1244
    #error "WOLFSSL_DTLS_FRAG_POOL_SZ must be at most 255"
1245
#endif
1246
1247
/* set minimum DH key size allowed */
1248
#ifndef WOLFSSL_MIN_DHKEY_BITS
1249
    #if defined(WOLFSSL_HARDEN_TLS) && !defined(WOLFSSL_HARDEN_TLS_NO_PKEY_CHECK)
1250
        /* Using guidance from section 5.6.1
1251
         * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf */
1252
        #if WOLFSSL_HARDEN_TLS >= 128
1253
            #define WOLFSSL_MIN_DHKEY_BITS 3072
1254
        #elif WOLFSSL_HARDEN_TLS >= 112
1255
            #define WOLFSSL_MIN_DHKEY_BITS 2048
1256
        #endif
1257
    #else
1258
6.41k
        #define WOLFSSL_MIN_DHKEY_BITS DH_MIN_SIZE
1259
    #endif
1260
#endif
1261
#if defined(WOLFSSL_HARDEN_TLS) && WOLFSSL_MIN_DHKEY_BITS < 2048 && \
1262
    !defined(WOLFSSL_HARDEN_TLS_NO_PKEY_CHECK)
1263
    /* Implementations MUST NOT negotiate cipher suites offering less than
1264
     * 112 bits of security.
1265
     * https://www.rfc-editor.org/rfc/rfc9325#section-4.1
1266
     * Using guidance from section 5.6.1
1267
     * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf */
1268
    #error "For 112 bits of security DH needs at least 2048 bit keys"
1269
#endif
1270
#if (WOLFSSL_MIN_DHKEY_BITS % 8)
1271
    #error DH minimum bit size must be multiple of 8
1272
#endif
1273
#if (WOLFSSL_MIN_DHKEY_BITS > 16000)
1274
    #error DH minimum bit size must not be greater than 16000
1275
#endif
1276
#if (WOLFSSL_MIN_DHKEY_BITS < DH_MIN_SIZE)
1277
    /* The TLS-layer minimum must not be looser than the wolfCrypt DH primitive
1278
     * minimum (DH_MIN_SIZE), otherwise a key size accepted during negotiation
1279
     * is later rejected by wc_DhAgree with WC_KEY_SIZE_E. */
1280
    #error "WOLFSSL_MIN_DHKEY_BITS must be >= DH_MIN_SIZE"
1281
#endif
1282
6.41k
#define MIN_DHKEY_SZ (WOLFSSL_MIN_DHKEY_BITS / 8)
1283
/* set maximum DH key size allowed */
1284
#ifndef WOLFSSL_MAX_DHKEY_BITS
1285
    #if (defined(USE_FAST_MATH) && defined(FP_MAX_BITS) && FP_MAX_BITS >= 16384)
1286
        #define WOLFSSL_MAX_DHKEY_BITS  (FP_MAX_BITS / 2)
1287
    #elif (defined(WOLFSSL_SP_MATH_ALL) || defined(WOLFSSL_SP_MATH)) && \
1288
           defined(SP_INT_BITS)
1289
        /* SP implementation supports numbers of SP_INT_BITS bits. */
1290
6.41k
        #define WOLFSSL_MAX_DHKEY_BITS  WC_BITS_FULL_BYTES(SP_INT_BITS)
1291
    #else
1292
        #define WOLFSSL_MAX_DHKEY_BITS  4096
1293
    #endif
1294
#endif
1295
#if (WOLFSSL_MAX_DHKEY_BITS % 8)
1296
    #error DH maximum bit size must be multiple of 8
1297
#endif
1298
#if (WOLFSSL_MAX_DHKEY_BITS > 16384)
1299
    #error DH maximum bit size must not be greater than 16384
1300
#endif
1301
6.41k
#define MAX_DHKEY_SZ (WOLFSSL_MAX_DHKEY_BITS / 8)
1302
1303
#ifndef NO_DH
1304
#if WOLFSSL_MAX_DHKEY_BITS < WOLFSSL_MIN_DHKEY_BITS
1305
#error "WOLFSSL_MAX_DHKEY_BITS has to be greater than WOLFSSL_MIN_DHKEY_BITS"
1306
#endif
1307
#endif /* NO_DH */
1308
1309
#ifndef MAX_PSK_KEY_LEN
1310
    #define MAX_PSK_KEY_LEN 64
1311
#endif
1312
1313
#ifndef MAX_EARLY_DATA_SZ
1314
    /* maximum early data size */
1315
    #define MAX_EARLY_DATA_SZ  4096
1316
#endif
1317
1318
/* Anti-replay eviction keys off the ticket's session ID. */
1319
#if defined(WOLFSSL_EARLY_DATA) && defined(HAVE_SESSION_TICKET) && \
1320
    !defined(WOLFSSL_TICKET_HAVE_ID)
1321
    #define WOLFSSL_TICKET_HAVE_ID
1322
#endif
1323
1324
1325
#if !defined(NO_RSA) || !defined(NO_DH) || defined(HAVE_ECC)
1326
    /* MySQL wants to be able to use 8192-bit numbers. */
1327
    #if defined(USE_FAST_MATH) && defined(FP_MAX_BITS)
1328
        /* Use the FP size up to 8192-bit and down to a min of 1024-bit. */
1329
        #if FP_MAX_BITS >= 16384
1330
            #define ENCRYPT_BASE_BITS  8192
1331
        #elif defined(HAVE_ECC)
1332
            #if FP_MAX_BITS > 2224
1333
                #define ENCRYPT_BASE_BITS  (FP_MAX_BITS / 2)
1334
            #else
1335
                /* 521-bit ASN.1 signature - 3 + 2 * (2 + 66) bytes. */
1336
                #define ENCRYPT_BASE_BITS  1112
1337
            #endif
1338
        #else
1339
            #if FP_MAX_BITS > 2048
1340
                #define ENCRYPT_BASE_BITS  (FP_MAX_BITS / 2)
1341
            #else
1342
                #define ENCRYPT_BASE_BITS  1024
1343
            #endif
1344
        #endif
1345
1346
        /* Check MySQL size requirements met. */
1347
        #if defined(WOLFSSL_MYSQL_COMPATIBLE) && ENCRYPT_BASE_BITS < 8192
1348
            #error "MySQL needs FP_MAX_BITS at least at 16384"
1349
        #endif
1350
1351
        #if !defined(NO_RSA) && defined(WC_MAX_RSA_BITS) && \
1352
            WC_MAX_RSA_BITS > ENCRYPT_BASE_BITS
1353
            #error "FP_MAX_BITS too small for WC_MAX_RSA_BITS"
1354
        #endif
1355
    #elif defined(WOLFSSL_SP_MATH_ALL) || defined(WOLFSSL_SP_MATH)
1356
        /* Use the SP size up to 8192-bit and down to a min of 1024-bit. */
1357
        #if SP_INT_BITS >= 8192
1358
            #define ENCRYPT_BASE_BITS  8192
1359
        #elif defined(HAVE_ECC)
1360
            #if SP_INT_BITS > 1112
1361
                #define ENCRYPT_BASE_BITS  SP_INT_BITS
1362
            #else
1363
                /* 521-bit ASN.1 signature - 3 + 2 * (2 + 66) bytes. */
1364
                #define ENCRYPT_BASE_BITS  1112
1365
            #endif
1366
        #else
1367
            #if SP_INT_BITS > 1024
1368
                #define ENCRYPT_BASE_BITS  SP_INT_BITS
1369
            #else
1370
                #define ENCRYPT_BASE_BITS  1024
1371
            #endif
1372
        #endif
1373
1374
        /* Check MySQL size requirements met. */
1375
        #if defined(WOLFSSL_MYSQL_COMPATIBLE) && ENCRYPT_BASE_BITS < 8192
1376
            #error "MySQL needs SP_INT_BITS at least at 8192"
1377
        #endif
1378
1379
        #if !defined(NO_RSA) && defined(WC_MAX_RSA_BITS) && \
1380
            WC_MAX_RSA_BITS > SP_INT_BITS
1381
            #error "SP_INT_BITS too small for WC_MAX_RSA_BITS"
1382
        #endif
1383
    #else
1384
        /* Integer/heap maths - support 4096-bit. */
1385
        #define ENCRYPT_BASE_BITS  4096
1386
    #endif
1387
#elif defined(HAVE_CURVE448)
1388
    #define ENCRYPT_BASE_BITS    (456 * 2)
1389
#elif defined(HAVE_CURVE25519)
1390
    #define ENCRYPT_BASE_BITS    (256 * 2)
1391
#else
1392
    /* No secret from public key operation but PSK key plus length used. */
1393
    #define ENCRYPT_BASE_BITS  ((MAX_PSK_KEY_LEN + 2) * 8)
1394
#endif
1395
1396
#ifdef WOLFSSL_DTLS_CID
1397
#ifndef DTLS_CID_MAX_SIZE
1398
/* DTLS parsing code copies the record header in a static buffer to decrypt
1399
 * the record. Increasing the CID max size does increase also this buffer,
1400
 * impacting on per-session runtime memory footprint. */
1401
#define DTLS_CID_MAX_SIZE 10
1402
#endif
1403
#else
1404
#undef DTLS_CID_MAX_SIZE
1405
#define DTLS_CID_MAX_SIZE 0
1406
#endif /* WOLFSSL_DTLS_CID */
1407
1408
/* This bounds the CID that we ask to receive and, for DTLS 1.2, also the
1409
 * peer-chosen CID that we send.
1410
 * For DTLS 1.3 the CID that we send is chosen by the peer and this does not
1411
 * bound it, only the wire format does (RFC 9146 Section 3: the ConnectionId
1412
 * is an opaque<0..2^8-1>). */
1413
#if DTLS_CID_MAX_SIZE > 255
1414
#error "Max size for DTLS CID is 255 bytes"
1415
#endif
1416
1417
/* the tx CID is the peer's choice, bounded only by its one byte length field */
1418
#define DTLS_CID_MAX_TX_SIZE 255
1419
1420
/* Record Payload Protection Section 5
1421
 *   https://www.rfc-editor.org/rfc/rfc9146.html#section-5 */
1422
#define WOLFSSL_TLS_HMAC_CID_INNER_SZ                               \
1423
           (8 +                 /* seq_num_placeholder */           \
1424
            1 +                 /* tls12_cid */                     \
1425
            1 +                 /* cid_length */                    \
1426
            1 +                 /* tls12_cid */                     \
1427
            2 +                 /* DTLSCiphertext.version */        \
1428
            2 +                 /* epoch */                         \
1429
            6 +                 /* sequence_number */               \
1430
            DTLS_CID_MAX_SIZE + /* cid */                           \
1431
            2)                  /* length_of_DTLSInnerPlaintext */
1432
1433
#define WOLFSSL_TLS_AEAD_CID_AAD_SZ                                 \
1434
           (8 +                 /* seq_num_placeholder */           \
1435
            1 +                 /* tls12_cid */                     \
1436
            1 +                 /* cid_length */                    \
1437
            1 +                 /* tls12_cid */                     \
1438
            2 +                 /* DTLSCiphertext.version */        \
1439
            2 +                 /* epoch */                         \
1440
            6 +                 /* sequence_number */               \
1441
            DTLS_CID_MAX_SIZE + /* cid */                           \
1442
            2)                  /* length_of_DTLSInnerPlaintext */
1443
1444
#ifndef MAX_TICKET_AGE_DIFF
1445
/* maximum ticket age difference in seconds, 10 seconds */
1446
#define MAX_TICKET_AGE_DIFF     10
1447
#endif
1448
#ifndef TLS13_MAX_TICKET_AGE
1449
/* max ticket age in seconds, 7 days */
1450
#define TLS13_MAX_TICKET_AGE    (7*24*60*60)
1451
#endif
1452
1453
1454
/* Limit is 2^24.5
1455
 * https://www.rfc-editor.org/rfc/rfc8446#section-5.5
1456
 * Without the fraction is 23726566 (0x016A09E6) */
1457
0
#define AEAD_AES_LIMIT                           w64From32(0, 0x016A09E6)
1458
/* Limit is 2^23
1459
 * https://www.rfc-editor.org/rfc/rfc9147.html#name-confidentiality-limits */
1460
#define DTLS_AEAD_AES_CCM_LIMIT                  w64From32(0, 1 << 23)
1461
1462
/* Limit is 2^36 (2^4 in the high 32 bits)
1463
 * https://www.rfc-editor.org/rfc/rfc9147.html#name-aead-limits */
1464
#define DTLS_AEAD_AES_GCM_CHACHA_FAIL_LIMIT      w64From32(1 << 4, 0)
1465
#define DTLS_AEAD_AES_GCM_CHACHA_FAIL_KU_LIMIT   w64From32(1 << 3, 0)
1466
/* Limit is 2^7
1467
 * https://www.rfc-editor.org/rfc/rfc9147.html#name-limits-for-aead_aes_128_ccm */
1468
#define DTLS_AEAD_AES_CCM_8_FAIL_LIMIT           w64From32(0, 1 << 7)
1469
#define DTLS_AEAD_AES_CCM_8_FAIL_KU_LIMIT        w64From32(0, 1 << 6)
1470
/* Limit is 2^23.5.
1471
 * https://www.rfc-editor.org/rfc/rfc9147.html#name-integrity-limits
1472
 * Without the fraction is 11863283 (0x00B504F3)
1473
 * Half of this value is    5931641 (0x005A8279) */
1474
#define DTLS_AEAD_AES_CCM_FAIL_LIMIT             w64From32(0, 0x00B504F3)
1475
#define DTLS_AEAD_AES_CCM_FAIL_KU_LIMIT          w64From32(0, 0x005A8279)
1476
1477
/* Limit is (2^22 - 1) full messages [2^36 - 31 octets]
1478
 * https://www.rfc-editor.org/rfc/rfc8998.html#name-aead_sm4_gcm
1479
 */
1480
0
#define AEAD_SM4_GCM_LIMIT                       w64From32(0, (1 << 22) - 1)
1481
/* Limit is (2^10 - 1) full messages [2^24 - 1 octets]
1482
 * https://www.rfc-editor.org/rfc/rfc8998.html#name-aead_sm4_ccm
1483
 */
1484
0
#define AEAD_SM4_CCM_LIMIT                       w64From32(0, (1 << 10) - 1)
1485
1486
#ifndef WOLFSSL_COOKIE_LEN
1487
/* Maximum size for a DTLS cookie */
1488
#define WOLFSSL_COOKIE_LEN 32
1489
#endif
1490
1491
#if WOLFSSL_COOKIE_LEN > 255
1492
#error "WOLFSSL_COOKIE_LEN must be <= 255 per RFC 6347 (opaque<0..2^8-1>)"
1493
#endif
1494
1495
#if defined(WOLFSSL_TLS13) || !defined(NO_PSK)
1496
1497
#define TLS13_TICKET_NONCE_MAX_SZ 255
1498
1499
#if (defined(HAVE_FIPS) &&                                                     \
1500
    !(defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3))) &&                    \
1501
    defined(TLS13_TICKET_NONCE_STATIC_SZ)
1502
#error "TLS13_TICKET_NONCE_STATIC_SZ is not supported in this FIPS version"
1503
#endif
1504
1505
#ifndef TLS13_TICKET_NONCE_STATIC_SZ
1506
#define TLS13_TICKET_NONCE_STATIC_SZ 8
1507
#endif
1508
1509
#if TLS13_TICKET_NONCE_STATIC_SZ > TLS13_TICKET_NONCE_MAX_SZ
1510
#error "Max size for ticket nonce is 255 bytes"
1511
#endif
1512
1513
#endif /* WOLFSSL_TLS13 || !NO_PSK */
1514
1515
#ifdef WOLFSSL_TLS13
1516
/* The length of the certificate verification label - client and server. */
1517
92
#define CERT_VFY_LABEL_SZ    34
1518
/* The number of prefix bytes for signature data. */
1519
92
#define SIGNING_DATA_PREFIX_SZ     64
1520
/* Maximum length of the signature data. */
1521
#define MAX_SIG_DATA_SZ            (SIGNING_DATA_PREFIX_SZ + \
1522
                                    CERT_VFY_LABEL_SZ      + \
1523
                                    WC_MAX_DIGEST_SIZE)
1524
#endif /* WOLFSSL_TLS13 */
1525
1526
enum Misc {
1527
    CIPHER_BYTE    = 0x00,         /* Default ciphers */
1528
    ECC_BYTE       = 0xC0,         /* ECC first cipher suite byte */
1529
    CHACHA_BYTE    = 0xCC,         /* ChaCha first cipher suite */
1530
    TLS13_BYTE     = 0x13,         /* TLS v1.3 first byte of cipher suite */
1531
    ECDHE_PSK_BYTE = 0xD0,         /* RFC 8442 */
1532
    SM_BYTE        = 0xE0,         /* SM first byte - private range */
1533
1534
    SEND_CERT       = 1,
1535
    SEND_BLANK_CERT = 2,
1536
1537
    DTLS_MAJOR      = 0xfe,     /* DTLS major version number */
1538
    DTLS_MINOR      = 0xff,     /* DTLS minor version number */
1539
    DTLS_BOGUS_MINOR = 0xfe,    /* DTLS 0xfe was skipped, see RFC6347 Sec. 1 */
1540
    DTLSv1_2_MINOR  = 0xfd,     /* DTLS minor version number */
1541
    DTLSv1_3_MINOR  = 0xfc,     /* DTLS minor version number */
1542
    SSLv3_MAJOR     = 3,        /* SSLv3 and TLSv1+  major version number */
1543
    SSLv3_MINOR     = 0,        /* TLSv1   minor version number */
1544
    TLSv1_MINOR     = 1,        /* TLSv1   minor version number */
1545
    TLSv1_1_MINOR   = 2,        /* TLSv1_1 minor version number */
1546
    TLSv1_2_MINOR   = 3,        /* TLSv1_2 minor version number */
1547
    TLSv1_3_MINOR   = 4,        /* TLSv1_3 minor version number */
1548
    TLS_DRAFT_MAJOR = 0x7f,     /* Draft TLS major version number */
1549
    OLD_HELLO_ID    = 0x01,     /* SSLv2 Client Hello Indicator */
1550
    INVALID_BYTE    = 0xff,     /* Used to initialize cipher specs values */
1551
    NO_COMPRESSION  =  0,
1552
    ZLIB_COMPRESSION = 221,     /* wolfSSL zlib compression */
1553
    HELLO_EXT_SIG_ALGO = 13,    /* ID for the sig_algo hello extension */
1554
    HELLO_EXT_EXTMS = 0x0017,   /* ID for the extended master secret ext */
1555
    SECRET_LEN      = WOLFSSL_MAX_MASTER_KEY_LENGTH,
1556
                                /* pre RSA and all master */
1557
#if !defined(WOLFSSL_TLS13) || defined(WOLFSSL_32BIT_MILLI_TIME)
1558
    TIMESTAMP_LEN   = 4,        /* timestamp size in ticket */
1559
#else
1560
    TIMESTAMP_LEN   = 8,        /* timestamp size in ticket */
1561
#endif
1562
#ifdef WOLFSSL_TLS13
1563
    AGEADD_LEN      = 4,        /* ageAdd size in ticket */
1564
    NAMEDGROUP_LEN  = 2,        /* namedGroup size in ticket */
1565
#ifdef WOLFSSL_EARLY_DATA
1566
    MAXEARLYDATASZ_LEN = 4,     /* maxEarlyDataSz size in ticket */
1567
#endif
1568
#endif
1569
#ifndef NO_PSK
1570
    ENCRYPT_LEN     = (ENCRYPT_BASE_BITS / 8) + MAX_PSK_KEY_LEN + 2,
1571
#else
1572
    ENCRYPT_LEN     = (ENCRYPT_BASE_BITS / 8),
1573
#endif
1574
    SIZEOF_SENDER   =  4,       /* clnt or srvr           */
1575
    FINISHED_SZ     = 36,       /* WC_MD5_DIGEST_SIZE + WC_SHA_DIGEST_SIZE */
1576
    MAX_PLAINTEXT_SZ   = (1 << 14),        /* Max plaintext sz   */
1577
    MAX_TLS_CIPHER_SZ  = (1 << 14) + 2048, /* Max TLS encrypted data sz */
1578
#ifdef WOLFSSL_TLS13
1579
    MAX_TLS13_PLAIN_SZ = (1 << 14) + 1,    /* Max unencrypted data sz */
1580
    MAX_TLS13_ENC_SZ   = (1 << 14) + 256,  /* Max encrypted data sz   */
1581
#endif
1582
    MAX_MSG_EXTRA   = 38 + WC_MAX_DIGEST_SIZE,
1583
                                /* max added to msg, mac + pad  from */
1584
                                /* RECORD_HEADER_SZ + BLOCK_SZ (pad) + Max
1585
                                   digest sz + BLOC_SZ (iv) + pad byte (1) */
1586
    MAX_COMP_EXTRA  = 1024,     /* max compression extra */
1587
    MAX_MTU         = WOLFSSL_MAX_MTU,     /* max expected MTU */
1588
    MAX_UDP_SIZE    = 8192 - 100, /* was MAX_MTU - 100 */
1589
    MAX_DH_SZ       = (MAX_DHKEY_SZ * 3) + 12, /* DH_P, DH_G and DH_Pub */
1590
                                /* 4096 p, pub, g + 2 byte size for each */
1591
    MAX_STR_VERSION = 8,        /* string rep of protocol version */
1592
1593
    PAD_MD5        = 48,       /* pad length for finished */
1594
    PAD_SHA        = 40,       /* pad length for finished */
1595
    MAX_PAD_SIZE   = 256,      /* maximum length of padding */
1596
1597
    LENGTH_SZ      =  2,       /* length field for HMAC, data only */
1598
    VERSION_SZ     =  2,       /* length of proctocol version */
1599
    SEQ_SZ         =  8,       /* 64 bit sequence number  */
1600
    ALERT_SIZE     =  2,       /* level + description     */
1601
    VERIFY_HEADER  =  2,       /* always use 2 bytes      */
1602
    EXTS_SZ        =  2,       /* always use 2 bytes      */
1603
    EXT_ID_SZ      =  2,       /* always use 2 bytes      */
1604
    MAX_DH_SIZE    = MAX_DHKEY_SZ+1,
1605
                               /* Max size plus possible leading 0 */
1606
    MIN_FFHDE_GROUP = 0x100,   /* Named group minimum for FFDHE parameters  */
1607
    MAX_FFHDE_GROUP = 0x1FF,   /* Named group maximum for FFDHE parameters  */
1608
    SESSION_HINT_SZ = 4,       /* session timeout hint */
1609
    SESSION_ADD_SZ = 4,        /* session age add */
1610
    TICKET_NONCE_LEN_SZ = 1,   /* Ticket nonce length size */
1611
    DEF_TICKET_NONCE_SZ = 1,   /* Default ticket nonce size */
1612
#if defined(WOLFSSL_TLS13) || !defined(NO_PSK)
1613
    MAX_TICKET_NONCE_STATIC_SZ = TLS13_TICKET_NONCE_STATIC_SZ,
1614
                               /* maximum ticket nonce static size */
1615
#endif /* WOLFSSL_TLS13 || !NO_PSK */
1616
    MAX_LIFETIME   = 604800,   /* maximum ticket lifetime */
1617
1618
    RAN_LEN      = 32,         /* random length           */
1619
    SEED_LEN     = RAN_LEN * 2, /* tls prf seed length    */
1620
    ID_LEN       = 32,         /* session id length       */
1621
    COOKIE_SECRET_SZ = 14,     /* dtls cookie secret size */
1622
    MAX_COOKIE_LEN = WOLFSSL_COOKIE_LEN, /* max dtls cookie size */
1623
    COOKIE_SZ    = 20,         /* use a 20 byte cookie    */
1624
    SUITE_LEN    =  2,         /* cipher suite sz length  */
1625
    ENUM_LEN     =  1,         /* always a byte           */
1626
    OPAQUE8_LEN  =  1,         /* 1 byte                  */
1627
    OPAQUE16_LEN =  2,         /* 2 bytes                 */
1628
    OPAQUE24_LEN =  3,         /* 3 bytes                 */
1629
    OPAQUE32_LEN =  4,         /* 4 bytes                 */
1630
    OPAQUE64_LEN =  8,         /* 8 bytes                 */
1631
    COMP_LEN     =  1,         /* compression length      */
1632
    CURVE_LEN    =  2,         /* ecc named curve length  */
1633
    KE_GROUP_LEN =  2,         /* key exchange group length */
1634
#if defined(NO_SHA) && !defined(NO_SHA256)
1635
    SERVER_ID_LEN = WC_SHA256_DIGEST_SIZE,
1636
#else
1637
    SERVER_ID_LEN = WC_SHA_DIGEST_SIZE,
1638
#endif
1639
1640
    HANDSHAKE_HEADER_SZ   = 4,  /* type + length(3)        */
1641
    DTLS13_HANDSHAKE_HEADER_SZ   = 12, /* sizeof(Dtls13HandshakeHeader) */
1642
    RECORD_HEADER_SZ      = 5,  /* type + version + len(2) */
1643
    CERT_HEADER_SZ        = 3,  /* always 3 bytes          */
1644
    REQ_HEADER_SZ         = 2,  /* cert request header sz  */
1645
    HINT_LEN_SZ           = 2,  /* length of hint size field */
1646
    TRUNCATED_HMAC_SZ     = 10, /* length of hmac w/ truncated hmac extension */
1647
    HELLO_EXT_SZ          = 4,  /* base length of a hello extension */
1648
    HELLO_EXT_TYPE_SZ     = 2,  /* length of a hello extension type */
1649
    HELLO_EXT_SZ_SZ       = 2,  /* length of a hello extension size */
1650
    HELLO_EXT_SIGALGO_SZ  = 2,  /* length of number of items in sigalgo list */
1651
1652
    DTLS_HANDSHAKE_HEADER_SZ = 12, /* normal + seq(2) + offset(3) + length(3) */
1653
    DTLS_RECORD_HEADER_SZ    = 13, /* normal + epoch(2) + seq_num(6) */
1654
    DTLS12_CID_OFFSET        = 11,
1655
    DTLS_UNIFIED_HEADER_MIN_SZ = 2,
1656
    /* flags + seq_number(2) + length(2) + CID */
1657
    DTLS_RECVD_RL_HEADER_MAX_SZ = 5 + DTLS_CID_MAX_SIZE,
1658
    DTLS_RECORD_HEADER_MAX_SZ = 13,
1659
    DTLS_HANDSHAKE_EXTRA     = 8,  /* diff from normal */
1660
    DTLS_RECORD_EXTRA        = 8,  /* diff from normal */
1661
    DTLS_HANDSHAKE_SEQ_SZ    = 2,  /* handshake header sequence number */
1662
    DTLS_HANDSHAKE_FRAG_SZ   = 3,  /* fragment offset and length are 24 bit */
1663
    DTLS_POOL_SZ             = 20, /* allowed number of list items in TX and
1664
                                    * RX pool */
1665
    DTLS_FRAG_POOL_SZ        = WOLFSSL_DTLS_FRAG_POOL_SZ,
1666
                                   /* allowed number of fragments per msg */
1667
    DTLS_EXPORT_PRO          = 165,/* wolfSSL protocol for serialized session */
1668
    DTLS_EXPORT_STATE_PRO    = 166,/* wolfSSL protocol for serialized state */
1669
    TLS_EXPORT_PRO           = 167,/* wolfSSL protocol for serialized TLS */
1670
    DTLS_EXPORT_OPT_SZ       = 67, /* number of bytes used from Options */
1671
    DTLS_EXPORT_OPT_SZ_6     = 66, /* number of bytes used from Options */
1672
    DTLS_EXPORT_OPT_SZ_5     = 62, /* number of bytes used from Options */
1673
    DTLS_EXPORT_OPT_SZ_4     = 61, /* number of bytes used from Options */
1674
    TLS_EXPORT_OPT_SZ        = 67, /* number of bytes used from Options */
1675
    TLS_EXPORT_OPT_SZ_6      = 66, /* number of bytes used from Options */
1676
    TLS_EXPORT_OPT_SZ_5      = 66, /* number of bytes used from Options */
1677
    TLS_EXPORT_OPT_SZ_4      = 65, /* number of bytes used from Options */
1678
    DTLS_EXPORT_OPT_SZ_3     = 60, /* number of bytes used from Options */
1679
    DTLS_EXPORT_MIN_KEY_SZ   = 85 + (DTLS_SEQ_SZ * 2),
1680
                                   /* min number of bytes used from Keys */
1681
    WOLFSSL_EXPORT_TLS       = 1,
1682
    WOLFSSL_EXPORT_DTLS      = 0,
1683
#ifndef WOLFSSL_EXPORT_SPC_SZ
1684
    WOLFSSL_EXPORT_SPC_SZ    = 16, /* number of bytes used from CipherSpecs */
1685
#endif
1686
    WOLFSSL_EXPORT_LEN       = 2,  /* 2 bytes for length and protocol */
1687
    WOLFSSL_EXPORT_VERSION   = 7,  /* wolfSSL version for serialized session */
1688
1689
    /* older export versions supported */
1690
    WOLFSSL_EXPORT_VERSION_6 = 6,  /* version before DTLS 1.3 state */
1691
    WOLFSSL_EXPORT_VERSION_5 = 5,  /* version before DTLS Encrypt-Then-MAC */
1692
    WOLFSSL_EXPORT_VERSION_4 = 4,  /* 5.6.4 release and before */
1693
    WOLFSSL_EXPORT_VERSION_3 = 3,  /* wolfSSL version before TLS 1.3 addition */
1694
1695
    MAX_EXPORT_IP            = 46, /* max ip size IPv4 mapped IPv6 */
1696
    DTLS_MTU_ADDITIONAL_READ_BUFFER = WOLFSSL_DTLS_MTU_ADDITIONAL_READ_BUFFER,
1697
                                   /* Additional bytes to read so that
1698
                                    * we can work with a peer that has
1699
                                    * a slightly different MTU than us. */
1700
    MAX_EXPORT_STATE_BUFFER  = (DTLS_EXPORT_MIN_KEY_SZ) + (3 * WOLFSSL_EXPORT_LEN),
1701
                                    /* max size of buffer for exporting state */
1702
    FINISHED_LABEL_SZ   = 15,  /* TLS finished label size */
1703
    TLS_FINISHED_SZ     = 12,  /* TLS has a shorter size  */
1704
    TLS_FINISHED_SZ_MAX = WC_MAX_DIGEST_SIZE,
1705
                            /* longest message digest size is SHA512, 64 */
1706
    EXT_MASTER_LABEL_SZ = 22,  /* TLS extended master secret label sz */
1707
    MASTER_LABEL_SZ     = 13,  /* TLS master secret label sz */
1708
    KEY_LABEL_SZ        = 13,  /* TLS key block expansion sz */
1709
    PROTOCOL_LABEL_SZ   = 9,   /* Length of the protocol label */
1710
    MAX_LABEL_SZ        = 34,  /* Maximum length of a label */
1711
    MAX_REQUEST_SZ      = 256, /* Maximum cert req len (no auth yet */
1712
    SESSION_FLUSH_COUNT = 256, /* Flush session cache unless user turns off */
1713
    TLS_MAX_PAD_SZ      = 255, /* Max padding in TLS */
1714
    MAX_EXT_DATA_LEN    = 65535,
1715
                          /* Max extension data length <0..2^16-1> RFC 8446
1716
                           * Section 4.2 */
1717
    MAX_SV_EXT_LEN      = 255,
1718
                          /* Max supported_versions extension length
1719
                           * <2..254> RFC 8446 Section 4.2.1.*/
1720
1721
#if defined(HAVE_NULL_CIPHER) && defined(WOLFSSL_TLS13)
1722
    #if defined(WOLFSSL_SHA384) && WC_MAX_SYM_KEY_SIZE < 48
1723
        MAX_SYM_KEY_SIZE    = WC_SHA384_DIGEST_SIZE,
1724
    #elif !defined(NO_SHA256) && WC_MAX_SYM_KEY_SIZE < 32
1725
        MAX_SYM_KEY_SIZE    = WC_SHA256_DIGEST_SIZE,
1726
    #else
1727
        MAX_SYM_KEY_SIZE    = WC_MAX_SYM_KEY_SIZE,
1728
    #endif
1729
#else
1730
    MAX_SYM_KEY_SIZE    = WC_MAX_SYM_KEY_SIZE,
1731
#endif
1732
1733
#if defined(HAVE_SELFTEST) && \
1734
    (!defined(HAVE_SELFTEST_VERSION) || (HAVE_SELFTEST_VERSION < 2))
1735
    #ifndef WOLFSSL_AES_KEY_SIZE_ENUM
1736
    #define WOLFSSL_AES_KEY_SIZE_ENUM
1737
    AES_IV_SIZE         = 16,
1738
    AES_128_KEY_SIZE    = 16,
1739
    AES_192_KEY_SIZE    = 24,
1740
    AES_256_KEY_SIZE    = 32,
1741
    #endif
1742
#endif
1743
1744
    MAX_IV_SZ           = WC_AES_BLOCK_SIZE,
1745
1746
    AEAD_SEQ_OFFSET     = 4,   /* Auth Data: Sequence number */
1747
    AEAD_TYPE_OFFSET    = 8,   /* Auth Data: Type            */
1748
    AEAD_VMAJ_OFFSET    = 9,   /* Auth Data: Major Version   */
1749
    AEAD_VMIN_OFFSET    = 10,  /* Auth Data: Minor Version   */
1750
    AEAD_LEN_OFFSET     = 11,  /* Auth Data: Length          */
1751
    AEAD_AUTH_DATA_SZ   = 13,  /* Size of the data to authenticate */
1752
    AEAD_NONCE_SZ       = 12,
1753
    AESGCM_IMP_IV_SZ    = 4,   /* Size of GCM AEAD implicit IV */
1754
    AESCCM_IMP_IV_SZ    = 4,   /* Size of CCM AEAD implicit IV */
1755
    AESGCM_EXP_IV_SZ    = 8,   /* Size of GCM/CCM AEAD explicit IV */
1756
    AESGCM_NONCE_SZ     = AESGCM_EXP_IV_SZ + AESGCM_IMP_IV_SZ,
1757
    GCM_IMP_IV_SZ       = 4,   /* Size of GCM AEAD implicit IV */
1758
    CCM_IMP_IV_SZ       = 4,   /* Size of CCM AEAD implicit IV */
1759
    GCM_EXP_IV_SZ       = 8,   /* Size of GCM/CCM AEAD explicit IV */
1760
    GCM_NONCE_SZ        = GCM_EXP_IV_SZ + GCM_IMP_IV_SZ,
1761
1762
    CHACHA20_IMP_IV_SZ  = 12,  /* Size of ChaCha20 AEAD implicit IV */
1763
    CHACHA20_NONCE_SZ   = 12,  /* Size of ChacCha20 nonce           */
1764
    CHACHA20_OLD_OFFSET = 4,   /* Offset for seq # in old poly1305  */
1765
    CHACHA20_OFFSET     = 4,   /* Offset for seq # in poly1305  */
1766
1767
    /* For any new implicit/explicit IV size adjust AEAD_MAX_***_SZ */
1768
1769
    AES_GCM_AUTH_SZ     = 16, /* AES-GCM Auth Tag length    */
1770
    AES_CCM_16_AUTH_SZ  = 16, /* AES-CCM-16 Auth Tag length */
1771
    AES_CCM_8_AUTH_SZ   = 8,  /* AES-CCM-8 Auth Tag Length  */
1772
    AESCCM_NONCE_SZ     = 12,
1773
1774
    SM4_GCM_AUTH_SZ     = 16, /* SM4-GCM Auth Tag length    */
1775
    SM4_GCM_NONCE_SZ    = 12, /* SM4 GCM Nonce length       */
1776
    SM4_CCM_AUTH_SZ     = 16, /* SM4-CCM Auth Tag length    */
1777
    SM4_CCM_NONCE_SZ    = 12, /* SM4 CCM Nonce length       */
1778
1779
    CAMELLIA_128_KEY_SIZE = 16, /* for 128 bit */
1780
    CAMELLIA_192_KEY_SIZE = 24, /* for 192 bit */
1781
    CAMELLIA_256_KEY_SIZE = 32, /* for 256 bit */
1782
    CAMELLIA_IV_SIZE      = 16, /* always block size */
1783
1784
    CHACHA20_256_KEY_SIZE = 32,  /* for 256 bit             */
1785
    CHACHA20_128_KEY_SIZE = 16,  /* for 128 bit             */
1786
    CHACHA20_IV_SIZE      = 12,  /* 96 bits for iv          */
1787
1788
    POLY1305_AUTH_SZ    = 16,  /* 128 bits                */
1789
1790
    HMAC_NONCE_SZ       = 12,  /* Size of HMAC nonce */
1791
1792
    EVP_SALT_SIZE       =  8,  /* evp salt size 64 bits   */
1793
1794
#ifndef ECDHE_SIZE /* allow this to be overridden at compile-time */
1795
    ECDHE_SIZE          = 32,  /* ECDHE server size defaults to 256 bit */
1796
#endif
1797
    MAX_EXPORT_ECC_SZ   = 256, /* Export ANSI X9.62 max future size */
1798
    MAX_CURVE_NAME_SZ   = 20,  /* Maximum size of curve name string */
1799
1800
    NEW_SA_MAJOR        = 8,   /* Most significant byte used with new sig algos */
1801
    RSA_PSS_RSAE_SHA256_MINOR = 0x04,
1802
    RSA_PSS_RSAE_SHA384_MINOR = 0x05,
1803
    RSA_PSS_RSAE_SHA512_MINOR = 0x06,
1804
    RSA_PSS_PSS_SHA256_MINOR = 0x09,
1805
    RSA_PSS_PSS_SHA384_MINOR = 0x0A,
1806
    RSA_PSS_PSS_SHA512_MINOR = 0x0B,
1807
    ECDSA_BRAINPOOLP256R1TLS13_SHA256_MINOR = 0x1A,
1808
    ECDSA_BRAINPOOLP384R1TLS13_SHA384_MINOR = 0x1B,
1809
    ECDSA_BRAINPOOLP512R1TLS13_SHA512_MINOR = 0x1C,
1810
1811
    ED25519_SA_MAJOR    = 8,   /* Most significant byte for ED25519 */
1812
    ED25519_SA_MINOR    = 7,   /* Least significant byte for ED25519 */
1813
    ED448_SA_MAJOR      = 8,   /* Most significant byte for ED448 */
1814
    ED448_SA_MINOR      = 8,   /* Least significant byte for ED448 */
1815
    SM2_SA_MAJOR        = 7,   /* Most significant byte for SM2 with SM3 */
1816
    SM2_SA_MINOR        = 8,   /* Least significant byte for SM2 with SM3 */
1817
1818
    FALCON_SA_MAJOR     = 0xFE,/* Most significant byte used with falcon sig algs */
1819
    MLDSA_SA_MAJOR      = 0x09,/* Most significant byte used with ML-DSA sig algs */
1820
1821
    /* These values for falcon match what OQS has defined. */
1822
    FALCON_LEVEL1_SA_MAJOR = 0xFE,
1823
    FALCON_LEVEL1_SA_MINOR = 0xD7,
1824
    FALCON_LEVEL5_SA_MAJOR = 0xFE,
1825
    FALCON_LEVEL5_SA_MINOR = 0xDA,
1826
1827
    /* These values for ML-DSA correspond to what is proposed in the IETF. */
1828
    MLDSA_44_SA_MAJOR = 0x09,
1829
    MLDSA_44_SA_MINOR = 0x04,
1830
    MLDSA_65_SA_MAJOR = 0x09,
1831
    MLDSA_65_SA_MINOR = 0x05,
1832
    MLDSA_87_SA_MAJOR = 0x09,
1833
    MLDSA_87_SA_MINOR = 0x06,
1834
1835
    /* These values for SLH-DSA correspond to the code points assigned in
1836
     * draft-reddy-tls-slhdsa (0x0911-0x091C) and match what oqs-provider uses.
1837
     * The major byte (0x09) is shared with ML-DSA. */
1838
    SLHDSA_SA_MAJOR             = 0x09,
1839
    SLHDSA_SHA2_128S_SA_MINOR   = 0x11,
1840
    SLHDSA_SHA2_128F_SA_MINOR   = 0x12,
1841
    SLHDSA_SHA2_192S_SA_MINOR   = 0x13,
1842
    SLHDSA_SHA2_192F_SA_MINOR   = 0x14,
1843
    SLHDSA_SHA2_256S_SA_MINOR   = 0x15,
1844
    SLHDSA_SHA2_256F_SA_MINOR   = 0x16,
1845
    SLHDSA_SHAKE_128S_SA_MINOR  = 0x17,
1846
    SLHDSA_SHAKE_128F_SA_MINOR  = 0x18,
1847
    SLHDSA_SHAKE_192S_SA_MINOR  = 0x19,
1848
    SLHDSA_SHAKE_192F_SA_MINOR  = 0x1A,
1849
    SLHDSA_SHAKE_256S_SA_MINOR  = 0x1B,
1850
    SLHDSA_SHAKE_256F_SA_MINOR  = 0x1C,
1851
1852
    MIN_RSA_SHA512_PSS_BITS = 512 * 2 + 8 * 8, /* Min key size */
1853
    MIN_RSA_SHA384_PSS_BITS = 384 * 2 + 8 * 8, /* Min key size */
1854
1855
    CLIENT_HELLO_FIRST =  35,  /* Protocol + RAN_LEN + sizeof(id_len) */
1856
    MAX_SUITE_NAME     =  48,  /* maximum length of cipher suite string */
1857
1858
    DTLS_TIMEOUT_INIT       =  1, /* default timeout init for DTLS receive  */
1859
    DTLS_TIMEOUT_MAX        = 64, /* default max timeout for DTLS receive */
1860
    DTLS_TIMEOUT_MULTIPLIER =  2, /* default timeout multiplier for DTLS recv */
1861
1862
    NULL_TERM_LEN        =   1,  /* length of null '\0' termination character */
1863
    MIN_PSK_ID_LEN       =   6,  /* min length of identities */
1864
    MIN_PSK_BINDERS_LEN  =  33,  /* min length of binders */
1865
1866
#ifndef MAX_WOLFSSL_FILE_SIZE
1867
    MAX_WOLFSSL_FILE_SIZE = 1024UL * 1024UL * 4,  /* 4 mb file size alloc limit */
1868
#endif
1869
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
1870
    MAX_WOLFSSL_CRYPTO_POLICY_SIZE = 1024UL, /* Crypto-policy file is one line.
1871
                                              * It should not be large. */
1872
    MIN_WOLFSSL_SEC_LEVEL = 0,
1873
    MAX_WOLFSSL_SEC_LEVEL = 5,
1874
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
1875
1876
    CERT_MIN_SIZE      =  256, /* min PEM cert size with header/footer */
1877
1878
    NO_SNIFF           =   0,  /* not sniffing */
1879
    SNIFF              =   1,  /* currently sniffing */
1880
1881
    HASH_SIG_SIZE      =   2,  /* default SHA1 RSA */
1882
1883
    NO_COPY            =   0,  /* should we copy static buffer for write */
1884
    COPY               =   1,  /* should we copy static buffer for write */
1885
1886
    INVALID_PEER_ID    = 0xFFFF, /* Initialize value for peer ID. */
1887
1888
    PREV_ORDER         = -1,   /* Sequence number is in previous epoch. */
1889
    PEER_ORDER         = 1,    /* Peer sequence number for verify. */
1890
    CUR_ORDER          = 0,    /* Current sequence number. */
1891
    WRITE_PROTO        = 1,    /* writing a protocol message */
1892
    READ_PROTO         = 0     /* reading a protocol message */
1893
};
1894
1895
1896
/* Size of the pre-master secret buffer. Not ENCRYPT_LEN, which also has to
1897
 * hold an RSA signature and so follows the biggest RSA key the build supports.
1898
 * Each term below is the largest secret one key exchange can produce, or 0
1899
 * when it is not compiled in. */
1900
1.59M
#define WOLFSSL_PMS_MAX2(a, b) (((a) > (b)) ? (a) : (b))
1901
1902
/* A hybrid key share appends a 32 byte ML-KEM secret to the ECDH one. A
1903
 * literal because wc_mlkem.h is out of scope here; an assert in src/tls.c
1904
 * pins it to WC_ML_KEM_SS_SZ. */
1905
#if defined(WOLFSSL_HAVE_MLKEM) && defined(WOLFSSL_TLS13)
1906
    #define PMS_MLKEM_SZ    32
1907
#else
1908
    #define PMS_MLKEM_SZ    0
1909
#endif
1910
1911
/* TLS 1.2 takes the parameters from the peer, up to MAX_DHKEY_SZ. TLS 1.3
1912
 * takes the group from the peer's key share and never checks it against
1913
 * maxDhKeySz, so the largest group compiled in has to fit as well. */
1914
#if defined(NO_DH)
1915
    #define PMS_DH_SZ       0
1916
#elif defined(HAVE_FFDHE_8192)
1917
    #define PMS_DH_SZ       WOLFSSL_PMS_MAX2(MAX_DHKEY_SZ, 8192 / 8)
1918
#elif defined(HAVE_FFDHE_6144)
1919
    #define PMS_DH_SZ       WOLFSSL_PMS_MAX2(MAX_DHKEY_SZ, 6144 / 8)
1920
#elif defined(HAVE_FFDHE_4096)
1921
    #define PMS_DH_SZ       WOLFSSL_PMS_MAX2(MAX_DHKEY_SZ, 4096 / 8)
1922
#elif defined(HAVE_FFDHE_3072)
1923
    #define PMS_DH_SZ       WOLFSSL_PMS_MAX2(MAX_DHKEY_SZ, 3072 / 8)
1924
#elif defined(HAVE_FFDHE_2048)
1925
    #define PMS_DH_SZ       WOLFSSL_PMS_MAX2(MAX_DHKEY_SZ, 2048 / 8)
1926
#else
1927
    #define PMS_DH_SZ       MAX_DHKEY_SZ
1928
#endif
1929
1930
/* Largest ECDH secret, taken per curve rather than from the widest one:
1931
 * MAX_ECC_BYTES follows the configured ECC key sizes, and a build can enable
1932
 * Curve448 alongside a smaller ECC. */
1933
#ifdef HAVE_ECC
1934
    #define PMS_ECC_SZ      MAX_ECC_BYTES
1935
#else
1936
    #define PMS_ECC_SZ      0
1937
#endif
1938
#ifdef HAVE_CURVE25519
1939
    #define PMS_X25519_SZ   CURVE25519_KEYSIZE
1940
#else
1941
    #define PMS_X25519_SZ   0
1942
#endif
1943
#ifdef HAVE_CURVE448
1944
    #define PMS_X448_SZ     CURVE448_KEY_SIZE
1945
#else
1946
    #define PMS_X448_SZ     0
1947
#endif
1948
#define PMS_ECDH_SZ (WOLFSSL_PMS_MAX2(PMS_ECC_SZ,                             \
1949
                     WOLFSSL_PMS_MAX2(PMS_X25519_SZ, PMS_X448_SZ)) +          \
1950
                     PMS_MLKEM_SZ)
1951
1952
/* A PSK only exchange pads with a zeroed copy of the key, and every PSK suite
1953
 * frames the two secrets with a length each. */
1954
#ifndef NO_PSK
1955
    #define PMS_PSK_SZ      MAX_PSK_KEY_LEN
1956
    #define PMS_PSK_EXTRA   (MAX_PSK_KEY_LEN + OPAQUE16_LEN * 2)
1957
#else
1958
    #define PMS_PSK_SZ      0
1959
    #define PMS_PSK_EXTRA   0
1960
#endif
1961
1962
/* wolfSSL_set_secret() has always accepted up to ENCRYPT_LEN bytes. */
1963
#ifdef WOLFSSL_MULTICAST
1964
    #define PMS_MCAST_SZ    ENCRYPT_LEN
1965
#else
1966
    #define PMS_MCAST_SZ    0
1967
#endif
1968
1969
/* A GenPreMasterCb writes the secret itself. ENCRYPT_LEN stays the default so
1970
 * a callback written against the old contract cannot be overrun; an
1971
 * integration that knows better sets this smaller. */
1972
#ifdef HAVE_PK_CALLBACKS
1973
    #ifndef WOLFSSL_MAX_GEN_PREMASTER_SZ
1974
        #define WOLFSSL_MAX_GEN_PREMASTER_SZ ENCRYPT_LEN
1975
    #endif
1976
    #define PMS_GEN_CB_SZ   WOLFSSL_MAX_GEN_PREMASTER_SZ
1977
#else
1978
    #define PMS_GEN_CB_SZ   0
1979
#endif
1980
1981
/* SECRET_LEN is the floor: the RSA key exchange works with a master secret
1982
 * sized buffer, and TLS 1.3 reuses this buffer for the handshake secret,
1983
 * which is one MAC hash and never longer than SHA-384. */
1984
#define PMS_KX_SZ                                                             \
1985
    WOLFSSL_PMS_MAX2(WOLFSSL_PMS_MAX2(SECRET_LEN, PMS_DH_SZ),                 \
1986
                     WOLFSSL_PMS_MAX2(PMS_ECDH_SZ, PMS_PSK_SZ))
1987
#define MAX_PREMASTER_SZ                                                      \
1988
66.2k
    WOLFSSL_PMS_MAX2(WOLFSSL_PMS_MAX2(PMS_MCAST_SZ, PMS_GEN_CB_SZ),           \
1989
66.2k
                     PMS_KX_SZ + PMS_PSK_EXTRA)
1990
1991
/* The PSK layout - length, secret, length, key - is what decides the size,
1992
 * and getting it wrong is what overran the buffer before. */
1993
#if !defined(NO_PSK) && !defined(NO_DH)
1994
wc_static_assert(MAX_PREMASTER_SZ >=
1995
    OPAQUE16_LEN + MAX_DHKEY_SZ + OPAQUE16_LEN + MAX_PSK_KEY_LEN);
1996
#endif
1997
1998
/* Size of the data to authenticate */
1999
#if defined(WOLFSSL_DTLS) && defined(WOLFSSL_DTLS_CID)
2000
#define AEAD_AUTH_DATA_SZ WOLFSSL_TLS_AEAD_CID_AAD_SZ
2001
#else
2002
#define AEAD_AUTH_DATA_SZ 13
2003
#endif
2004
2005
#define WOLFSSL_NAMED_GROUP_IS_FFDHE(group) \
2006
282k
    (WOLFSSL_FFDHE_START <= (group) && (group) <= WOLFSSL_FFDHE_END)
2007
#ifdef WOLFSSL_HAVE_MLKEM
2008
WOLFSSL_LOCAL int NamedGroupIsPqc(int group);
2009
WOLFSSL_LOCAL int NamedGroupIsPqcHybrid(int group);
2010
537k
#define WOLFSSL_NAMED_GROUP_IS_PQC(group) NamedGroupIsPqc(group)
2011
272k
#define WOLFSSL_NAMED_GROUP_IS_PQC_HYBRID(group) NamedGroupIsPqcHybrid(group)
2012
#else
2013
#define WOLFSSL_NAMED_GROUP_IS_PQC(group)        0
2014
#define WOLFSSL_NAMED_GROUP_IS_PQC_HYBRID(group) 0
2015
#endif /* WOLFSSL_HAVE_MLKEM */
2016
2017
/* minimum Downgrade Minor version */
2018
#ifndef WOLFSSL_MIN_DOWNGRADE
2019
    #ifndef NO_OLD_TLS
2020
        #define WOLFSSL_MIN_DOWNGRADE TLSv1_MINOR
2021
    #else
2022
6.41k
        #define WOLFSSL_MIN_DOWNGRADE TLSv1_2_MINOR
2023
    #endif
2024
#endif
2025
2026
/* minimum DTLS Downgrade Minor version */
2027
#ifndef WOLFSSL_MIN_DTLS_DOWNGRADE
2028
#define WOLFSSL_MIN_DTLS_DOWNGRADE DTLS_MINOR;
2029
#endif
2030
2031
/* Set max implicit IV size for AEAD cipher suites */
2032
#if defined(WOLFSSL_TLS13) && defined(HAVE_NULL_CIPHER) && defined(WOLFSSL_SHA384)
2033
    /* Integrity-only cipher suites use IV size equal to hash output size */
2034
    #define AEAD_MAX_IMP_SZ 48
2035
#elif defined(WOLFSSL_TLS13) && defined(HAVE_NULL_CIPHER) && !defined(NO_SHA256)
2036
    /* Integrity-only cipher suites use IV size equal to hash output size */
2037
    #define AEAD_MAX_IMP_SZ 32
2038
#else
2039
    #define AEAD_MAX_IMP_SZ 12
2040
#endif
2041
2042
/* Set max explicit IV size for AEAD cipher suites */
2043
0
#define AEAD_MAX_EXP_SZ 8
2044
2045
2046
#ifndef WOLFSSL_MAX_SUITE_SZ
2047
11.3k
    #define WOLFSSL_MAX_SUITE_SZ 300
2048
    /* 150 suites for now! */
2049
#endif
2050
2051
/* InitSuites() haveNull value used when NULL suites are requested explicitly
2052
 * (cipher list "eNULL" keyword) rather than merely allowed by default (1). */
2053
0
#define SUITES_NULL_EXPLICIT 2
2054
2055
/* number of items in the signature algo list */
2056
#ifndef WOLFSSL_MAX_SIGALGO
2057
#if (defined(WOLFSSL_LEANPSK) || defined(WOLFSSL_LEANTLS)) && \
2058
    !defined(HAVE_FALCON) && !defined(WOLFSSL_HAVE_MLDSA) && \
2059
    !defined(WOLFSSL_HAVE_SLHDSA)
2060
    /* Lean builds keep the list small to minimize the memory footprint, unless
2061
     * they are post-quantum builds: those want to inter-op with OQS's OpenSSL
2062
     * that sends a lot more sigalgs, so they fall through to the larger default.
2063
     */
2064
    #define WOLFSSL_MAX_SIGALGO 44
2065
#else
2066
882
    #define WOLFSSL_MAX_SIGALGO 128
2067
#endif
2068
#endif
2069
2070
2071
/* set minimum ECC key size allowed */
2072
#ifndef WOLFSSL_MIN_ECC_BITS
2073
    #ifdef WOLFSSL_MAX_STRENGTH
2074
        #define WOLFSSL_MIN_ECC_BITS  256
2075
    #else
2076
12.8k
        #define WOLFSSL_MIN_ECC_BITS 224
2077
    #endif
2078
#endif /* WOLFSSL_MIN_ECC_BITS */
2079
#if (WOLFSSL_MIN_ECC_BITS % 8)
2080
    /* Some ECC keys are not divisible by 8 such as prime239v1 or sect131r1.
2081
       In these cases round down to the nearest value divisible by 8. The
2082
       restriction of being divisible by 8 is in place to match wc_ecc_size
2083
       function from wolfSSL.
2084
     */
2085
    #error ECC minimum bit size must be a multiple of 8
2086
#endif
2087
12.8k
#define MIN_ECCKEY_SZ (WOLFSSL_MIN_ECC_BITS / 8)
2088
2089
#ifdef HAVE_FALCON
2090
#ifndef MIN_FALCONKEY_SZ
2091
    #define MIN_FALCONKEY_SZ    1281
2092
#endif
2093
#endif
2094
#ifdef WOLFSSL_HAVE_MLDSA
2095
#ifndef MIN_MLDSAKEY_SZ
2096
    #define MIN_MLDSAKEY_SZ    2528
2097
#endif
2098
#endif
2099
2100
/* set minimum RSA key size allowed */
2101
#ifndef WOLFSSL_MIN_RSA_BITS
2102
    #if defined(WOLFSSL_HARDEN_TLS) && !defined(WOLFSSL_HARDEN_TLS_NO_PKEY_CHECK)
2103
        /* Using guidance from section 5.6.1
2104
         * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf */
2105
        #if WOLFSSL_HARDEN_TLS >= 128
2106
            #define WOLFSSL_MIN_RSA_BITS 3072
2107
        #elif WOLFSSL_HARDEN_TLS >= 112
2108
            #define WOLFSSL_MIN_RSA_BITS 2048
2109
        #endif
2110
    #elif defined(WOLFSSL_MAX_STRENGTH)
2111
        #define WOLFSSL_MIN_RSA_BITS 2048
2112
    #else
2113
12.8k
        #define WOLFSSL_MIN_RSA_BITS 1024
2114
    #endif
2115
#endif /* WOLFSSL_MIN_RSA_BITS */
2116
#if defined(WOLFSSL_HARDEN_TLS) && WOLFSSL_MIN_RSA_BITS < 2048 && \
2117
    !defined(WOLFSSL_HARDEN_TLS_NO_PKEY_CHECK)
2118
    /* Implementations MUST NOT negotiate cipher suites offering less than
2119
     * 112 bits of security.
2120
     * https://www.rfc-editor.org/rfc/rfc9325#section-4.1
2121
     * Using guidance from section 5.6.1
2122
     * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf */
2123
    #error "For 112 bits of security RSA needs at least 2048 bit keys"
2124
#endif
2125
#if (WOLFSSL_MIN_RSA_BITS % 8)
2126
    /* This is to account for the example case of a min size of 2050 bits but
2127
       still allows 2049 bit key. So we need the measurement to be in bytes. */
2128
    #error RSA minimum bit size must be a multiple of 8
2129
#endif
2130
12.8k
#define MIN_RSAKEY_SZ (WOLFSSL_MIN_RSA_BITS / 8)
2131
2132
#ifdef SESSION_INDEX
2133
/* Shift values for making a session index */
2134
#define SESSIDX_ROW_SHIFT 4
2135
#define SESSIDX_IDX_MASK  0x0F
2136
#endif
2137
2138
/* Size of the static per-certificate slot in a cached session's chain. This is
2139
 * embedded by value MAX_CHAIN_DEPTH times in every WOLFSSL_SESSION, so it is
2140
 * deliberately not sized from a post-quantum signature: a certificate too
2141
 * large for a slot takes an empty one, keeping the chain positional. Use
2142
 * MAX_CERT_WIRE_SZ for anything bounding a certificate on the wire. */
2143
#ifndef MAX_X509_SIZE
2144
    /* 9 KB holds the largest ML-DSA certificate (ML-DSA-87: 4627 byte signature
2145
     * plus 2592 byte public key, ~7.6 KB in practice) and an ML-DSA-44 dual
2146
     * algorithm certificate, which carries a second key and signature. Not
2147
     * derived from the enabled parameter set: the slot holds any certificate in
2148
     * a peer's chain, so tying it to the local ML-DSA level would make a
2149
     * level-restricted build silently drop certificates a full build kept. */
2150
    #if defined(HAVE_FALCON) || defined(WOLFSSL_HAVE_MLDSA) || \
2151
        defined(WOLFSSL_HAVE_SLHDSA)
2152
        #define MAX_X509_SIZE   (9*1024) /* max static x509 buffer size; ML-DSA is big */
2153
    #elif defined(WOLFSSL_HAPROXY)
2154
        #define MAX_X509_SIZE   3072 /* max static x509 buffer size */
2155
    #else
2156
35.3k
        #define MAX_X509_SIZE   2048 /* max static x509 buffer size */
2157
    #endif
2158
#endif
2159
2160
/* Largest single certificate that may appear in a handshake message. A
2161
 * post-quantum certificate's DER size is dominated by the issuer signature
2162
 * embedded in it, whose length depends on the parameter sets compiled in, plus
2163
 * headroom for the subject public key (largest is ML-DSA-87 at 2592 bytes) and
2164
 * the rest of the TBSCertificate. A leaf may be signed by a root of a larger
2165
 * parameter set, so the signature maximum is taken family-wide. */
2166
#ifndef MAX_CERT_WIRE_SZ
2167
    #if defined(WOLFSSL_HAVE_SLHDSA) && \
2168
        ((WC_SLHDSA_MAX_SIG_LEN + 4096) > MAX_X509_SIZE)
2169
        #define MAX_CERT_WIRE_SZ    (WC_SLHDSA_MAX_SIG_LEN + 4096)
2170
    #elif defined(WOLFSSL_HAVE_MLDSA) && \
2171
        ((MLDSA_MAX_SIG_SIZE + 4096) > MAX_X509_SIZE)
2172
        #define MAX_CERT_WIRE_SZ    (MLDSA_MAX_SIG_SIZE + 4096)
2173
    #else
2174
35.3k
        #define MAX_CERT_WIRE_SZ    MAX_X509_SIZE
2175
    #endif
2176
#endif
2177
2178
/* max cert chain peer depth */
2179
#ifndef MAX_CHAIN_DEPTH
2180
41.7k
    #define MAX_CHAIN_DEPTH 9
2181
#endif
2182
2183
#if defined(HAVE_CERTIFICATE_STATUS_REQUEST) || \
2184
                    defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
2185
    #if !defined(HAVE_OCSP)
2186
        #error OCSP Stapling and Stapling V2 needs OCSP. Please define HAVE_OCSP.
2187
    #endif
2188
#endif
2189
2190
/* Max certificate extensions in TLS1.3 */
2191
#if defined(HAVE_CERTIFICATE_STATUS_REQUEST)
2192
    /* Number of extensions to set each OCSP response */
2193
    #define MAX_CERT_EXTENSIONS (1 + MAX_CHAIN_DEPTH)
2194
#else
2195
    /* Only empty extensions */
2196
    #define MAX_CERT_EXTENSIONS 1
2197
#endif
2198
2199
/* Chain depth assumed when sizing the certificate message. Deliberately not
2200
 * MAX_CHAIN_DEPTH: that bounds how deep a chain may be verified, while this
2201
 * sizes a buffer an unauthenticated peer can make us allocate. Only reduced
2202
 * when a post-quantum certificate has inflated the per-certificate size, where
2203
 * the full verification depth would reserve hundreds of kilobytes and chains
2204
 * that deep are not realistic. Classic builds keep the historical depth, since
2205
 * the resulting buffer is small either way. Raise it for a deployment that
2206
 * presents deeper chains of post-quantum certificates. */
2207
#ifndef MAX_CERT_MSG_DEPTH
2208
    /* Trim only once a single certificate is large enough that the full
2209
     * verification depth would reserve an unreasonable amount for an
2210
     * unauthenticated peer. The threshold sits above any classic or ML-DSA
2211
     * certificate, so those builds keep the historical depth, and the test is
2212
     * on the size itself rather than on which macro produced it, so raising
2213
     * MAX_X509_SIZE cannot disengage the trim. */
2214
    #if (MAX_CERT_WIRE_SZ > (16*1024)) && (MAX_CHAIN_DEPTH > 5)
2215
        #define MAX_CERT_MSG_DEPTH 5
2216
    #else
2217
35.3k
        #define MAX_CERT_MSG_DEPTH MAX_CHAIN_DEPTH
2218
    #endif
2219
#endif
2220
2221
/* max size of a certificate message payload */
2222
/* assumes MAX_CERT_MSG_DEPTH certificates of MAX_CERT_WIRE_SZ each */
2223
#ifndef MAX_CERTIFICATE_SZ
2224
    #define MAX_CERTIFICATE_SZ \
2225
35.3k
                (CERT_HEADER_SZ + \
2226
35.3k
                (MAX_CERT_WIRE_SZ + CERT_HEADER_SZ) * MAX_CERT_MSG_DEPTH)
2227
#endif
2228
2229
/* max size of a handshake message, currently set to the certificate */
2230
#ifndef MAX_HANDSHAKE_SZ
2231
35.3k
    #define MAX_HANDSHAKE_SZ MAX_CERTIFICATE_SZ
2232
#endif
2233
2234
#ifndef PREALLOC_SESSION_TICKET_LEN
2235
    #define PREALLOC_SESSION_TICKET_LEN 512
2236
#endif
2237
2238
#ifndef PREALLOC_SESSION_TICKET_NONCE_LEN
2239
    #define PREALLOC_SESSION_TICKET_NONCE_LEN 32
2240
#endif
2241
2242
#ifndef SESSION_TICKET_HINT_DEFAULT
2243
    #define SESSION_TICKET_HINT_DEFAULT 300
2244
#endif
2245
2246
#if !defined(WOLFSSL_NO_DEF_TICKET_ENC_CB) && !defined(NO_WOLFSSL_SERVER)
2247
    /* Check chosen encryption is available. */
2248
    #if !(defined(HAVE_CHACHA) && defined(HAVE_POLY1305)) && \
2249
        defined(WOLFSSL_TICKET_ENC_CHACHA20_POLY1305)
2250
        #error "ChaCha20-Poly1305 not available for default ticket encryption"
2251
    #endif
2252
    #if !defined(HAVE_AESGCM) && (defined(WOLFSSL_TICKET_ENC_AES128_GCM) || \
2253
        defined(WOLFSSL_TICKET_ENC_AES256_GCM))
2254
        #error "AES-GCM not available for default ticket encryption"
2255
    #endif
2256
2257
    #ifndef WOLFSSL_TICKET_KEY_LIFETIME
2258
        /* Default lifetime is 1 hour from issue of first ticket with key. */
2259
        #define WOLFSSL_TICKET_KEY_LIFETIME       (60 * 60)
2260
    #endif
2261
    #if WOLFSSL_TICKET_KEY_LIFETIME <= SESSION_TICKET_HINT_DEFAULT
2262
        #error "Ticket Key lifetime must be longer than ticket life hint."
2263
    #endif
2264
#endif
2265
2266
0
#define MAX_ENCRYPT_SZ ENCRYPT_LEN
2267
2268
#define WOLFSSL_ASSERT_EQ(x, y) wc_static_assert((x) == (y))
2269
#define WOLFSSL_ASSERT_GE(x, y) wc_static_assert((x) >= (y))
2270
2271
0
#define WOLFSSL_ASSERT_SIZEOF_GE(x, y) wc_static_assert(sizeof(x) >= sizeof(y))
2272
#define WOLFSSL_ASSERT_SIZEOF_EQ(x, y) wc_static_assert(sizeof(x) == sizeof(y))
2273
2274
/* states. Adding state before HANDSHAKE_DONE will break session importing */
2275
enum states {
2276
    NULL_STATE = 0,
2277
2278
    SERVER_HELLOVERIFYREQUEST_COMPLETE,
2279
    SERVER_HELLO_RETRY_REQUEST_COMPLETE,
2280
    SERVER_HELLO_COMPLETE,
2281
    SERVER_ENCRYPTED_EXTENSIONS_COMPLETE,
2282
    SERVER_CERT_COMPLETE,
2283
    SERVER_CERT_VERIFY_COMPLETE,
2284
    SERVER_KEYEXCHANGE_COMPLETE,
2285
    SERVER_HELLODONE_COMPLETE,
2286
    SERVER_CHANGECIPHERSPEC_COMPLETE,
2287
    SERVER_FINISHED_COMPLETE,
2288
2289
    CLIENT_HELLO_RETRY,
2290
    CLIENT_HELLO_COMPLETE,
2291
    CLIENT_KEYEXCHANGE_COMPLETE,
2292
    CLIENT_CHANGECIPHERSPEC_COMPLETE,
2293
    CLIENT_FINISHED_COMPLETE,
2294
2295
    HANDSHAKE_DONE,
2296
2297
#ifdef WOLFSSL_DTLS13
2298
    SERVER_FINISHED_ACKED,
2299
#endif /* WOLFSSL_DTLS13 */
2300
    WOLF_ENUM_DUMMY_LAST_ELEMENT(states)
2301
};
2302
2303
/* SSL Version */
2304
typedef struct ProtocolVersion {
2305
    byte major;
2306
    byte minor;
2307
} WOLFSSL_PACK ProtocolVersion;
2308
2309
2310
WOLFSSL_LOCAL ProtocolVersion MakeSSLv3(void);
2311
WOLFSSL_LOCAL ProtocolVersion MakeTLSv1(void);
2312
WOLFSSL_LOCAL ProtocolVersion MakeTLSv1_1(void);
2313
WOLFSSL_LOCAL ProtocolVersion MakeTLSv1_2(void);
2314
WOLFSSL_LOCAL ProtocolVersion MakeTLSv1_3(void);
2315
2316
#ifdef WOLFSSL_DTLS
2317
    WOLFSSL_LOCAL ProtocolVersion MakeDTLSv1(void);
2318
    WOLFSSL_LOCAL ProtocolVersion MakeDTLSv1_2(void);
2319
2320
#ifdef WOLFSSL_DTLS13
2321
    WOLFSSL_LOCAL ProtocolVersion MakeDTLSv1_3(void);
2322
#endif /* WOLFSSL_DTLS13 */
2323
2324
#endif
2325
#ifdef WOLFSSL_SESSION_EXPORT
2326
WOLFSSL_LOCAL int wolfSSL_session_export_internal(WOLFSSL* ssl, byte* buf,
2327
        word32* sz, int type);
2328
WOLFSSL_LOCAL int wolfSSL_session_import_internal(WOLFSSL* ssl, const byte* buf,
2329
        word32 sz, int type);
2330
#ifdef WOLFSSL_DTLS
2331
    WOLFSSL_LOCAL int wolfSSL_dtls_export_state_internal(WOLFSSL* ssl,
2332
                                                          byte* buf, word32 sz);
2333
    WOLFSSL_LOCAL int wolfSSL_dtls_import_state_internal(WOLFSSL* ssl,
2334
                                                    const byte* buf, word32 sz);
2335
    WOLFSSL_LOCAL int wolfSSL_send_session(WOLFSSL* ssl);
2336
#endif
2337
#endif
2338
2339
struct WOLFSSL_BY_DIR_HASH {
2340
    unsigned long hash_value;
2341
    int last_suffix;
2342
};
2343
2344
struct WOLFSSL_BY_DIR_entry {
2345
    char*   dir_name;
2346
    int     dir_type;
2347
    WOLF_STACK_OF(WOLFSSL_BY_DIR_HASH) *hashes;
2348
};
2349
2350
struct WOLFSSL_BY_DIR {
2351
    WOLF_STACK_OF(WOLFSSL_BY_DIR_entry) *dir_entry;
2352
    wolfSSL_Mutex    lock; /* dir list lock */
2353
};
2354
2355
/* wolfSSL method type */
2356
struct WOLFSSL_METHOD {
2357
    ProtocolVersion version;
2358
    byte            side;         /* connection side, server or client */
2359
    byte            downgrade;    /* whether to downgrade version, default no */
2360
};
2361
2362
/* wolfSSL buffer type - internal uses "buffer" type */
2363
typedef WOLFSSL_BUFFER_INFO buffer;
2364
2365
typedef struct Suites Suites;
2366
2367
/* Declare opaque struct for API to use */
2368
#ifndef WOLFSSL_CLIENT_SESSION_DEFINED
2369
    typedef struct ClientSession ClientSession;
2370
    #define WOLFSSL_CLIENT_SESSION_DEFINED
2371
#endif
2372
2373
/* defaults to client */
2374
WOLFSSL_LOCAL void InitSSL_Method(WOLFSSL_METHOD* method, ProtocolVersion pv);
2375
2376
WOLFSSL_LOCAL void InitSSL_CTX_Suites(const WOLFSSL_CTX* ctx,
2377
    Suites* suites);
2378
WOLFSSL_LOCAL int InitSSL_Suites(WOLFSSL* ssl);
2379
WOLFSSL_LOCAL int InitSSL_Side(WOLFSSL* ssl, word16 side);
2380
2381
2382
#if defined(HAVE_CURVE25519) && !defined(WOLFSSL_X25519_NO_MASK_PEER)
2383
WOLFSSL_LOCAL const byte* MaskCurve25519PeerKey(const byte* pub, word32 pubSz,
2384
                                               byte maskBuf[CURVE25519_KEYSIZE]);
2385
#endif
2386
2387
WOLFSSL_LOCAL int DoHandShakeMsgType(WOLFSSL* ssl, byte* input,
2388
        word32* inOutIdx, byte type, word32 size, word32 totalSz);
2389
/* for sniffer */
2390
WOLFSSL_LOCAL int DoFinished(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
2391
                            word32 size, word32 totalSz, int sniff);
2392
#ifdef WOLFSSL_TLS13
2393
WOLFSSL_LOCAL int DoTls13Finished(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
2394
                           word32 size, word32 totalSz, int sniff);
2395
#endif
2396
#ifdef WOLFSSL_API_PREFIX_MAP
2397
    #define DoApplicationData wolfSSL_DoApplicationData
2398
#endif
2399
WOLFSSL_TEST_VIS int DoApplicationData(WOLFSSL* ssl, byte* input, word32* inOutIdx,
2400
                                    int sniff);
2401
/* TLS v1.3 needs these */
2402
WOLFSSL_LOCAL int  HandleTlsResumption(WOLFSSL* ssl, Suites* clSuites);
2403
#ifdef WOLFSSL_TLS13
2404
WOLFSSL_LOCAL byte SuiteMac(const byte* suite);
2405
#endif
2406
#if (defined(WOLFSSL_DTLS) || defined(WOLFSSL_SEND_HRR_COOKIE)) && \
2407
    !defined(NO_WOLFSSL_SERVER)
2408
WOLFSSL_LOCAL void FreeCookieSecret(WOLFSSL* ssl, buffer* secret);
2409
WOLFSSL_LOCAL int SetCookieSecret(WOLFSSL* ssl, buffer* dst,
2410
                                  const byte* secret, word32 secretSz,
2411
                                  const char* name);
2412
WOLFSSL_LOCAL int CookiePolicySet(WOLFSSL* ssl, const byte* hrrSecret,
2413
                                  word32 hrrSecretSz, int replaceHrr);
2414
WOLFSSL_LOCAL int CookiePolicyEnable(WOLFSSL* ssl);
2415
WOLFSSL_LOCAL int CheckCookieState(WOLFSSL* ssl);
2416
#endif
2417
/* A verified client certificate with proof of possession, on this connection
2418
 * or the one it resumed. Nothing is verified under verifyNone. */
2419
#define SSL_PEER_CERT_VERIFIED(ssl) \
2420
0
    (((ssl)->options.havePeerCert && (ssl)->options.havePeerVerify && \
2421
0
      !(ssl)->options.verifyNone) || \
2422
0
     ((ssl)->options.resuming && (ssl)->session->peerAuthOk))
2423
WOLFSSL_LOCAL int ClientAuthRequired(const WOLFSSL* ssl, int usingPsk);
2424
WOLFSSL_LOCAL int  DoClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
2425
                             word32 helloSz);
2426
#ifdef WOLFSSL_TLS13
2427
WOLFSSL_LOCAL int DoTls13ClientHello(WOLFSSL* ssl, const byte* input,
2428
                                     word32* inOutIdx, word32 helloSz);
2429
#endif
2430
WOLFSSL_LOCAL int  DoServerHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
2431
                      word32 helloSz);
2432
WOLFSSL_LOCAL int  CompleteServerHello(WOLFSSL *ssl);
2433
WOLFSSL_LOCAL int  CheckVersion(WOLFSSL *ssl, ProtocolVersion pv);
2434
WOLFSSL_LOCAL int  PickHashSigAlgo(WOLFSSL* ssl, const byte* hashSigAlgo,
2435
                                   word32 hashSigAlgoSz, int matchSuites);
2436
#if defined(WOLF_PRIVATE_KEY_ID) && !defined(NO_CHECK_PRIVATE_KEY)
2437
/* slhParam is the enum SlhDsaParam for DYNAMIC_TYPE_SLHDSA, whose parameter
2438
 * set cannot be derived from a device-side identifier. Pass -1 otherwise. */
2439
WOLFSSL_LOCAL int  CreateDevPrivateKey(void** pkey, byte* data, word32 length,
2440
                                       int hsType, int label, int id,
2441
                                       void* heap, int devId, int slhParam);
2442
#endif
2443
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
2444
WOLFSSL_LOCAL int wolfssl_priv_der_blind(WC_RNG* rng, DerBuffer* key,
2445
    DerBuffer** mask);
2446
WOLFSSL_LOCAL void wolfssl_priv_der_blind_toggle(DerBuffer* key,
2447
    const DerBuffer* mask);
2448
WOLFSSL_LOCAL WARN_UNUSED_RESULT DerBuffer *wolfssl_priv_der_unblind(
2449
    const DerBuffer* key, const DerBuffer* mask);
2450
WOLFSSL_LOCAL void wolfssl_priv_der_unblind_free(DerBuffer* key);
2451
#endif
2452
WOLFSSL_LOCAL int  DecodePrivateKey(WOLFSSL *ssl, word32* sigLen);
2453
#ifdef WOLFSSL_DUAL_ALG_CERTS
2454
WOLFSSL_LOCAL int  DecodeAltPrivateKey(WOLFSSL *ssl, word32* sigLen);
2455
#endif
2456
#if defined(WOLF_PRIVATE_KEY_ID) || defined(HAVE_PK_CALLBACKS)
2457
WOLFSSL_LOCAL int GetPrivateKeySigSize(WOLFSSL* ssl);
2458
#ifndef NO_ASN
2459
    WOLFSSL_LOCAL int  InitSigPkCb(WOLFSSL* ssl, SignatureCtx* sigCtx);
2460
#endif
2461
#endif
2462
WOLFSSL_LOCAL int CreateSigData(WOLFSSL* ssl, byte* sigData, word16* sigDataSz,
2463
                                int check);
2464
WOLFSSL_LOCAL int CreateRSAEncodedSig(byte* sig, byte* sigData, int sigDataSz,
2465
                                      int sigAlgo, int hashAlgo);
2466
#ifdef WOLFSSL_ASYNC_IO
2467
WOLFSSL_LOCAL void FreeAsyncCtx(WOLFSSL* ssl, byte freeAsync);
2468
#endif
2469
WOLFSSL_LOCAL void FreeKeyExchange(WOLFSSL* ssl);
2470
WOLFSSL_LOCAL void FreePeerCertKeys(WOLFSSL* ssl);
2471
WOLFSSL_LOCAL void FreeSuites(WOLFSSL* ssl);
2472
WOLFSSL_LOCAL int  ProcessPeerCerts(WOLFSSL* ssl, byte* input, word32* inOutIdx, word32 totalSz);
2473
#ifdef WOLFSSL_API_PREFIX_MAP
2474
    #define MatchDomainName wolfSSL_MatchDomainName
2475
#endif
2476
WOLFSSL_TEST_VIS int  MatchDomainName(const char* pattern, int len,
2477
                                      const char* str, word32 strLen,
2478
                                      unsigned int flags);
2479
#if !defined(NO_CERTS) && !defined(NO_ASN)
2480
WOLFSSL_LOCAL int  CheckForAltNames(DecodedCert* dCert, const char* domain,
2481
                                    word32 domainLen, int* checkCN,
2482
                                    unsigned int flags, byte isIP);
2483
WOLFSSL_LOCAL int  CheckIPAddr(DecodedCert* dCert, const char* ipasc,
2484
                               size_t ipascLen);
2485
WOLFSSL_LOCAL void CopyDecodedName(WOLFSSL_X509_NAME* name, DecodedCert* dCert, int nameType);
2486
#endif
2487
WOLFSSL_LOCAL int  SetupTicket(WOLFSSL* ssl);
2488
WOLFSSL_LOCAL int  CreateTicket(WOLFSSL* ssl);
2489
WOLFSSL_LOCAL int  DefTicketHintTooLarge(WOLFSSL* ssl);
2490
WOLFSSL_LOCAL int  HashRaw(WOLFSSL* ssl, const byte* data, int sz);
2491
WOLFSSL_LOCAL int  HashOutput(WOLFSSL* ssl, const byte* output, int sz,
2492
                              int ivSz);
2493
WOLFSSL_LOCAL int  HashInput(WOLFSSL* ssl, const byte* input, int sz);
2494
2495
#ifdef HAVE_SNI
2496
#ifndef NO_WOLFSSL_SERVER
2497
WOLFSSL_LOCAL int SNI_Callback(WOLFSSL* ssl);
2498
#endif
2499
#endif
2500
2501
#ifdef HAVE_ALPN
2502
WOLFSSL_LOCAL int ALPN_Select(WOLFSSL* ssl);
2503
#endif
2504
2505
WOLFSSL_LOCAL int ChachaAEADEncrypt(WOLFSSL* ssl, byte* out, const byte* input,
2506
                              word16 sz, byte type); /* needed by sniffer */
2507
WOLFSSL_LOCAL int ChachaAEADDecrypt(WOLFSSL* ssl, byte* plain, const byte* input,
2508
                              word16 sz); /* needed by sniffer */
2509
2510
#ifdef WOLFSSL_TLS13
2511
WOLFSSL_LOCAL int  DecryptTls13(WOLFSSL* ssl, byte* output, const byte* input,
2512
                                word16 sz, const byte* aad, word16 aadSz);
2513
WOLFSSL_LOCAL int  DoTls13MsgDerives(WOLFSSL* ssl, byte type);
2514
/* A crypto/PK callback pending is finished by re-invoking the provider:
2515
 * wolfSSL_AsyncPoll() never runs a callback. Exported so tests compile in
2516
 * only where a callback pend is resumable. */
2517
#if defined(WOLFSSL_ASYNC_CRYPT) && \
2518
    (defined(WOLF_CRYPTO_CB) || defined(HAVE_PK_CALLBACKS)) && \
2519
    !defined(WOLFSSL_ASYNC_CRYPT_SW) && !defined(HAVE_INTEL_QA) && \
2520
    !defined(HAVE_CAVIUM)
2521
    #define WOLFSSL_ASYNC_REINVOKE
2522
#endif
2523
#if defined(WOLFSSL_ASYNC_REINVOKE) && !defined(NO_HMAC)
2524
WOLFSSL_LOCAL void Tls13FreeHsHmac(WOLFSSL* ssl);
2525
#endif
2526
WOLFSSL_LOCAL int  DoTls13HandShakeMsgType(WOLFSSL* ssl, byte* input,
2527
                                           word32* inOutIdx, byte type,
2528
                                           word32 size, word32 totalSz);
2529
WOLFSSL_LOCAL int  DoTls13HandShakeMsg(WOLFSSL* ssl, byte* input,
2530
                                       word32* inOutIdx, word32 totalSz);
2531
WOLFSSL_LOCAL int DoTls13ServerHello(WOLFSSL* ssl, const byte* input,
2532
                                     word32* inOutIdx, word32 helloSz,
2533
                                     byte* extMsgType);
2534
WOLFSSL_LOCAL int RestartHandshakeHash(WOLFSSL* ssl);
2535
2536
WOLFSSL_LOCAL int Tls13DeriveKey(WOLFSSL *ssl, byte *output, int outputLen,
2537
    const byte *secret, const byte *label, word32 labelLen, int hashAlgo,
2538
    int includeMsgs, int side);
2539
#endif
2540
int TimingPadVerify(WOLFSSL* ssl, const byte* input, int padLen, int macSz,
2541
                    int pLen, int content);
2542
2543
2544
enum {
2545
    FORCED_FREE = 1,
2546
    NO_FORCED_FREE = 0
2547
};
2548
2549
2550
/* only use compression extra if using compression */
2551
#ifdef HAVE_LIBZ
2552
    #define COMP_EXTRA MAX_COMP_EXTRA
2553
#else
2554
0
    #define COMP_EXTRA 0
2555
#endif
2556
2557
/* only the sniffer needs space in the buffer for extra MTU record(s) */
2558
#ifdef WOLFSSL_SNIFFER
2559
    #define MTU_EXTRA MAX_MTU * 3
2560
#else
2561
    #define MTU_EXTRA 0
2562
#endif
2563
2564
2565
/* embedded callbacks require large static buffers, make sure on */
2566
#ifdef WOLFSSL_CALLBACKS
2567
    #undef  LARGE_STATIC_BUFFERS
2568
    #define LARGE_STATIC_BUFFERS
2569
#endif
2570
2571
2572
/* determine maximum record size */
2573
0
#define MAX_RECORD_SIZE 16384  /* 2^14, max size by standard */
2574
2575
#ifdef RECORD_SIZE
2576
    /* user supplied value */
2577
    #if RECORD_SIZE < 128 || RECORD_SIZE > MAX_RECORD_SIZE
2578
        #error Invalid record size
2579
    #endif
2580
#else
2581
    /* give user option to use 16K static buffers */
2582
    #if defined(LARGE_STATIC_BUFFERS)
2583
        #define RECORD_SIZE     MAX_RECORD_SIZE
2584
    #else
2585
        #ifdef WOLFSSL_DTLS
2586
            #define RECORD_SIZE MAX_MTU
2587
        #else
2588
            #define RECORD_SIZE 128
2589
        #endif
2590
    #endif
2591
#endif
2592
2593
2594
/* user option to turn off 16K output option */
2595
/* if using small static buffers (default) and SSL_write tries to write data
2596
   larger than the record we have, dynamically get it, unless user says only
2597
   write in static buffer chunks  */
2598
#ifndef STATIC_CHUNKS_ONLY
2599
0
    #define OUTPUT_RECORD_SIZE MAX_RECORD_SIZE
2600
#else
2601
    #define OUTPUT_RECORD_SIZE RECORD_SIZE
2602
#endif
2603
2604
/* wolfSSL input buffer
2605
2606
   RFC 2246:
2607
2608
   length
2609
       The length (in bytes) of the following TLSPlaintext.fragment.
2610
       The length should not exceed 2^14.
2611
*/
2612
#ifdef STATIC_BUFFER_LEN
2613
    /* user supplied option */
2614
#elif defined(LARGE_STATIC_BUFFERS)
2615
    #define STATIC_BUFFER_LEN (RECORD_HEADER_SZ + RECORD_SIZE + COMP_EXTRA + \
2616
             MTU_EXTRA + MAX_MSG_EXTRA)
2617
#else
2618
    /* don't fragment memory from the record header */
2619
688k
    #define STATIC_BUFFER_LEN RECORD_HEADER_SZ
2620
#endif
2621
2622
/* RECORD_HEADER_SZ is an enum constant, so the preprocessor can't check
2623
 * this bound. */
2624
wc_static_assert(STATIC_BUFFER_LEN >= RECORD_HEADER_SZ);
2625
2626
/* Default read-ahead window: when read-ahead is enabled the record header read
2627
 * requests up to a full record's worth of data in a single recv() so the body
2628
 * (and possibly following records) can be pulled in without a second syscall.
2629
 * Sized to one maximum TLS record (MAX_RECORD_SIZE, not the buffer-sizing
2630
 * RECORD_SIZE which may be small) so the whole record is captured. Defined
2631
 * unconditionally so the setters and CTX init can reference it as the default
2632
 * window even when read-ahead I/O is not built. */
2633
#ifndef WOLFSSL_READ_AHEAD_SZ
2634
#define WOLFSSL_READ_AHEAD_SZ (RECORD_HEADER_SZ + MAX_RECORD_SIZE + \
2635
         COMP_EXTRA + MTU_EXTRA + MAX_MSG_EXTRA)
2636
#endif
2637
2638
/* Upper bound for a caller-configured read-ahead window
2639
 * (wolfSSL_CTX/SSL_set_default_read_buffer_len()). The window feeds signed int
2640
 * arithmetic in GetInputData_ex(); bounding it well below INT_MAX ensures a
2641
 * large caller-supplied size can never overflow that arithmetic to a negative
2642
 * value (which would skip GrowInputBuffer() and drive an oversized recv()).
2643
 * 16 MB is far above any realistic coalescing window. Defined unconditionally
2644
 * so the setters can clamp even when read-ahead I/O is not built. */
2645
#ifndef WOLFSSL_MAX_READ_AHEAD_SZ
2646
#define WOLFSSL_MAX_READ_AHEAD_SZ (16 * 1024 * 1024)
2647
#endif
2648
2649
typedef struct {
2650
    ALIGN16 byte staticBuffer[STATIC_BUFFER_LEN];
2651
    byte*  buffer;       /* place holder for static or dynamic buffer */
2652
    word32 length;       /* total buffer length used */
2653
    word32 idx;          /* idx to part of length already consumed */
2654
    word32 bufferSize;   /* current buffer size */
2655
    byte   dynamicFlag;  /* dynamic memory currently in use */
2656
    byte   offset;       /* alignment offset attempt */
2657
} bufferStatic;
2658
2659
/* Cipher Suites holder */
2660
struct Suites {
2661
    word16 suiteSz;                 /* suite length in bytes        */
2662
    word16 hashSigAlgoSz;           /* SigAlgo extension length in bytes */
2663
    byte   suites[WOLFSSL_MAX_SUITE_SZ];
2664
    byte   hashSigAlgo[WOLFSSL_MAX_SIGALGO]; /* sig/algo to offer */
2665
    byte   setSuites:1;             /* user set suites from default */
2666
};
2667
2668
typedef struct CipherSuite {
2669
    byte   cipherSuite0;
2670
    byte   cipherSuite;
2671
    word32 ecdhCurveOID;
2672
    struct KeyShareEntry* clientKSE;
2673
#if defined(WOLFSSL_TLS13) && defined(HAVE_SUPPORTED_CURVES)
2674
    int    doHelloRetry;
2675
#endif
2676
} CipherSuite;
2677
2678
#ifdef WOLFSSL_API_PREFIX_MAP
2679
    #define InitSuitesHashSigAlgo wolfSSL_InitSuitesHashSigAlgo
2680
#endif
2681
WOLFSSL_TEST_VIS void InitSuitesHashSigAlgo(byte* hashSigAlgo, int have,
2682
                                       int tls1_2, int tls1_3, int keySz,
2683
                                       word16* len);
2684
WOLFSSL_LOCAL int AllocateCtxSuites(WOLFSSL_CTX* ctx);
2685
WOLFSSL_LOCAL int InitCtxSuitesWithMutex(WOLFSSL_CTX* ctx);
2686
WOLFSSL_LOCAL int AllocateSuites(WOLFSSL* ssl);
2687
WOLFSSL_LOCAL void InitSuites(Suites* suites, ProtocolVersion pv, int keySz,
2688
                              word16 haveRSA, word16 havePSK, word16 haveDH,
2689
                              word16 haveECDSAsig, word16 haveECC,
2690
                              word16 haveStaticRSA, word16 haveStaticECC,
2691
                              word16 haveAnon, word16 haveNull,
2692
                              word16 haveAES128, word16 haveSHA1,
2693
                              word16 haveRC4, int side);
2694
2695
void refineSuites(const Suites* sslSuites, const Suites* peerSuites,
2696
        Suites* outSuites, byte useClientOrder);
2697
void sslRefineSuites(WOLFSSL* ssl, Suites* peerSuites);
2698
2699
typedef struct TLSX TLSX;
2700
WOLFSSL_LOCAL int MatchSuite_ex(const WOLFSSL* ssl, Suites* peerSuites,
2701
                                CipherSuite* cs, TLSX* extensions);
2702
WOLFSSL_LOCAL int  MatchSuite(WOLFSSL* ssl, Suites* peerSuites);
2703
WOLFSSL_LOCAL int  SetCipherList_ex(const WOLFSSL_CTX* ctx, const WOLFSSL* ssl,
2704
        Suites* suites, const char* list);
2705
WOLFSSL_LOCAL int  SetCipherList(const WOLFSSL_CTX* ctx, Suites* suites,
2706
                                 const char* list);
2707
WOLFSSL_LOCAL int  SetCipherListFromBytes(WOLFSSL_CTX* ctx, Suites* suites,
2708
                                          const byte* list, const int listSz);
2709
WOLFSSL_LOCAL int  SetSuitesHashSigAlgo(Suites* suites, const char* list);
2710
2711
#ifndef PSK_TYPES_DEFINED
2712
    typedef unsigned int (*wc_psk_client_callback)(WOLFSSL*, const char*, char*,
2713
                          unsigned int, unsigned char*, unsigned int);
2714
    typedef unsigned int (*wc_psk_server_callback)(WOLFSSL*, const char*,
2715
                          unsigned char*, unsigned int);
2716
#ifdef WOLFSSL_TLS13
2717
    typedef unsigned int (*wc_psk_client_cs_callback)(WOLFSSL*, const char*,
2718
                          char*, unsigned int, unsigned char*, unsigned int,
2719
                          const char* cipherName);
2720
    typedef unsigned int (*wc_psk_client_tls13_callback)(WOLFSSL*, const char*,
2721
                          char*, unsigned int, unsigned char*, unsigned int,
2722
                          const char** cipherName);
2723
    typedef unsigned int (*wc_psk_server_tls13_callback)(WOLFSSL*, const char*,
2724
                          unsigned char*, unsigned int,
2725
                          const char** cipherName);
2726
#endif
2727
#endif /* PSK_TYPES_DEFINED */
2728
#if defined(WOLFSSL_DTLS) && defined(WOLFSSL_SESSION_EXPORT) && \
2729
   !defined(WOLFSSL_DTLS_EXPORT_TYPES)
2730
    typedef int (*wc_dtls_export)(WOLFSSL* ssl,
2731
2732
#define WOLFSSL_DTLS_EXPORT_TYPES
2733
#endif /* WOLFSSL_DTLS_EXPORT_TYPES */
2734
2735
2736
/* A cipher suite and the version reported for it. */
2737
struct WOLFSSL_CIPHER {
2738
    byte cipherSuite0;
2739
    byte cipherSuite;
2740
    ProtocolVersion pv;     /* version reported */
2741
};
2742
2743
2744
#ifdef NO_ASN
2745
    /* no_asn won't have */
2746
    typedef struct CertStatus CertStatus;
2747
#endif
2748
2749
#ifndef HAVE_OCSP
2750
    typedef struct WOLFSSL_OCSP WOLFSSL_OCSP;
2751
#endif
2752
2753
/* wolfSSL OCSP controller */
2754
#ifdef HAVE_OCSP
2755
struct WOLFSSL_OCSP {
2756
    WOLFSSL_CERT_MANAGER* cm;            /* pointer back to cert manager */
2757
    OcspEntry*            ocspList;      /* OCSP response list */
2758
    wolfSSL_Mutex         ocspLock;      /* OCSP list lock */
2759
    int                   error;
2760
    int(*statusCb)(WOLFSSL*, void*);
2761
    void*                 statusCbArg;
2762
};
2763
#endif
2764
2765
typedef struct CRL_Entry CRL_Entry;
2766
2767
/* DecodeCRL() fills issuerHash with CalcHashId_ex(), the same as a Signer. */
2768
#define CRL_DIGEST_SIZE KEYID_SIZE
2769
2770
#ifdef NO_ASN
2771
    typedef struct RevokedCert RevokedCert;
2772
#endif
2773
#ifdef CRL_STATIC_REVOKED_LIST
2774
    #ifndef CRL_MAX_REVOKED_CERTS
2775
        #define CRL_MAX_REVOKED_CERTS 4
2776
    #elif CRL_MAX_REVOKED_CERTS > 22000
2777
        #error CRL_MAX_REVOKED_CERTS too big, max is 22000
2778
    #endif
2779
#endif
2780
2781
#ifdef HAVE_CRL
2782
/* Complete CRL */
2783
struct CRL_Entry {
2784
    byte*   toBeSigned;
2785
    byte*   signature;
2786
#ifdef WC_RSA_PSS
2787
    byte*   sigParams;   /* buffer with signature parameters */
2788
#endif
2789
#if defined(OPENSSL_EXTRA)
2790
    WOLFSSL_X509_NAME*    issuer;     /* X509_NAME type issuer */
2791
#endif
2792
    CRL_Entry* next;                      /* next entry */
2793
#ifdef CRL_STATIC_REVOKED_LIST
2794
    RevokedCert certs[CRL_MAX_REVOKED_CERTS];
2795
#else
2796
    RevokedCert* certs;             /* revoked cert list  */
2797
#endif
2798
    wolfSSL_Mutex verifyMutex;
2799
    /* DupCRL_Entry bulk copies the data after the `verifyMutex` member, so
2800
     * only self-contained value data belongs below it. Anything holding a
2801
     * pointer goes above, where DupCRL_Entry copies it explicitly. Using the
2802
     * mutex as the marker because clang-tidy doesn't like taking the sizeof a
2803
     * pointer. */
2804
    char    crlNumber[CRL_MAX_NUM_HEX_STR_SZ];    /* CRL number extension */
2805
    byte    issuerHash[CRL_DIGEST_SIZE];  /* issuer hash                 */
2806
    /* byte    crlHash[CRL_DIGEST_SIZE];      raw crl data hash           */
2807
    /* restore the hash here if needed for optimized comparisons */
2808
    byte    lastDate[MAX_DATE_SIZE]; /* last date updated  */
2809
    byte    nextDate[MAX_DATE_SIZE]; /* next update date   */
2810
    byte    lastDateFormat;          /* last date format */
2811
    byte    nextDateFormat;          /* next date format */
2812
#if defined(OPENSSL_EXTRA)
2813
    WOLFSSL_ASN1_TIME lastDateAsn1;  /* last date updated  */
2814
    WOLFSSL_ASN1_TIME nextDateAsn1;  /* next update date   */
2815
#endif
2816
    int     totalCerts;             /* number on list     */
2817
    int     version;                /* version of certificate */
2818
    int     verified;
2819
    word32  tbsSz;
2820
    word32  signatureSz;
2821
#ifdef WC_RSA_PSS
2822
    word32  sigParamsSz; /* length of signature parameters   */
2823
#endif
2824
    word32  signatureOID;
2825
#if !defined(NO_SKID) && !defined(NO_ASN)
2826
    byte    extAuthKeyId[KEYID_SIZE];
2827
    byte    extAuthKeyIdSet:1;  /* Auth key identifier set indicator */
2828
#endif
2829
    byte    crlNumberSet:1;     /* CRL number set indicator */
2830
};
2831
2832
2833
#ifdef HAVE_CRL_MONITOR
2834
typedef struct CRL_Monitor CRL_Monitor;
2835
2836
/* CRL directory monitor */
2837
struct CRL_Monitor {
2838
    char* path;      /* full dir path, if valid pointer we're using */
2839
    int   type;      /* PEM or ASN1 type */
2840
};
2841
2842
2843
#if defined(HAVE_CRL) && defined(NO_FILESYSTEM)
2844
    #undef HAVE_CRL_MONITOR
2845
#endif
2846
2847
/* PEM and DER possible */
2848
#define WOLFSSL_CRL_MONITORS_LEN 2
2849
2850
#if defined(__MACH__) || defined(__FreeBSD__) || defined(__linux__)
2851
typedef int    wolfSSL_CRL_mfd_t; /* monitor fd, -1 if no init yet */
2852
/* mfd for bsd is kqueue fd, eventfd for linux */
2853
#define WOLFSSL_CRL_MFD_INIT_VAL (-1)
2854
#elif defined(_MSC_VER)
2855
typedef HANDLE wolfSSL_CRL_mfd_t; /* monitor fd, INVALID_HANDLE_VALUE if
2856
                                   * no init yet */
2857
#define WOLFSSL_CRL_MFD_INIT_VAL (INVALID_HANDLE_VALUE)
2858
#endif
2859
#endif
2860
2861
/* wolfSSL CRL controller */
2862
struct WOLFSSL_CRL {
2863
    WOLFSSL_CERT_MANAGER* cm;            /* pointer back to cert manager */
2864
    CRL_Entry*            crlList;       /* our CRL list */
2865
#ifdef HAVE_CRL_IO
2866
    CbCrlIO               crlIOCb;
2867
#endif
2868
    wolfSSL_RwLock        crlLock;       /* CRL list lock */
2869
#ifdef HAVE_CRL_MONITOR
2870
    CRL_Monitor           monitors[WOLFSSL_CRL_MONITORS_LEN];
2871
    COND_TYPE             cond;          /* condition to signal setup */
2872
    THREAD_TYPE           tid;           /* monitoring thread */
2873
    wolfSSL_CRL_mfd_t     mfd;
2874
    int                   setup;         /* thread is setup predicate */
2875
#endif
2876
#ifdef OPENSSL_ALL
2877
    wolfSSL_Ref           ref;
2878
#endif
2879
#if defined(OPENSSL_EXTRA)
2880
    WOLFSSL_STACK*        revokedStack;  /* cached STACK_OF(X509_REVOKED) */
2881
#endif
2882
    void*                 heap;          /* heap hint for dynamic memory */
2883
};
2884
#endif
2885
2886
2887
#ifdef NO_ASN
2888
    typedef struct Signer Signer;
2889
#ifdef WOLFSSL_TRUST_PEER_CERT
2890
    typedef struct TrustedPeerCert TrustedPeerCert;
2891
#endif
2892
#endif
2893
2894
2895
#ifndef CA_TABLE_SIZE
2896
68.5k
    #define CA_TABLE_SIZE 11
2897
#endif
2898
#ifdef WOLFSSL_TRUST_PEER_CERT
2899
    #define TP_TABLE_SIZE 11
2900
#endif
2901
2902
/* wolfSSL Certificate Manager */
2903
struct WOLFSSL_CERT_MANAGER {
2904
    Signer*         caTable[CA_TABLE_SIZE]; /* the CA signer table */
2905
    void*           heap;                /* heap helper */
2906
#ifdef WOLFSSL_TRUST_PEER_CERT
2907
    TrustedPeerCert* tpTable[TP_TABLE_SIZE]; /* table of trusted peer certs */
2908
    wolfSSL_Mutex   tpLock;                  /* trusted peer list lock */
2909
#endif
2910
    WOLFSSL_CRL*    crl;                 /* CRL checker */
2911
    WOLFSSL_OCSP*   ocsp;                /* OCSP checker */
2912
#if !defined(NO_WOLFSSL_SERVER) && (defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
2913
                               ||  defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2))
2914
    WOLFSSL_OCSP*   ocsp_stapling;       /* OCSP checker for OCSP stapling */
2915
#endif
2916
    char*           ocspOverrideURL;     /* use this responder */
2917
    void*           ocspIOCtx;           /* I/O callback CTX */
2918
#ifndef NO_WOLFSSL_CM_VERIFY
2919
    VerifyCallback  verifyCallback;      /* Verify callback */
2920
#endif
2921
    CallbackCACache caCacheCallback;       /* CA cache addition callback */
2922
    CbMissingCRL    cbMissingCRL;          /* notify thru cb of missing crl */
2923
    crlErrorCb      crlCb;                 /* Allow user to override error */
2924
    void*           crlCbCtx;
2925
    CbOCSPIO        ocspIOCb;              /* I/O callback for OCSP lookup */
2926
    CbOCSPRespFree  ocspRespFreeCb;        /* Frees OCSP Response from IO Cb */
2927
    wolfSSL_Mutex   caLock;                /* CA list lock */
2928
    byte            crlEnabled:1;          /* is CRL on ? */
2929
    byte            crlCheckAll:1;         /* always leaf, but all ? */
2930
    byte            ocspEnabled:1;         /* is OCSP on ? */
2931
    byte            ocspCheckAll:1;        /* always leaf, but all ? */
2932
    byte            ocspFailIfNotSupported:1; /* refuse a cert that advertises
2933
                                              * no OCSP responder ? */
2934
    byte            ocspSendNonce:1;       /* send the OCSP nonce ? */
2935
    byte            ocspUseOverrideURL:1;  /* ignore cert responder, override */
2936
    byte            ocspStaplingEnabled:1; /* is OCSP Stapling on ? */
2937
#if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
2938
||  defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
2939
    byte            ocspMustStaple:1;      /* server must respond with staple */
2940
#endif
2941
    /* Tracks which resources were successfully initialized so that
2942
     * DoCertManagerFree can dispose of them safely even when construction
2943
     * fails partway through. */
2944
    WC_BITFIELD     caLockInit:1;          /* caLock has been initialized */
2945
#ifdef WOLFSSL_TRUST_PEER_CERT
2946
    WC_BITFIELD     tpLockInit:1;          /* tpLock has been initialized */
2947
#endif
2948
    WC_BITFIELD     refInit:1;             /* ref has been initialized */
2949
2950
#ifndef NO_RSA
2951
    short           minRsaKeySz;         /* minimum allowed RSA key size */
2952
#endif
2953
#if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
2954
    short           minEccKeySz;         /* minimum allowed ECC key size */
2955
#endif
2956
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
2957
    WOLFSSL_X509_STORE  *x509_store_p;  /* a pointer back to CTX x509 store  */
2958
                                        /* CTX has ownership and free this   */
2959
                                        /* with CTX free.                    */
2960
#endif
2961
    wolfSSL_Ref     ref;
2962
#ifdef HAVE_FALCON
2963
    short           minFalconKeySz;     /* minimum allowed Falcon key size */
2964
#endif
2965
#ifdef WOLFSSL_HAVE_MLDSA
2966
    short           minMlDsaKeySz;      /* minimum allowed ML-DSA key size */
2967
#endif
2968
#ifdef WC_ASN_UNKNOWN_EXT_CB
2969
    wc_UnknownExtCallback     unknownExtCallback;
2970
    wc_UnknownExtCallback32   unknownExtCallback32;
2971
#if defined(HAVE_CRL)
2972
    wc_UnknownExtCallback     crlUnknownExtCallback;
2973
    wc_UnknownExtCallback32   crlUnknownExtCallback32;
2974
    wc_UnknownExtCallbackEx   crlUnknownExtCallbackEx;
2975
    wc_UnknownExtCallback32Ex crlUnknownExtCallback32Ex;
2976
    void*                     crlUnknownExtCallbackExCtx;
2977
    void*                     crlUnknownExtCallback32ExCtx;
2978
#endif
2979
#endif
2980
#ifdef HAVE_CRL_UPDATE_CB
2981
    CbUpdateCRL    cbUpdateCRL; /* notify thru cb that crl has updated */
2982
#endif
2983
};
2984
2985
WOLFSSL_LOCAL int CM_SaveCertCache(WOLFSSL_CERT_MANAGER* cm,
2986
                                   const char* fname);
2987
WOLFSSL_LOCAL int CM_RestoreCertCache(WOLFSSL_CERT_MANAGER* cm,
2988
                                      const char* fname);
2989
WOLFSSL_LOCAL int CM_MemSaveCertCache(WOLFSSL_CERT_MANAGER* cm, void* mem,
2990
                                      int sz, int* used);
2991
WOLFSSL_LOCAL int CM_MemRestoreCertCache(WOLFSSL_CERT_MANAGER* cm,
2992
                                         const void* mem, int sz);
2993
WOLFSSL_LOCAL int CM_GetCertCacheMemSize(WOLFSSL_CERT_MANAGER* cm);
2994
WOLFSSL_LOCAL int CM_VerifyBuffer_ex(WOLFSSL_CERT_MANAGER* cm, const byte* buff,
2995
                                     long sz, int format, int prev_err,
2996
                                     int* crlErr);
2997
2998
2999
#ifndef NO_CERTS
3000
#if !defined(NO_WOLFSSL_CLIENT) || !defined(WOLFSSL_NO_CLIENT_AUTH)
3001
typedef struct ProcPeerCertArgs {
3002
    buffer*      certs;
3003
#ifdef WOLFSSL_TLS13
3004
    buffer*      exts; /* extensions */
3005
#endif
3006
#ifndef NO_ASN
3007
    DecodedCert* dCert;
3008
#endif
3009
    word32 idx;
3010
    word32 begin;
3011
    int    totalCerts; /* number of certs in certs buffer */
3012
    int    count;
3013
    int    certIdx;
3014
    int    lastErr;
3015
    int    leafVerifyErr;
3016
#ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
3017
    int    csr2ReqIdx; /* 1 + certIdx of the last status_request_v2 request */
3018
#endif
3019
#ifdef WOLFSSL_TLS13
3020
    byte   ctxSz;
3021
#endif
3022
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
3023
    char   untrustedDepth;
3024
#endif
3025
    word16 fatal:1;
3026
    word16 verifyErr:1;
3027
    word16 dCertInit:1;
3028
#ifdef WOLFSSL_CHAIN_VERIFY_CB
3029
    word16 chainDecoded:1; /* peer certs already decode-checked */
3030
#endif
3031
#ifdef WOLFSSL_TRUST_PEER_CERT
3032
    word16 haveTrustPeer:1; /* was cert verified by loaded trusted peer cert */
3033
#endif
3034
#ifdef HAVE_CERTIFICATE_STATUS_REQUEST
3035
    word16 csrAcked:1; /* survives the staple checks clearing status_request */
3036
#endif
3037
#ifdef KEEP_PEER_CERT
3038
    word16 peerCertSet:1; /* leaf already kept in ssl->peerCert, or only its
3039
                           * encoding in ssl->peerCertDer */
3040
    word16 leafDecodeErr:1; /* parsing the leaf returned an error, so a later
3041
                             * decode of it may not give the same result */
3042
#endif
3043
} ProcPeerCertArgs;
3044
WOLFSSL_LOCAL int DoVerifyCallback(WOLFSSL_CERT_MANAGER* cm, WOLFSSL* ssl,
3045
        int cert_err, ProcPeerCertArgs* args);
3046
WOLFSSL_LOCAL void DoCrlCallback(WOLFSSL_CERT_MANAGER* cm, WOLFSSL* ssl,
3047
        ProcPeerCertArgs* args, int* outRet);
3048
3049
WOLFSSL_LOCAL int SetupStoreCtxCallback(WOLFSSL_X509_STORE_CTX** store_pt,
3050
        WOLFSSL* ssl, WOLFSSL_CERT_MANAGER* cm, ProcPeerCertArgs* args,
3051
        int cert_err, void* heap, int* x509Free);
3052
WOLFSSL_LOCAL void CleanupStoreCtxCallback(WOLFSSL_X509_STORE_CTX* store,
3053
        WOLFSSL* ssl, void* heap, int x509Free);
3054
#endif /* !defined(NO_WOLFSSL_CLIENT) || !defined(WOLFSSL_NO_CLIENT_AUTH) */
3055
WOLFSSL_LOCAL int X509StoreLoadCertBuffer(WOLFSSL_X509_STORE *str,
3056
                                        byte *buf, word32 bufLen, int type);
3057
WOLFSSL_LOCAL int X509StorePushCertsToCM(WOLFSSL_X509_STORE* store);
3058
#endif /* !defined NO_CERTS */
3059
3060
/* wolfSSL Sock Addr */
3061
struct WOLFSSL_SOCKADDR {
3062
    unsigned int sz; /* sockaddr size */
3063
    unsigned int bufSz; /* size of allocated buffer */
3064
    void*        sa; /* pointer to the sockaddr_in or sockaddr_in6 */
3065
};
3066
3067
#ifdef WOLFSSL_DTLS
3068
typedef struct WOLFSSL_DTLS_CTX {
3069
#ifdef WOLFSSL_RW_THREADED
3070
    /* Protect peer access after the handshake */
3071
    wolfSSL_RwLock peerLock;
3072
#endif
3073
    WOLFSSL_SOCKADDR peer;
3074
#ifdef WOLFSSL_DTLS_CID
3075
    WOLFSSL_SOCKADDR pendingPeer; /* When using CID's, we don't want to update
3076
                                   * the peer's address until we successfully
3077
                                   * de-protect the record. */
3078
#endif
3079
    int rfd;
3080
    int wfd;
3081
    WolfSSLRecvFrom recvfrom;
3082
    WolfSSLSento sendto;
3083
    byte userSet:1;
3084
    byte connected:1; /* When set indicates rfd and wfd sockets are
3085
                       * connected (connect() and bind() both called).
3086
                       * This means that sendto and recvfrom do not need to
3087
                       * specify and store the peer address. */
3088
    byte rfdIsDGram:1; /* whether rfd is a SOCK_DGRAM socket; probed with
3089
                        * getsockopt(SO_TYPE) where rfd is assigned to keep
3090
                        * the syscall out of the I/O callbacks. */
3091
    byte wfdIsDGram:1; /* as rfdIsDGram, for wfd; rfd and wfd may be
3092
                        * different sockets of different types. */
3093
#ifdef WOLFSSL_DTLS_CID
3094
    byte processingPendingRecord:1;
3095
#endif
3096
} WOLFSSL_DTLS_CTX;
3097
#endif
3098
3099
3100
typedef struct WOLFSSL_DTLS_PEERSEQ {
3101
    word32 window[WOLFSSL_DTLS_WINDOW_WORDS];
3102
                        /* Sliding window for current epoch    */
3103
    word16 nextEpoch;   /* Expected epoch in next record       */
3104
    word16 nextSeq_hi;  /* Expected sequence in next record    */
3105
    word32 nextSeq_lo;
3106
3107
    word32 prevWindow[WOLFSSL_DTLS_WINDOW_WORDS];
3108
                        /* Sliding window for old epoch        */
3109
    word32 prevSeq_lo;
3110
    word16 prevSeq_hi;  /* Next sequence in allowed old epoch  */
3111
3112
#ifdef WOLFSSL_MULTICAST
3113
    word16 peerId;
3114
    word32 highwaterMark;
3115
#endif
3116
} WOLFSSL_DTLS_PEERSEQ;
3117
3118
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
3119
struct WOLFSSL_BIO {
3120
    WOLFSSL_BUF_MEM* mem_buf;
3121
    WOLFSSL_BIO_METHOD* method;
3122
    WOLFSSL_BIO* prev;          /* previous in chain */
3123
    WOLFSSL_BIO* next;          /* next in chain */
3124
    WOLFSSL_BIO* pair;          /* BIO paired with */
3125
    void*        heap;          /* user heap hint */
3126
    union {
3127
        byte*    mem_buf_data;
3128
#ifndef WOLFCRYPT_ONLY
3129
        WOLFSSL* ssl;
3130
        WOLFSSL_EVP_MD_CTX* md_ctx;
3131
#endif
3132
#ifndef NO_FILESYSTEM
3133
        XFILE    fh;
3134
#endif
3135
    } ptr;
3136
    void*        usrCtx;        /* user set pointer */
3137
    char*        ip;            /* IP address for wolfIO_TcpConnect */
3138
    word16       port;          /* Port for wolfIO_TcpConnect */
3139
    char*        infoArg;       /* BIO callback argument */
3140
    wolf_bio_info_cb infoCb;    /* BIO callback */
3141
    int          wrSz;          /* write buffer size (mem) */
3142
    int          wrSzReset;     /* First buffer size (mem) - read ONLY data */
3143
    int          wrIdx;         /* current index for write buffer */
3144
    int          rdIdx;         /* current read index */
3145
    int          readRq;        /* read request */
3146
    union {
3147
        SOCKET_T fd;
3148
        size_t   length;
3149
    } num;
3150
    int          eof;           /* eof flag */
3151
    int          flags;
3152
    int          type;          /* method type */
3153
    byte         init:1;        /* bio has been initialized */
3154
    byte         shutdown:1;    /* close flag */
3155
    byte         connected:1;   /* connected state, for datagram BIOs -- as for
3156
                                 * struct WOLFSSL_DTLS_CTX, when set, sendto and
3157
                                 * recvfrom leave the peer_addr unchanged. */
3158
#ifdef WOLFSSL_HAVE_BIO_ADDR
3159
    union WOLFSSL_BIO_ADDR peer_addr; /* for datagram BIOs, the socket address stored
3160
                                       * with BIO_CTRL_DGRAM_CONNECT,
3161
                                       * BIO_CTRL_DGRAM_SET_CONNECTED, or
3162
                                       * BIO_CTRL_DGRAM_SET_PEER, or stored when a
3163
                                       * packet was received on an unconnected BIO. */
3164
#endif
3165
3166
#if defined(WORD64_AVAILABLE) && !defined(WOLFSSL_BIO_NO_FLOW_STATS)
3167
    #define WOLFSSL_BIO_HAVE_FLOW_STATS
3168
    word64       bytes_read;
3169
    word64       bytes_written;
3170
#endif
3171
3172
#ifdef HAVE_EX_DATA
3173
    WOLFSSL_CRYPTO_EX_DATA ex_data;
3174
#endif
3175
#if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA)
3176
    wolfSSL_Ref  ref;
3177
#endif
3178
};
3179
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
3180
3181
#if defined(WOLFSSL_HAVE_BIO_ADDR) && defined(OPENSSL_EXTRA)
3182
WOLFSSL_LOCAL socklen_t wolfSSL_BIO_ADDR_size(const WOLFSSL_BIO_ADDR *addr);
3183
#endif
3184
3185
#if defined(WOLFSSL_TLS13) && defined(HAVE_NULL_CIPHER) && defined(WOLFSSL_SHA384)
3186
    /* Integrity-only cipher suites use IV size equal to hash output size */
3187
    #define MAX_WRITE_IV_SZ 48
3188
#elif defined(WOLFSSL_TLS13) && defined(HAVE_NULL_CIPHER) && !defined(NO_SHA256)
3189
    /* Integrity-only cipher suites use IV size equal to hash output size */
3190
    #define MAX_WRITE_IV_SZ 32
3191
#else
3192
    #define MAX_WRITE_IV_SZ 16 /* max size of client/server write_IV */
3193
#endif
3194
3195
/* worst case serialized size of what ExportKeyState() writes */
3196
#define DTLS_EXPORT_KEY_SZ                                                   \
3197
    ((4 * OPAQUE32_LEN) +                 /* TLS sequence numbers */         \
3198
     (2 * OPAQUE16_LEN) + OPAQUE32_LEN +   /* peer next epoch and seq */     \
3199
     (2 * OPAQUE16_LEN) + OPAQUE32_LEN +   /* current epoch and seq */       \
3200
     OPAQUE16_LEN + OPAQUE32_LEN +         /* peer previous seq */           \
3201
     (2 * OPAQUE16_LEN) +                  /* peer, expected hs numbers */   \
3202
     (2 * (OPAQUE16_LEN + OPAQUE32_LEN)) + /* DTLS seq and previous seq */   \
3203
     (2 * OPAQUE16_LEN) +                  /* DTLS epoch and hs number */    \
3204
     (2 * OPAQUE32_LEN) + (2 * OPAQUE8_LEN) + /* encryptSz, padSz, flags */  \
3205
     (2 * (OPAQUE16_LEN + DTLS_SEQ_SZ)) +  /* window and prevWindow */       \
3206
     OPAQUE8_LEN +                        /* truncated hmac flag */          \
3207
     (OPAQUE8_LEN + (2 * WC_MAX_DIGEST_SIZE)) +   /* MAC secrets */          \
3208
     (OPAQUE8_LEN + (2 * MAX_SYM_KEY_SIZE)) +     /* write keys */           \
3209
     (OPAQUE8_LEN + (2 * MAX_WRITE_IV_SZ) + AEAD_MAX_EXP_SZ) + /* IVs */     \
3210
     (OPAQUE8_LEN + (2 * AEAD_MAX_IMP_SZ)))       /* implicit AEAD IVs */
3211
3212
#if defined(WOLFSSL_SESSION_EXPORT) && defined(WOLFSSL_DTLS13)
3213
/* epoch number, send/peer sequence numbers, failed decryption count and
3214
 * replay window; key material is derived again on import */
3215
#define DTLS_EXPORT_DTLS13_EPOCH_SZ                                          \
3216
    ((4 * OPAQUE64_LEN) + OPAQUE16_LEN +                                     \
3217
     (WOLFSSL_DTLS_WINDOW_WORDS * OPAQUE32_LEN))
3218
/* key material appended to the previous peer epoch: write key, record number
3219
 * key and write IV of the direction the peer sends in, each with its length */
3220
#define DTLS_EXPORT_DTLS13_EPOCH_KEY_SZ                                      \
3221
    ((2 * OPAQUE8_LEN) + (2 * MAX_SYM_KEY_SIZE) + MAX_WRITE_IV_SZ)
3222
/* epoch numbers and three length prefixed epoch fields */
3223
#define DTLS_EXPORT_DTLS13_SZ                                                \
3224
    ((3 * OPAQUE64_LEN) + (3 * WOLFSSL_EXPORT_LEN) +                         \
3225
     (3 * DTLS_EXPORT_DTLS13_EPOCH_SZ) + DTLS_EXPORT_DTLS13_EPOCH_KEY_SZ)
3226
#endif /* WOLFSSL_SESSION_EXPORT && WOLFSSL_DTLS13 */
3227
3228
#if defined(WOLFSSL_SESSION_EXPORT) && defined(WOLFSSL_TLS13)
3229
/* secret length, traffic and resumption secrets, KeyUpdate response flag,
3230
 * nonce length and a DEF_TICKET_NONCE_SZ wide nonce field, what
3231
 * ExportTls13State() writes */
3232
#define WOLFSSL_EXPORT_TLS13_SZ                                              \
3233
    (OPAQUE8_LEN + (3 * SECRET_LEN) + (2 * OPAQUE8_LEN) + DEF_TICKET_NONCE_SZ)
3234
#endif /* WOLFSSL_SESSION_EXPORT && WOLFSSL_TLS13 */
3235
3236
#if defined(WOLFSSL_SESSION_EXPORT) && defined(WOLFSSL_DTLS_CID)
3237
/* negotiated flag plus the length prefixed rx and tx connection ids */
3238
#define DTLS_EXPORT_CID_SZ                                                   \
3239
    (OPAQUE8_LEN + (OPAQUE8_LEN + DTLS_CID_MAX_SIZE) +                       \
3240
     (OPAQUE8_LEN + DTLS_CID_MAX_TX_SIZE))
3241
#define DTLS_EXPORT_CID_TOTAL (WOLFSSL_EXPORT_LEN + DTLS_EXPORT_CID_SZ)
3242
#elif defined(WOLFSSL_SESSION_EXPORT)
3243
/* the length prefix is written whether or not CID is compiled in */
3244
#define DTLS_EXPORT_CID_TOTAL WOLFSSL_EXPORT_LEN
3245
#else
3246
#define DTLS_EXPORT_CID_TOTAL 0
3247
#endif /* WOLFSSL_SESSION_EXPORT && WOLFSSL_DTLS_CID */
3248
3249
/* protocol and total length bytes, then the length prefixed options, key
3250
 * state, cipher specs and peer address */
3251
#define DTLS_EXPORT_BASE_SZ                                                  \
3252
    ((2 * WOLFSSL_EXPORT_LEN) +                                              \
3253
     (WOLFSSL_EXPORT_LEN + DTLS_EXPORT_OPT_SZ) +                             \
3254
     (WOLFSSL_EXPORT_LEN + DTLS_EXPORT_KEY_SZ) +                             \
3255
     (WOLFSSL_EXPORT_LEN + WOLFSSL_EXPORT_SPC_SZ) +                          \
3256
     (WOLFSSL_EXPORT_LEN + MAX_EXPORT_IP + (3 * WOLFSSL_EXPORT_LEN)))
3257
3258
/* max size of buffer for exporting */
3259
#if defined(WOLFSSL_SESSION_EXPORT) && defined(WOLFSSL_DTLS13)
3260
#define MAX_EXPORT_BUFFER (DTLS_EXPORT_BASE_SZ + WOLFSSL_EXPORT_LEN +        \
3261
                           WOLFSSL_EXPORT_TLS13_SZ + WOLFSSL_EXPORT_LEN +    \
3262
                           DTLS_EXPORT_DTLS13_SZ + DTLS_EXPORT_CID_TOTAL)
3263
#else
3264
#define MAX_EXPORT_BUFFER (DTLS_EXPORT_BASE_SZ + DTLS_EXPORT_CID_TOTAL)
3265
#endif
3266
3267
/* keys and secrets
3268
 * keep as a constant size (no additional ifdefs) for session export */
3269
typedef struct Keys {
3270
#if !defined(WOLFSSL_AEAD_ONLY) || defined(WOLFSSL_TLS13)
3271
    byte client_write_MAC_secret[WC_MAX_DIGEST_SIZE];   /* max sizes */
3272
    byte server_write_MAC_secret[WC_MAX_DIGEST_SIZE];
3273
#endif
3274
    byte client_write_key[MAX_SYM_KEY_SIZE];         /* max sizes */
3275
    byte server_write_key[MAX_SYM_KEY_SIZE];
3276
    byte client_write_IV[MAX_WRITE_IV_SZ];               /* max sizes */
3277
    byte server_write_IV[MAX_WRITE_IV_SZ];
3278
#if defined(HAVE_AEAD) || defined(WOLFSSL_SESSION_EXPORT)
3279
    byte aead_exp_IV[AEAD_MAX_EXP_SZ];
3280
    byte aead_enc_imp_IV[AEAD_MAX_IMP_SZ];
3281
    byte aead_dec_imp_IV[AEAD_MAX_IMP_SZ];
3282
#endif
3283
3284
#ifdef WOLFSSL_DTLS13
3285
    byte client_sn_key[MAX_SYM_KEY_SIZE];
3286
    byte server_sn_key[MAX_SYM_KEY_SIZE];
3287
#endif /* WOLFSSL_DTLS13 */
3288
3289
    word32 peer_sequence_number_hi;
3290
    word32 peer_sequence_number_lo;
3291
    word32 sequence_number_hi;
3292
    word32 sequence_number_lo;
3293
3294
#ifdef WOLFSSL_DTLS
3295
    word16 curEpoch;    /* Received epoch in current record    */
3296
    word16 curSeq_hi;   /* Received sequence in current record */
3297
    word32 curSeq_lo;
3298
3299
#ifdef WOLFSSL_DTLS13
3300
    w64wrapper curEpoch64;    /* Received epoch in current record    */
3301
    w64wrapper curSeq;
3302
#endif /* WOLFSSL_DTLS13 */
3303
3304
#ifdef WOLFSSL_MULTICAST
3305
    byte   curPeerId;   /* Received peer group ID in current record */
3306
#endif
3307
    WOLFSSL_DTLS_PEERSEQ peerSeq[WOLFSSL_DTLS_PEERSEQ_SZ];
3308
3309
    word16 dtls_peer_handshake_number;
3310
    word16 dtls_expected_peer_handshake_number;
3311
3312
    word16 dtls_epoch;                          /* Current epoch    */
3313
    word16 dtls_sequence_number_hi;             /* Current epoch */
3314
    word32 dtls_sequence_number_lo;
3315
    word16 dtls_prev_sequence_number_hi;        /* Previous epoch */
3316
    word32 dtls_prev_sequence_number_lo;
3317
    word16 dtls_handshake_number;               /* Current tx handshake seq */
3318
#endif
3319
3320
    word32 encryptSz;             /* last size of encrypted data   */
3321
    word32 padSz;                 /* how much to advance after decrypt part */
3322
    byte   encryptionOn;          /* true after change cipher spec */
3323
    byte   decryptedCur;          /* only decrypt current record once */
3324
#ifdef WOLFSSL_TLS13
3325
    byte   updateResponseReq;     /* KeyUpdate response from peer required. */
3326
    byte   keyUpdateRespond;      /* KeyUpdate is to be responded to. */
3327
    w64wrapper keyUpdateCount;    /* Sending key updates performed (RFC 9846). */
3328
#endif
3329
#ifdef WOLFSSL_RENESAS_TSIP_TLS
3330
3331
    tsip_hmac_sha_key_index_t tsip_client_write_MAC_secret;
3332
    tsip_hmac_sha_key_index_t tsip_server_write_MAC_secret;
3333
3334
#endif
3335
#ifdef WOLFSSL_RENESAS_FSPSM_TLS
3336
    FSPSM_HMAC_WKEY fspsm_client_write_MAC_secret;
3337
    FSPSM_HMAC_WKEY fspsm_server_write_MAC_secret;
3338
#endif
3339
} Keys;
3340
3341
/* RFC 9846 Section 4.7.3: a TLS 1.3 sender MUST NOT allow its number of key
3342
 * updates to exceed 2^48-1. Receivers MUST NOT enforce this. Expressed as the
3343
 * high and low 32-bit halves of a w64wrapper. */
3344
0
#define TLS13_KEY_UPDATE_MAX_HI32 0x0000FFFFU
3345
0
#define TLS13_KEY_UPDATE_MAX_LO32 0xFFFFFFFFU
3346
3347
/* Forward declare opaque pointer to make available for func def */
3348
typedef struct Options Options;
3349
3350
3351
/** TLS Extensions - RFC 6066 */
3352
#ifdef HAVE_TLS_EXTENSIONS
3353
3354
762
#define TLSXT_SERVER_NAME                0x0000 /* a.k.a. SNI  */
3355
195
#define TLSXT_MAX_FRAGMENT_LENGTH        0x0001
3356
80
#define TLSXT_TRUSTED_CA_KEYS            0x0003
3357
234
#define TLSXT_TRUNCATED_HMAC             0x0004
3358
506
#define TLSXT_STATUS_REQUEST             0x0005 /* a.k.a. OCSP stapling   */
3359
3.58k
#define TLSXT_SUPPORTED_GROUPS           0x000a /* a.k.a. Supported Curves */
3360
988
#define TLSXT_EC_POINT_FORMATS           0x000b
3361
1.52k
#define TLSXT_SIGNATURE_ALGORITHMS       0x000d /* HELLO_EXT_SIG_ALGO */
3362
111
#define TLSXT_USE_SRTP                   0x000e /* 14 */
3363
200
#define TLSXT_APPLICATION_LAYER_PROTOCOL 0x0010 /* a.k.a. ALPN */
3364
98
#define TLSXT_STATUS_REQUEST_V2          0x0011 /* a.k.a. OCSP stapling v2 */
3365
72
#define TLSXT_CLIENT_CERTIFICATE         0x0013 /* RFC8446 */
3366
47
#define TLSXT_SERVER_CERTIFICATE         0x0014 /* RFC8446 */
3367
641
#define TLSXT_ENCRYPT_THEN_MAC           0x0016 /* RFC 7366 */
3368
#define TLSXT_EXTENDED_MASTER_SECRET     0x0017 /* HELLO_EXT_EXTMS */
3369
77
#define TLSXT_CERT_WITH_EXTERN_PSK       0x0021 /* RFC 9973 */
3370
623
#define TLSXT_SESSION_TICKET             0x0023
3371
491
#define TLSXT_PRE_SHARED_KEY             0x0029
3372
269
#define TLSXT_EARLY_DATA                 0x002a
3373
#define TLSXT_SUPPORTED_VERSIONS         0x002b
3374
94
#define TLSXT_COOKIE                     0x002c
3375
640
#define TLSXT_PSK_KEY_EXCHANGE_MODES     0x002d
3376
105
#define TLSXT_CERTIFICATE_AUTHORITIES    0x002f
3377
131
#define TLSXT_POST_HANDSHAKE_AUTH        0x0031
3378
125
#define TLSXT_SIGNATURE_ALGORITHMS_CERT  0x0032
3379
2.05k
#define TLSXT_KEY_SHARE                  0x0033
3380
49
#define TLSXT_CONNECTION_ID              0x0036
3381
#define TLSXT_KEY_QUIC_TP_PARAMS         0x0039 /* RFC 9001, ch. 8.2 */
3382
20
#define TLSXT_ECH                        0xfe0d /* RFC 9849 */
3383
#define TLSXT_ECH_OUTER_EXTENSIONS       0xfd00 /* RFC 9849 */
3384
/* The 0xFF section is experimental/custom/personal use */
3385
#define TLSXT_CKS                        0xff92 /* X9.146 */
3386
581
#define TLSXT_RENEGOTIATION_INFO         0xff01
3387
7
#define TLSXT_KEY_QUIC_TP_PARAMS_DRAFT   0xffa5 /* from */
3388
                                                /* draft-ietf-quic-tls-27 */
3389
3390
typedef enum {
3391
#ifdef HAVE_SNI
3392
    TLSX_SERVER_NAME                = TLSXT_SERVER_NAME,
3393
#endif
3394
    TLSX_MAX_FRAGMENT_LENGTH        = TLSXT_MAX_FRAGMENT_LENGTH,
3395
    TLSX_TRUSTED_CA_KEYS            = TLSXT_TRUSTED_CA_KEYS,
3396
    TLSX_TRUNCATED_HMAC             = TLSXT_TRUNCATED_HMAC,
3397
    TLSX_STATUS_REQUEST             = TLSXT_STATUS_REQUEST,
3398
    TLSX_SUPPORTED_GROUPS           = TLSXT_SUPPORTED_GROUPS,
3399
    TLSX_EC_POINT_FORMATS           = TLSXT_EC_POINT_FORMATS,
3400
#if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
3401
    TLSX_SIGNATURE_ALGORITHMS       = TLSXT_SIGNATURE_ALGORITHMS,
3402
#endif
3403
#ifdef WOLFSSL_SRTP
3404
    TLSX_USE_SRTP                   = TLSXT_USE_SRTP,
3405
#endif
3406
    TLSX_APPLICATION_LAYER_PROTOCOL = TLSXT_APPLICATION_LAYER_PROTOCOL,
3407
    TLSX_STATUS_REQUEST_V2          = TLSXT_STATUS_REQUEST_V2,
3408
#ifdef HAVE_RPK
3409
    TLSX_CLIENT_CERTIFICATE_TYPE    = TLSXT_CLIENT_CERTIFICATE,
3410
    TLSX_SERVER_CERTIFICATE_TYPE    = TLSXT_SERVER_CERTIFICATE,
3411
#endif
3412
#if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
3413
    TLSX_ENCRYPT_THEN_MAC           = TLSXT_ENCRYPT_THEN_MAC,
3414
#endif
3415
    TLSX_EXTENDED_MASTER_SECRET     = TLSXT_EXTENDED_MASTER_SECRET,
3416
    TLSX_SESSION_TICKET             = TLSXT_SESSION_TICKET,
3417
#ifdef WOLFSSL_TLS13
3418
    #ifdef WOLFSSL_EARLY_DATA
3419
    TLSX_EARLY_DATA                 = TLSXT_EARLY_DATA,
3420
    #endif
3421
    TLSX_SUPPORTED_VERSIONS         = TLSXT_SUPPORTED_VERSIONS,
3422
    TLSX_COOKIE                     = TLSXT_COOKIE,
3423
    #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
3424
    TLSX_PSK_KEY_EXCHANGE_MODES     = TLSXT_PSK_KEY_EXCHANGE_MODES,
3425
    #if defined(WOLFSSL_CERT_WITH_EXTERN_PSK)
3426
    TLSX_CERT_WITH_EXTERN_PSK       = TLSXT_CERT_WITH_EXTERN_PSK,
3427
    #endif
3428
    #endif
3429
    #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES)
3430
    TLSX_CERTIFICATE_AUTHORITIES    = TLSXT_CERTIFICATE_AUTHORITIES,
3431
    #endif
3432
    #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
3433
    TLSX_POST_HANDSHAKE_AUTH        = TLSXT_POST_HANDSHAKE_AUTH,
3434
    #endif
3435
    #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
3436
    TLSX_SIGNATURE_ALGORITHMS_CERT  = TLSXT_SIGNATURE_ALGORITHMS_CERT,
3437
    #endif
3438
    #ifdef WOLFSSL_QUIC
3439
    TLSX_KEY_QUIC_TP_PARAMS         = TLSXT_KEY_QUIC_TP_PARAMS,
3440
    #endif
3441
    #ifdef HAVE_ECH
3442
    TLSX_ECH                        = TLSXT_ECH,
3443
    #endif
3444
#endif
3445
#if defined(WOLFSSL_DTLS_CID)
3446
    TLSX_CONNECTION_ID              = TLSXT_CONNECTION_ID,
3447
#endif /* defined(WOLFSSL_DTLS_CID) */
3448
#if defined(WOLFSSL_TLS13) || !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS)
3449
    #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
3450
    TLSX_PRE_SHARED_KEY             = TLSXT_PRE_SHARED_KEY,
3451
    #endif
3452
    TLSX_KEY_SHARE                  = TLSXT_KEY_SHARE,
3453
#endif
3454
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_DUAL_ALG_CERTS)
3455
    TLSX_CKS                        = TLSXT_CKS,
3456
#endif
3457
#ifdef WOLFSSL_QUIC
3458
    TLSX_KEY_QUIC_TP_PARAMS_DRAFT   = TLSXT_KEY_QUIC_TP_PARAMS_DRAFT,
3459
#endif
3460
    TLSX_RENEGOTIATION_INFO         = TLSXT_RENEGOTIATION_INFO
3461
} TLSX_Type;
3462
3463
/* TLS Certificate type defined RFC7250
3464
 * https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#tls-extensiontype-values-3
3465
 */
3466
#if defined(HAVE_RPK)
3467
/* WOLFSSL_MAX_RPK_PINS (default 4) is defined in the public header
3468
 * wolfssl/ssl.h, which this header includes, so applications can see and
3469
 * override it. The pin table is stored inline in RpkConfig (see below),
3470
 * costing WOLFSSL_MAX_RPK_PINS * WC_SHA256_DIGEST_SIZE bytes per WOLFSSL_CTX and
3471
 * WOLFSSL. Out-of-band RPK pinning needs SHA-256 (pins are stored as digests);
3472
 * under NO_SHA256 there is no in-library pinning and trust must be expressed
3473
 * through a verify callback instead. */
3474
3475
typedef struct RpkConfig {
3476
    /* user's preference */
3477
    byte preferred_ClientCertTypeCnt;
3478
    byte preferred_ClientCertTypes[MAX_CLIENT_CERT_TYPE_CNT];
3479
    byte preferred_ServerCertTypeCnt;
3480
    byte preferred_ServerCertTypes[MAX_CLIENT_CERT_TYPE_CNT];
3481
    /* reflect to client_certificate_type extension in xxxHello */
3482
#ifndef NO_SHA256
3483
    /* SHA-256 digests of the DER SubjectPublicKeyInfo(s) the peer is expected
3484
     * to present as a Raw Public Key (RFC 7250), pinned out of band via
3485
     * wolfSSL_set_expected_rpk()/wolfSSL_CTX_set_expected_rpk(). A received RPK
3486
     * whose SPKI digest matches one of these is treated as authenticated.
3487
     * Stored inline (not a pointer) so the by-value RpkConfig copy from CTX to
3488
     * SSL needs no deep-copy or free handling. */
3489
    byte expectedRpkCnt;
3490
    byte expectedRpk[WOLFSSL_MAX_RPK_PINS][WC_SHA256_DIGEST_SIZE];
3491
#endif /* !NO_SHA256 */
3492
} RpkConfig;
3493
3494
typedef struct RpkState {
3495
    byte sending_ClientCertTypeCnt;
3496
    byte sending_ClientCertTypes[MAX_CLIENT_CERT_TYPE_CNT];
3497
    /* reflect to server_certificate_type extension in xxxHello */
3498
    byte sending_ServerCertTypeCnt;
3499
    byte sending_ServerCertTypes[MAX_SERVER_CERT_TYPE_CNT];
3500
    /* client_certificate_type extension in received yyyHello  */
3501
    byte received_ClientCertTypeCnt;
3502
    byte received_ClientCertTypes[MAX_CLIENT_CERT_TYPE_CNT];
3503
    /* server_certificate_type extension in received yyyHello  */
3504
    byte received_ServerCertTypeCnt;
3505
    byte received_ServerCertTypes[MAX_SERVER_CERT_TYPE_CNT];
3506
    /* set if Raw-public-key cert is loaded as own certificate */
3507
    int  isRPKLoaded;
3508
} RpkState;
3509
#endif /* HAVE_RPK */
3510
3511
#if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
3512
#define ECH_ACCEPT_CONFIRMATION_SZ 8
3513
#define ECH_PADDING_TO_32(length) (31 - (((length) - 1) % 32))
3514
3515
typedef enum {
3516
    ECH_TYPE_OUTER = 0,
3517
    ECH_TYPE_INNER = 1
3518
} EchType;
3519
3520
typedef enum {
3521
    ECH_WRITE_GREASE,
3522
    ECH_WRITE_REAL,
3523
    ECH_WRITE_RETRY_CONFIGS,
3524
    ECH_WRITE_NONE,
3525
    ECH_PARSED_INTERNAL,
3526
} EchState;
3527
3528
typedef struct EchCipherSuite {
3529
    word16 kdfId;
3530
    word16 aeadId;
3531
} EchCipherSuite;
3532
3533
typedef struct WOLFSSL_EchConfig {
3534
    byte* raw;
3535
    char* publicName;
3536
    void* receiverPrivkey;
3537
    struct WOLFSSL_EchConfig* next;
3538
    EchCipherSuite* cipherSuites;
3539
    word32 rawLen;
3540
    word16 kemId;
3541
    byte configId;
3542
    byte numCipherSuites;
3543
    byte receiverPubkey[HPKE_Npk_MAX];
3544
    byte maxNameLen;
3545
} WOLFSSL_EchConfig;
3546
3547
typedef struct WOLFSSL_ECH {
3548
    Hpke* hpke;
3549
    HpkeBaseContext* hpkeContext;
3550
    const byte* aad;
3551
    void* ephemeralKey;
3552
    WOLFSSL_EchConfig* echConfig;
3553
    byte* innerClientHello;
3554
    byte* outerClientPayload;
3555
    /* the 'public' extensions (i.e., the public SNI would be stored here) */
3556
    TLSX* extensions;
3557
    byte* confBuf;
3558
    EchCipherSuite cipherSuite;
3559
    word32 aadLen;
3560
    word32 innerClientHelloLen;
3561
    word16 paddingLen;
3562
    word16 kemId;
3563
    word16 encLen;
3564
    EchState state;
3565
    byte type;
3566
    byte configId;
3567
    byte enc[HPKE_Npk_MAX];
3568
    byte innerCount;
3569
    byte writeEncoded;
3570
} WOLFSSL_ECH;
3571
3572
WOLFSSL_LOCAL int EchConfigGetSupportedCipherSuite(WOLFSSL_EchConfig* config);
3573
3574
WOLFSSL_LOCAL int TLSX_FinalizeEch(WOLFSSL* ssl, WOLFSSL_ECH* ech, byte* aad,
3575
    word32 aadLen);
3576
3577
WOLFSSL_LOCAL int TLSX_EchReplaceExtensions(WOLFSSL* ssl, byte accepted);
3578
3579
#ifdef WOLFSSL_API_PREFIX_MAP
3580
    #define TLSX_EchSwapExtensions wolfSSL_TLSX_EchSwapExtensions
3581
#endif
3582
WOLFSSL_TEST_VIS int TLSX_EchSwapExtensions(TLSX** sslExts, TLSX** echExts,
3583
    word16* appended);
3584
3585
#ifdef WOLFSSL_API_PREFIX_MAP
3586
    #define TLSX_ServerECH_Use wolfSSL_TLSX_ServerECH_Use
3587
#endif
3588
WOLFSSL_TEST_VIS int TLSX_ServerECH_Use(TLSX** extensions, void* heap,
3589
    WOLFSSL_EchConfig* configs);
3590
3591
WOLFSSL_TEST_VIS int wolfSSL_local_SetEchConfigsEx(
3592
    WOLFSSL_EchConfig** outputConfigs, void* heap,
3593
    const byte* echConfigs, word32 echConfigsLen);
3594
3595
WOLFSSL_TEST_VIS int wolfSSL_local_GetEchConfig(WOLFSSL_EchConfig* config,
3596
                                               byte* output, word32* outputLen);
3597
3598
WOLFSSL_TEST_VIS int wolfSSL_local_GetEchConfigsEx(WOLFSSL_EchConfig* configs,
3599
    byte* output, word32* outputLen);
3600
3601
WOLFSSL_TEST_VIS void wolfSSL_local_FreeEchConfigs(WOLFSSL_EchConfig* configs,
3602
                                                   void* heap);
3603
3604
WOLFSSL_TEST_VIS int wolfSSL_local_SetRetryConfigs(WOLFSSL* ssl,
3605
                                  const byte* echConfigs, word32 echConfigsLen);
3606
3607
WOLFSSL_LOCAL int EchRejected(const WOLFSSL* ssl);
3608
#endif
3609
3610
struct TLSX {
3611
    TLSX_Type    type; /* Extension Type  */
3612
    void*        data; /* Extension Data  */
3613
    word32       val;  /* Extension Value */
3614
    byte         resp; /* IsResponse Flag */
3615
    struct TLSX* next; /* List Behavior   */
3616
};
3617
3618
#if defined(HAVE_TLS_EXTENSIONS) && defined(OPENSSL_EXTRA)
3619
/* OpenSSL-compatible custom (application-defined) TLS extension.
3620
 * Registered on a WOLFSSL_CTX via wolfSSL_CTX_add_client_custom_ext(). These
3621
 * extensions are not part of the TLSX framework but are processed in parallel
3622
 * for unknown extension types. Currently the client side for TLS 1.2 and below
3623
 * is supported, mirroring SSL_CTX_add_client_custom_ext(). */
3624
typedef struct WOLFSSL_CustomExt {
3625
    word16                      ext_type;  /* extension type on the wire     */
3626
    wolfSSL_custom_ext_add_cb   add_cb;    /* build outgoing extension data  */
3627
    wolfSSL_custom_ext_free_cb  free_cb;   /* free data produced by add_cb   */
3628
    wolfSSL_custom_ext_parse_cb parse_cb;  /* parse incoming extension data  */
3629
    void*                       add_arg;   /* opaque arg for add_cb/free_cb  */
3630
    void*                       parse_arg; /* opaque arg for parse_cb        */
3631
    struct WOLFSSL_CustomExt*   next;      /* list behaviour                 */
3632
} WOLFSSL_CustomExt;
3633
3634
WOLFSSL_LOCAL void TLSX_CustomExt_FreeAll(WOLFSSL_CustomExt* list, void* heap);
3635
#ifdef WOLFSSL_API_PREFIX_MAP
3636
    #define TLSX_CustomExt_BuildRequest wolfSSL_TLSX_CustomExt_BuildRequest
3637
#endif
3638
WOLFSSL_TEST_VIS int TLSX_CustomExt_BuildRequest(WOLFSSL* ssl, word16* pSz);
3639
WOLFSSL_LOCAL int  TLSX_CustomExt_Parse(WOLFSSL* ssl, byte msgType, word16 type,
3640
        const byte* input, word16 size, int* found);
3641
#endif /* HAVE_TLS_EXTENSIONS && OPENSSL_EXTRA */
3642
3643
#ifdef WOLFSSL_API_PREFIX_MAP
3644
    #define TLSX_Find wolfSSL_TLSX_Find
3645
#endif
3646
WOLFSSL_TEST_VIS TLSX* TLSX_Find(TLSX* list, TLSX_Type type);
3647
WOLFSSL_LOCAL void  TLSX_Remove(TLSX** list, TLSX_Type type, void* heap);
3648
WOLFSSL_LOCAL void  TLSX_FreeAll(TLSX* list, void* heap);
3649
WOLFSSL_LOCAL int   TLSX_SupportExtensions(WOLFSSL* ssl);
3650
WOLFSSL_LOCAL int   TLSX_PopulateExtensions(WOLFSSL* ssl, byte isRequest);
3651
3652
#if defined(WOLFSSL_TLS13) || !defined(NO_WOLFSSL_CLIENT)
3653
#ifdef WOLFSSL_API_PREFIX_MAP
3654
    #define TLSX_GetRequestSize wolfSSL_TLSX_GetRequestSize
3655
    #define TLSX_WriteRequest   wolfSSL_TLSX_WriteRequest
3656
#endif
3657
WOLFSSL_TEST_VIS int   TLSX_GetRequestSize(WOLFSSL* ssl, byte msgType,
3658
                                         word32* pLength);
3659
WOLFSSL_TEST_VIS int   TLSX_WriteRequest(WOLFSSL* ssl, byte* output,
3660
                                       byte msgType, word32* pOffset);
3661
#endif
3662
3663
#if defined(WOLFSSL_TLS13) || !defined(NO_WOLFSSL_SERVER)
3664
/* TLS 1.3 Certificate messages have extensions. */
3665
WOLFSSL_LOCAL int   TLSX_GetResponseSize(WOLFSSL* ssl, byte msgType,
3666
                                          word16* pLength);
3667
WOLFSSL_LOCAL int   TLSX_WriteResponse(WOLFSSL *ssl, byte* output, byte msgType,
3668
                                        word16* pOffset);
3669
#endif
3670
3671
WOLFSSL_LOCAL int   TLSX_ParseVersion(WOLFSSL* ssl, const byte* input,
3672
                                      word16 length, byte msgType, int* found);
3673
WOLFSSL_LOCAL int TLSX_SupportedVersions_Parse(const WOLFSSL* ssl,
3674
        const byte* input, word16 length, byte msgType, ProtocolVersion* pv,
3675
        Options* opts, TLSX** exts);
3676
#ifdef WOLFSSL_API_PREFIX_MAP
3677
    #define TLSX_Parse wolfSSL_TLSX_Parse
3678
#endif
3679
WOLFSSL_TEST_VIS int TLSX_Parse(WOLFSSL* ssl, const byte* input, word16 length,
3680
                               byte msgType, Suites *suites);
3681
WOLFSSL_LOCAL int TLSX_Push(TLSX** list, TLSX_Type type,
3682
                            const void* data, void* heap);
3683
WOLFSSL_LOCAL int TLSX_Append(TLSX** list, TLSX_Type type,
3684
                            const void* data, void* heap);
3685
3686
#elif defined(HAVE_SNI)                           \
3687
   || defined(HAVE_MAX_FRAGMENT)                  \
3688
   || defined(HAVE_TRUSTED_CA)                    \
3689
   || defined(HAVE_TRUNCATED_HMAC)                \
3690
   || defined(HAVE_CERTIFICATE_STATUS_REQUEST)    \
3691
   || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) \
3692
   || defined(HAVE_SUPPORTED_CURVES)              \
3693
   || defined(HAVE_ALPN)                          \
3694
   || defined(HAVE_SESSION_TICKET)                \
3695
   || defined(HAVE_SECURE_RENEGOTIATION)          \
3696
   || defined(HAVE_SERVER_RENEGOTIATION_INFO)
3697
3698
#ifndef NO_TLS
3699
#error Using TLS extensions requires HAVE_TLS_EXTENSIONS to be defined.
3700
#endif
3701
#endif /* HAVE_TLS_EXTENSIONS */
3702
3703
#if !defined(WOLFSSL_TLS13) || !defined(HAVE_ECH)
3704
0
    #define EchRejected(ssl) 0
3705
#endif
3706
3707
/** Server Name Indication - RFC 6066 (session 3) */
3708
#ifdef HAVE_SNI
3709
3710
typedef struct SNI {
3711
    byte                       type;    /* SNI Type         */
3712
    struct SNI*                next;    /* List Behavior    */
3713
    byte                       status;  /* Matching result  */
3714
#ifndef NO_WOLFSSL_SERVER
3715
    byte                       options; /* Behavior options */
3716
#endif
3717
    /* Ignore "nonstandard extension used : zero-sized array in struct/union"
3718
     * MSVC warning */
3719
    #ifdef _MSC_VER
3720
    #pragma warning(disable: 4200)
3721
    #endif
3722
    char host_name[WC_FLEXIBLE_ARRAY_SIZE]; /* SNI Data   */
3723
} SNI;
3724
3725
WOLFSSL_LOCAL int TLSX_UseSNI(TLSX** extensions, byte type, const void* data,
3726
                                                       word16 size, void* heap);
3727
WOLFSSL_LOCAL byte TLSX_SNI_Status(TLSX* extensions, byte type);
3728
#ifdef WOLFSSL_API_PREFIX_MAP
3729
    #define TLSX_SNI_GetRequest wolfSSL_TLSX_SNI_GetRequest
3730
#endif
3731
WOLFSSL_TEST_VIS word16 TLSX_SNI_GetRequest(TLSX* extensions, byte type,
3732
                                                void** data, byte ignoreStatus);
3733
#ifdef WOLFSSL_API_PREFIX_MAP
3734
    #define TLSX_SNI_GetSize wolfSSL_TLSX_SNI_GetSize
3735
#endif
3736
WOLFSSL_TEST_VIS word16 TLSX_SNI_GetSize(SNI* list);
3737
3738
#ifndef NO_WOLFSSL_SERVER
3739
WOLFSSL_LOCAL void   TLSX_SNI_SetOptions(TLSX* extensions, byte type,
3740
                                                                  byte options);
3741
WOLFSSL_LOCAL int    TLSX_SNI_GetFromBuffer(const byte* clientHello,
3742
                         word32 helloSz, byte type, byte* sni, word32* inOutSz);
3743
#endif
3744
3745
#endif /* HAVE_SNI */
3746
3747
/* Trusted CA Key Indication - RFC 6066 (section 6) */
3748
#ifdef HAVE_TRUSTED_CA
3749
3750
typedef struct TCA {
3751
    byte                       type;    /* TCA Type            */
3752
    word16                     idSz;    /* TCA identifier size */
3753
    struct TCA*                next;    /* List Behavior       */
3754
    /* Ignore "nonstandard extension used : zero-sized array in struct/union"
3755
     * MSVC warning */
3756
    #ifdef _MSC_VER
3757
    #pragma warning(disable: 4200)
3758
    #endif
3759
    byte id[WC_FLEXIBLE_ARRAY_SIZE];    /* TCA identifier      */
3760
} TCA;
3761
3762
WOLFSSL_LOCAL int TLSX_UseTrustedCA(TLSX** extensions, byte type,
3763
                    const byte* id, word16 idSz, void* heap);
3764
3765
#endif /* HAVE_TRUSTED_CA */
3766
3767
/* Application-Layer Protocol Negotiation - RFC 7301 */
3768
#ifdef HAVE_ALPN
3769
typedef struct ALPN {
3770
    struct ALPN* next;            /* List Behavior      */
3771
    word16       protocol_nameSz; /* length of protocol_name in bytes */
3772
    byte         options;         /* Behavior options */
3773
    byte         negotiated;      /* ALPN protocol negotiated or not */
3774
    /* Ignore "nonstandard extension used : zero-sized array in struct/union"
3775
     * MSVC warning */
3776
    #ifdef _MSC_VER
3777
    #pragma warning(disable: 4200)
3778
    #endif
3779
    char protocol_name[WC_FLEXIBLE_ARRAY_SIZE]; /* ALPN protocol name */
3780
} ALPN;
3781
3782
WOLFSSL_LOCAL int TLSX_ALPN_GetRequest(TLSX* extensions,
3783
                                       void** data, word16 *dataSz);
3784
3785
WOLFSSL_LOCAL int TLSX_UseALPN(TLSX** extensions, const void* data,
3786
                               word16 size, byte options, void* heap);
3787
3788
WOLFSSL_LOCAL int TLSX_ALPN_SetOptions(TLSX** extensions, byte option);
3789
3790
#endif /* HAVE_ALPN */
3791
3792
/** Maximum Fragment Length Negotiation - RFC 6066 (session 4) */
3793
#ifdef HAVE_MAX_FRAGMENT
3794
3795
WOLFSSL_LOCAL int TLSX_UseMaxFragment(TLSX** extensions, byte mfl, void* heap);
3796
3797
#endif /* HAVE_MAX_FRAGMENT */
3798
3799
/** Truncated HMAC - RFC 6066 (session 7) */
3800
#ifdef HAVE_TRUNCATED_HMAC
3801
3802
WOLFSSL_LOCAL int TLSX_UseTruncatedHMAC(TLSX** extensions, void* heap);
3803
3804
#endif /* HAVE_TRUNCATED_HMAC */
3805
3806
/** Certificate Status Request - RFC 6066 (session 8) */
3807
#ifdef HAVE_CERTIFICATE_STATUS_REQUEST
3808
3809
typedef struct {
3810
    byte status_type;
3811
    byte options;
3812
    WOLFSSL* ssl;
3813
    union {
3814
        OcspRequest ocsp[MAX_CERT_EXTENSIONS];
3815
    } request;
3816
    word16 requests;
3817
#ifdef WOLFSSL_TLS13
3818
    buffer responses[MAX_CERT_EXTENSIONS];
3819
#endif
3820
} CertificateStatusRequest;
3821
3822
WOLFSSL_LOCAL int   TLSX_UseCertificateStatusRequest(TLSX** extensions,
3823
           byte status_type, byte options, WOLFSSL* ssl, void* heap, int devId);
3824
#ifndef NO_CERTS
3825
WOLFSSL_LOCAL int   TLSX_CSR_InitRequest(TLSX* extensions, DecodedCert* cert,
3826
                                                                    void* heap);
3827
WOLFSSL_LOCAL int   TLSX_CSR_InitRequest_ex(TLSX* extensions, DecodedCert* cert,
3828
                                            void* heap, int idx);
3829
#endif
3830
WOLFSSL_LOCAL void* TLSX_CSR_GetRequest(TLSX* extensions);
3831
WOLFSSL_LOCAL int   TLSX_CSR_ForceRequest(WOLFSSL* ssl);
3832
WOLFSSL_LOCAL word16 TLSX_CSR_GetSize_ex(CertificateStatusRequest* csr,
3833
                                        byte isRequest,
3834
                                        int idx);
3835
WOLFSSL_LOCAL int TLSX_CSR_Write_ex(CertificateStatusRequest* csr, byte* output,
3836
                          byte isRequest, int idx);
3837
WOLFSSL_LOCAL void* TLSX_CSR_GetRequest_ex(TLSX* extensions, int idx);
3838
3839
WOLFSSL_LOCAL int TLSX_CSR_SetResponseWithStatusCB(WOLFSSL *ssl);
3840
WOLFSSL_LOCAL int ProcessChainOCSPRequest(WOLFSSL* ssl);
3841
3842
#endif
3843
#if defined(HAVE_CERTIFICATE_STATUS_REQUEST) || \
3844
    defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
3845
WOLFSSL_LOCAL int CreateOcspRequest(WOLFSSL* ssl, OcspRequest* request,
3846
                             DecodedCert* cert, byte* certData, word32 length);
3847
#endif
3848
#if defined(HAVE_OCSP) && (defined(HAVE_CERTIFICATE_STATUS_REQUEST) || \
3849
                           defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2))
3850
WOLFSSL_LOCAL int CsrDoChainFallbackLookup(WOLFSSL* ssl, OcspRequest* request,
3851
                                           int idx);
3852
#endif
3853
/** Certificate Status Request v2 - RFC 6961 */
3854
#ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
3855
3856
typedef struct CSRIv2 {
3857
    byte status_type;
3858
    byte options;
3859
    word16 requests;
3860
    union {
3861
        OcspRequest ocsp[1 + MAX_CHAIN_DEPTH];
3862
    } request;
3863
    struct CSRIv2* next;
3864
    Signer *pendingSigners;
3865
} CertificateStatusRequestItemV2;
3866
3867
WOLFSSL_LOCAL int   TLSX_UseCertificateStatusRequestV2(TLSX** extensions,
3868
                         byte status_type, byte options, void* heap, int devId);
3869
#ifndef NO_CERTS
3870
WOLFSSL_LOCAL int TLSX_CSR2_IsMulti(TLSX *extensions);
3871
WOLFSSL_LOCAL int TLSX_CSR2_AddPendingSigner(TLSX *extensions, Signer *s);
3872
WOLFSSL_LOCAL Signer* TLSX_CSR2_GetPendingSigners(TLSX *extensions);
3873
WOLFSSL_LOCAL int TLSX_CSR2_ClearPendingCA(WOLFSSL *ssl);
3874
WOLFSSL_LOCAL int TLSX_CSR2_MergePendingCA(WOLFSSL* ssl);
3875
WOLFSSL_LOCAL int   TLSX_CSR2_InitRequests(TLSX* extensions, DecodedCert* cert,
3876
                                                       byte isPeer, void* heap);
3877
#endif
3878
WOLFSSL_LOCAL void* TLSX_CSR2_GetRequest(TLSX* extensions, byte status_type,
3879
                                                                    byte idx);
3880
WOLFSSL_LOCAL int   TLSX_CSR2_ChainFallback(WOLFSSL* ssl, int idx);
3881
WOLFSSL_LOCAL int   TLSX_CSR2_ForceRequest(WOLFSSL* ssl);
3882
3883
#endif
3884
3885
#if defined(WOLFSSL_PUBLIC_ASN) && defined(HAVE_PK_CALLBACKS)
3886
/* Internal callback guarded by WOLFSSL_TEST_VIS because of DecodedCert. */
3887
typedef int (*CallbackProcessPeerCert)(WOLFSSL* ssl, DecodedCert* p_cert);
3888
WOLFSSL_TEST_VIS void wolfSSL_CTX_SetProcessPeerCertCb(WOLFSSL_CTX* ctx,
3889
       CallbackProcessPeerCert cb);
3890
#endif /* DecodedCert && HAVE_PK_CALLBACKS */
3891
3892
/** Certificate Authorities - RFC 8446 section 4.2.4.
3893
 * wolfSSL native list node holding the inner content of one DER-encoded Name
3894
 * (no SEQUENCE header; that is added on the wire). */
3895
#if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES) && \
3896
    defined(WOLFSSL_TLS13)
3897
typedef struct CertificateAuthority {
3898
    struct CertificateAuthority* next;
3899
    word16                       dnSz;
3900
    /* Ignore "nonstandard extension used : zero-sized array in struct/union"
3901
     * MSVC warning */
3902
    #ifdef _MSC_VER
3903
    #pragma warning(push)
3904
    #pragma warning(disable: 4200)
3905
    #endif
3906
    byte                         dn[];
3907
    #ifdef _MSC_VER
3908
    #pragma warning(pop)
3909
    #endif
3910
} CertificateAuthority;
3911
3912
WOLFSSL_LOCAL int  TLSX_CertificateAuthorities_Add(CertificateAuthority** head,
3913
        const byte* dn, word16 dnSz, void* heap);
3914
WOLFSSL_LOCAL int  TLSX_CertificateAuthorities_Add_ex(
3915
        CertificateAuthority** head, CertificateAuthority** tail,
3916
        const byte* dn, word16 dnSz, void* heap);
3917
WOLFSSL_LOCAL void TLSX_CertificateAuthorities_FreeAll(
3918
        CertificateAuthority* head, void* heap);
3919
#endif
3920
3921
/** Supported Elliptic Curves - RFC 4492 (session 4) */
3922
#ifdef HAVE_SUPPORTED_CURVES
3923
3924
typedef struct SupportedCurves {
3925
    word16 count;                        /* Curve names in use */
3926
    word16 cap;                          /* Curve names allocated */
3927
    /* Ignore "nonstandard extension used : zero-sized array in struct/union"
3928
     * MSVC warning */
3929
    #ifdef _MSC_VER
3930
    #pragma warning(disable: 4200)
3931
    #endif
3932
    word16 name[WC_FLEXIBLE_ARRAY_SIZE]; /* Curve names */
3933
} SupportedCurves;
3934
3935
typedef struct PointFormats {
3936
    byte count;                            /* Formats in use */
3937
    byte cap;                              /* Formats allocated */
3938
    /* Ignore "nonstandard extension used : zero-sized array in struct/union"
3939
     * MSVC warning */
3940
    #ifdef _MSC_VER
3941
    #pragma warning(disable: 4200)
3942
    #endif
3943
    byte format[WC_FLEXIBLE_ARRAY_SIZE];   /* Point formats */
3944
} PointFormats;
3945
3946
WOLFSSL_LOCAL int TLSX_SupportedCurve_Copy(TLSX* src, TLSX** dst, void* heap);
3947
WOLFSSL_LOCAL int TLSX_UseSupportedCurve(TLSX** extensions, word16 name,
3948
                                                          void* heap, int side);
3949
3950
#ifdef WOLFSSL_API_PREFIX_MAP
3951
    #define TLSX_UsePointFormat wolfSSL_TLSX_UsePointFormat
3952
#endif
3953
/* WOLFSSL_TEST_VIS so the API tests can seed a client's ec_point_formats
3954
 * extension (the point-format negotiation has no public API). */
3955
WOLFSSL_TEST_VIS int TLSX_UsePointFormat(TLSX** extensions, byte point,
3956
                                                                    void* heap);
3957
WOLFSSL_LOCAL int TLSX_IsGroupSupported(int namedGroup, int side);
3958
3959
#ifndef NO_WOLFSSL_SERVER
3960
WOLFSSL_LOCAL int TLSX_ValidateSupportedCurves(const WOLFSSL* ssl, byte first,
3961
                                               byte second, word32* ecdhCurveOID);
3962
#ifdef WOLFSSL_API_PREFIX_MAP
3963
    #define TLSX_SupportedCurve_CheckPriority \
3964
            wolfSSL_TLSX_SupportedCurve_CheckPriority
3965
    #define TLSX_SupportedFFDHE_Set wolfSSL_TLSX_SupportedFFDHE_Set
3966
#endif
3967
WOLFSSL_TEST_VIS int TLSX_SupportedCurve_CheckPriority(WOLFSSL* ssl);
3968
WOLFSSL_TEST_VIS int TLSX_SupportedFFDHE_Set(WOLFSSL* ssl);
3969
#endif
3970
WOLFSSL_LOCAL int TLSX_SupportedCurve_IsSupported(WOLFSSL* ssl, word16 name);
3971
WOLFSSL_LOCAL int TLSX_SupportedCurve_Preferred(WOLFSSL* ssl,
3972
                                                            int checkSupported);
3973
WOLFSSL_LOCAL int TLSX_SupportedCurve_Parse(const WOLFSSL* ssl,
3974
        const byte* input, word16 length, byte isRequest, TLSX** extensions);
3975
3976
#endif /* HAVE_SUPPORTED_CURVES */
3977
3978
/** Renegotiation Indication - RFC 5746 */
3979
#if defined(HAVE_SECURE_RENEGOTIATION) \
3980
 || defined(HAVE_SERVER_RENEGOTIATION_INFO)
3981
3982
enum key_cache_state {
3983
    SCR_CACHE_NULL   = 0,       /* empty / begin state */
3984
    SCR_CACHE_NEEDED,           /* need to cache keys */
3985
    SCR_CACHE_COPY,             /* we have a cached copy */
3986
    SCR_CACHE_PARTIAL,          /* partial restore to real keys */
3987
    SCR_CACHE_COMPLETE          /* complete restore to real keys */
3988
};
3989
3990
/* Additional Connection State according to rfc5746 section 3.1 */
3991
typedef struct SecureRenegotiation {
3992
   /* Single-bit flags grouped together so they pack into one storage unit. */
3993
   WC_BITFIELD          enabled:1;  /* secure_renegotiation flag in rfc */
3994
   WC_BITFIELD          verifySet:1;
3995
   WC_BITFIELD          startScr:1; /* server requested client to start scr */
3996
   WC_BITFIELD          renegInfoSeen:1; /* renegotiation_info ext seen this
3997
                                          * handshake (RFC 5746 3.7) */
3998
   WC_BITFIELD          peer_cert_hash_set:1; /* if peer cert hash is set */
3999
#ifdef HAVE_SECURE_RENEGOTIATION
4000
   WC_BITFIELD          advertiseOnly:1; /* extension advertised for the RFC
4001
                                          * 5746 initial-handshake check only;
4002
                                          * refuse peer-initiated renegotiation */
4003
   WC_BITFIELD          peer_cert_unknown:1; /* resumed session that does not
4004
                                              * record its peer cert, so no
4005
                                              * peer cert can be checked */
4006
#endif
4007
   enum key_cache_state cache_status;  /* track key cache state */
4008
   byte                 client_verify_data[TLS_FINISHED_SZ];  /* cached */
4009
   byte                 server_verify_data[TLS_FINISHED_SZ];  /* cached */
4010
   byte                 peer_cert_hash[KEYID_SIZE];  /* peer cert hash */
4011
   Keys                 tmp_keys;  /* can't overwrite real keys yet */
4012
} SecureRenegotiation;
4013
4014
WOLFSSL_LOCAL int TLSX_UseSecureRenegotiation(TLSX** extensions, void* heap);
4015
4016
#ifdef HAVE_SECURE_RENEGOTIATION
4017
/* What a session records about the peer certificate for the secure
4018
 * renegotiation check (scrPeerCertState). */
4019
enum ScrPeerCertState {
4020
    SCR_PEER_CERT_UNKNOWN = 0,  /* not recorded */
4021
    SCR_PEER_CERT_NONE    = 1,  /* peer sent no certificate */
4022
    SCR_PEER_CERT_HASH    = 2   /* scrPeerCertHash is the peer cert hash */
4023
};
4024
#endif
4025
4026
#ifdef HAVE_SERVER_RENEGOTIATION_INFO
4027
WOLFSSL_LOCAL int TLSX_AddEmptyRenegotiationInfo(TLSX** extensions, void* heap);
4028
#endif
4029
4030
WOLFSSL_LOCAL int SetupClientSecureRenegotiation(WOLFSSL* ssl);
4031
4032
#endif /* HAVE_SECURE_RENEGOTIATION */
4033
4034
#if defined(HAVE_SNI) || defined(HAVE_ALPN)
4035
/* Hash algorithm used for SNI/ALPN binding in sessions and tickets.
4036
 * Pick the best available at compile time. */
4037
#ifndef TICKET_BINDING_HASH_TYPE
4038
    #if !defined(NO_SHA256)
4039
0
        #define TICKET_BINDING_HASH_TYPE WC_HASH_TYPE_SHA256
4040
0
        #define TICKET_BINDING_HASH_SZ   WC_SHA256_DIGEST_SIZE
4041
    #elif defined(WOLFSSL_SHA384)
4042
        #define TICKET_BINDING_HASH_TYPE WC_HASH_TYPE_SHA384
4043
        #define TICKET_BINDING_HASH_SZ   WC_SHA384_DIGEST_SIZE
4044
    #elif !defined(NO_SHA)
4045
        #define TICKET_BINDING_HASH_TYPE WC_HASH_TYPE_SHA
4046
        #define TICKET_BINDING_HASH_SZ   WC_SHA_DIGEST_SIZE
4047
    #else
4048
        #error "No hash algorithm available for ticket binding"
4049
    #endif
4050
#endif
4051
#endif
4052
4053
#ifdef HAVE_SESSION_TICKET
4054
/* Max peer cert size for ticket: 2KB is reasonable for most RSA/ECC certs */
4055
#ifndef MAX_TICKET_PEER_CERT_SZ
4056
#define MAX_TICKET_PEER_CERT_SZ 2048
4057
#endif
4058
4059
/* Our ticket format. All members need to be a byte or array of byte to
4060
 * avoid alignment issues */
4061
typedef struct InternalTicket {
4062
    ProtocolVersion pv;                    /* version when ticket created */
4063
    byte            suite[SUITE_LEN];      /* cipher suite when created */
4064
    byte            msecret[SECRET_LEN];   /* master secret */
4065
    byte            timestamp[TIMESTAMP_LEN];          /* born on */
4066
    byte            haveEMS:1;             /* have extended master secret */
4067
    byte            peerAuthOk:1;          /* client cert was verified */
4068
    byte            isPSK:1;               /* a PSK authenticated the client */
4069
#ifdef WOLFSSL_TLS13
4070
    byte            ageAdd[AGEADD_LEN];    /* Obfuscation of age */
4071
    byte            namedGroup[NAMEDGROUP_LEN]; /* Named group used */
4072
    byte            ticketNonceLen;
4073
    byte            ticketNonce[MAX_TICKET_NONCE_STATIC_SZ];
4074
#ifdef WOLFSSL_EARLY_DATA
4075
    byte            maxEarlyDataSz[MAXEARLYDATASZ_LEN]; /* Max size of
4076
                                                         * early data */
4077
#endif
4078
#endif
4079
#ifdef WOLFSSL_TICKET_HAVE_ID
4080
    byte            id[ID_LEN];
4081
#endif
4082
#ifdef HAVE_SNI
4083
    byte            sniHash[TICKET_BINDING_HASH_SZ]; /* digest of server name
4084
                                                      * at ticket issue */
4085
#endif
4086
#ifdef HAVE_ALPN
4087
    byte            alpnHash[TICKET_BINDING_HASH_SZ]; /* digest of negotiated
4088
                                                       * ALPN at issue */
4089
#endif
4090
#ifdef OPENSSL_EXTRA
4091
    byte            sessionCtxSz;          /* sessionCtx length        */
4092
    byte            sessionCtx[ID_LEN];    /* app specific context id */
4093
#endif /* OPENSSL_EXTRA */
4094
#ifdef HAVE_SECURE_RENEGOTIATION
4095
    byte            scrPeerCertState;      /* enum ScrPeerCertState */
4096
    byte            scrPeerCertHash[KEYID_SIZE]; /* peer cert hash */
4097
#endif
4098
#if defined(OPENSSL_ALL) && defined(KEEP_PEER_CERT) && \
4099
    !defined(NO_CERT_IN_TICKET)
4100
    byte            peerCertLen[OPAQUE16_LEN]; /* peer cert length */
4101
    byte            peerCert[]; /* peer certificate DER - variable length */
4102
#endif
4103
} InternalTicket;
4104
4105
/* Base size of InternalTicket without the variable-length peerCert field */
4106
#define WOLFSSL_INTERNAL_TICKET_BASE_SZ  (sizeof(InternalTicket))
4107
4108
/* Minimum internal ticket length (no peer cert) */
4109
#ifndef WOLFSSL_TICKET_ENC_CBC_HMAC
4110
    #define WOLFSSL_INTERNAL_TICKET_LEN     WOLFSSL_INTERNAL_TICKET_BASE_SZ
4111
#else
4112
    #define WOLFSSL_INTERNAL_TICKET_LEN     \
4113
        (((WOLFSSL_INTERNAL_TICKET_BASE_SZ + 15) / 16) * 16)
4114
#endif
4115
4116
/* Maximum internal ticket length (with max peer cert) */
4117
#if defined(OPENSSL_ALL) && defined(KEEP_PEER_CERT) && \
4118
    !defined(NO_CERT_IN_TICKET)
4119
    #define WOLFSSL_INTERNAL_TICKET_MAX_SZ  \
4120
        (WOLFSSL_INTERNAL_TICKET_BASE_SZ + MAX_TICKET_PEER_CERT_SZ)
4121
#else
4122
    #define WOLFSSL_INTERNAL_TICKET_MAX_SZ  WOLFSSL_INTERNAL_TICKET_BASE_SZ
4123
#endif
4124
4125
#ifndef WOLFSSL_TICKET_EXTRA_PADDING_SZ
4126
#define WOLFSSL_TICKET_EXTRA_PADDING_SZ 32
4127
#endif
4128
4129
/* Maximum encrypted ticket size */
4130
#define WOLFSSL_TICKET_ENC_SZ \
4131
    (WOLFSSL_INTERNAL_TICKET_MAX_SZ + WOLFSSL_TICKET_EXTRA_PADDING_SZ)
4132
4133
/* Encrypted size of a ticket that carries no peer certificate */
4134
#define WOLFSSL_TICKET_ENC_BASE_SZ \
4135
    (WOLFSSL_INTERNAL_TICKET_BASE_SZ + WOLFSSL_TICKET_EXTRA_PADDING_SZ)
4136
4137
/* RFC 5077 defines this for session tickets. All members need to be a byte or
4138
 * array of byte to avoid alignment issues */
4139
typedef struct ExternalTicket {
4140
    byte key_name[WOLFSSL_TICKET_NAME_SZ];     /* key context name - 16 */
4141
    byte iv[WOLFSSL_TICKET_IV_SZ];             /* this ticket's iv - 16 */
4142
    byte enc_len[OPAQUE16_LEN];                /* encrypted length - 2 */
4143
    byte enc_ticket[WC_FLEXIBLE_ARRAY_SIZE];   /* encrypted ticket - var length
4144
                                                * + total mac - 32 */
4145
} ExternalTicket;
4146
4147
/* Fixed portion of external ticket (key_name + iv + enc_len) */
4148
#define WOLFSSL_TICKET_FIXED_SZ  \
4149
    (WOLFSSL_TICKET_NAME_SZ + WOLFSSL_TICKET_IV_SZ + OPAQUE16_LEN + \
4150
        WOLFSSL_TICKET_MAC_SZ)
4151
4152
/* Maximum session ticket length */
4153
#define SESSION_TICKET_LEN  \
4154
    ((int)(WOLFSSL_TICKET_FIXED_SZ + WOLFSSL_TICKET_ENC_SZ))
4155
4156
/* Length of a session ticket that carries no peer certificate. Sizes the
4157
 * static ticket buffer of WOLFSSL_SESSION; a longer ticket is kept in a
4158
 * dynamic buffer. Same as SESSION_TICKET_LEN when tickets carry no cert. */
4159
#define SESSION_TICKET_STATIC_LEN  \
4160
    ((int)(WOLFSSL_TICKET_FIXED_SZ + WOLFSSL_TICKET_ENC_BASE_SZ))
4161
4162
typedef struct SessionTicket {
4163
    word32 lifetime;
4164
#ifdef WOLFSSL_TLS13
4165
    word64 seen;
4166
    word32 ageAdd;
4167
#endif
4168
    word16 size;
4169
    /* Ignore "nonstandard extension used : zero-sized array in struct/union"
4170
     * MSVC warning */
4171
    #ifdef _MSC_VER
4172
    #pragma warning(disable: 4200)
4173
    #endif
4174
    byte   data[WC_FLEXIBLE_ARRAY_SIZE];
4175
} SessionTicket;
4176
4177
#if !defined(WOLFSSL_NO_DEF_TICKET_ENC_CB) && !defined(NO_WOLFSSL_SERVER)
4178
4179
/* Data passed to default SessionTicket enc/dec callback. */
4180
typedef struct TicketEncCbCtx {
4181
    /* Name for this context. */
4182
    byte name[WOLFSSL_TICKET_NAME_SZ];
4183
    /* Current keys - current and next. */
4184
    byte key[2][WOLFSSL_TICKET_KEY_SZ];
4185
    /* Expirary date of keys. */
4186
    word32 expirary[2];
4187
    /* Random number generator to use for generating name, keys and IV. */
4188
    WC_RNG rng;
4189
#ifndef SINGLE_THREADED
4190
    /* Mutex for access to changing keys. */
4191
    wolfSSL_Mutex mutex;
4192
#endif
4193
    /* Pointer back to SSL_CTX. */
4194
    WOLFSSL_CTX* ctx;
4195
} TicketEncCbCtx;
4196
4197
#endif /* !WOLFSSL_NO_DEF_TICKET_ENC_CB && !NO_WOLFSSL_SERVER */
4198
4199
#ifdef WOLFSSL_API_PREFIX_MAP
4200
    #define TLSX_UseSessionTicket     wolfSSL_TLSX_UseSessionTicket
4201
    #define TLSX_SessionTicket_Create wolfSSL_TLSX_SessionTicket_Create
4202
    #define TLSX_SessionTicket_Free   wolfSSL_TLSX_SessionTicket_Free
4203
#endif
4204
WOLFSSL_TEST_VIS int  TLSX_UseSessionTicket(TLSX** extensions,
4205
                                             SessionTicket* ticket, void* heap);
4206
WOLFSSL_TEST_VIS SessionTicket* TLSX_SessionTicket_Create(word32 lifetime,
4207
                                           byte* data, word16 size, void* heap);
4208
WOLFSSL_TEST_VIS void TLSX_SessionTicket_Free(SessionTicket* ticket, void* heap);
4209
4210
#endif /* HAVE_SESSION_TICKET */
4211
4212
#ifndef MAX_PSK_ID_LEN
4213
    /* max psk identity/hint supported */
4214
    #if defined(WOLFSSL_TLS13)
4215
        #ifdef SESSION_TICKET_STATIC_LEN
4216
            /* Not grown by a peer cert in the ticket: a server accepts its
4217
             * longer tickets up to MAX_PSK_ID_WIRE_LEN. */
4218
            #define MAX_PSK_ID_LEN SESSION_TICKET_STATIC_LEN
4219
        #else
4220
            /* Previous value. Use as fallback for when tickets are disabled. */
4221
            #define MAX_PSK_ID_LEN 1536
4222
        #endif
4223
    #else
4224
        #define MAX_PSK_ID_LEN 128
4225
    #endif
4226
#endif
4227
4228
/* Longest identity a server accepts in a TLS 1.3 pre_shared_key extension:
4229
 * an external PSK identity or one of its session tickets. */
4230
#ifdef HAVE_SESSION_TICKET
4231
    #define MAX_PSK_ID_WIRE_LEN \
4232
        ((int)MAX_PSK_ID_LEN > SESSION_TICKET_LEN ? (int)MAX_PSK_ID_LEN : \
4233
            SESSION_TICKET_LEN)
4234
#else
4235
    #define MAX_PSK_ID_WIRE_LEN MAX_PSK_ID_LEN
4236
#endif
4237
4238
#if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
4239
int TLSX_EncryptThenMac_Respond(WOLFSSL* ssl);
4240
#endif
4241
4242
#ifdef WOLFSSL_TLS13
4243
4244
/* Cookie support is mandatory per RFC 8446 9.2 */
4245
#if !defined(NO_WOLFSSL_CLIENT) || defined(WOLFSSL_SEND_HRR_COOKIE)
4246
    #define WOLFSSL_TLS13_COOKIE
4247
#endif
4248
4249
/* Largest cookie a client stores from a HelloRetryRequest to echo back in the
4250
 * second ClientHello. RFC 8446 4.2.2 allows up to 2^16-1 bytes, but the cookie
4251
 * sits inside an extension body of that same size, so its own two byte length
4252
 * prefix leaves 65533. */
4253
#ifndef WOLFSSL_MAX_TLS13_COOKIE_SZ
4254
0
    #define WOLFSSL_MAX_TLS13_COOKIE_SZ 4096
4255
#endif
4256
#if WOLFSSL_MAX_TLS13_COOKIE_SZ > 65533
4257
    #error "WOLFSSL_MAX_TLS13_COOKIE_SZ must be <= 65533"
4258
#endif
4259
4260
/* Cookie extension information - cookie data. */
4261
typedef struct Cookie {
4262
    word16 len;
4263
    /* Ignore "nonstandard extension used : zero-sized array in struct/union"
4264
     * MSVC warning */
4265
    #ifdef _MSC_VER
4266
    #pragma warning(disable: 4200)
4267
    #endif
4268
    byte   data[WC_FLEXIBLE_ARRAY_SIZE];
4269
} Cookie;
4270
4271
WOLFSSL_LOCAL int TLSX_Cookie_Use(const WOLFSSL* ssl, const byte* data,
4272
        word16 len, byte* mac, byte macSz, int resp, TLSX** exts);
4273
WOLFSSL_LOCAL int TlsCheckCookie(const WOLFSSL* ssl, const byte* cookie,
4274
                                 word16 cookieSz);
4275
4276
4277
/* Key Share - TLS v1.3 Specification */
4278
4279
/* The KeyShare extension information - entry in a linked list. */
4280
typedef struct KeyShareEntry {
4281
    word16                group;     /* NamedGroup                        */
4282
    byte*                 ke;        /* Key exchange data                 */
4283
    word32                keLen;     /* Key exchange data length          */
4284
    void*                 key;       /* Key struct                        */
4285
    word32                keyLen;    /* Key size (bytes)                  */
4286
    byte*                 pubKey;    /* Public key                        */
4287
    word32                pubKeyLen; /* Public key length                 */
4288
#if !defined(NO_DH) || defined(WOLFSSL_HAVE_MLKEM)
4289
    byte*                 privKey;   /* Private key                       */
4290
    word32                privKeyLen;/* Private key length - PQC only     */
4291
#endif
4292
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
4293
    word16                session;   /* NamedGroup that was in session    */
4294
#endif
4295
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK) || \
4296
    defined(WOLFSSL_ASYNC_CRYPT)
4297
    /* Also under WOLFSSL_ASYNC_CRYPT: a pending operation retried on the
4298
     * same accept state re-enters the derive with the peer key freed, and
4299
     * this is the marker that stops the re-derive. */
4300
    word16                derived;   /* preMaster has been derived        */
4301
#endif
4302
#ifdef WOLFSSL_ASYNC_CRYPT
4303
    int                   lastRet;
4304
#endif
4305
    struct KeyShareEntry* next;      /* List pointer             */
4306
} KeyShareEntry;
4307
4308
WOLFSSL_LOCAL int TLSX_KeyShare_Use(const WOLFSSL* ssl, word16 group,
4309
        word16 len, byte* data, KeyShareEntry **kse, TLSX** extensions);
4310
WOLFSSL_LOCAL int TLSX_KeyShare_Empty(WOLFSSL* ssl);
4311
WOLFSSL_LOCAL int TLSX_KeyShare_SetSupported(const WOLFSSL* ssl,
4312
        TLSX** extensions);
4313
WOLFSSL_LOCAL int TLSX_KeyShare_GenKey(WOLFSSL *ssl, KeyShareEntry *kse);
4314
WOLFSSL_LOCAL int TLSX_KeyShare_Choose(const WOLFSSL *ssl, TLSX* extensions,
4315
        byte cipherSuite0, byte cipherSuite, KeyShareEntry** kse,
4316
        byte* searched);
4317
WOLFSSL_LOCAL int TLSX_KeyShare_Setup(WOLFSSL *ssl, KeyShareEntry* clientKSE);
4318
WOLFSSL_LOCAL int TLSX_KeyShare_Establish(WOLFSSL* ssl, int* doHelloRetry);
4319
WOLFSSL_LOCAL int TLSX_KeyShare_DeriveSecret(WOLFSSL* ssl);
4320
WOLFSSL_LOCAL int TLSX_KeyShare_Parse(WOLFSSL* ssl, const byte* input,
4321
        word16 length, byte msgType);
4322
WOLFSSL_LOCAL int TLSX_KeyShare_Parse_ClientHello(const WOLFSSL* ssl,
4323
        const byte* input, word16 length, TLSX** extensions);
4324
WOLFSSL_LOCAL int TLSX_KeyShare_HandlePqcHybridKeyServer(WOLFSSL* ssl,
4325
        KeyShareEntry* keyShareEntry, byte* data, word16 len);
4326
#ifdef WOLFSSL_DUAL_ALG_CERTS
4327
#ifdef WOLFSSL_API_PREFIX_MAP
4328
    #define TLSX_CKS_Parse wolfSSL_TLSX_CKS_Parse
4329
#endif
4330
WOLFSSL_TEST_VIS int TLSX_CKS_Parse(WOLFSSL* ssl, byte* input,
4331
                                 word16 length, TLSX** extensions);
4332
WOLFSSL_LOCAL int TLSX_CKS_Set(WOLFSSL* ssl, TLSX** extensions);
4333
#endif
4334
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
4335
4336
enum PskDecryptReturn {
4337
    PSK_DECRYPT_NONE = 0,
4338
    PSK_DECRYPT_OK,
4339
    PSK_DECRYPT_CREATE,
4340
    PSK_DECRYPT_FAIL
4341
};
4342
4343
#ifdef HAVE_SESSION_TICKET
4344
typedef struct psk_sess_free_cb_ctx {
4345
    word32 row;
4346
#ifdef HAVE_EXT_CACHE
4347
    int extCache;
4348
    int freeSess;
4349
#endif
4350
} psk_sess_free_cb_ctx;
4351
typedef void (psk_sess_free_cb)(const WOLFSSL* ssl, const WOLFSSL_SESSION* sess,
4352
        psk_sess_free_cb_ctx* freeCtx);
4353
#endif
4354
4355
/* The PreSharedKey extension information - entry in a linked list. */
4356
typedef struct PreSharedKey {
4357
    word16               identityLen;             /* Length of identity */
4358
    byte*                identity;                /* PSK identity       */
4359
    word32               ticketAge;               /* Age of the ticket  */
4360
    byte                 cipherSuite0;            /* Cipher Suite       */
4361
    byte                 cipherSuite;             /* Cipher Suite       */
4362
    word32               binderLen;               /* Length of HMAC     */
4363
    byte                 binder[WC_MAX_DIGEST_SIZE]; /* HMAC of handshake */
4364
    byte                 hmac;                    /* HMAC algorithm     */
4365
#ifdef HAVE_SESSION_TICKET
4366
    InternalTicket*      it;                      /* ptr to ticket      */
4367
    const WOLFSSL_SESSION* sess; /* ptr to session either from external cache or
4368
                                  * into SessionCache. Work around so that we
4369
                                  * don't call into the cache more than once */
4370
    psk_sess_free_cb* sess_free_cb;               /* callback to free sess */
4371
    psk_sess_free_cb_ctx sess_free_cb_ctx;        /* info for sess_free_cb */
4372
#endif
4373
    byte                 resumption:1;            /* Resumption PSK     */
4374
    byte                 chosen:1;                /* Server's choice    */
4375
    byte                 decryptRet:3;            /* Ticket decrypt return */
4376
    struct PreSharedKey* next;                    /* List pointer       */
4377
} PreSharedKey;
4378
4379
WOLFSSL_LOCAL int TLSX_PreSharedKey_WriteBinders(PreSharedKey* list,
4380
                                                 byte* output, byte msgType,
4381
                                                 word16* pSz);
4382
WOLFSSL_LOCAL int TLSX_PreSharedKey_GetSizeBinders(PreSharedKey* list,
4383
                                                   byte msgType, word16* pSz);
4384
WOLFSSL_LOCAL int TLSX_PreSharedKey_Use(TLSX** extensions, const byte* identity,
4385
                                        word16 len, word32 age, byte hmac,
4386
                                        byte cipherSuite0, byte cipherSuite,
4387
                                        byte resumption,
4388
                                        PreSharedKey **preSharedKey,
4389
                                        void* heap);
4390
WOLFSSL_LOCAL int TLSX_PreSharedKey_Parse_ClientHello(TLSX** extensions,
4391
                                  const byte* input, word16 length, void* heap);
4392
#if defined(WOLFSSL_CERT_WITH_EXTERN_PSK) && defined(WOLFSSL_TLS13)
4393
WOLFSSL_LOCAL int TLSX_CertWithExternPsk_Use(WOLFSSL* ssl);
4394
#endif
4395
4396
/* The possible Pre-Shared Key key exchange modes. */
4397
enum PskKeyExchangeMode {
4398
    PSK_KE,
4399
    PSK_DHE_KE
4400
};
4401
4402
/* User can define this. */
4403
#ifndef WOLFSSL_DEF_PSK_CIPHER
4404
#define WOLFSSL_DEF_PSK_CIPHER    TLS_AES_128_GCM_SHA256
4405
#endif
4406
4407
WOLFSSL_LOCAL int TLSX_PskKeyModes_Use(WOLFSSL* ssl, byte modes);
4408
WOLFSSL_LOCAL int TLSX_PskKeyModes_Parse_Modes(const byte* input, word16 length,
4409
                                              byte msgType, byte* modes);
4410
4411
#ifdef WOLFSSL_EARLY_DATA
4412
WOLFSSL_LOCAL int TLSX_EarlyData_Use(WOLFSSL* ssl, word32 max, int is_response);
4413
#endif
4414
#endif /* HAVE_SESSION_TICKET || !NO_PSK */
4415
4416
4417
/* The types of keys to derive for. */
4418
enum DeriveKeyType {
4419
    no_key,
4420
    early_data_key,
4421
    handshake_key,
4422
    traffic_key,
4423
    update_traffic_key
4424
};
4425
4426
WOLFSSL_LOCAL int DeriveEarlySecret(WOLFSSL* ssl);
4427
WOLFSSL_LOCAL int DeriveHandshakeSecret(WOLFSSL* ssl);
4428
#ifdef WOLFSSL_API_PREFIX_MAP
4429
    #define DeriveTls13Keys wolfSSL_DeriveTls13Keys
4430
#endif
4431
WOLFSSL_TEST_VIS int DeriveTls13Keys(WOLFSSL* ssl, int secret, int side, int store);
4432
WOLFSSL_LOCAL int Tls13DeriveRecordKeys(WOLFSSL* ssl, int provision);
4433
WOLFSSL_LOCAL int DeriveMasterSecret(WOLFSSL* ssl);
4434
WOLFSSL_LOCAL int DeriveResumptionPSK(WOLFSSL* ssl, byte* nonce, byte nonceLen, byte* secret);
4435
WOLFSSL_LOCAL int DeriveResumptionSecret(WOLFSSL* ssl, byte* key);
4436
#ifdef WOLFSSL_SESSION_EXPORT
4437
WOLFSSL_LOCAL int ExportTls13State(WOLFSSL* ssl, byte* exp, word32 len);
4438
WOLFSSL_LOCAL int ImportTls13State(WOLFSSL* ssl, const byte* exp, word32 len);
4439
#endif
4440
4441
WOLFSSL_LOCAL int Tls13_Exporter(WOLFSSL* ssl, unsigned char *out, size_t outLen,
4442
        const char *label, size_t labelLen,
4443
        const unsigned char *context, size_t contextLen);
4444
4445
/* The key update request values for KeyUpdate message. */
4446
enum KeyUpdateRequest {
4447
    update_not_requested,
4448
    update_requested
4449
};
4450
#endif /* WOLFSSL_TLS13 */
4451
4452
#ifdef WOLFSSL_DTLS_CID
4453
WOLFSSL_LOCAL void TLSX_ConnectionID_Free(byte* ext, void* heap);
4454
WOLFSSL_LOCAL word16 TLSX_ConnectionID_Write(byte* ext, byte* output);
4455
WOLFSSL_LOCAL word16 TLSX_ConnectionID_GetSize(byte* ext);
4456
WOLFSSL_LOCAL int TLSX_ConnectionID_Use(WOLFSSL* ssl);
4457
WOLFSSL_LOCAL int TLSX_ConnectionID_Parse(WOLFSSL* ssl, const byte* input,
4458
    word16 length, byte isRequest);
4459
WOLFSSL_LOCAL void DtlsCIDOnExtensionsParsed(WOLFSSL* ssl);
4460
WOLFSSL_LOCAL byte DtlsCIDIsNegotiated(WOLFSSL* ssl);
4461
WOLFSSL_LOCAL byte DtlsCIDCheck(WOLFSSL* ssl, const byte* input,
4462
    word16 inputSize);
4463
WOLFSSL_LOCAL int DtlsCidReplaceTx(WOLFSSL* ssl, const byte* cid, byte size);
4464
WOLFSSL_LOCAL int Dtls13UnifiedHeaderCIDPresent(byte flags);
4465
#endif /* WOLFSSL_DTLS_CID */
4466
WOLFSSL_LOCAL byte DtlsGetCidTxSize(WOLFSSL* ssl);
4467
WOLFSSL_LOCAL byte DtlsGetCidRxSize(WOLFSSL* ssl);
4468
#ifdef WOLFSSL_SESSION_EXPORT
4469
WOLFSSL_LOCAL word32 DtlsCidExportSize(WOLFSSL* ssl);
4470
WOLFSSL_LOCAL int DtlsCidExport(WOLFSSL* ssl, byte* exp, word32 len);
4471
WOLFSSL_LOCAL int DtlsCidImport(WOLFSSL* ssl, const byte* exp, word32 len);
4472
WOLFSSL_LOCAL void DtlsCidClear(WOLFSSL* ssl);
4473
#endif
4474
4475
#ifdef OPENSSL_EXTRA
4476
enum SetCBIO {
4477
    WOLFSSL_CBIO_NONE = 0,
4478
    WOLFSSL_CBIO_RECV = 0x1,
4479
    WOLFSSL_CBIO_SEND = 0x2,
4480
};
4481
#endif
4482
4483
#ifdef WOLFSSL_STATIC_EPHEMERAL
4484
/* contains static ephemeral keys */
4485
typedef struct {
4486
#ifndef NO_DH
4487
    DerBuffer* dhKey;
4488
#endif
4489
#ifdef HAVE_ECC
4490
    DerBuffer* ecKey;
4491
#endif
4492
#ifdef HAVE_CURVE25519
4493
    DerBuffer* x25519Key;
4494
#endif
4495
#ifdef HAVE_CURVE448
4496
    DerBuffer* x448Key;
4497
#endif
4498
} StaticKeyExchangeInfo_t;
4499
#endif /* WOLFSSL_STATIC_EPHEMERAL */
4500
4501
4502
/* wolfSSL context type */
4503
struct WOLFSSL_CTX {
4504
    WOLFSSL_METHOD* method;
4505
#ifdef SINGLE_THREADED
4506
    WC_RNG*         rng;          /* to be shared with WOLFSSL w/o locking */
4507
#endif
4508
    wolfSSL_RefWithMutex ref;
4509
    int         err;              /* error code in case of mutex not created */
4510
#ifndef NO_DH
4511
    buffer      serverDH_P;
4512
    buffer      serverDH_G;
4513
#endif
4514
#ifndef NO_CERTS
4515
    DerBuffer*  certificate;
4516
    DerBuffer*  certChain;
4517
    int         certChainCnt;
4518
                 /* chain after self, in DER, with leading size for each cert */
4519
    #if !defined(WOLFSSL_NO_CA_NAMES) && defined(OPENSSL_EXTRA)
4520
    WOLF_STACK_OF(WOLFSSL_X509_NAME)* client_ca_names;
4521
    WOLF_STACK_OF(WOLFSSL_X509_NAME)* ca_names;
4522
    #endif
4523
    #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES) && \
4524
        defined(WOLFSSL_TLS13)
4525
    /* wolfSSL native CA DN list sent in certificate_authorities. */
4526
    CertificateAuthority* ws_ca_names;
4527
    #endif
4528
    #ifdef OPENSSL_EXTRA
4529
    WOLF_STACK_OF(WOLFSSL_X509)* x509Chain;
4530
    #endif
4531
#ifdef WOLFSSL_CERT_SETUP_CB
4532
#ifdef OPENSSL_EXTRA
4533
    client_cert_cb CBClientCert;  /* client certificate callback */
4534
#endif
4535
    CertSetupCallback  certSetupCb;
4536
    void*              certSetupCbArg;
4537
#endif
4538
    DerBuffer*  privateKey;
4539
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
4540
    DerBuffer*  privateKeyMask;             /* Mask of private key DER. */
4541
#endif
4542
    byte        privateKeyType;
4543
    byte        privateKeyId:1;
4544
    byte        privateKeyLabel:1;
4545
    int         privateKeySz;
4546
    int         privateKeyDevId;
4547
4548
#ifdef WOLFSSL_DUAL_ALG_CERTS
4549
    DerBuffer*  altPrivateKey;
4550
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
4551
    DerBuffer*  altPrivateKeyMask;          /* Mask of alt private key DER. */
4552
#endif
4553
    byte        altPrivateKeyType;
4554
    byte        altPrivateKeyId:1;
4555
    byte        altPrivateKeyLabel:1;
4556
    int         altPrivateKeySz;
4557
    int         altPrivateKeyDevId;
4558
#endif /* WOLFSSL_DUAL_ALG_CERTS */
4559
#ifdef OPENSSL_ALL
4560
    /* note it is the privateKeyPKey pointer that is volatile, not the object it
4561
     * points to:
4562
     */
4563
    WOLFSSL_EVP_PKEY* volatile privateKeyPKey;
4564
#endif
4565
    WOLFSSL_CERT_MANAGER* cm;      /* our cert manager, ctx owns SSL will use */
4566
#endif
4567
#ifdef KEEP_OUR_CERT
4568
    WOLFSSL_X509*    ourCert;     /* keep alive a X509 struct of cert */
4569
    int              ownOurCert;  /* Dispose of certificate if we own */
4570
#endif
4571
    Suites*     suites;           /* make dynamic, user may not need/set */
4572
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL) || \
4573
    defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
4574
    WOLF_STACK_OF(WOLFSSL_CIPHER)* suitesStack; /* stack of available cipher
4575
                                                 * suites */
4576
#endif
4577
    void*       heap;             /* for user memory overrides */
4578
    byte        verifyDepth;
4579
    byte        verifyPeer:1;
4580
    byte        verifyNone:1;
4581
    byte        failNoCert:1;
4582
    byte        failNoCertxPSK:1; /* fail if no cert with the exception of PSK*/
4583
    byte        failNoPSK:1;      /* fail if no PSK is negotiated */
4584
    byte        sessionCacheOff:1;
4585
    byte        sessionCacheFlushOff:1;
4586
#ifdef HAVE_EXT_CACHE
4587
    byte        internalCacheOff:1;
4588
    byte        internalCacheLookupOff:1;
4589
#endif
4590
    byte        sendVerify:2;     /* for client side (can not be single bit) */
4591
    byte        haveRSA:1;        /* RSA available */
4592
    byte        haveECC:1;        /* ECC available */
4593
    byte        haveDH:1;         /* server DH params set by user */
4594
    byte        haveECDSAsig:1;   /* server cert signed w/ ECDSA */
4595
    byte        haveFalconSig:1;  /* server cert signed w/ Falcon */
4596
    byte        haveMlDsaSig:1;   /* server cert signed w/ ML-DSA */
4597
    byte        haveSlhDsaSig:1;  /* server cert signed w/ SLH-DSA */
4598
    byte        haveStaticECC:1;  /* static server ECC private key */
4599
    byte        partialWrite:1;   /* only one msg per write call */
4600
    byte        autoRetry:1;      /* retry read/write on a WANT_{READ|WRITE} */
4601
    byte        quietShutdown:1;  /* don't send close notify */
4602
    byte        groupMessages:1;  /* group handshake messages before sending */
4603
    byte        minDowngrade;     /* minimum downgrade version */
4604
    byte        minVersionSet:1;  /* minimum set by the user, not the default */
4605
    byte        haveEMS:1;        /* have extended master secret extension */
4606
#ifdef HAVE_EXTENDED_MASTER
4607
    byte        disableEMS:1;     /* user disabled extended master secret,
4608
                                   * ignore peer's EMS request (server) and
4609
                                   * don't advertise it (client) */
4610
    byte        requireEMS:1;     /* user requires extended master secret,
4611
                                   * abort if EMS is not negotiated */
4612
#endif
4613
    byte        useClientOrder:1; /* Use client's cipher preference order */
4614
#if defined(HAVE_SESSION_TICKET)
4615
    byte        noTicketTls12:1;  /* TLS 1.2 server won't send ticket */
4616
#endif
4617
#ifdef WOLFSSL_TLS13
4618
    #if defined(HAVE_SESSION_TICKET) && !defined(NO_WOLFSSL_SERVER)
4619
    unsigned int maxTicketTls13;  /* maximum number of tickets to send */
4620
    #endif
4621
    byte        noTicketTls13:1;  /* TLS 1.3 Server won't create new Ticket */
4622
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
4623
    byte        noPskDheKe:1;     /* Don't use (EC)DHE with PSK */
4624
#ifdef HAVE_SUPPORTED_CURVES
4625
    byte        onlyPskDheKe:1;   /* Only use (EC)DHE with PSK */
4626
#endif
4627
#if defined(WOLFSSL_CERT_WITH_EXTERN_PSK)
4628
    byte        certWithExternPsk:1; /* Use tls_cert_with_extern_psk extension */
4629
#endif
4630
#endif
4631
#endif /* WOLFSSL_TLS13 */
4632
    byte        mutualAuth:1;     /* Mutual authentication required */
4633
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
4634
    byte        postHandshakeAuth:1;  /* Post-handshake auth supported. */
4635
    byte        verifyPostHandshake:1; /* Only send client cert req post
4636
                                        * handshake, not also during */
4637
#endif
4638
#ifndef NO_DH
4639
    #if !defined(WOLFSSL_OLD_PRIME_CHECK) && !defined(HAVE_FIPS) && \
4640
        !defined(HAVE_SELFTEST)
4641
    byte        dhKeyTested:1;   /* Set when key has been tested. */
4642
    #endif
4643
#endif
4644
#if defined(HAVE_SECURE_RENEGOTIATION) || defined(HAVE_SERVER_RENEGOTIATION_INFO)
4645
    byte        useSecureReneg:1; /* when set will set WOLFSSL objects generated to enable */
4646
#endif
4647
#if !defined(NO_WOLFSSL_CLIENT) && !defined(WOLFSSL_NO_TLS12) && \
4648
    defined(HAVE_SERVER_RENEGOTIATION_INFO) && \
4649
    !defined(WOLFSSL_HARDEN_TLS_NO_SCR_CHECK)
4650
    byte        scr_check_enabled:1; /* require server renegotiation_info on the
4651
                                      * initial handshake (RFC 5746/9325);
4652
                                      * inherited by WOLFSSL objects */
4653
#endif
4654
#ifdef HAVE_ENCRYPT_THEN_MAC
4655
    byte        disallowEncThenMac:1;  /* Don't do Encrypt-Then-MAC */
4656
#endif
4657
#ifdef WOLFSSL_STATIC_MEMORY
4658
    byte        onHeapHint:1; /* whether the ctx/method is put on heap hint */
4659
#endif
4660
#if defined(WOLFSSL_STATIC_EPHEMERAL) && !defined(SINGLE_THREADED)
4661
    byte        staticKELockInit:1;
4662
#endif
4663
#if defined(WOLFSSL_DTLS) && defined(WOLFSSL_SCTP)
4664
    byte        dtlsSctp:1;         /* DTLS-over-SCTP mode */
4665
#endif
4666
#if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
4667
    byte        disableECH:1;
4668
    byte        enableEchTrialDecrypt:1;  /* Trial decryption of the
4669
                                             inner hello */
4670
#endif
4671
    word16      minProto:1; /* sets min to min available */
4672
    word16      maxProto:1; /* sets max to max available */
4673
#if defined(HAVE_RPK)
4674
    RpkConfig   rpkConfig;
4675
    RpkState    rpkState;
4676
#endif /* HAVE_RPK */
4677
#ifdef WOLFSSL_SRTP
4678
    word16      dtlsSrtpProfiles;  /* DTLS-with-SRTP mode
4679
                                    * (list of selected profiles - up to 16) */
4680
#endif
4681
#if defined(WOLFSSL_DTLS) && defined(WOLFSSL_MULTICAST)
4682
    byte        haveMcast;        /* multicast requested */
4683
    byte        mcastID;          /* multicast group ID */
4684
#endif
4685
#if defined(WOLFSSL_DTLS) && \
4686
    (defined(WOLFSSL_SCTP) || defined(WOLFSSL_DTLS_MTU))
4687
    word16      dtlsMtuSz;        /* DTLS MTU size */
4688
#endif
4689
#ifndef NO_DH
4690
    word16      minDhKeySz;       /* minimum DH key size */
4691
    word16      maxDhKeySz;       /* maximum DH key size */
4692
#endif
4693
#ifndef NO_RSA
4694
    short       minRsaKeySz;      /* minimum RSA key size */
4695
#ifdef WC_RSA_PSS
4696
    word8       useRsaPss;        /* cert supports RSA-PSS */
4697
#endif
4698
#endif
4699
#if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
4700
    short       minEccKeySz;      /* minimum ECC key size */
4701
#endif
4702
#ifdef HAVE_FALCON
4703
    short       minFalconKeySz;   /* minimum Falcon key size */
4704
#endif
4705
#ifdef WOLFSSL_HAVE_MLDSA
4706
    short       minMlDsaKeySz;    /* minimum ML-DSA key size */
4707
#endif
4708
    unsigned long     mask;             /* store SSL_OP_ flags */
4709
#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL)
4710
    word32            disabledCurves;   /* curves disabled by user */
4711
#endif
4712
#ifdef WOLFSSL_SESSION_ID_CTX
4713
    byte              sessionCtx[ID_LEN]; /* app session context ID */
4714
    byte              sessionCtxSz;
4715
#endif
4716
#ifdef OPENSSL_EXTRA
4717
    const unsigned char *alpn_cli_protos;/* ALPN client protocol list */
4718
    unsigned int         alpn_cli_protos_len;
4719
    byte              cbioFlag;  /* WOLFSSL_CBIO_RECV/SEND: CBIORecv/Send is set */
4720
    CallbackInfoState* CBIS;      /* used to get info about SSL state */
4721
    WOLFSSL_X509_VERIFY_PARAM* param;    /* verification parameters*/
4722
#endif
4723
#ifdef WOLFSSL_WOLFSENTRY_HOOKS
4724
    NetworkFilterCallback_t AcceptFilter;
4725
    void *AcceptFilter_arg;
4726
    NetworkFilterCallback_t ConnectFilter;
4727
    void *ConnectFilter_arg;
4728
#endif /* WOLFSSL_WOLFSENTRY_HOOKS */
4729
    CallbackIORecv CBIORecv;
4730
    CallbackIOSend CBIOSend;
4731
#ifdef WOLFSSL_DTLS
4732
    CallbackGenCookie CBIOCookie;       /* gen cookie callback */
4733
#endif /* WOLFSSL_DTLS */
4734
#ifdef WOLFSSL_SESSION_EXPORT
4735
#ifdef WOLFSSL_DTLS
4736
    wc_dtls_export  dtls_export;        /* export function for DTLS session */
4737
#endif
4738
    CallbackGetPeer CBGetPeer;
4739
    CallbackSetPeer CBSetPeer;
4740
#endif
4741
    VerifyCallback  verifyCallback;     /* cert verification callback */
4742
    void*           verifyCbCtx;        /* cert verify callback user ctx*/
4743
#ifdef OPENSSL_ALL
4744
    CertVerifyCallback verifyCertCb;
4745
    void*              verifyCertCbArg;
4746
#endif /* OPENSSL_ALL */
4747
#ifdef WOLFSSL_CHAIN_VERIFY_CB
4748
    ChainVerifyCb   chainVerifyCb;      /* replaces peer chain verification */
4749
    void*           chainVerifyCtx;     /* chain verify callback user ctx */
4750
#endif
4751
#ifdef OPENSSL_EXTRA
4752
    SSL_Msg_Cb      protoMsgCb;         /* inspect protocol message callback */
4753
    void*           protoMsgCtx;        /* user set context with msg callback */
4754
    word16          maxSendFragment;    /* send record plaintext cap, 0 none */
4755
#endif
4756
    word32          timeout;            /* session timeout */
4757
#if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_CURVE25519) || \
4758
    defined(HAVE_ED448) || defined(HAVE_CURVE448)
4759
    word32          ecdhCurveOID;       /* curve Ecc_Sum */
4760
#endif
4761
#ifdef HAVE_ECC
4762
    word16          eccTempKeySz;       /* in octets 20 - 66 */
4763
#endif
4764
#if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \
4765
    defined(HAVE_FALCON) || defined(WOLFSSL_HAVE_MLDSA) || \
4766
    defined(WOLFSSL_HAVE_SLHDSA)
4767
    word32          pkCurveOID;         /* curve Ecc_Sum */
4768
#endif
4769
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
4770
    byte        havePSK;                /* psk key set by user */
4771
    wc_psk_client_callback client_psk_cb;  /* client callback */
4772
    wc_psk_server_callback server_psk_cb;  /* server callback */
4773
#ifdef WOLFSSL_TLS13
4774
    wc_psk_client_cs_callback    client_psk_cs_cb;     /* client callback */
4775
    wc_psk_client_tls13_callback client_psk_tls13_cb;  /* client callback */
4776
    wc_psk_server_tls13_callback server_psk_tls13_cb;  /* server callback */
4777
#endif
4778
    void*       psk_ctx;
4779
    char        server_hint[MAX_PSK_ID_LEN + NULL_TERM_LEN];
4780
#endif /* HAVE_SESSION_TICKET || !NO_PSK */
4781
#ifdef WOLFSSL_TLS13
4782
    word16          group[WOLFSSL_MAX_GROUP_COUNT];
4783
    byte            numGroups;
4784
#endif
4785
#ifdef WOLFSSL_EARLY_DATA
4786
    word32          maxEarlyDataSz;
4787
#if defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET) && !defined(NO_TLS)
4788
    /* RFC 8446 Section 8.2: reject 0-RTT for tickets minted before this
4789
     * context was created. */
4790
#ifdef WOLFSSL_32BIT_MILLI_TIME
4791
    word32          ticketStartTime;    /* Ctx creation time (ms) */
4792
#else
4793
    sword64         ticketStartTime;    /* Ctx creation time (ms) */
4794
#endif
4795
    byte            noFreshStartCheck:1; /* Skip the fresh start check */
4796
#endif
4797
#endif
4798
#ifdef HAVE_ANON
4799
    byte        useAnon;               /* User wants to allow Anon suites */
4800
#endif /* HAVE_ANON */
4801
#ifdef WOLFSSL_ENCRYPTED_KEYS
4802
    wc_pem_password_cb* passwd_cb;
4803
    void*               passwd_userdata;
4804
#endif
4805
#ifdef WOLFSSL_LOCAL_X509_STORE
4806
    WOLFSSL_X509_STORE x509_store; /* points to ctx->cm */
4807
    WOLFSSL_X509_STORE* x509_store_pt; /* take ownership of external store */
4808
#endif
4809
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || \
4810
    defined(WOLFSSL_WPAS_SMALL) || defined(WOLFSSL_TLS_READ_AHEAD)
4811
    byte            readAhead;
4812
#endif
4813
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_TLS_READ_AHEAD)
4814
    /* Read-ahead coalescing buffer size. 0 = use one record (default). See
4815
     * wolfSSL_CTX_set_default_read_buffer_len(). */
4816
    word32          readAheadSz;
4817
#endif
4818
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || defined(WOLFSSL_WPAS_SMALL)
4819
    void*           userPRFArg; /* passed to prf callback */
4820
#endif
4821
#ifdef HAVE_EX_DATA
4822
    WOLFSSL_CRYPTO_EX_DATA ex_data;
4823
#endif
4824
#if defined(HAVE_ALPN) && (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
4825
    defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY) || defined(WOLFSSL_QUIC))
4826
    CallbackALPNSelect alpnSelect;
4827
    void*              alpnSelectArg;
4828
#endif
4829
#ifdef HAVE_SNI
4830
    CallbackSniRecv sniRecvCb;
4831
    void*           sniRecvCbArg;
4832
#endif
4833
#if defined(WOLFSSL_MULTICAST) && defined(WOLFSSL_DTLS)
4834
    CallbackMcastHighwater mcastHwCb; /* Sequence number highwater callback */
4835
    word32      mcastFirstSeq;    /* first trigger level */
4836
    word32      mcastSecondSeq;   /* second trigger level */
4837
    word32      mcastMaxSeq;      /* max level */
4838
#endif
4839
#ifdef HAVE_OCSP
4840
    WOLFSSL_OCSP      ocsp;
4841
#endif
4842
    int             devId;              /* async device id to use */
4843
#ifdef HAVE_TLS_EXTENSIONS
4844
    TLSX* extensions;                  /* RFC 6066 TLS Extensions data */
4845
    #ifdef OPENSSL_EXTRA
4846
        WOLFSSL_CustomExt* customExt;  /* App-defined custom TLS extensions */
4847
    #endif
4848
    #ifndef NO_WOLFSSL_SERVER
4849
        #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
4850
         || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
4851
            OcspRequest* certOcspRequest;
4852
        #endif
4853
        #if defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
4854
            OcspRequest* chainOcspRequest[MAX_CHAIN_DEPTH];
4855
        #endif
4856
    #endif
4857
    #if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
4858
     || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
4859
        ocspVerifyStatusCb ocspStatusVerifyCb;
4860
        void* ocspStatusVerifyCbArg;
4861
    #endif
4862
    #if defined(HAVE_SESSION_TICKET) && !defined(NO_WOLFSSL_SERVER)
4863
        SessionTicketEncCb ticketEncCb;   /* enc/dec session ticket Cb */
4864
        void*              ticketEncCtx;  /* session encrypt context */
4865
        #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) \
4866
          || defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY)
4867
        ticketCompatCb     ticketEncWrapCb; /* callback for OpenSSL ticket key callback */
4868
        #endif
4869
        int                ticketHint;    /* ticket hint in seconds */
4870
        #ifndef WOLFSSL_NO_DEF_TICKET_ENC_CB
4871
            TicketEncCbCtx ticketKeyCtx;
4872
        #endif
4873
    #endif
4874
    #endif
4875
    #ifdef HAVE_SUPPORTED_CURVES
4876
        byte userCurves;                  /* indicates user called wolfSSL_CTX_UseSupportedCurve */
4877
    #endif
4878
#ifdef ATOMIC_USER
4879
    CallbackMacEncrypt    MacEncryptCb;    /* Atomic User Mac/Encrypt Cb */
4880
    CallbackDecryptVerify DecryptVerifyCb; /* Atomic User Decrypt/Verify Cb */
4881
    #ifdef HAVE_ENCRYPT_THEN_MAC
4882
        CallbackEncryptMac    EncryptMacCb;    /* Atomic User Mac/Enc Cb */
4883
        CallbackVerifyDecrypt VerifyDecryptCb; /* Atomic User Dec/Verify Cb */
4884
    #endif
4885
#endif
4886
#ifdef HAVE_PK_CALLBACKS
4887
    #ifdef HAVE_ECC
4888
        CallbackEccKeyGen EccKeyGenCb;  /* User EccKeyGen Callback Handler */
4889
        CallbackEccSign   EccSignCb;    /* User EccSign   Callback handler */
4890
        void*             EccSignCtx;   /* Ecc Sign       Callback Context */
4891
        CallbackEccVerify EccVerifyCb;  /* User EccVerify Callback handler */
4892
        CallbackEccSharedSecret EccSharedSecretCb; /* User EccVerify Callback handler */
4893
    #endif /* HAVE_ECC */
4894
    #ifdef HAVE_HKDF
4895
        CallbackHKDFExtract HkdfExtractCb; /* User hkdf Extract Callback handler */
4896
    #endif
4897
    #ifdef HAVE_ED25519
4898
        /* User Ed25519Sign   Callback handler */
4899
        CallbackEd25519Sign   Ed25519SignCb;
4900
        /* User Ed25519Verify Callback handler */
4901
        CallbackEd25519Verify Ed25519VerifyCb;
4902
    #endif
4903
    #ifdef HAVE_CURVE25519
4904
        /* User X25519 KeyGen Callback Handler */
4905
        CallbackX25519KeyGen X25519KeyGenCb;
4906
        /* User X25519 SharedSecret Callback handler */
4907
        CallbackX25519SharedSecret X25519SharedSecretCb;
4908
    #endif
4909
    #ifdef HAVE_ED448
4910
        /* User Ed448Sign   Callback handler */
4911
        CallbackEd448Sign   Ed448SignCb;
4912
        /* User Ed448Verify Callback handler */
4913
        CallbackEd448Verify Ed448VerifyCb;
4914
    #endif
4915
    #ifdef HAVE_CURVE448
4916
        /* User X448 KeyGen Callback Handler */
4917
        CallbackX448KeyGen X448KeyGenCb;
4918
        /* User X448 SharedSecret Callback handler */
4919
        CallbackX448SharedSecret X448SharedSecretCb;
4920
    #endif
4921
    #ifndef NO_DH
4922
        /* User DH KeyGen Callback handler*/
4923
        CallbackDhGenerateKeyPair DhGenerateKeyPairCb;
4924
        /* User DH Agree Callback handler */
4925
        CallbackDhAgree DhAgreeCb;
4926
    #endif
4927
    #ifndef NO_RSA
4928
        /* User RsaSign Callback handler (priv key) */
4929
        CallbackRsaSign   RsaSignCb;
4930
        /* User RsaVerify Callback handler (pub key) */
4931
        CallbackRsaVerify RsaVerifyCb;
4932
        /* User VerifyRsaSign Callback handler (priv key) */
4933
        CallbackRsaVerify RsaSignCheckCb;
4934
        #ifdef WC_RSA_PSS
4935
            /* User RsaSign (priv key) */
4936
            CallbackRsaPssSign   RsaPssSignCb;
4937
            /* User RsaVerify (pub key) */
4938
            CallbackRsaPssVerify RsaPssVerifyCb;
4939
            /* User VerifyRsaSign (priv key) */
4940
            CallbackRsaPssVerify RsaPssSignCheckCb;
4941
        #endif
4942
        CallbackRsaEnc    RsaEncCb;     /* User Rsa Public Encrypt  handler */
4943
        CallbackRsaDec    RsaDecCb;     /* User Rsa Private Decrypt handler */
4944
    #endif /* NO_RSA */
4945
4946
    /* User generate pre-master handler */
4947
    CallbackGenPreMaster        GenPreMasterCb;
4948
    /* User generate master secret handler */
4949
    CallbackGenMasterSecret     GenMasterCb;
4950
    /* User generate Extended master secret handler */
4951
    CallbackGenExtMasterSecret  GenExtMasterCb;
4952
    /* User generate session key handler */
4953
    CallbackGenSessionKey       GenSessionKeyCb;
4954
    /* User setting encrypt keys handler */
4955
    CallbackEncryptKeys         EncryptKeysCb;
4956
    /* User Tls finished handler */
4957
    CallbackTlsFinished         TlsFinishedCb;
4958
#if !defined(WOLFSSL_NO_TLS12) && !defined(WOLFSSL_AEAD_ONLY)
4959
    /* User Verify mac handler */
4960
    CallbackVerifyMac           VerifyMacCb;
4961
#endif
4962
#if defined(WOLFSSL_PUBLIC_ASN)
4963
    /* User handler to process a certificate */
4964
    CallbackProcessPeerCert ProcessPeerCertCb;
4965
#endif
4966
    /* User handler to process the server's key exchange public key */
4967
    CallbackProcessServerSigKex ProcessServerSigKexCb;
4968
    /* User handler to process the TLS record */
4969
    CallbackPerformTlsRecordProcessing PerformTlsRecordProcessingCb;
4970
    /* User handler to do HKDF expansions */
4971
    CallbackHKDFExpandLabel HKDFExpandLabelCb;
4972
4973
#endif /* HAVE_PK_CALLBACKS */
4974
#ifdef HAVE_WOLF_EVENT
4975
    WOLF_EVENT_QUEUE event_queue;
4976
#endif /* HAVE_WOLF_EVENT */
4977
#ifdef HAVE_EXT_CACHE
4978
    WOLFSSL_SESSION*(*get_sess_cb)(WOLFSSL*, const unsigned char*, int, int*);
4979
    int (*new_sess_cb)(WOLFSSL*, WOLFSSL_SESSION*);
4980
#endif
4981
#if defined(HAVE_EXT_CACHE) || defined(HAVE_EX_DATA)
4982
    Rem_Sess_Cb rem_sess_cb;
4983
#endif
4984
#if defined(OPENSSL_EXTRA) && defined(WOLFCRYPT_HAVE_SRP) && !defined(NO_SHA256)
4985
    Srp*  srp;  /* TLS Secure Remote Password Protocol*/
4986
    byte* srp_password;
4987
#endif
4988
#if defined(OPENSSL_EXTRA) && defined(HAVE_SECRET_CALLBACK)
4989
    wolfSSL_CTX_keylog_cb_func keyLogCb;
4990
#endif /* OPENSSL_EXTRA && HAVE_SECRET_CALLBACK */
4991
#ifdef WOLFSSL_STATIC_EPHEMERAL
4992
    StaticKeyExchangeInfo_t staticKE;
4993
    #ifndef SINGLE_THREADED
4994
    wolfSSL_Mutex staticKELock;
4995
    #endif
4996
#endif
4997
#ifdef WOLFSSL_QUIC
4998
    struct {
4999
        const WOLFSSL_QUIC_METHOD *method;
5000
    } quic;
5001
#endif
5002
#if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
5003
    WOLFSSL_EchConfig* echConfigs;
5004
#endif
5005
#if defined(__APPLE__) && defined(WOLFSSL_SYS_CA_CERTS)
5006
    byte doAppleNativeCertValidationFlag:1;
5007
#endif /* defined(__APPLE__) && defined(WOLFSSL_SYS_CA_CERTS) */
5008
#ifdef WOLFSSL_DUAL_ALG_CERTS
5009
    byte *sigSpec;
5010
    word16 sigSpecSz;
5011
#endif
5012
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
5013
    int secLevel; /* The security level of system-wide crypto policy. */
5014
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
5015
5016
#ifdef WOLFSSL_TEST_APPLE_NATIVE_CERT_VALIDATION
5017
    CFMutableArrayRef testTrustedCAs;
5018
#endif /* WOLFSSL_TEST_APPLE_NATIVE_CERT_VALIDATION */
5019
};
5020
5021
WOLFSSL_LOCAL
5022
int InitSSL_Ctx(WOLFSSL_CTX* ctx, WOLFSSL_METHOD* method, void* heap);
5023
WOLFSSL_LOCAL
5024
void FreeSSL_Ctx(WOLFSSL_CTX* ctx);
5025
WOLFSSL_LOCAL
5026
void SSL_CtxResourceFree(WOLFSSL_CTX* ctx);
5027
5028
#ifdef HAVE_EX_DATA_CLEANUP_HOOKS
5029
    #ifndef HAVE_EX_DATA
5030
        #error "HAVE_EX_DATA_CLEANUP_HOOKS requires HAVE_EX_DATA to be defined"
5031
    #endif
5032
void wolfSSL_CRYPTO_cleanup_ex_data(WOLFSSL_CRYPTO_EX_DATA* ex_data);
5033
#endif
5034
5035
WOLFSSL_LOCAL
5036
int DeriveTlsKeys(WOLFSSL* ssl);
5037
WOLFSSL_LOCAL
5038
int ProcessOldClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
5039
                          word32 inSz, word16 sz);
5040
5041
#ifndef NO_CERTS
5042
    WOLFSSL_LOCAL int AddSigner(WOLFSSL_CERT_MANAGER* cm, Signer *s);
5043
    WOLFSSL_LOCAL
5044
    int AddCA(WOLFSSL_CERT_MANAGER* cm, DerBuffer** pDer, int type, int verify);
5045
    WOLFSSL_LOCAL int RemoveCA(WOLFSSL_CERT_MANAGER* cm, byte* hash, int type);
5046
    WOLFSSL_LOCAL int SetCAType(WOLFSSL_CERT_MANAGER* cm, byte* hash, int type);
5047
    WOLFSSL_LOCAL
5048
    int AlreadySigner(WOLFSSL_CERT_MANAGER* cm, byte* hash);
5049
#ifdef WOLFSSL_TRUST_PEER_CERT
5050
    WOLFSSL_LOCAL
5051
    int AddTrustedPeer(WOLFSSL_CERT_MANAGER* cm, DerBuffer** pDer, int verify);
5052
    WOLFSSL_LOCAL
5053
    int AlreadyTrustedPeer(WOLFSSL_CERT_MANAGER* cm, DecodedCert* cert);
5054
#endif
5055
#endif
5056
5057
#ifdef WOLFSSL_TEST_APPLE_NATIVE_CERT_VALIDATION
5058
    WOLFSSL_API
5059
    int wolfSSL_TestAppleNativeCertValidation_AppendCA(WOLFSSL_CTX* ctx,
5060
                                                    const byte* derCert,
5061
                                                    int derLen);
5062
#endif /* WOLFSSL_TEST_APPLE_NATIVE_CERT_VALIDATION */
5063
5064
/* All cipher suite related info
5065
 * Keep as a constant size (no ifdefs) for session export */
5066
typedef struct CipherSpecs {
5067
    word16 key_size;
5068
    word16 iv_size;
5069
    word16 block_size;
5070
    word16 aead_mac_size;
5071
    byte bulk_cipher_algorithm;
5072
    byte cipher_type;               /* block, stream, or aead */
5073
    byte mac_algorithm;
5074
    byte kea;                       /* key exchange algo */
5075
    byte sig_algo;
5076
    byte hash_size;
5077
    byte pad_size;
5078
    byte static_ecdh;
5079
} CipherSpecs;
5080
5081
5082
void InitCipherSpecs(CipherSpecs* cs);
5083
5084
5085
/* Supported Key Exchange Protocols */
5086
enum KeyExchangeAlgorithm {
5087
    no_kea,
5088
    rsa_kea,
5089
    diffie_hellman_kea,
5090
    fortezza_kea,
5091
    psk_kea,
5092
    dhe_psk_kea,
5093
    ecdhe_psk_kea,
5094
    ecc_diffie_hellman_kea,
5095
    ecc_static_diffie_hellman_kea,      /* for verify suite only */
5096
    any_kea
5097
};
5098
5099
/* Used with InitSuitesHashSigAlgo */
5100
0
#define SIG_ECDSA       0x01
5101
0
#define SIG_RSA         0x02
5102
0
#define SIG_SM2         0x04
5103
0
#define SIG_FALCON      0x08
5104
0
#define SIG_MLDSA       0x10
5105
#define SIG_ANON        0x20
5106
0
#define SIG_SLHDSA      0x40
5107
/* SIG_ANON is omitted by default */
5108
0
#define SIG_ALL         (SIG_ECDSA | SIG_RSA | SIG_SM2 | SIG_FALCON | \
5109
0
                         SIG_MLDSA | SIG_SLHDSA)
5110
5111
/* Supported Authentication Schemes */
5112
enum SignatureAlgorithm {
5113
    anonymous_sa_algo            = 0,
5114
    rsa_sa_algo                  = 1,
5115
    dsa_sa_algo                  = 2,
5116
    ecc_dsa_sa_algo              = 3,
5117
    rsa_pss_sa_algo              = 8,
5118
    ed25519_sa_algo              = 9,
5119
    rsa_pss_pss_algo             = 10,
5120
    ed448_sa_algo                = 11,
5121
    falcon_level1_sa_algo        = 12,
5122
    falcon_level5_sa_algo        = 13,
5123
    mldsa_44_sa_algo             = 14,
5124
    mldsa_65_sa_algo             = 15,
5125
    mldsa_87_sa_algo             = 16,
5126
    sm2_sa_algo                  = 17,
5127
    any_sa_algo                  = 18,
5128
    ecc_brainpool_sa_algo        = 19,
5129
    slhdsa_sha2_128s_sa_algo     = 20,
5130
    slhdsa_sha2_128f_sa_algo     = 21,
5131
    slhdsa_sha2_192s_sa_algo     = 22,
5132
    slhdsa_sha2_192f_sa_algo     = 23,
5133
    slhdsa_sha2_256s_sa_algo     = 24,
5134
    slhdsa_sha2_256f_sa_algo     = 25,
5135
    slhdsa_shake_128s_sa_algo    = 26,
5136
    slhdsa_shake_128f_sa_algo    = 27,
5137
    slhdsa_shake_192s_sa_algo    = 28,
5138
    slhdsa_shake_192f_sa_algo    = 29,
5139
    slhdsa_shake_256s_sa_algo    = 30,
5140
    slhdsa_shake_256f_sa_algo    = 31,
5141
    invalid_sa_algo              = 255
5142
};
5143
5144
#define PSS_RSAE_TO_PSS_PSS(macAlgo) \
5145
    ((macAlgo) + (pss_sha256 - sha256_mac))
5146
5147
#define PSS_PSS_HASH_TO_MAC(macAlgo) \
5148
    ((macAlgo) - (pss_sha256 - sha256_mac))
5149
5150
enum SigAlgRsaPss {
5151
    pss_sha256  = 0x09,
5152
    pss_sha384  = 0x0a,
5153
    pss_sha512  = 0x0b
5154
};
5155
5156
#ifdef WOLFSSL_SM2
5157
    /* Default SM2 signature ID. */
5158
0
    #define TLS12_SM2_SIG_ID        ((byte*)"1234567812345678")
5159
    /* Length of default SM2 signature ID. */
5160
0
    #define TLS12_SM2_SIG_ID_SZ     16
5161
5162
    /* https://www.rfc-editor.org/rfc/rfc8998.html#name-sm2-signature-scheme */
5163
    /* ID to use when signing/verifying TLS v1.3 data. */
5164
0
    #define TLS13_SM2_SIG_ID        ((byte*)"TLSv1.3+GM+Cipher+Suite")
5165
    /* Length of ID to use when signing/verifying TLS v1.3 data. */
5166
0
    #define TLS13_SM2_SIG_ID_SZ     23
5167
#endif
5168
5169
/* Supported ECC Curve Types */
5170
enum EccCurves {
5171
    named_curve = 3
5172
};
5173
5174
5175
/* Valid client certificate request types from page 27 */
5176
enum ClientCertificateType {
5177
    rsa_sign            = 1,
5178
    dss_sign            = 2,
5179
    rsa_fixed_dh        = 3,
5180
    dss_fixed_dh        = 4,
5181
    rsa_ephemeral_dh    = 5,
5182
    dss_ephemeral_dh    = 6,
5183
    fortezza_kea_cert   = 20,
5184
    ecdsa_sign          = 64,
5185
    rsa_fixed_ecdh      = 65,
5186
    ecdsa_fixed_ecdh    = 66,
5187
    falcon_sign         = 67,
5188
    mldsa_sign          = 68
5189
};
5190
5191
/* Maximum number of ClientCertificateType bytes the server emits in a
5192
 * CertificateRequest. Currently rsa_sign and ecdsa_sign. */
5193
#define MAX_CERT_REQ_CERT_TYPE_CNT 2
5194
5195
5196
#ifndef WOLFSSL_AEAD_ONLY
5197
enum CipherType { stream, block, aead };
5198
#else
5199
enum CipherType { aead };
5200
#endif
5201
5202
5203
#if defined(BUILD_AES) || defined(BUILD_AESGCM) || defined(HAVE_ARIA) || \
5204
        (defined(HAVE_CHACHA) && defined(HAVE_POLY1305)) || defined(WOLFSSL_TLS13)
5205
    #define CIPHER_NONCE
5206
#endif
5207
5208
#if defined(WOLFSSL_DTLS) && defined(HAVE_SECURE_RENEGOTIATION)
5209
enum CipherSrc {
5210
    KEYS_NOT_SET = 0,
5211
    KEYS,     /* keys from ssl->keys are loaded */
5212
    SCR       /* keys from ssl->secure_renegotiation->tmp_keys are loaded */
5213
};
5214
#endif
5215
5216
#ifdef WOLFSSL_CIPHER_TEXT_CHECK
5217
    #ifndef WOLFSSL_CIPHER_CHECK_SZ
5218
        /* 64-bits to confirm encrypt operation worked */
5219
        #define WOLFSSL_CIPHER_CHECK_SZ 8
5220
    #endif
5221
#endif
5222
5223
/* cipher for now */
5224
typedef struct Ciphers {
5225
#ifdef BUILD_ARC4
5226
    Arc4*   arc4;
5227
#endif
5228
#ifdef BUILD_DES3
5229
    Des3*   des3;
5230
#endif
5231
#if defined(BUILD_AES) || defined(BUILD_AESGCM)
5232
    Aes*    aes;
5233
#endif
5234
#if (defined(BUILD_AESGCM) || defined(HAVE_AESCCM)) && !defined(WOLFSSL_NO_TLS12)
5235
    byte* additional;
5236
#endif
5237
#ifdef HAVE_ARIA
5238
    wc_Aria* aria;
5239
#endif
5240
#ifdef CIPHER_NONCE
5241
    byte* nonce;
5242
#endif
5243
#ifdef HAVE_CAMELLIA
5244
    wc_Camellia* cam;
5245
#endif
5246
#ifdef HAVE_CHACHA
5247
    ChaCha*   chacha;
5248
#endif
5249
#ifdef WOLFSSL_SM4
5250
    wc_Sm4*   sm4;
5251
#endif
5252
#if defined(WOLFSSL_TLS13) && defined(HAVE_NULL_CIPHER) && !defined(NO_HMAC)
5253
    Hmac* hmac;
5254
#endif
5255
#ifdef WOLFSSL_CIPHER_TEXT_CHECK
5256
    word32 sanityCheck[WOLFSSL_CIPHER_CHECK_SZ/sizeof(word32)];
5257
#endif
5258
    byte    state;
5259
    byte    setup;       /* have we set it up flag for detection */
5260
#if defined(WOLFSSL_DTLS) && defined(HAVE_SECURE_RENEGOTIATION)
5261
    enum CipherSrc src;  /* DTLS uses this to determine which keys
5262
                          * are currently loaded */
5263
#endif
5264
} Ciphers;
5265
5266
#ifdef WOLFSSL_DTLS13
5267
typedef struct RecordNumberCiphers {
5268
#if defined(BUILD_AES) || defined(BUILD_AESGCM)
5269
        Aes *aes;
5270
#endif /*  BUILD_AES || BUILD_AESGCM */
5271
#ifdef HAVE_CHACHA
5272
        ChaCha *chacha;
5273
#endif
5274
} RecordNumberCiphers;
5275
#endif /* WOLFSSL_DTLS13 */
5276
5277
#ifdef HAVE_ONE_TIME_AUTH
5278
/* Ciphers for one time authentication such as poly1305 */
5279
typedef struct OneTimeAuth {
5280
#ifdef HAVE_POLY1305
5281
    Poly1305* poly1305;
5282
#endif
5283
    byte    setup;      /* flag for if a cipher has been set */
5284
5285
} OneTimeAuth;
5286
#endif
5287
5288
5289
WOLFSSL_LOCAL void InitCiphers(WOLFSSL* ssl);
5290
WOLFSSL_LOCAL void FreeCiphers(WOLFSSL* ssl);
5291
5292
5293
/* hashes type */
5294
typedef struct Hashes {
5295
    #if !defined(NO_MD5) && !defined(NO_OLD_TLS)
5296
        byte md5[WC_MD5_DIGEST_SIZE];
5297
    #endif
5298
    #if !defined(NO_SHA) && (!defined(NO_OLD_TLS) || \
5299
                              defined(WOLFSSL_ALLOW_TLS_SHA1))
5300
        byte sha[WC_SHA_DIGEST_SIZE];
5301
    #endif
5302
    #ifndef NO_SHA256
5303
        byte sha256[WC_SHA256_DIGEST_SIZE];
5304
    #endif
5305
    #ifdef WOLFSSL_SHA384
5306
        byte sha384[WC_SHA384_DIGEST_SIZE];
5307
    #endif
5308
    #ifdef WOLFSSL_SHA512
5309
        byte sha512[WC_SHA512_DIGEST_SIZE];
5310
    #endif
5311
    #ifdef WOLFSSL_SM3
5312
        byte sm3[WC_SM3_DIGEST_SIZE];
5313
    #endif
5314
} Hashes;
5315
5316
WOLFSSL_LOCAL int BuildCertHashes(const WOLFSSL* ssl, Hashes* hashes);
5317
5318
#ifdef WOLFSSL_TLS13
5319
typedef union Digest {
5320
#ifndef NO_SHA256
5321
    wc_Sha256 sha256;
5322
#endif
5323
#ifdef WOLFSSL_SHA384
5324
    wc_Sha384 sha384;
5325
#endif
5326
#ifdef WOLFSSL_SHA512
5327
    wc_Sha512 sha512;
5328
#endif
5329
#ifdef WOLFSSL_SM3
5330
    wc_Sm3    sm3;
5331
#endif
5332
} Digest;
5333
#endif
5334
5335
/* Static x509 buffer */
5336
typedef struct x509_buffer {
5337
    int  length;                  /* actual size */
5338
    byte buffer[MAX_X509_SIZE];   /* max static cert size */
5339
} x509_buffer;
5340
5341
5342
/* wolfSSL X509_CHAIN, for no dynamic memory SESSION_CACHE */
5343
struct WOLFSSL_X509_CHAIN {
5344
    int         count;                    /* total number in chain */
5345
    x509_buffer certs[MAX_CHAIN_DEPTH];   /* only allow max depth 4 for now */
5346
};
5347
5348
typedef enum WOLFSSL_SESSION_TYPE {
5349
    WOLFSSL_SESSION_TYPE_UNKNOWN,
5350
    WOLFSSL_SESSION_TYPE_SSL,    /* in ssl->session */
5351
    WOLFSSL_SESSION_TYPE_CACHE,  /* pointer to internal cache */
5352
    WOLFSSL_SESSION_TYPE_HEAP    /* allocated from heap SESSION_new */
5353
} WOLFSSL_SESSION_TYPE;
5354
5355
#ifdef WOLFSSL_QUIC
5356
typedef struct QuicRecord QuicRecord;
5357
typedef struct QuicRecord {
5358
    struct QuicRecord *next;
5359
    uint8_t *data;
5360
    word32 capacity;
5361
    word32 len;
5362
    word32 start;
5363
    word32 end;
5364
    WOLFSSL_ENCRYPTION_LEVEL level;
5365
    word32 rec_hdr_remain;
5366
} QuicEncData;
5367
5368
typedef struct QuicTransportParam QuicTransportParam;
5369
struct QuicTransportParam {
5370
    const uint8_t *data;
5371
    word16 len;
5372
};
5373
5374
WOLFSSL_LOCAL const QuicTransportParam *QuicTransportParam_new(const uint8_t *data, size_t len, void *heap);
5375
WOLFSSL_LOCAL const QuicTransportParam *QuicTransportParam_dup(const QuicTransportParam *tp, void *heap);
5376
WOLFSSL_LOCAL void QuicTransportParam_free(const QuicTransportParam *tp, void *heap);
5377
WOLFSSL_LOCAL int TLSX_QuicTP_Use(WOLFSSL* ssl, TLSX_Type ext_type, int is_response);
5378
WOLFSSL_LOCAL int wolfSSL_quic_add_transport_extensions(WOLFSSL *ssl, int msg_type);
5379
5380
#define QTP_FREE     QuicTransportParam_free
5381
5382
#endif /* WOLFSSL_QUIC */
5383
5384
/** Session Ticket - RFC 5077 (session 3.2) */
5385
#if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
5386
/* Ticket nonce - for deriving PSK.
5387
   Length allowed to be: 1..255. Only support
5388
 * TLS13_TICKET_NONCE_STATIC_SZ length bytes.
5389
 */
5390
typedef struct TicketNonce {
5391
    byte len;
5392
#if defined(WOLFSSL_TICKET_NONCE_MALLOC) &&                                    \
5393
    (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
5394
    byte *data;
5395
    byte dataStatic[MAX_TICKET_NONCE_STATIC_SZ];
5396
#else
5397
    byte data[MAX_TICKET_NONCE_STATIC_SZ];
5398
#endif /* WOLFSSL_TICKET_NONCE_MALLOC  && FIPS_VERSION_GE(5,3) */
5399
} TicketNonce;
5400
#endif /* WOLFSSL_TLS13 && (HAVE_SESSION_TICKET || !NO_PSK) */
5401
5402
/* wolfSSL session type */
5403
struct WOLFSSL_SESSION {
5404
    /* WARNING Do not add fields here. They will be ignored in
5405
     *         wolfSSL_DupSession. */
5406
    WOLFSSL_SESSION_TYPE type;
5407
#ifndef NO_SESSION_CACHE
5408
    int                cacheRow;          /* row in session cache     */
5409
    word32             cacheGen;          /* writes into this entry   */
5410
#endif /* !NO_SESSION_CACHE */
5411
    wolfSSL_Ref        ref;
5412
    byte               altSessionID[ID_LEN];
5413
    byte               haveAltSessionID:1;
5414
#ifdef HAVE_EX_DATA
5415
    byte               ownExData:1;
5416
#endif /* HAVE_EX_DATA */
5417
#if defined(HAVE_EXT_CACHE) || defined(HAVE_EX_DATA)
5418
    Rem_Sess_Cb        rem_sess_cb;
5419
#endif /* HAVE_EXT_CACHE || HAVE_EX_DATA */
5420
    void*              heap;
5421
    /* WARNING The above fields (up to and including the heap) are not copied
5422
     *         in wolfSSL_DupSession. Place new fields after the heap
5423
     *         member */
5424
5425
    byte               side;              /* Either WOLFSSL_CLIENT_END or
5426
                                                    WOLFSSL_SERVER_END */
5427
5428
    word32             bornOn;            /* create time in seconds   */
5429
    word32             timeout;           /* timeout in seconds       */
5430
5431
    byte               sessionID[ID_LEN]; /* id for protocol or bogus
5432
                                           * ID for TLS 1.3           */
5433
    byte               sessionIDSz;
5434
5435
    byte               masterSecret[SECRET_LEN]; /* stored secret     */
5436
    word16             haveEMS;           /* ext master secret flag   */
5437
#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
5438
    WOLFSSL_X509*      peer;              /* peer cert */
5439
#endif /* SESSION_CERTS && OPENSSL_EXTRA */
5440
    ProtocolVersion    version;           /* which version was used   */
5441
#if defined(SESSION_CERTS) || !defined(NO_RESUME_SUITE_CHECK) || \
5442
                        (defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET))
5443
    byte               cipherSuite0;      /* first byte, normally 0   */
5444
    byte               cipherSuite;       /* 2nd byte, actual suite   */
5445
#endif /* SESSION_CERTS || !NO_RESUME_SUITE_CHECK || ... */
5446
#ifndef NO_CLIENT_CACHE
5447
    word16             idLen;             /* serverID length          */
5448
    byte               serverID[SERVER_ID_LEN]; /* for easier client lookup */
5449
#endif /* !NO_CLIENT_CACHE */
5450
#ifdef WOLFSSL_SESSION_ID_CTX
5451
    byte               sessionCtxSz;      /* sessionCtx length        */
5452
    byte               sessionCtx[ID_LEN]; /* app specific context id */
5453
#endif /* WOLFSSL_SESSION_ID_CTX */
5454
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
5455
    byte               peerVerifyRet;     /* cert verify error */
5456
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
5457
#ifdef WOLFSSL_TLS13
5458
    word16             namedGroup;
5459
#endif /* WOLFSSL_TLS13 */
5460
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
5461
    #ifdef WOLFSSL_TLS13
5462
    #ifdef WOLFSSL_32BIT_MILLI_TIME
5463
    word32             ticketSeen;        /* Time ticket seen (ms) */
5464
    #else
5465
    sword64            ticketSeen;        /* Time ticket seen (ms) */
5466
    #endif /* WOLFSSL_32BIT_MILLI_TIME */
5467
    word32             ticketAdd;         /* Added by client */
5468
    TicketNonce        ticketNonce;       /* Nonce used to derive PSK */
5469
    #endif /* WOLFSSL_TLS13 */
5470
    #ifdef WOLFSSL_EARLY_DATA
5471
    word32             maxEarlyDataSz;
5472
    #endif /* WOLFSSL_EARLY_DATA */
5473
#endif /* HAVE_SESSION_TICKET || !NO_PSK */
5474
#ifdef HAVE_SESSION_TICKET
5475
    byte               staticTicket[SESSION_TICKET_STATIC_LEN];
5476
    byte*              ticket;
5477
    word16             ticketLen;
5478
    word16             ticketLenAlloc;    /* is dynamic */
5479
#endif /* HAVE_SESSION_TICKET */
5480
#ifdef HAVE_SNI
5481
    byte               sniHash[TICKET_BINDING_HASH_SZ];  /* SNI at issue */
5482
#endif /* HAVE_SNI */
5483
#ifdef HAVE_ALPN
5484
    byte               alpnHash[TICKET_BINDING_HASH_SZ]; /* ALPN at issue */
5485
#endif /* HAVE_ALPN */
5486
5487
#ifdef SESSION_CERTS
5488
    WOLFSSL_X509_CHAIN chain;             /* peer cert chain, static  */
5489
    #ifdef WOLFSSL_ALT_CERT_CHAINS
5490
    WOLFSSL_X509_CHAIN altChain;          /* peer alt cert chain, static */
5491
    #endif /* WOLFSSL_ALT_CERT_CHAINS */
5492
#endif
5493
#ifdef HAVE_EX_DATA
5494
    WOLFSSL_CRYPTO_EX_DATA ex_data;
5495
#endif /* HAVE_EX_DATA */
5496
#ifdef HAVE_MAX_FRAGMENT
5497
    byte               mfl; /* max fragment length negotiated i.e.
5498
                             * WOLFSSL_MFL_2_8  (6) */
5499
#endif /* HAVE_MAX_FRAGMENT */
5500
    byte               isSetup:1;
5501
#ifndef NO_WOLFSSL_SERVER
5502
    /* Client presented a certificate and proved key possession. Server
5503
     * sessions only. */
5504
    byte               peerAuthOk:1;
5505
    /* A PSK authenticated the client. Server sessions only. */
5506
    byte               isPSK:1;
5507
#endif
5508
#ifdef HAVE_SECURE_RENEGOTIATION
5509
    /* Peer certificate to hold a renegotiation of a resumption to. */
5510
    byte               scrPeerCertState;  /* enum ScrPeerCertState */
5511
    byte               scrPeerCertHash[KEYID_SIZE];
5512
#endif
5513
};
5514
5515
#if defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET) &&                  \
5516
        defined(WOLFSSL_TICKET_NONCE_MALLOC) &&                                \
5517
    (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
5518
WOLFSSL_LOCAL int SessionTicketNoncePopulate(WOLFSSL_SESSION *session,
5519
    const byte* nonce, byte len);
5520
#endif /* WOLFSSL_TLS13 &&  */
5521
5522
WOLFSSL_LOCAL int wolfSSL_RAND_Init(void);
5523
5524
WOLFSSL_LOCAL WOLFSSL_SESSION* wolfSSL_NewSession(void* heap);
5525
WOLFSSL_LOCAL WOLFSSL_SESSION* wolfSSL_GetSession(
5526
    WOLFSSL* ssl, byte* masterSecret, byte restoreSessionCerts);
5527
WOLFSSL_LOCAL void SetupSession(WOLFSSL* ssl);
5528
WOLFSSL_LOCAL void AddSession(WOLFSSL* ssl);
5529
#if !defined(NO_TLS) && defined(WOLFSSL_TLS13) && \
5530
    defined(HAVE_SESSION_TICKET) && !defined(NO_WOLFSSL_SERVER)
5531
WOLFSSL_LOCAL int SessionNewAltId(WOLFSSL* ssl);
5532
#endif
5533
#ifdef WOLFSSL_API_PREFIX_MAP
5534
    #define AddSessionToCache wolfSSL_AddSessionToCache
5535
#endif
5536
WOLFSSL_TEST_VIS int AddSessionToCache(WOLFSSL_CTX* ctx,
5537
    WOLFSSL_SESSION* addSession, const byte* id, byte idSz, int* sessionIndex,
5538
    int side, word16 useTicket, ClientSession** clientCacheEntry);
5539
#ifndef NO_CLIENT_CACHE
5540
WOLFSSL_LOCAL ClientSession* AddSessionToClientCache(int side, int row, int idx,
5541
                      byte* serverID, word16 idLen, const byte* sessionID,
5542
                      word16 useTicket, word32 cacheGen);
5543
#endif
5544
WOLFSSL_LOCAL
5545
WOLFSSL_SESSION* ClientSessionToSession(const WOLFSSL_SESSION* session);
5546
WOLFSSL_LOCAL void TlsSessionCacheUnlockRow(word32 row);
5547
WOLFSSL_LOCAL int TlsSessionCacheGetAndRdLock(const byte *id,
5548
    const WOLFSSL_SESSION **sess, word32 *lockedRow, byte side);
5549
WOLFSSL_LOCAL int TlsSessionCacheGetAndWrLock(const byte *id,
5550
    WOLFSSL_SESSION **sess, word32 *lockedRow, byte side);
5551
WOLFSSL_LOCAL void EvictSessionFromCache(WOLFSSL_SESSION* session);
5552
WOLFSSL_TEST_VIS int wolfSSL_GetSessionFromCache(WOLFSSL* ssl, WOLFSSL_SESSION* output);
5553
WOLFSSL_LOCAL int wolfSSL_GetSessionFromInternalCache(WOLFSSL* ssl,
5554
    WOLFSSL_SESSION* output);
5555
WOLFSSL_LOCAL int wolfSSL_SetSession(WOLFSSL* ssl, WOLFSSL_SESSION* session);
5556
WOLFSSL_LOCAL void wolfSSL_FreeSession(WOLFSSL_CTX* ctx,
5557
        WOLFSSL_SESSION* session);
5558
WOLFSSL_LOCAL int wolfSSL_DupSession(const WOLFSSL_SESSION* input,
5559
        WOLFSSL_SESSION* output, int avoidSysCalls);
5560
5561
5562
typedef int (*hmacfp) (WOLFSSL*, byte*, const byte*, word32, int, int, int, int);
5563
5564
#ifndef NO_CLIENT_CACHE
5565
    WOLFSSL_LOCAL WOLFSSL_SESSION* wolfSSL_GetSessionClient(
5566
        WOLFSSL* ssl, const byte* id, int len);
5567
#endif
5568
5569
/* client connect state for nonblocking restart */
5570
enum ConnectState {
5571
    CONNECT_BEGIN = 0,
5572
    CLIENT_HELLO_SENT,
5573
    HELLO_AGAIN,               /* HELLO_AGAIN s for DTLS case */
5574
    HELLO_AGAIN_REPLY,
5575
    FIRST_REPLY_DONE,
5576
    FIRST_REPLY_FIRST,
5577
    FIRST_REPLY_SECOND,
5578
    FIRST_REPLY_THIRD,
5579
    FIRST_REPLY_FOURTH,
5580
    FINISHED_DONE,
5581
    SECOND_REPLY_DONE,
5582
5583
#ifdef WOLFSSL_DTLS13
5584
    WAIT_FINISHED_ACK
5585
#endif /* WOLFSSL_DTLS13 */
5586
5587
};
5588
5589
5590
/* server accept state for nonblocking restart */
5591
enum AcceptState {
5592
    ACCEPT_BEGIN = 0,
5593
    ACCEPT_BEGIN_RENEG,
5594
    ACCEPT_CLIENT_HELLO_DONE,
5595
    ACCEPT_HELLO_RETRY_REQUEST_DONE,
5596
    ACCEPT_FIRST_REPLY_DONE,
5597
    SERVER_HELLO_SENT,
5598
    CERT_SENT,
5599
    CERT_VERIFY_SENT,
5600
    CERT_STATUS_SENT,
5601
    KEY_EXCHANGE_SENT,
5602
    CERT_REQ_SENT,
5603
    SERVER_HELLO_DONE,
5604
    ACCEPT_SECOND_REPLY_DONE,
5605
    TICKET_SENT,
5606
    CHANGE_CIPHER_SENT,
5607
    ACCEPT_FINISHED_DONE,
5608
    ACCEPT_THIRD_REPLY_DONE
5609
};
5610
5611
/* TLS 1.3 server accept state for nonblocking restart */
5612
enum AcceptStateTls13 {
5613
    TLS13_ACCEPT_BEGIN = 0,
5614
    TLS13_ACCEPT_BEGIN_RENEG,
5615
    TLS13_ACCEPT_CLIENT_HELLO_DONE,
5616
    TLS13_ACCEPT_HELLO_RETRY_REQUEST_DONE,
5617
    TLS13_ACCEPT_FIRST_REPLY_DONE,
5618
    TLS13_ACCEPT_SECOND_REPLY_DONE,
5619
    TLS13_SERVER_HELLO_SENT,
5620
    TLS13_ACCEPT_THIRD_REPLY_DONE,
5621
    TLS13_SERVER_EXTENSIONS_SENT,
5622
    TLS13_CERT_REQ_SENT,
5623
    TLS13_CERT_SENT,
5624
    TLS13_CERT_VERIFY_SENT,
5625
    TLS13_ACCEPT_FINISHED_SENT,
5626
    TLS13_PRE_TICKET_SENT,
5627
    TLS13_ACCEPT_FINISHED_DONE,
5628
    TLS13_TICKET_SENT
5629
};
5630
5631
#ifdef WOLFSSL_THREADED_CRYPT
5632
5633
#include <pthread.h>
5634
5635
typedef struct ThreadCrypt {
5636
    Ciphers encrypt;
5637
    bufferStatic buffer;
5638
    unsigned char nonce[AESGCM_NONCE_SZ];
5639
    unsigned char additional[AEAD_AUTH_DATA_SZ];
5640
    int init;
5641
    int offset;
5642
    int cryptLen;
5643
    int done;
5644
    int avail;
5645
    int stop;
5646
    WOLFSSL_THREAD_SIGNAL signal;
5647
    void*                 signalCtx;
5648
} ThreadCrypt;
5649
5650
#endif
5651
5652
/* Streamed TLS 1.3 CertificateVerify send. When the CertificateVerify body
5653
 * (the signature) does not fit in a single record - a post-quantum signature
5654
 * such as SLH-DSA or ML-DSA, or any signature under a small
5655
 * max_fragment_length - it is generated once into a connection-level buffer and
5656
 * emitted one record at a time, so the output buffer never has to hold the
5657
 * whole signature. The assembled body must be held at the connection level
5658
 * (not on the stack) because these signatures are randomized: a non-blocking
5659
 * WANT_WRITE can return control mid-send, and the records already sent are
5660
 * bound into the transcript, so the resumed send must continue emitting the
5661
 * exact same signature - it cannot be regenerated. This is algorithm-neutral;
5662
 * it applies to any signature scheme whose CertificateVerify can exceed a
5663
 * record. It is not used with WOLFSSL_ASYNC_CRYPT, whose record-AEAD pends are
5664
 * handled by the existing in-place fragmented path. */
5665
#if defined(WOLFSSL_TLS13) && !defined(WOLFSSL_ASYNC_CRYPT) && \
5666
    (defined(WOLFSSL_HAVE_SLHDSA) || defined(WOLFSSL_HAVE_MLDSA) || \
5667
     defined(HAVE_FALCON))
5668
    #define WOLFSSL_TLS13_STREAM_CERT_VERIFY
5669
#endif
5670
5671
/* buffers for struct WOLFSSL */
5672
typedef struct Buffers {
5673
    bufferStatic    inputBuffer;
5674
    bufferStatic    outputBuffer;
5675
#ifdef WOLFSSL_THREADED_CRYPT
5676
    ThreadCrypt     encrypt[WOLFSSL_THREADED_CRYPT_CNT];
5677
#endif
5678
    buffer          domainName;            /* for client check */
5679
    buffer          ipasc;                 /* for client IP SAN check */
5680
    buffer          clearOutputBuffer;
5681
    buffer          sig;                   /* signature data */
5682
    buffer          digest;                /* digest data */
5683
    word32          prevSent;              /* previous plain text bytes sent
5684
                                              when got WANT_WRITE            */
5685
    word32          plainSz;               /* plain text bytes in buffer to send
5686
                                              when got WANT_WRITE            */
5687
    byte            weOwnCert;             /* SSL own cert flag */
5688
    byte            weOwnCertChain;        /* SSL own cert chain flag */
5689
    byte            weOwnKey;              /* SSL own key flag */
5690
#ifdef WOLFSSL_DUAL_ALG_CERTS
5691
    byte            weOwnAltKey;           /* SSL own alt key flag */
5692
#endif
5693
    byte            weOwnDH;               /* SSL own dh (p,g)  flag */
5694
#ifndef NO_DH
5695
    /* SSL owns p and g when weOwnDH is set. Otherwise they point at the
5696
     * static parameters of a named group, which nothing owns. */
5697
    buffer          serverDH_P;
5698
    buffer          serverDH_G;
5699
    buffer          serverDH_Pub;
5700
    buffer          serverDH_Priv;
5701
    DhKey*          serverDH_Key;
5702
#endif
5703
#ifndef NO_CERTS
5704
    DerBuffer*      certificate;           /* WOLFSSL_CTX owns, unless we own */
5705
    DerBuffer*      key;                   /* WOLFSSL_CTX owns, unless we own */
5706
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
5707
    DerBuffer*      keyMask;               /* Mask of private key DER. */
5708
#endif
5709
    byte            keyType;               /* Type of key */
5710
    byte            keyId:1;               /* Key data is an id not data */
5711
    byte            keyLabel:1;            /* Key data is a label not data */
5712
    int             keySz;                 /* Size of RSA key */
5713
    int             keyDevId;              /* Device Id for key */
5714
#ifdef WOLFSSL_DUAL_ALG_CERTS
5715
    DerBuffer*      altKey;                /* WOLFSSL_CTX owns, unless we own */
5716
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
5717
    DerBuffer*      altKeyMask;            /* Mask of alt private key DER. */
5718
#endif
5719
    byte            altKeyType;            /* Type of alt key */
5720
    byte            altKeyId:1;            /* Key data is an id not data */
5721
    byte            altKeyLabel:1;         /* Key data is a label not data */
5722
    int             altKeySz;              /* Size of alt key */
5723
    int             altKeyDevId;           /* Device Id for alt key */
5724
#endif
5725
    DerBuffer*      certChain;             /* WOLFSSL_CTX owns, unless we own */
5726
                 /* chain after self, in DER, with leading size for each cert */
5727
    int             certChainCnt;
5728
#ifdef WOLFSSL_TLS13
5729
    DerBuffer*      certExts[MAX_CERT_EXTENSIONS];
5730
#endif
5731
#endif
5732
#ifdef WOLFSSL_SEND_HRR_COOKIE
5733
    buffer          tls13CookieSecret;     /* HRR cookie secret */
5734
    /* Secondary HRR cookie secret, used only when verifying a cookie if the
5735
     * primary secret fails.  Lets a stateless DTLS 1.3 server keep accepting
5736
     * cookies issued under the secret it had before an application-driven
5737
     * rotation.  DTLS only - never used to issue cookies. */
5738
    buffer          tls13CookieSecretSecondary;
5739
#endif
5740
#ifdef WOLFSSL_DTLS
5741
    WOLFSSL_DTLS_CTX dtlsCtx;              /* DTLS connection context */
5742
    #ifndef NO_WOLFSSL_SERVER
5743
        buffer       dtlsCookieSecret;     /* DTLS cookie secret */
5744
        /* Secondary DTLS 1.2 cookie secret, used only when verifying a
5745
         * received HelloVerifyRequest cookie if the primary secret fails.
5746
         * Lets a stateless server keep accepting cookies issued under the
5747
         * secret it had before an application-driven rotation.  Never used to
5748
         * issue cookies. */
5749
        buffer       dtlsCookieSecretSecondary;
5750
    #endif /* NO_WOLFSSL_SERVER */
5751
#endif
5752
#ifdef HAVE_PK_CALLBACKS
5753
    #ifdef HAVE_ECC
5754
        buffer peerEccDsaKey;              /* we own for Ecc Verify Callbacks */
5755
    #endif /* HAVE_ECC */
5756
    #ifdef HAVE_ED25519
5757
        buffer peerEd25519Key;             /* for Ed25519 Verify Callbacks */
5758
    #endif /* HAVE_ED25519 */
5759
    #ifdef HAVE_ED448
5760
        buffer peerEd448Key;             /* for Ed448 Verify Callbacks */
5761
    #endif /* HAVE_ED448 */
5762
    #ifndef NO_RSA
5763
        buffer peerRsaKey;                 /* we own for Rsa Verify Callbacks */
5764
    #endif /* NO_RSA */
5765
#endif /* HAVE_PK_CALLBACKS */
5766
#ifdef WOLFSSL_TLS13_STREAM_CERT_VERIFY
5767
    /* Assembled TLS 1.3 CertificateVerify body (sig-alg | length | signature)
5768
     * held across records while it is streamed, so a non-blocking WANT_WRITE
5769
     * can resume the send without recomputing the signature. NULL when idle;
5770
     * freed by wolfSSL_ResourceFree. See WOLFSSL_TLS13_STREAM_CERT_VERIFY. */
5771
    buffer          certVerifyMsg;
5772
#endif
5773
#ifdef HAVE_LIBZ
5774
    /* Plaintext of the application data record currently being decompressed.
5775
     * A compressed fragment expands to as much as MAX_RECORD_SIZE, so the
5776
     * result must not be written back over the record it came from: the input
5777
     * buffer is only sized for the wire (compressed) record and may already
5778
     * hold the records queued behind it.  Allocated on the first compressed
5779
     * record received, length is its fixed capacity, released by
5780
     * wolfSSL_ResourceFree(). */
5781
    buffer          decompBuffer;
5782
#endif
5783
} Buffers;
5784
5785
#ifndef NO_DH
5786
/* Give the SSL object its own copy of the context's DH parameters. They are
5787
 * not reference counted, so a session must not point at the context's. */
5788
WOLFSSL_LOCAL int CopySSL_CTX_DhParams(WOLFSSL* ssl, WOLFSSL_CTX* ctx);
5789
#endif
5790
#ifndef NO_CERTS
5791
WOLFSSL_LOCAL int SetSSL_CTX_CertsAndKeys(WOLFSSL* ssl, WOLFSSL_CTX* ctx);
5792
#endif
5793
#if !defined(NO_CERTS) && \
5794
    (defined(HAVE_SNI) || defined(WOLFSSL_CERT_SETUP_CB))
5795
#ifdef WOLFSSL_API_PREFIX_MAP
5796
    #define CheckSSL_CTX_CertsAndKeys wolfSSL_CheckSSL_CTX_CertsAndKeys
5797
#endif
5798
WOLFSSL_TEST_VIS int CheckSSL_CTX_CertsAndKeys(const WOLFSSL* ssl);
5799
#endif
5800
5801
/* sub-states for send/do key share (key exchange) */
5802
enum asyncState {
5803
    TLS_ASYNC_BEGIN = 0,
5804
    TLS_ASYNC_BUILD,
5805
    TLS_ASYNC_DO,
5806
    TLS_ASYNC_VERIFY,
5807
    TLS_ASYNC_FINALIZE,
5808
    TLS_ASYNC_END
5809
};
5810
5811
/* Handshake message processing can suspend part way through and resume when
5812
 * the application re-enters wolfSSL_connect()/wolfSSL_accept(). State for the
5813
 * message in flight is held in ssl->async. */
5814
#if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLFSSL_NONBLOCK_OCSP) || \
5815
    defined(WOLFSSL_CHAIN_VERIFY_CB)
5816
    #undef  WOLFSSL_HAVE_HS_SUSPEND
5817
    #define WOLFSSL_HAVE_HS_SUSPEND
5818
#endif
5819
5820
#ifdef WOLFSSL_HAVE_HS_SUSPEND
5821
/* True for error codes that suspend handshake processing instead of failing
5822
 * it. Only the codes whose feature is compiled in are recognized. */
5823
WOLFSSL_LOCAL int IsHsSuspendErr(int err);
5824
#endif
5825
5826
#ifdef WOLFSSL_CHAIN_VERIFY_CB
5827
/* Non-zero when the context or object is configured for something the chain
5828
 * verify callback does not support. */
5829
WOLFSSL_LOCAL int ChainVerifyCbCheckCtx(const WOLFSSL_CTX* ctx);
5830
WOLFSSL_LOCAL int ChainVerifyCbCheckSsl(const WOLFSSL* ssl);
5831
#endif
5832
5833
/* sub-states for build message */
5834
enum buildMsgState {
5835
    BUILD_MSG_BEGIN = 0,
5836
    BUILD_MSG_SIZE,
5837
    BUILD_MSG_HASH,
5838
    BUILD_MSG_VERIFY_MAC,
5839
    BUILD_MSG_ENCRYPT,
5840
    BUILD_MSG_ENCRYPTED_VERIFY_MAC
5841
};
5842
5843
/* sub-states for cipher operations */
5844
enum cipherState {
5845
    CIPHER_STATE_BEGIN = 0,
5846
    CIPHER_STATE_DO,
5847
    CIPHER_STATE_END
5848
};
5849
5850
struct Options {
5851
#ifndef NO_PSK
5852
    wc_psk_client_callback client_psk_cb;
5853
    wc_psk_server_callback server_psk_cb;
5854
#ifdef OPENSSL_EXTRA
5855
    wc_psk_use_session_cb_func session_psk_cb;
5856
#endif
5857
#ifdef WOLFSSL_TLS13
5858
    wc_psk_client_cs_callback    client_psk_cs_cb;     /* client callback */
5859
    wc_psk_client_tls13_callback client_psk_tls13_cb;  /* client callback */
5860
    wc_psk_server_tls13_callback server_psk_tls13_cb;  /* server callback */
5861
#endif
5862
    void*             psk_ctx;
5863
#endif /* NO_PSK */
5864
    unsigned long     mask; /* store SSL_OP_ flags */
5865
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || defined(WOLFSSL_WPAS_SMALL)
5866
    word16            minProto:1; /* sets min to min available */
5867
    word16            maxProto:1; /* sets max to max available */
5868
#endif
5869
#if defined(HAVE_SESSION_TICKET) && defined(WOLFSSL_TLS13)
5870
    unsigned int      maxTicketTls13;  /* maximum number of tickets to send */
5871
    unsigned int      ticketsSent;     /* keep track of the total sent */
5872
#if !defined(NO_WOLFSSL_SERVER) && \
5873
    defined(WOLFSSL_TLS13_TICKET_CHECK_PSK_MODES)
5874
    byte              pskKeModes;      /* modes client advertised in CH */
5875
#endif
5876
#endif
5877
5878
    /* on/off or small bit flags, optimize layout */
5879
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
5880
    word16            havePSK:1;            /* psk key set by user */
5881
#endif /* HAVE_SESSION_TICKET || !NO_PSK */
5882
    word16            sendVerify:2;     /* false = 0, true = 1, sendBlank = 2 */
5883
    word16            sessionCacheOff:1;
5884
    word16            sessionCacheFlushOff:1;
5885
#ifdef HAVE_EXT_CACHE
5886
    word16            internalCacheOff:1;
5887
    word16            internalCacheLookupOff:1;
5888
#endif
5889
    word16            side:2;             /* client, server or neither end */
5890
    word16            verifyPeer:1;
5891
    word16            verifyNone:1;
5892
    word16            failNoCert:1;
5893
    word16            failNoCertxPSK:1;   /* fail for no cert except with PSK */
5894
    word16            failNoPSK:1;        /* fail if no PSK is negotiated */
5895
    word16            downgrade:1;        /* allow downgrade of versions */
5896
    word16            versionSet:1;       /* max version set by SetVersion */
5897
    word16            minVersionSet:1;    /* min version set by SetMinVersion */
5898
    word16            resuming:1;
5899
#ifdef HAVE_SECURE_RENEGOTIATION
5900
    word16            resumed:1;          /* resuming may be reset on SCR */
5901
#endif
5902
    word16            haveSessionId:1;    /* server may not send */
5903
    word16            tls:1;              /* using TLS ? */
5904
    word16            tls1_1:1;           /* using TLSv1.1+ ? */
5905
    word16            tls1_3:1;           /* using TLSv1.3+ ? */
5906
    word16            dtls:1;             /* using datagrams ? */
5907
#ifdef WOLFSSL_DTLS
5908
    word16            dtlsStateful:1;     /* allow stateful processing ? */
5909
#endif
5910
    word16            connReset:1;        /* has the peer reset */
5911
    word16            isClosed:1;         /* if we consider conn closed */
5912
    word16            fatalAlert:1;       /* fatal alert sent or received */
5913
    word16            closeNotify:1;      /* we've received a close notify */
5914
    word16            sentNotify:1;       /* we've sent a close notify */
5915
    word16            usingCompression:1; /* are we using compression */
5916
    word16            haveRSA:1;          /* RSA available */
5917
    word16            haveECC:1;          /* ECC available */
5918
    word16            haveDH:1;           /* server DH params set by user */
5919
    word16            haveECDSAsig:1;     /* server ECDSA signed cert */
5920
    word16            haveStaticECC:1;    /* static server ECC private key */
5921
    word16            haveFalconSig:1;    /* server Falcon signed cert */
5922
    word16            haveMlDsaSig:1;     /* server ML-DSA signed cert */
5923
    word16            haveSlhDsaSig:1;    /* server SLH-DSA signed cert */
5924
    word16            havePeerCert:1;     /* do we have peer's cert */
5925
    word16            havePeerVerify:1;   /* and peer's cert verify */
5926
    word16            usingPSK_cipher:1;  /* are using psk as cipher */
5927
    word16            usingAnon_cipher:1; /* are we using an anon cipher */
5928
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
5929
    word16            noPskDheKe:1;       /* Don't use (EC)DHE with PSK */
5930
    /* noPskDheKe doubles as negotiated state - it is set when psk_ke is chosen
5931
     * and cleared on every certificate handshake. Decisions that must follow
5932
     * what the application configured use this copy, which is only written by
5933
     * the configuration APIs. */
5934
    word16            noPskDheKePolicy:1; /* Configured no (EC)DHE with PSK */
5935
#ifdef HAVE_SUPPORTED_CURVES
5936
    word16            onlyPskDheKe:1;     /* Only use (EC)DHE with PSK */
5937
#endif
5938
#if defined(WOLFSSL_CERT_WITH_EXTERN_PSK)
5939
    word16            certWithExternPsk:1; /* Cert auth with external PSK */
5940
#endif
5941
#endif
5942
    word16            partialWrite:1;     /* only one msg per write call */
5943
    word16            quietShutdown:1;    /* don't send close notify */
5944
    word16            quietShutdownRestore:1; /* wolfSSL_SendUserCanceled()
5945
                                           * turned quietShutdown off until
5946
                                           * its close_notify is flushed */
5947
    word16            certOnly:1;         /* stop once we get cert */
5948
    word16            groupMessages:1;    /* group handshake messages */
5949
    word16            saveArrays:1;       /* save array Memory for user get keys
5950
                                           or psk */
5951
    word16            weOwnRng:1;         /* will be true unless CTX owns */
5952
    word16            dontFreeDigest:1;   /* when true, we used SetDigest */
5953
    word16            haveEMS:1;          /* using extended master secret */
5954
#ifdef HAVE_EXTENDED_MASTER
5955
    word16            disableEMS:1;       /* user disabled extended master
5956
                                           * secret */
5957
    word16            requireEMS:1;       /* user requires extended master
5958
                                           * secret */
5959
#endif
5960
#ifdef HAVE_POLY1305
5961
    word16            oldPoly:1;        /* set when to use old rfc way of poly*/
5962
#endif
5963
    word16            useAnon:1;       /* User wants to allow Anon suites */
5964
#ifdef HAVE_SESSION_TICKET
5965
    word16            createTicket:1;     /* Server to create new Ticket */
5966
    word16            useTicket:1;        /* Use Ticket not session cache */
5967
    word16            rejectTicket:1;     /* Callback rejected ticket */
5968
    word16            noTicketTls12:1;    /* TLS 1.2 server won't send ticket */
5969
#ifdef WOLFSSL_TLS13
5970
    word16            noTicketTls13:1;    /* Server won't create new Ticket */
5971
#ifdef WOLFSSL_EARLY_DATA
5972
    word16            ticketPredatesCtx:1; /* PSK ticket minted before ctx */
5973
#ifndef NO_SESSION_CACHE
5974
    word16            ticketCacheHit:1;   /* Ticket's session was cached */
5975
#endif
5976
#endif
5977
#if !defined(NO_WOLFSSL_SERVER) && \
5978
    defined(WOLFSSL_TLS13_TICKET_CHECK_PSK_MODES)
5979
    word16            pskKeModesRecvd:1;  /* CH had psk_key_exchange_modes */
5980
#endif
5981
#endif
5982
#endif
5983
#ifdef WOLFSSL_DTLS
5984
#ifdef HAVE_SECURE_RENEGOTIATION
5985
    word16            dtlsDoSCR:1;        /* Enough packets were dropped. We
5986
                                           * need to re-key. */
5987
#endif
5988
    word16            dtlsUseNonblock:1;  /* are we using nonblocking socket */
5989
    word16            dtlsHsRetain:1;     /* DTLS retaining HS data */
5990
#ifdef WOLFSSL_SCTP
5991
    word16            dtlsSctp:1;         /* DTLS-over-SCTP mode */
5992
#endif
5993
#endif /* WOLFSSL_DTLS */
5994
#if defined(HAVE_TLS_EXTENSIONS) && defined(HAVE_SUPPORTED_CURVES)
5995
    word16            userCurves:1;       /* indicates user called wolfSSL_UseSupportedCurve */
5996
    word16            peerNoUncompPF:1;   /* peer sent ec_point_formats without
5997
                                           * the uncompressed (0) format */
5998
#endif
5999
    word16            keepResources:1;    /* Keep resources after handshake */
6000
    word16            useClientOrder:1;   /* Use client's cipher order */
6001
    word16            mutualAuth:1;       /* Mutual authentication is required */
6002
    word16            peerAuthGood:1;     /* Any required peer auth done */
6003
#if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
6004
    word16            pskNegotiated:1;    /* Session Ticket/PSK negotiated. */
6005
#endif
6006
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
6007
    word16            postHandshakeAuth:1;/* Client send post_handshake_auth
6008
                                           * extension */
6009
    word16            verifyPostHandshake:1; /* Only send client cert req post
6010
                                              * handshake, not also during */
6011
#endif
6012
#if (defined(WOLFSSL_TLS13) || defined(WOLFSSL_DTLS)) && \
6013
    !defined(NO_WOLFSSL_SERVER)
6014
    word16            sendCookie:1;       /* DTLS cookies / TLS 1.3 HRR cookie */
6015
#endif
6016
#ifdef WOLFSSL_ALT_CERT_CHAINS
6017
    word16            usingAltCertChain:1;/* Alternate cert chain was used */
6018
#endif
6019
#ifdef WOLFSSL_TLS13
6020
    word16            sentChangeCipher:1; /* Change Cipher Spec sent */
6021
#endif
6022
#if !defined(WOLFSSL_NO_CLIENT_AUTH) && \
6023
               ((defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)) || \
6024
                (defined(HAVE_ED25519) && !defined(NO_ED25519_CLIENT_AUTH)) || \
6025
                (defined(HAVE_ED448) && !defined(NO_ED448_CLIENT_AUTH)))
6026
    word16            cacheMessages:1;    /* Cache messages for sign/verify */
6027
#endif
6028
#ifndef NO_DH
6029
    #if !defined(WOLFSSL_OLD_PRIME_CHECK) && \
6030
        !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)
6031
        word16        dhDoKeyTest:1;      /* Need to do the DH Key prime test */
6032
        word16        dhKeyTested:1;      /* Set when key has been tested. */
6033
    #endif
6034
#endif
6035
#ifdef HAVE_ENCRYPT_THEN_MAC
6036
    word16            disallowEncThenMac:1;   /* Don't do Encrypt-Then-MAC */
6037
    word16            encThenMac:1;           /* Doing Encrypt-Then-MAC */
6038
    word16            startedETMRead:1;       /* Doing Encrypt-Then-MAC read */
6039
    word16            startedETMWrite:1;      /* Doing Encrypt-Then-MAC write */
6040
#endif
6041
#ifdef WOLFSSL_ASYNC_CRYPT
6042
    word16            buildArgsSet:1;         /* buildArgs are set and need to
6043
                                               * be free'd */
6044
#ifdef WOLFSSL_TLS13
6045
    word16            buildArgs13Set:1;       /* a TLS 1.3 record build is in
6046
                                               * progress and must resume,
6047
                                               * not restart */
6048
    word16            chHashInput:1;          /* current ClientHello already
6049
                                               * hashed into the transcript;
6050
                                               * a PSK-binder pend must not
6051
                                               * re-hash it on resume */
6052
    word16            asyncReplayMsg:1;       /* the next TLS 1.3 handshake
6053
                                               * message is a replay of one
6054
                                               * whose handler pended; skip
6055
                                               * its sanity check once */
6056
#endif
6057
#endif
6058
#ifdef WOLFSSL_DTLS13
6059
    word16            dtls13SendMoreAcks:1;  /* Send more acks during the
6060
                                              * handshake process */
6061
#ifdef WOLFSSL_DTLS13_NO_HRR_ON_RESUME
6062
    word16            dtls13NoHrrOnResume:1;
6063
#endif
6064
#ifdef WOLFSSL_DTLS_CH_FRAG
6065
    word16            dtls13ChFrag:1;
6066
#endif
6067
#endif
6068
#ifdef WOLFSSL_TLS13
6069
    word16            tls13MiddleBoxCompat:1; /* TLSv1.3 middlebox compatibility */
6070
#endif
6071
#ifdef WOLFSSL_DTLS_CID
6072
    word16            useDtlsCID:1;
6073
#ifdef WOLFSSL_DTLS13
6074
    word16            haveSupportedVersions:1; /* Current Hello's version
6075
                                                * pre-scan succeeded and found
6076
                                                * supported_versions. */
6077
#endif
6078
#endif /* WOLFSSL_DTLS_CID */
6079
#if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
6080
    word16            echAccepted:1;
6081
    word16            disableECH:1;             /* Did the user disable ech */
6082
    word16            echProcessingInner:1;     /* Processing the inner hello */
6083
    word16            echRetryConfigsAccepted:1;
6084
    word16            enableEchTrialDecrypt:1;  /* Trial decryption of the
6085
                                                   inner hello */
6086
#endif
6087
#ifdef WOLFSSL_SEND_HRR_COOKIE
6088
    word16            cookieGood:1;
6089
#endif
6090
#ifdef WOLFSSL_TLS13
6091
#ifdef WOLFSSL_TLS13_COOKIE
6092
    word16            hrrSentCookie:1;    /* HRR sent with cookie */
6093
#endif
6094
    word16            hrrSentKeyShare:1;  /* HRR sent with key share */
6095
    word16            shSentKeyShare:1;   /* SH sent with key share */
6096
#endif
6097
    word16            returnOnGoodCh:1;
6098
    word16            disableRead:1;
6099
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WOLFSSL_ASYNC_CERT_YIELD)
6100
    /* Opt-in (WOLFSSL_ASYNC_CERT_YIELD): set when we deliberately returned
6101
     * WC_PENDING_E between peer certificate verifies so a cooperative scheduler
6102
     * can run. Lives in (zero-initialized, persistent) ssl->options so the
6103
     * fresh-entry vs. resume decision in ProcessPeerCerts is reliable; the
6104
     * transient ProcPeerCertArgs scratch buffer is not zeroed on alloc. */
6105
    word16            certYieldPending:1;
6106
#endif
6107
6108
#ifdef WOLFSSL_EARLY_DATA
6109
    word16            clientInEarlyData:1; /* Client is in wolfSSL_read_early_data */
6110
#endif
6111
#if defined(WOLFSSL_TLS13) && !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
6112
    word16            peerSha1CertOk:1;   /* Peer advertised a SHA-1 signature
6113
                                           * scheme for certificates */
6114
#endif
6115
#ifdef WOLFSSL_DTLS
6116
    byte              haveMcast;          /* using multicast ? */
6117
#endif
6118
    byte              buildingMsg;        /* If set then we need to re-enter the
6119
                                           * handshake logic. */
6120
    byte              seenUnifiedHdr;     /* received msg with unified header */
6121
    byte              shutdownDone;       /* we've completed a shutdown */
6122
    byte              sendKeyUpdate;      /* Key Update to write */
6123
#if defined(HAVE_RPK)
6124
    RpkConfig         rpkConfig;
6125
    RpkState          rpkState;
6126
#endif /* HAVE_RPK */
6127
6128
    /* need full byte values for this section */
6129
    byte            processReply;           /* nonblocking resume */
6130
    byte            cipherSuite0;           /* first byte, normally 0 */
6131
    byte            cipherSuite;            /* second byte, actual suite */
6132
#ifdef WOLFSSL_TLS13
6133
    byte            hrrCipherSuite0;        /* first byte, normally 0 */
6134
    byte            hrrCipherSuite;         /* second byte, actual suite */
6135
#endif
6136
    byte            hashAlgo;               /* selected hash algorithm */
6137
    byte            sigAlgo;                /* selected sig algorithm */
6138
    byte            peerHashAlgo;           /* peer's chosen hash algo */
6139
    byte            peerSigAlgo;            /* peer's chosen sig algo */
6140
    byte            serverState;
6141
    byte            clientState;
6142
    byte            handShakeState;
6143
    byte            handShakeDone;      /* at least one handshake complete */
6144
    byte            minDowngrade;       /* minimum downgrade version */
6145
    byte            maxVersionMinor;    /* maximum set by SetVersion. Version
6146
                                         * negotiation does not change it. */
6147
    byte            connectState;       /* nonblocking resume */
6148
    byte            acceptState;        /* nonblocking resume */
6149
    byte            asyncState;         /* sub-state for enum asyncState */
6150
    byte            buildMsgState;      /* sub-state for enum buildMsgState */
6151
    byte            alertCount;         /* detect warning dos attempt */
6152
    byte            emptyRecordCount;   /* detect empty record dos attempt */
6153
#ifdef WOLFSSL_TLS13
6154
    byte            ccsIgnoredCount;    /* detect TLS 1.3 CCS dos attempt */
6155
#endif
6156
#ifdef WOLFSSL_MULTICAST
6157
    word16          mcastID;            /* Multicast group ID */
6158
#endif
6159
#ifndef NO_DH
6160
    word16          minDhKeySz;         /* minimum DH key size */
6161
    word16          maxDhKeySz;         /* minimum DH key size */
6162
    word16          dhKeySz;            /* actual DH key size */
6163
#endif
6164
#ifndef NO_RSA
6165
    short           minRsaKeySz;      /* minimum RSA key size */
6166
#endif
6167
#if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
6168
    short           minEccKeySz;      /* minimum ECC key size */
6169
#endif
6170
#if defined(HAVE_FALCON)
6171
    short           minFalconKeySz;   /* minimum Falcon key size */
6172
#endif
6173
#if defined(WOLFSSL_HAVE_MLDSA)
6174
    short           minMlDsaKeySz;    /* minimum ML-DSA key size */
6175
#endif
6176
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
6177
    byte            verifyDepth;      /* maximum verification depth */
6178
#endif
6179
#ifdef WOLFSSL_EARLY_DATA
6180
    word16          pskIdIndex;
6181
    word32          maxEarlyDataSz;
6182
#endif
6183
#ifdef WOLFSSL_TLS13
6184
    byte            oldMinor;          /* client preferred version < TLS 1.3 */
6185
#endif
6186
};
6187
6188
typedef struct Arrays {
6189
    /* In the struct, not a second allocation, so nothing tracks or frees
6190
     * it separately. */
6191
    byte            preMasterSecret[MAX_PREMASTER_SZ];
6192
    word32          preMasterSz;        /* differs for DH, actual size */
6193
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
6194
    word32          psk_keySz;          /* actual size */
6195
    char            client_identity[MAX_PSK_ID_LEN + NULL_TERM_LEN];
6196
    char            server_hint[MAX_PSK_ID_LEN + NULL_TERM_LEN];
6197
    byte            psk_key[MAX_PSK_KEY_LEN];
6198
#endif
6199
    byte            clientRandom[RAN_LEN];
6200
#if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
6201
    byte            clientRandomInner[RAN_LEN];
6202
#endif
6203
    byte            serverRandom[RAN_LEN];
6204
    byte            sessionID[ID_LEN];
6205
    byte            sessionIDSz;
6206
#ifdef WOLFSSL_TLS13
6207
    byte            secret[SECRET_LEN];
6208
#endif
6209
#ifdef HAVE_KEYING_MATERIAL
6210
    byte            exporterSecret[WC_MAX_DIGEST_SIZE];
6211
#endif
6212
    byte            masterSecret[SECRET_LEN];
6213
#if defined(WOLFSSL_RENESAS_TSIP_TLS) && \
6214
   !defined(NO_WOLFSSL_RENESAS_TSIP_TLS_SESSION)
6215
    byte            tsip_masterSecret[TSIP_TLS_MASTERSECRET_SIZE];
6216
#endif
6217
#if defined(WOLFSSL_RENESAS_FSPSM_TLS)
6218
    byte            fspsm_masterSecret[FSPSM_TLS_MASTERSECRET_SIZE];
6219
#endif
6220
#ifdef WOLFSSL_DTLS
6221
    byte            cookie[MAX_COOKIE_LEN];
6222
    byte            cookieSz;
6223
#endif
6224
} Arrays;
6225
6226
#ifndef ASN_NAME_MAX
6227
    #ifndef NO_ASN
6228
        /* use value from asn.h */
6229
0
        #define ASN_NAME_MAX WC_ASN_NAME_MAX
6230
    #else
6231
        /* calculate for WOLFSSL_X509 */
6232
        #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
6233
            defined(WOLFSSL_CERT_EXT)
6234
            #define ASN_NAME_MAX 330
6235
        #else
6236
            #define ASN_NAME_MAX 256
6237
        #endif
6238
    #endif
6239
#endif
6240
6241
typedef enum {
6242
    STACK_TYPE_X509               = 0,
6243
    STACK_TYPE_GEN_NAME           = 1,
6244
    STACK_TYPE_BIO                = 2,
6245
    STACK_TYPE_OBJ                = 3,
6246
    STACK_TYPE_STRING             = 4,
6247
    STACK_TYPE_CIPHER             = 5,
6248
    STACK_TYPE_ACCESS_DESCRIPTION = 6,
6249
    STACK_TYPE_X509_EXT           = 7,
6250
    STACK_TYPE_NULL               = 8,
6251
    STACK_TYPE_X509_NAME          = 9,
6252
    STACK_TYPE_CONF_VALUE         = 10,
6253
    STACK_TYPE_X509_INFO          = 11,
6254
    STACK_TYPE_BY_DIR_entry       = 12,
6255
    STACK_TYPE_BY_DIR_hash        = 13,
6256
    STACK_TYPE_X509_OBJ           = 14,
6257
    STACK_TYPE_DIST_POINT         = 15,
6258
    STACK_TYPE_X509_CRL           = 16,
6259
    STACK_TYPE_X509_NAME_ENTRY    = 17,
6260
    STACK_TYPE_X509_REQ_ATTR      = 18,
6261
    STACK_TYPE_GENERAL_SUBTREE    = 19,
6262
    STACK_TYPE_X509_REVOKED       = 20
6263
} WOLF_STACK_TYPE;
6264
6265
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
6266
6267
struct WOLFSSL_STACK {
6268
    unsigned long num; /* number of nodes in stack
6269
                        * (safety measure for freeing and shortcut for count) */
6270
    #if defined(OPENSSL_ALL)
6271
    wolf_sk_hash_cb hash_fn;
6272
    unsigned long hash;
6273
    #endif
6274
6275
    union {
6276
        WOLFSSL_X509*          x509;
6277
        WOLFSSL_X509_NAME*     name;
6278
        WOLFSSL_X509_NAME_ENTRY* name_entry;
6279
        WOLFSSL_X509_INFO*     info;
6280
        WOLFSSL_BIO*           bio;
6281
        WOLFSSL_ASN1_OBJECT*   obj;
6282
        WOLFSSL_CIPHER         cipher;
6283
        WOLFSSL_ACCESS_DESCRIPTION* access;
6284
        WOLFSSL_X509_EXTENSION* ext;
6285
#ifdef OPENSSL_EXTRA
6286
        WOLFSSL_CONF_VALUE*    conf;
6287
#endif
6288
        void*                  generic;
6289
        char*                  string;
6290
        WOLFSSL_GENERAL_NAME*  gn;
6291
        WOLFSSL_GENERAL_SUBTREE* subtree;
6292
        WOLFSSL_BY_DIR_entry*  dir_entry;
6293
        WOLFSSL_BY_DIR_HASH*   dir_hash;
6294
        WOLFSSL_X509_OBJECT*   x509_obj;
6295
        WOLFSSL_DIST_POINT*    dp;
6296
        WOLFSSL_X509_CRL*      crl;
6297
        WOLFSSL_X509_REVOKED*  revoked;
6298
    } data;
6299
    void* heap; /* memory heap hint */
6300
    WOLFSSL_STACK* next;
6301
    WOLF_STACK_TYPE type;     /* Identifies type of stack. */
6302
};
6303
6304
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
6305
6306
struct WOLFSSL_X509_NAME {
6307
    char  *name;
6308
    int   dynamicName;
6309
    int   sz;
6310
    char  staticName[ASN_NAME_MAX];
6311
#if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
6312
    !defined(NO_ASN)
6313
    int   entrySz; /* number of entries */
6314
    WOLFSSL_X509_NAME_ENTRY entry[MAX_NAME_ENTRIES]; /* all entries i.e. CN */
6315
    WOLFSSL_X509*           x509;   /* x509 that struct belongs to */
6316
#endif /* OPENSSL_EXTRA */
6317
#if !defined(WOLFSSL_NO_CA_NAMES) && defined(OPENSSL_EXTRA)
6318
    /* DER encoding of the RDNs, without the SEQUENCE header, to send in a list
6319
     * of CA names. Allocated only for names that have one: see
6320
     * wolfSSL_X509_NAME_copy(). */
6321
    byte* raw;
6322
    int   rawLen;
6323
    /* Offset of the encoded name in x509->derCert when this is a
6324
     * certificate's issuer or subject as parsed. 0 when not. */
6325
    word32 rawCertOff;
6326
#endif
6327
#ifndef WOLFSSL_NO_CA_NAMES
6328
    WOLF_STACK_OF(WOLFSSL_X509_NAME_ENTRY)* entries;
6329
#endif
6330
    void* heap;
6331
};
6332
6333
#ifndef EXTERNAL_SERIAL_SIZE
6334
    #define EXTERNAL_SERIAL_SIZE 32
6335
#endif
6336
6337
#ifdef NO_ASN
6338
    typedef struct DNS_entry DNS_entry;
6339
    #ifndef IGNORE_NAME_CONSTRAINTS
6340
        typedef struct Base_entry Base_entry;
6341
    #endif
6342
#endif
6343
6344
#ifndef WOLFSSL_AIA_ENTRY_DEFINED
6345
#ifndef WOLFSSL_MAX_AIA_ENTRIES
6346
    #define WOLFSSL_MAX_AIA_ENTRIES 8
6347
#endif
6348
6349
#define WOLFSSL_AIA_ENTRY_DEFINED
6350
typedef struct WOLFSSL_AIA_ENTRY {
6351
    word32      method; /* AIA method OID sum (e.g., AIA_OCSP_OID). */
6352
    const byte* uri;    /* Pointer into cert DER for the URI. */
6353
    word32      uriSz;  /* Length of URI data. */
6354
} WOLFSSL_AIA_ENTRY;
6355
#endif /* WOLFSSL_AIA_ENTRY_DEFINED */
6356
6357
struct WOLFSSL_X509 {
6358
    int              version;
6359
    int              serialSz;
6360
#ifdef WOLFSSL_SEP
6361
    int              deviceTypeSz;
6362
    int              hwTypeSz;
6363
    byte             deviceType[EXTERNAL_SERIAL_SIZE];
6364
    byte             hwType[EXTERNAL_SERIAL_SIZE];
6365
    int              hwSerialNumSz;
6366
    byte             hwSerialNum[EXTERNAL_SERIAL_SIZE];
6367
    byte             certPolicySet;
6368
    byte             certPolicyCrit;
6369
#endif /* WOLFSSL_SEP */
6370
#if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA)
6371
    WOLFSSL_STACK* ext_sk; /* Store X509_EXTENSIONS from wolfSSL_X509_get_ext */
6372
    WOLFSSL_STACK* ext_sk_full; /* Store X509_EXTENSIONS from wolfSSL_X509_get0_extensions */
6373
    WOLFSSL_STACK* ext_d2i;/* Store d2i extensions from wolfSSL_X509_get_ext_d2i */
6374
#endif /* WOLFSSL_QT || OPENSSL_ALL */
6375
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
6376
    WOLFSSL_ASN1_INTEGER* serialNumber; /* Stores SN from wolfSSL_X509_get_serialNumber */
6377
#endif
6378
    WOLFSSL_ASN1_TIME notBefore;
6379
    WOLFSSL_ASN1_TIME notAfter;
6380
    buffer           sig;
6381
    int              sigOID;
6382
    DNS_entry*       altNames;                       /* alt names list */
6383
#ifndef IGNORE_NAME_CONSTRAINTS
6384
    Base_entry*      permittedNames;                 /* name constraints */
6385
    Base_entry*      excludedNames;
6386
    byte             nameConstraintCrit:1;
6387
#endif
6388
    buffer           pubKey;
6389
    int              pubKeyOID;
6390
    DNS_entry*       altNamesNext;                   /* hint for retrieval */
6391
#if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \
6392
    defined(HAVE_FALCON) || defined(WOLFSSL_HAVE_MLDSA) || \
6393
    defined(WOLFSSL_HAVE_SLHDSA)
6394
    word32       pkCurveOID;
6395
#endif
6396
#ifndef NO_CERTS
6397
    DerBuffer*   derCert;                            /* may need  */
6398
#endif
6399
    void*            heap;                           /* heap hint */
6400
    byte             dynamicMemory;                  /* dynamic memory flag */
6401
    byte             isCa:1;
6402
#ifdef WOLFSSL_CERT_EXT
6403
    char             certPolicies[MAX_CERTPOL_NB][MAX_CERTPOL_SZ];
6404
    int              certPoliciesNb;
6405
#endif /* WOLFSSL_CERT_EXT */
6406
#if defined(OPENSSL_EXTRA_X509_SMALL) || defined(OPENSSL_EXTRA)
6407
    wolfSSL_Ref      ref;
6408
#endif
6409
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
6410
#ifdef HAVE_EX_DATA
6411
    WOLFSSL_CRYPTO_EX_DATA ex_data;
6412
#endif
6413
    byte*            authKeyId; /* Points into authKeyIdSrc */
6414
    byte*            authKeyIdSrc;
6415
    byte*            subjKeyId;
6416
    WOLFSSL_ASN1_STRING* subjKeyIdStr;
6417
    byte*            extKeyUsageSrc;
6418
#ifdef OPENSSL_ALL
6419
    byte*            subjAltNameSrc;
6420
#endif
6421
    byte*            rawCRLInfo;
6422
    byte*            CRLInfo;
6423
    byte*            authInfo;
6424
#ifdef WOLFSSL_ASN_CA_ISSUER
6425
    byte*            authInfoCaIssuer;
6426
    int              authInfoCaIssuerSz;
6427
#endif
6428
    WOLFSSL_AIA_ENTRY authInfoList[WOLFSSL_MAX_AIA_ENTRIES];
6429
    byte             authInfoListSz:7;
6430
    byte             authInfoListOverflow:1;
6431
    word32           pathLength;
6432
    word16           keyUsage;
6433
    int              rawCRLInfoSz;
6434
    int              CRLInfoSz;
6435
    int              authInfoSz;
6436
    word32           authKeyIdSz;
6437
    word32           authKeyIdSrcSz;
6438
    word32           subjKeyIdSz;
6439
    byte             extKeyUsage;
6440
    word32           extKeyUsageSz;
6441
    word32           extKeyUsageCount;
6442
#ifndef IGNORE_NETSCAPE_CERT_TYPE
6443
    byte             nsCertType;
6444
#endif
6445
#ifdef OPENSSL_ALL
6446
    word32           subjAltNameSz;
6447
#endif
6448
6449
    byte             CRLdistSet:1;
6450
    byte             CRLdistCrit:1;
6451
    byte             authInfoSet:1;
6452
    byte             authInfoCrit:1;
6453
    byte             keyUsageSet:1;
6454
    byte             keyUsageCrit:1;
6455
    byte             extKeyUsageCrit:1;
6456
    byte             subjKeyIdSet:1;
6457
    byte             pathLengthSet:1;
6458
6459
    byte             subjKeyIdCrit:1;
6460
    byte             basicConstSet:1;
6461
    byte             basicConstCrit:1;
6462
    byte             basicConstPlSet:1;
6463
    byte             subjAltNameSet:1;
6464
    byte             subjAltNameCrit:1;
6465
    byte             authKeyIdSet:1;
6466
    byte             authKeyIdCrit:1;
6467
    byte             issuerSet:1;
6468
#ifdef WOLFSSL_CUSTOM_OID
6469
    CertExtension    custom_exts[NUM_CUSTOM_EXT];
6470
    int              customExtCount;
6471
#endif /* WOLFSSL_CUSTOM_OID */
6472
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
6473
#ifdef WOLFSSL_CERT_REQ
6474
    byte             isCSR:1;
6475
#endif
6476
    byte             serial[EXTERNAL_SERIAL_SIZE];
6477
    char             subjectCN[ASN_NAME_MAX];        /* common name short cut */
6478
#if defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_GEN)
6479
#if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA)
6480
    /* stack of CSR attributes */
6481
    WOLF_STACK_OF(WOLFSSL_X509_ATRIBUTE)* reqAttributes;
6482
#endif
6483
    #if defined(WOLFSSL_CERT_REQ)
6484
    char             challengePw[CTC_NAME_SIZE]; /* for REQ certs */
6485
    char             contentType[CTC_NAME_SIZE];
6486
    #endif
6487
#endif /* WOLFSSL_CERT_REQ || WOLFSSL_CERT_GEN */
6488
    WOLFSSL_X509_NAME issuer;
6489
    WOLFSSL_X509_NAME subject;
6490
#if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) || \
6491
    defined(OPENSSL_EXTRA_X509_SMALL) || defined(WOLFSSL_APACHE_HTTPD) || \
6492
    defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_WPAS)
6493
    WOLFSSL_X509_ALGOR algor;
6494
    WOLFSSL_X509_PUBKEY key;
6495
#endif
6496
#if defined(OPENSSL_EXTRA_X509_SMALL) || defined(OPENSSL_EXTRA) || \
6497
    defined(OPENSSL_ALL) || defined(KEEP_OUR_CERT) || \
6498
    defined(KEEP_PEER_CERT) || defined(SESSION_CERTS)
6499
    byte            notBeforeData[CTC_DATE_SIZE];
6500
    byte            notAfterData[CTC_DATE_SIZE];
6501
#endif
6502
#ifdef WOLFSSL_DUAL_ALG_CERTS
6503
    /* Subject Alternative Public Key Info */
6504
    byte *sapkiDer;
6505
    int sapkiLen;
6506
    /* Alternative Signature Algorithm */
6507
    byte *altSigAlgDer;
6508
    int altSigAlgLen;
6509
    /* Alternative Signature Value */
6510
    byte *altSigValDer;
6511
    int altSigValLen;
6512
6513
    byte sapkiCrit:1;
6514
    byte altSigAlgCrit:1;
6515
    byte altSigValCrit:1;
6516
#endif /* WOLFSSL_DUAL_ALG_CERTS */
6517
};
6518
6519
#if defined(WOLFSSL_ACERT)
6520
struct WOLFSSL_X509_ACERT {
6521
    int               version;
6522
    int               serialSz;
6523
    byte              serial[EXTERNAL_SERIAL_SIZE];
6524
    WOLFSSL_ASN1_TIME notBefore;
6525
    WOLFSSL_ASN1_TIME notAfter;
6526
    buffer            sig;
6527
    int               sigOID;
6528
#ifndef NO_CERTS
6529
    DerBuffer *       derCert;
6530
#endif
6531
    void *            heap;
6532
    int               dynamic; /* whether struct was dynamically allocated */
6533
    /* copy of raw Attributes field from */
6534
    byte              holderSerial[EXTERNAL_SERIAL_SIZE];
6535
    int               holderSerialSz;
6536
    DNS_entry *       holderEntityName;  /* Holder entityName from ACERT */
6537
    DNS_entry *       holderIssuerName;  /* issuerName from ACERT */
6538
    DNS_entry *       AttCertIssuerName; /* AttCertIssuer name from ACERT */
6539
    byte *            rawAttr;
6540
    word32            rawAttrLen;
6541
};
6542
#endif /* WOLFSSL_ACERT */
6543
6544
/* record layer header for PlainText, Compressed, and CipherText */
6545
typedef struct RecordLayerHeader {
6546
    byte            type;
6547
    byte            pvMajor;
6548
    byte            pvMinor;
6549
    byte            length[2];
6550
} RecordLayerHeader;
6551
6552
6553
/* record layer header for DTLS PlainText, Compressed, and CipherText */
6554
typedef struct DtlsRecordLayerHeader {
6555
    byte            type;
6556
    byte            pvMajor;
6557
    byte            pvMinor;
6558
    byte            sequence_number[8];   /* per record */
6559
    byte            length[2];
6560
} DtlsRecordLayerHeader;
6561
6562
typedef struct DtlsFragBucket {
6563
    /* m stands for meta */
6564
    union {
6565
        struct {
6566
            struct DtlsFragBucket* next;
6567
            word32 offset;
6568
            word32 sz;
6569
        } m;
6570
        /* Make sure we have at least DTLS_HANDSHAKE_HEADER_SZ bytes before the
6571
         * buf so that we can reconstruct the header in the allocated
6572
         * DtlsFragBucket buffer. */
6573
        byte padding[DTLS_HANDSHAKE_HEADER_SZ];
6574
    } m;
6575
/* Ignore "nonstandard extension used : zero-sized array in struct/union"
6576
 * MSVC warning */
6577
#ifdef _MSC_VER
6578
#pragma warning(disable: 4200)
6579
#endif
6580
    byte buf[WC_FLEXIBLE_ARRAY_SIZE];
6581
} DtlsFragBucket;
6582
6583
typedef struct DtlsMsg {
6584
    struct DtlsMsg* next;
6585
    byte*           raw;
6586
    byte*           fullMsg;   /* for TX fullMsg == raw. For RX this points to
6587
                                * the start of the message after headers. */
6588
    DtlsFragBucket* fragBucketList;
6589
    word32          bytesReceived;
6590
    word16          epoch;     /* Epoch that this message belongs to */
6591
    word32          seq;       /* Handshake sequence number    */
6592
    word32          sz;        /* Length of whole message      */
6593
    byte            type;
6594
    byte            fragBucketListCount;
6595
    byte            ready:1;
6596
    byte            encrypted:1;
6597
} DtlsMsg;
6598
6599
6600
#ifdef HAVE_NETX
6601
6602
    /* NETX I/O Callback default */
6603
    typedef struct NetX_Ctx {
6604
        NX_TCP_SOCKET* nxTcpSocket; /* send/recv tcp socket handle */
6605
        NX_PACKET*     nxPacket;    /* incoming packet handle for short reads */
6606
        ULONG          nxOffset;    /* offset already read from nxPacket */
6607
        ULONG          nxWait;      /* wait option flag */
6608
/* WOLFSSL_NETX_DUO: requires ThreadX NetX Duo (NXD_ADDRESS, nxd_udp_socket_send) */
6609
#if defined(WOLFSSL_DTLS) && defined(WOLFSSL_NETX_DUO)
6610
        NX_UDP_SOCKET* nxUdpSocket; /* send/recv udp socket handle */
6611
        NXD_ADDRESS    nxdIp;       /* destination IP address for udp send */
6612
        USHORT         nxPort;      /* destination port for udp send */
6613
#endif /* WOLFSSL_DTLS && WOLFSSL_NETX_DUO */
6614
    } NetX_Ctx;
6615
6616
#endif
6617
6618
/* Handshake messages received from peer (plus change cipher */
6619
typedef struct MsgsReceived {
6620
    word16 got_hello_request:1;
6621
    word16 got_client_hello:2;
6622
    word16 got_server_hello:1;
6623
    word16 got_hello_verify_request:1;
6624
    word16 got_session_ticket:1;
6625
    word16 got_end_of_early_data:1;
6626
    word16 got_hello_retry_request:1;
6627
    word16 got_encrypted_extensions:1;
6628
    word16 got_certificate:1;
6629
    word16 got_certificate_status:1;
6630
    word16 got_server_key_exchange:1;
6631
    word16 got_certificate_request:1;
6632
    word16 got_server_hello_done:1;
6633
    word16 got_certificate_verify:1;
6634
    word16 got_client_key_exchange:1;
6635
    word16 got_finished:1;
6636
    word16 got_key_update:1;
6637
    word16 got_change_cipher:1;
6638
} MsgsReceived;
6639
6640
6641
/* configure and CMake refuse this; a user_settings.h build reaches neither
6642
 * and would fail with "no member named hashSha512" instead. */
6643
#if defined(WOLFSSL_TLS13_SHA512) && !defined(WOLFSSL_SHA512)
6644
    #error "WOLFSSL_TLS13_SHA512 requires WOLFSSL_SHA512"
6645
#endif
6646
6647
/* Hashed for the TLS 1.2 signature algorithms, and kept for TLS 1.3 when
6648
 * WOLFSSL_TLS13_SHA512 allows SHA-512 as its handshake hash. No suite selects
6649
 * SHA-512, so TLS 1.3 reaches it only for the HRR cookie HMAC. */
6650
#if defined(WOLFSSL_SHA512) && (!defined(WOLFSSL_NO_TLS12) || \
6651
                                defined(WOLFSSL_TLS13_SHA512))
6652
    #define WOLFSSL_HS_HASH_SHA512
6653
#endif
6654
6655
/* Handshake hashes */
6656
typedef struct HS_Hashes {
6657
#ifndef WOLFSSL_NO_TLS12
6658
    Hashes          verifyHashes;
6659
    Hashes          certHashes;         /* for cert verify */
6660
#endif
6661
#if !defined(NO_SHA) && (!defined(NO_OLD_TLS) || \
6662
                          defined(WOLFSSL_ALLOW_TLS_SHA1))
6663
    wc_Sha          hashSha;            /* sha hash of handshake msgs */
6664
#endif
6665
#if !defined(NO_MD5) && !defined(NO_OLD_TLS)
6666
    wc_Md5          hashMd5;            /* md5 hash of handshake msgs */
6667
#endif
6668
#ifndef NO_SHA256
6669
    wc_Sha256       hashSha256;         /* sha256 hash of handshake msgs */
6670
#endif
6671
#ifdef WOLFSSL_SHA384
6672
    wc_Sha384       hashSha384;         /* sha384 hash of handshake msgs */
6673
#endif
6674
#ifdef WOLFSSL_HS_HASH_SHA512
6675
    wc_Sha512       hashSha512;         /* sha512 hash of handshake msgs */
6676
#endif
6677
#ifdef WOLFSSL_SM3
6678
    wc_Sm3          hashSm3;            /* sm3 hash of handshake msgs */
6679
#endif
6680
#if (defined(HAVE_ED25519) || defined(HAVE_ED448) || \
6681
     (defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3))) && \
6682
    !defined(WOLFSSL_NO_CLIENT_AUTH)
6683
    byte*           messages;           /* handshake messages */
6684
    int             length;             /* length of handshake messages' data */
6685
    int             prevLen;            /* length of messages but last */
6686
#endif
6687
} HS_Hashes;
6688
6689
6690
#if !defined(WOLFSSL_NO_TLS12) || defined(WOLFSSL_TLS13)
6691
/* Persistable BuildMessage/BuildTls13Message arguments */
6692
typedef struct BuildMsgArgs {
6693
    word32 digestSz;
6694
    word32 sz;
6695
    word32 pad;
6696
    word32 idx;
6697
    word32 headerSz;
6698
    word16 size;
6699
    word32 ivSz;      /* TLSv1.1  IV */
6700
    byte   type;
6701
    byte*  iv;
6702
    ALIGN16 byte staticIvBuffer[MAX_IV_SZ];
6703
} BuildMsgArgs;
6704
#endif
6705
6706
#ifdef WOLFSSL_ASYNC_IO
6707
    #define MAX_ASYNC_ARGS 24
6708
    typedef void (*FreeArgsCb)(struct WOLFSSL* ssl, void* pArgs);
6709
6710
    struct WOLFSSL_ASYNC {
6711
#if defined(WOLFSSL_ASYNC_CRYPT) && \
6712
    (!defined(WOLFSSL_NO_TLS12) || defined(WOLFSSL_TLS13))
6713
        /* Record builder resume args, shared by BuildMessage() and
6714
         * BuildTls13Message(): a connection runs only one of them. */
6715
        BuildMsgArgs  buildArgs;
6716
#endif
6717
        FreeArgsCb    freeArgs; /* function pointer to cleanup args */
6718
#ifdef WC_NO_PTR_INT_CAST
6719
        max_align_t args[MAX_ASYNC_ARGS * sizeof(word32) / sizeof(max_align_t)]; /* holder for current args */
6720
#else
6721
        word32        args[MAX_ASYNC_ARGS]; /* holder for current args */
6722
#endif
6723
    };
6724
#endif
6725
6726
#ifdef HAVE_WRITE_DUP
6727
6728
    #define WRITE_DUP_SIDE 1
6729
    #define READ_DUP_SIDE 2
6730
6731
    typedef struct WriteDup {
6732
        wolfSSL_Mutex   dupMutex;       /* field access mutex */
6733
        int             dupCount;       /* reference count */
6734
        int             dupErr;         /* under dupMutex, pass to other side */
6735
#ifdef WOLFSSL_DTLS13
6736
        struct Dtls13RecordNumber* sendAckList; /* ownership transferred */
6737
        /* Key update ACK tracking: write side stores the (epoch, seq) of its
6738
         * in-flight KeyUpdate; read side sets keyUpdateAcked when the ACK for
6739
         * that exact record arrives.  Both epoch and seq are checked to avoid
6740
         * false positives from data records in the same epoch. */
6741
        w64wrapper keyUpdateEpoch;     /* epoch of the KeyUpdate */
6742
        w64wrapper keyUpdateSeq;       /* seq num of the KeyUpdate */
6743
#endif /* WOLFSSL_DTLS13 */
6744
#ifdef WOLFSSL_TLS13
6745
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
6746
        /* Post-handshake certificate request delegation: the read side received
6747
         * a CertificateRequest but cannot write; it saves state here and the
6748
         * write side sends Certificate+CertificateVerify+Finished. */
6749
        struct HS_Hashes* postHandshakeHashState;    /* transcript at CR time */
6750
        struct CertReqCtx* postHandshakeCertReqCtx; /* context from CR */
6751
        byte postHandshakeSendVerify;    /* ssl->options.sendVerify */
6752
        byte postHandshakeSigAlgo;       /* ssl->options.sigAlgo */
6753
        byte postHandshakeHashAlgo;      /* ssl->options.hashAlgo */
6754
#if !defined(NO_CERTS) && !defined(WOLFSSL_NO_SIGALG)
6755
        byte postHandshakeSha1CertOk;    /* ssl->options.peerSha1CertOk */
6756
#endif
6757
        /* After the write side sends the PHA response, it stores its updated
6758
         * transcript here so the read side can resume from it on the next
6759
         * CertificateRequest (keeps client/server transcript in sync). */
6760
        struct HS_Hashes* postHandshakeSyncedHashState;
6761
#endif /* WOLFSSL_POST_HANDSHAKE_AUTH */
6762
#endif /* WOLFSSL_TLS13 */
6763
6764
        /* Flags */
6765
#ifdef WOLFSSL_DTLS13
6766
        WC_BITFIELD keyUpdateWaiting:1; /* write side has an unACKed KeyUpdate */
6767
        WC_BITFIELD keyUpdateAcked:1;   /* read side confirmed the ACK arrived */
6768
        /* DTLS 1.3: read side cannot write, so it passes ACK work to the
6769
         * write side. */
6770
        WC_BITFIELD sendAcks:1;
6771
#endif /* WOLFSSL_DTLS13 */
6772
#ifdef WOLFSSL_TLS13
6773
        /* TLS 1.3 (and DTLS 1.3): read side received a KeyUpdate(update_requested)
6774
         * but cannot send the response; write side handles it. */
6775
        WC_BITFIELD keyUpdateRespond:1; /* write side must send a KeyUpdate response */
6776
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
6777
        WC_BITFIELD postHandshakeAuthPending:1; /* write side must respond */
6778
#endif /* WOLFSSL_POST_HANDSHAKE_AUTH */
6779
#endif /* WOLFSSL_TLS13 */
6780
    } WriteDup;
6781
6782
    WOLFSSL_LOCAL void FreeWriteDup(WOLFSSL* ssl);
6783
    WOLFSSL_LOCAL int  NotifyWriteSide(WOLFSSL* ssl, int err);
6784
#endif /* HAVE_WRITE_DUP */
6785
6786
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
6787
typedef struct CertReqCtx CertReqCtx;
6788
6789
struct CertReqCtx {
6790
    CertReqCtx* next;
6791
    byte        len;
6792
    byte        ctx;
6793
};
6794
#endif
6795
6796
#ifdef WOLFSSL_EARLY_DATA
6797
typedef enum EarlyDataState {
6798
    no_early_data,
6799
    early_data_ext,
6800
    expecting_early_data,
6801
    process_early_data,
6802
    done_early_data
6803
} EarlyDataState;
6804
#endif
6805
6806
#ifdef WOLFSSL_DTLS13
6807
6808
/* size of the mask used to encrypt/decrypt Record Number  */
6809
#define DTLS13_RN_MASK_SIZE 16
6810
6811
typedef struct Dtls13UnifiedHdrInfo {
6812
    word16 recordLength;
6813
    byte seqLo;
6814
    byte seqHi;
6815
    byte seqHiPresent:1;
6816
    byte epochBits;
6817
} Dtls13UnifiedHdrInfo;
6818
6819
enum  {
6820
    DTLS13_EPOCH_EARLYDATA = 1,
6821
    DTLS13_EPOCH_HANDSHAKE = 2,
6822
    DTLS13_EPOCH_TRAFFIC0 = 3
6823
};
6824
6825
/* Sender-side DTLS 1.3 epoch ceiling: we MUST NOT advance our own epoch past
6826
 * 2^48-1 (RFC 9147 Section 4.2.1). This gates only the sending epoch; receivers
6827
 * MUST NOT enforce it on the peer epoch (RFC 9147 Section 8). Expressed as the
6828
 * high/low 32-bit halves of a w64wrapper. */
6829
#define DTLS13_EPOCH_MAX_HI32 0x0000FFFFU
6830
#define DTLS13_EPOCH_MAX_LO32 0xFFFFFFFFU
6831
6832
/* 64-bit epoch + 64-bit sequence number */
6833
#define DTLS13_RN_SIZE (OPAQUE64_LEN + OPAQUE64_LEN)
6834
/* Maximum number of ACK records allowed in an ACK message */
6835
#ifndef DTLS13_ACK_MAX_RECORDS
6836
#define DTLS13_ACK_MAX_RECORDS 128
6837
#endif
6838
/* WOLFSSL_MAX_16BIT / DTLS13_RN_SIZE (0xffff / (OPAQUE64_LEN + OPAQUE64_LEN))
6839
 * Literals are used because OPAQUE64_LEN is an enum value, invisible to the
6840
 * preprocessor. */
6841
#if DTLS13_ACK_MAX_RECORDS > 0xffff / 16
6842
#error "DTLS13_ACK_MAX_RECORDS exceeds the maximum encodable in the word16 length field"
6843
#endif
6844
6845
6846
typedef struct Dtls13Epoch {
6847
    w64wrapper epochNumber;
6848
6849
    w64wrapper nextSeqNumber;
6850
    w64wrapper nextPeerSeqNumber;
6851
6852
#ifndef WOLFSSL_TLS13_IGNORE_AEAD_LIMITS
6853
    w64wrapper dropCount; /* Amount of records that failed decryption */
6854
#endif
6855
6856
    word32 window[WOLFSSL_DTLS_WINDOW_WORDS];
6857
6858
    /* key material for the epoch */
6859
    byte client_write_key[MAX_SYM_KEY_SIZE];
6860
    byte server_write_key[MAX_SYM_KEY_SIZE];
6861
    byte client_write_IV[MAX_WRITE_IV_SZ];
6862
    byte server_write_IV[MAX_WRITE_IV_SZ];
6863
6864
    byte aead_exp_IV[AEAD_MAX_EXP_SZ];
6865
    byte aead_enc_imp_IV[AEAD_MAX_IMP_SZ];
6866
    byte aead_dec_imp_IV[AEAD_MAX_IMP_SZ];
6867
6868
    byte client_sn_key[MAX_SYM_KEY_SIZE];
6869
    byte server_sn_key[MAX_SYM_KEY_SIZE];
6870
6871
    byte isValid;
6872
    byte side;
6873
} Dtls13Epoch;
6874
6875
#ifndef DTLS13_EPOCH_SIZE
6876
#define DTLS13_EPOCH_SIZE 4
6877
#endif
6878
6879
/* our epoch, peer epoch, peer epoch - 1 and a free slot for a new epoch */
6880
#if DTLS13_EPOCH_SIZE < 4
6881
#error "DTLS13_EPOCH_SIZE must be at least 4"
6882
#endif
6883
6884
#ifndef DTLS13_RETRANS_RN_SIZE
6885
#define DTLS13_RETRANS_RN_SIZE 3
6886
#endif
6887
6888
enum Dtls13RtxFsmState {
6889
    DTLS13_RTX_FSM_PREPARING = 0,
6890
    DTLS13_RTX_FSM_SENDING,
6891
    DTLS13_RTX_FSM_WAITING,
6892
    DTLS13_RTX_FSM_FINISHED
6893
};
6894
6895
typedef struct Dtls13RtxRecord {
6896
    struct Dtls13RtxRecord *next;
6897
    word16 length;
6898
    byte *data;
6899
    w64wrapper epoch;
6900
    w64wrapper seq[DTLS13_RETRANS_RN_SIZE];
6901
    byte rnIdx;
6902
    byte handshakeType;
6903
} Dtls13RtxRecord;
6904
6905
typedef struct Dtls13RecordNumber {
6906
    struct Dtls13RecordNumber *next;
6907
    w64wrapper epoch;
6908
    w64wrapper seq;
6909
} Dtls13RecordNumber;
6910
6911
typedef struct Dtls13Rtx {
6912
#ifdef WOLFSSL_RW_THREADED
6913
    wolfSSL_Mutex mutex;
6914
#endif
6915
    enum Dtls13RtxFsmState state; /* Unused? */
6916
    Dtls13RtxRecord *rtxRecords;
6917
    Dtls13RtxRecord **rtxRecordTailPtr;
6918
    Dtls13RecordNumber *seenRecords;
6919
    word16 seenRecordsCount;
6920
#ifdef WOLFSSL_32BIT_MILLI_TIME
6921
    word32 lastRtx;
6922
#else
6923
    sword64 lastRtx;
6924
#endif
6925
    byte triggeredRtxs; /* Unused? */
6926
    byte sendAcks;
6927
    byte retransmit;
6928
} Dtls13Rtx;
6929
6930
#endif /* WOLFSSL_DTLS13 */
6931
6932
#ifdef WOLFSSL_DTLS_CID
6933
typedef struct ConnectionID {
6934
    byte length;
6935
/* Ignore "nonstandard extension used : zero-sized array in struct/union"
6936
 * MSVC warning */
6937
#ifdef _MSC_VER
6938
#pragma warning(disable: 4200)
6939
#endif
6940
    byte id[];
6941
} ConnectionID;
6942
6943
typedef struct CIDInfo {
6944
    ConnectionID* tx;
6945
    ConnectionID* rx;
6946
    byte negotiated : 1;
6947
} CIDInfo;
6948
6949
/* ConnectionIdUsage of the NewConnectionId message (RFC 9147 Section 9) */
6950
enum ConnectionIdUsage {
6951
    cid_immediate = 0,
6952
    cid_spare     = 1
6953
};
6954
#endif /* WOLFSSL_DTLS_CID */
6955
6956
/* The idea is to reuse the context suites object whenever possible to save
6957
 * space. */
6958
#define WOLFSSL_SUITES(ssl) \
6959
28.4k
    ((const Suites*) ((ssl)->suites != NULL ? \
6960
28.4k
        (ssl)->suites : \
6961
28.4k
        (ssl)->ctx->suites))
6962
6963
/* wolfSSL ssl type */
6964
6965
/* TLS 1.3 key-schedule resume steps (kdfMsgStep/kdfDeriveStep). A value is
6966
 * recorded after its named operation completes ("step <= X" = X not done);
6967
 * 0 = sequence not entered or finished. Values repeat across sequences. */
6968
6969
/* Receive side (kdfMsgStep), driven by DoTls13MsgDerives(). */
6970
enum Tls13KdfMsgStep {
6971
    TLS13_MSG_KDF_NONE                    = 0,
6972
    /* client processing server_hello */
6973
    TLS13_MSG_KDF_SH_ENTERED              = 1,
6974
    TLS13_MSG_KDF_SH_EARLY_SECRET         = 2,
6975
    TLS13_MSG_KDF_SH_HS_SECRET            = 3,
6976
    TLS13_MSG_KDF_SH_HS_KEYS              = 4,
6977
    TLS13_MSG_KDF_SH_KEYS_SET             = 5,
6978
    TLS13_MSG_KDF_SH_DTLS_EPOCH           = 6,
6979
    /* client processing finished */
6980
    TLS13_MSG_KDF_FIN_ENTERED             = 1,
6981
    TLS13_MSG_KDF_FIN_MASTER_SECRET       = 2,
6982
    TLS13_MSG_KDF_FIN_QUIC_EARLY_KEYS     = 3,
6983
    TLS13_MSG_KDF_FIN_TRAFFIC_KEYS        = 4,
6984
    TLS13_MSG_KDF_FIN_TRAFFIC_DONE        = 5,
6985
    TLS13_MSG_KDF_FIN_KEYS_SET            = 6,
6986
    /* server processing finished (resumption secret for tickets) */
6987
    TLS13_MSG_KDF_SFIN_ENTERED            = 1,
6988
    TLS13_MSG_KDF_SFIN_RESUMPTION_SECRET  = 2
6989
};
6990
6991
/* Send side (kdfDeriveStep), inside the senders themselves. */
6992
enum Tls13KdfSendStep {
6993
    TLS13_SEND_KDF_NONE                   = 0,
6994
    /* SendTls13EncryptedExtensions() */
6995
    TLS13_SEND_KDF_EE_HS_SECRET           = 1,
6996
    TLS13_SEND_KDF_EE_HS_KEYS             = 2,
6997
    TLS13_SEND_KDF_EE_ENC_KEYS_SET        = 3,
6998
    TLS13_SEND_KDF_EE_KEYS_SET            = 4,
6999
    TLS13_SEND_KDF_EE_DTLS_EPOCH          = 5,
7000
    /* SendTls13Finished() */
7001
    TLS13_SEND_KDF_FIN_ENTERED            = 1,
7002
    TLS13_SEND_KDF_FIN_MASTER_SECRET      = 2,
7003
    TLS13_SEND_KDF_FIN_ENC_TRAFFIC_KEYS   = 3,
7004
    TLS13_SEND_KDF_FIN_TRAFFIC_KEYS       = 4,
7005
    TLS13_SEND_KDF_FIN_ENC_KEYS_SET       = 5,
7006
    TLS13_SEND_KDF_FIN_DTLS_TRAFFIC_EPOCH = 6,
7007
    TLS13_SEND_KDF_FIN_EARLY_ENC_KEYS     = 7,
7008
    TLS13_SEND_KDF_FIN_EARLY_KEYS_SET     = 8,
7009
    TLS13_SEND_KDF_FIN_RESUMPTION_SECRET  = 9,
7010
    TLS13_SEND_KDF_FIN_DTLS_EPOCH_SET     = 10
7011
};
7012
7013
7014
struct WOLFSSL {
7015
    WOLFSSL_CTX*    ctx;
7016
#if defined(WOLFSSL_HAPROXY)
7017
    WOLFSSL_CTX*    initial_ctx; /* preserve session key materials */
7018
#endif
7019
    Suites*         suites; /* Only need during handshake. Can be NULL when
7020
                             * reusing the context's object. When WOLFSSL
7021
                             * object needs separate instance of suites use
7022
                             * AllocateSuites(). */
7023
    Suites*         clSuites;
7024
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL) || \
7025
    defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
7026
    WOLF_STACK_OF(WOLFSSL_CIPHER)* suitesStack; /* stack of available cipher
7027
                                                 * suites */
7028
    WOLF_STACK_OF(WOLFSSL_CIPHER)* clSuitesStack; /* stack of client cipher
7029
                                                   * suites */
7030
#endif
7031
    Arrays*         arrays;
7032
    /* Buffer used to reassemble a handshake message that is fragmented across
7033
     * multiple records. Kept in WOLFSSL (not Arrays) so that post-handshake
7034
     * messages (e.g. a TLS 1.3 NewSessionTicket) can still be defragmented
7035
     * after the handshake arrays have been released by FreeArrays(). */
7036
    byte*           pendingMsg;         /* defrag buffer */
7037
    word32          pendingMsgSz;       /* defrag buffer size */
7038
    word32          pendingMsgOffset;   /* current offset into defrag buffer */
7039
    byte            pendingMsgType;     /* defrag buffer message type */
7040
#ifdef WOLFSSL_TLS13
7041
    byte            clientSecret[SECRET_LEN];
7042
    byte            serverSecret[SECRET_LEN];
7043
#endif
7044
    HS_Hashes*      hsHashes;
7045
#if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
7046
    HS_Hashes*      hsHashesEch;
7047
#endif
7048
    void*           IOCB_ReadCtx;
7049
    void*           IOCB_WriteCtx;
7050
    WC_RNG*         rng;
7051
    void*           verifyCbCtx;        /* cert verify callback user ctx*/
7052
    VerifyCallback  verifyCallback;     /* cert verification callback */
7053
#ifdef WOLFSSL_CHAIN_VERIFY_CB
7054
    ChainVerifyCb   chainVerifyCb;      /* overrides the ctx's when set */
7055
    void*           chainVerifyCtx;     /* chain verify callback user ctx */
7056
#endif
7057
    void*           heap;               /* for user overrides */
7058
#ifdef HAVE_WRITE_DUP
7059
    WriteDup*       dupWrite;           /* valid pointer indicates ON */
7060
             /* side that decrements dupCount to zero frees overall structure */
7061
    byte            dupSide;            /* write side or read side */
7062
#endif
7063
#ifdef OPENSSL_EXTRA
7064
    byte              cbioFlag;         /* WOLFSSL_CBIO_RECV/SEND:
7065
                                         * CBIORecv/Send is set */
7066
#endif
7067
#ifdef WOLFSSL_WOLFSENTRY_HOOKS
7068
    NetworkFilterCallback_t AcceptFilter;
7069
    void *AcceptFilter_arg;
7070
    NetworkFilterCallback_t ConnectFilter;
7071
    void *ConnectFilter_arg;
7072
#endif /* WOLFSSL_WOLFSENTRY_HOOKS */
7073
    CallbackIORecv  CBIORecv;
7074
    CallbackIOSend  CBIOSend;
7075
#ifdef WOLFSSL_STATIC_MEMORY
7076
    WOLFSSL_HEAP_HINT heap_hint;
7077
#endif
7078
#if defined(WOLFSSL_DTLS) && !defined(NO_WOLFSSL_SERVER)
7079
    ClientHelloGoodCb chGoodCb;        /* notify user we parsed a verified
7080
                                        * ClientHello that passed basic tests */
7081
    void*             chGoodCtx;       /* user ClientHello cb context  */
7082
#endif
7083
#ifndef NO_HANDSHAKE_DONE_CB
7084
    HandShakeDoneCb hsDoneCb;          /* notify user handshake done */
7085
    void*           hsDoneCtx;         /* user handshake cb context  */
7086
#endif
7087
#ifdef WOLFSSL_ASYNC_IO
7088
#ifdef WOLFSSL_ASYNC_CRYPT
7089
    WC_ASYNC_DEV* asyncDev;
7090
#endif
7091
    /* Message building context should be stored here for functions that expect
7092
     * to encounter encryption blocking or fragment the message. */
7093
    struct WOLFSSL_ASYNC* async;
7094
#endif
7095
    void*           hsKey;              /* Handshake key (RsaKey or ecc_key)
7096
                                         * allocated from heap */
7097
    word32          hsType;             /* Type of Handshake key (hsKey) */
7098
    WOLFSSL_CIPHER  cipher;
7099
#ifdef WOLFSSL_DUAL_ALG_CERTS
7100
    void*           hsAltKey;           /* Handshake key (ML-DSA, falcon)
7101
                                         * allocated from heap */
7102
    word32          hsAltType;          /* Type of Handshake key (hsAltKey) */
7103
#endif
7104
#ifndef WOLFSSL_AEAD_ONLY
7105
    hmacfp          hmac;
7106
#endif
7107
    Ciphers         encrypt;
7108
    Ciphers         decrypt;
7109
    Buffers         buffers;
7110
    WOLFSSL_SESSION* session;
7111
#ifndef NO_CLIENT_CACHE
7112
    ClientSession*  clientSession;
7113
#endif
7114
    WOLFSSL_ALERT_HISTORY alert_history;
7115
    WOLFSSL_ALERT   pendingAlert;
7116
    int             error;
7117
    int             rfd;                /* read  file descriptor */
7118
    int             wfd;                /* write file descriptor */
7119
    int             rflags;             /* user read  flags */
7120
    int             wflags;             /* user write flags */
7121
    word32          timeout;            /* session timeout */
7122
    word32          fragOffset;         /* fragment offset */
7123
    word16          curSize;
7124
    word32          curStartIdx;
7125
    byte            verifyDepth;
7126
    RecordLayerHeader curRL;
7127
    MsgsReceived    msgsReceived;       /* peer messages received */
7128
    ProtocolVersion version;            /* negotiated version */
7129
    ProtocolVersion chVersion;          /* client hello version */
7130
    CipherSpecs     specs;
7131
    Keys            keys;
7132
    Options         options;
7133
#ifdef WOLFSSL_SESSION_ID_CTX
7134
    byte             sessionCtx[ID_LEN]; /* app session context ID */
7135
    byte             sessionCtxSz;       /* size of sessionCtx stored */
7136
#endif
7137
#ifdef OPENSSL_EXTRA
7138
    CallbackInfoState* CBIS;             /* used to get info about SSL state */
7139
    int              cbmode;             /* read or write on info callback */
7140
    int              cbtype;             /* event type in info callback */
7141
    WOLFSSL_BIO*     biord;              /* socket bio read  to free/close */
7142
    WOLFSSL_BIO*     biowr;              /* socket bio write to free/close */
7143
    WOLFSSL_X509_VERIFY_PARAM* param;    /* verification parameters*/
7144
#endif
7145
#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL)
7146
    word32            disabledCurves;   /* curves disabled by user */
7147
#endif
7148
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
7149
    defined(OPENSSL_ALL)
7150
    unsigned long    peerVerifyRet;
7151
#endif
7152
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_TLS_READ_AHEAD)
7153
    byte             readAhead;
7154
    /* Read-ahead coalescing buffer size; 0 = one record (default). */
7155
    word32           readAheadSz;
7156
#endif
7157
#ifdef OPENSSL_EXTRA
7158
#ifdef HAVE_PK_CALLBACKS
7159
    void*            loggingCtx;         /* logging callback argument */
7160
#endif
7161
    WOLFSSL_TLSEXT_DEBUG_CB tlsextDebugCb; /* TLS ext debug callback */
7162
    void*            tlsextDebugArg;     /* TLS ext debug callback argument */
7163
#endif /* OPENSSL_EXTRA */
7164
#ifndef NO_RSA
7165
    RsaKey*         peerRsaKey;
7166
#if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_FSPSM_TLS)
7167
    void*           RenesasUserCtx;
7168
    byte*           peerSceTsipEncRsaKeyIndex;
7169
#endif
7170
    byte            peerRsaKeyPresent;
7171
#ifdef WC_RSA_PSS
7172
    word8           useRsaPss;           /* cert supports RSA-PSS */
7173
#endif
7174
#endif
7175
#if defined(WOLFSSL_TLS13) || defined(HAVE_FFDHE)
7176
    word16          namedGroup;
7177
#endif
7178
#ifdef WOLFSSL_TLS13
7179
    word16          group[WOLFSSL_MAX_GROUP_COUNT];
7180
    byte            numGroups;
7181
#endif
7182
    word16          pssAlgo;
7183
#ifdef WOLFSSL_TLS13
7184
    word16          certHashSigAlgoSz;  /* SigAlgoCert ext length in bytes */
7185
    byte*           certHashSigAlgo;    /* peer's cert sig/algo list */
7186
#endif
7187
#if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
7188
    int             eccVerifyRes;
7189
#endif
7190
#if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_CURVE25519) || \
7191
    defined(HAVE_ED448) || defined(HAVE_CURVE448)
7192
    word32          ecdhCurveOID;            /* curve Ecc_Sum     */
7193
    ecc_key*        eccTempKey;              /* private ECDHE key */
7194
    byte            eccTempKeyPresent;       /* also holds type */
7195
    byte            peerEccKeyPresent;
7196
#endif
7197
#ifdef HAVE_ECC
7198
    ecc_key*        peerEccKey;              /* peer's  ECDHE key */
7199
    ecc_key*        peerEccDsaKey;           /* peer's  ECDSA key */
7200
    word16          eccTempKeySz;            /* in octets 20 - 66 */
7201
    byte            peerEccDsaKeyPresent;
7202
#endif
7203
#if defined(HAVE_ECC) || defined(HAVE_ED25519) || \
7204
    defined(HAVE_CURVE448) || defined(HAVE_ED448) || \
7205
    defined(HAVE_FALCON) || defined(WOLFSSL_HAVE_MLDSA) || \
7206
    defined(WOLFSSL_HAVE_SLHDSA)
7207
    word32          pkCurveOID;              /* curve Ecc_Sum     */
7208
#endif
7209
#ifdef HAVE_ED25519
7210
    ed25519_key*    peerEd25519Key;
7211
    byte            peerEd25519KeyPresent;
7212
#endif
7213
#ifdef HAVE_CURVE25519
7214
    curve25519_key* peerX25519Key;
7215
    byte            peerX25519KeyPresent;
7216
#endif
7217
#ifdef HAVE_ED448
7218
    ed448_key*      peerEd448Key;
7219
    byte            peerEd448KeyPresent;
7220
#endif
7221
#ifdef HAVE_CURVE448
7222
    curve448_key*   peerX448Key;
7223
    byte            peerX448KeyPresent;
7224
#endif
7225
#ifdef HAVE_FALCON
7226
    falcon_key*     peerFalconKey;
7227
    byte            peerFalconKeyPresent;
7228
#endif
7229
#ifdef WOLFSSL_HAVE_MLDSA
7230
    wc_MlDsaKey*    peerMlDsaKey;
7231
    byte            peerMlDsaKeyPresent;
7232
#endif
7233
#ifdef WOLFSSL_HAVE_SLHDSA
7234
    SlhDsaKey*      peerSlhDsaKey;
7235
    byte            peerSlhDsaKeyPresent;
7236
#endif
7237
#ifdef HAVE_LIBZ
7238
    z_stream        c_stream;           /* compression   stream */
7239
    z_stream        d_stream;           /* decompression stream */
7240
    byte            didStreamInit;      /* for stream init and end */
7241
#endif
7242
#ifdef WOLFSSL_DTLS
7243
    int             dtls_timeout_init;  /* starting timeout value */
7244
    int             dtls_timeout_max;   /* maximum timeout value */
7245
    int             dtls_timeout;       /* current timeout value, changes */
7246
#ifndef NO_ASN_TIME
7247
    word32          dtls_start_timeout;
7248
#endif /* !NO_ASN_TIME */
7249
    word32          dtls_tx_msg_list_sz;
7250
    word32          dtls_rx_msg_list_sz;
7251
    DtlsMsg*        dtls_tx_msg_list;
7252
    DtlsMsg*        dtls_tx_msg;
7253
    DtlsMsg*        dtls_rx_msg_list;
7254
    void*           IOCB_CookieCtx;     /* gen cookie ctx */
7255
#ifdef WOLFSSL_SESSION_EXPORT
7256
    wc_dtls_export  dtls_export;        /* export function for session */
7257
#endif
7258
#if defined(WOLFSSL_SCTP) || defined(WOLFSSL_DTLS_MTU)
7259
    word16          dtlsMtuSz;
7260
#endif /* WOLFSSL_SCTP || WOLFSSL_DTLS_MTU */
7261
#ifdef WOLFSSL_MULTICAST
7262
    void*           mcastHwCbCtx;       /* Multicast highwater callback ctx */
7263
#endif /* WOLFSSL_MULTICAST */
7264
#ifdef WOLFSSL_DTLS_DROP_STATS
7265
    word32 macDropCount;
7266
    word32 replayDropCount;
7267
#endif /* WOLFSSL_DTLS_DROP_STATS */
7268
#ifdef WOLFSSL_SRTP
7269
    word16         dtlsSrtpProfiles;   /* DTLS-with-SRTP profiles list
7270
                                        * (selected profiles - up to 16) */
7271
    word16         dtlsSrtpId;         /* DTLS-with-SRTP profile ID selected */
7272
#endif
7273
#ifdef WOLFSSL_DTLS13
7274
    RecordNumberCiphers dtlsRecordNumberEncrypt;
7275
    RecordNumberCiphers dtlsRecordNumberDecrypt;
7276
    Dtls13Epoch dtls13Epochs[DTLS13_EPOCH_SIZE];
7277
    Dtls13Epoch *dtls13EncryptEpoch;
7278
    Dtls13Epoch *dtls13DecryptEpoch;
7279
    w64wrapper dtls13Epoch;
7280
    w64wrapper dtls13PeerEpoch;
7281
    w64wrapper dtls13InvalidateBefore;
7282
    byte dtls13CurRL[DTLS_RECVD_RL_HEADER_MAX_SZ];
7283
    word16 dtls13CurRlLength;
7284
7285
    /* used to store the message if it needs to be fragmented */
7286
    buffer dtls13FragmentsBuffer;
7287
    byte dtls13SendingFragments:1;
7288
    byte dtls13SendingAckOrRtx;
7289
    byte dtls13FastTimeout:1;
7290
#ifdef HAVE_WRITE_DUP
7291
    byte dtls13KeyUpdateAcked:1;
7292
#endif
7293
    byte dtls13WaitKeyUpdateAck;
7294
    byte dtls13DoKeyUpdate;
7295
    word32 dtls13MessageLength;
7296
    word32 dtls13FragOffset;
7297
    byte dtls13FragHandshakeType;
7298
    Dtls13Rtx dtls13Rtx;
7299
    byte *dtls13ClientHello;
7300
    word16 dtls13ClientHelloSz;
7301
7302
#endif /* WOLFSSL_DTLS13 */
7303
#ifdef WOLFSSL_DTLS_CID
7304
    CIDInfo *dtlsCidInfo;
7305
#endif /* WOLFSSL_DTLS_CID */
7306
7307
#endif /* WOLFSSL_DTLS */
7308
#ifdef WOLFSSL_CALLBACKS
7309
    TimeoutInfo     timeoutInfo;        /* info saved during handshake */
7310
    HandShakeInfo   handShakeInfo;      /* info saved during handshake */
7311
#endif
7312
#ifdef OPENSSL_EXTRA
7313
    SSL_Msg_Cb      protoMsgCb;         /* inspect protocol message callback */
7314
    void*           protoMsgCtx;        /* user set context with msg callback */
7315
    word16          maxSendFragment;    /* send record plaintext cap, 0 none */
7316
#endif
7317
#if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
7318
    byte            hsInfoOn;           /* track handshake info        */
7319
    byte            toInfoOn;           /* track timeout   info        */
7320
#endif
7321
#ifdef HAVE_FUZZER
7322
    CallbackFuzzer  fuzzerCb;           /* for testing with using fuzzer */
7323
    void*           fuzzerCtx;          /* user defined pointer */
7324
#endif
7325
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
7326
    CertReqCtx*     certReqCtx;
7327
#endif
7328
#ifdef WOLFSSL_LOCAL_X509_STORE
7329
    WOLFSSL_X509_STORE* x509_store_pt; /* take ownership of external store */
7330
#endif
7331
#ifdef KEEP_PEER_CERT
7332
#ifdef WOLFSSL_DYNAMIC_PEER_CERT
7333
    WOLFSSL_X509*    peerCert;           /* X509 peer cert, NULL when none
7334
                                            or not built yet from
7335
                                            peerCertDer. Holds one reference;
7336
                                            replaced, never reused, by a new
7337
                                            cert */
7338
    DerBuffer*       peerCertDer;        /* Encoding of the peer cert until
7339
                                            peerCert is built from it, then
7340
                                            NULL. See GetPeerCert() */
7341
#else
7342
    WOLFSSL_X509     peerCert;           /* X509 peer cert */
7343
#endif
7344
#endif
7345
#ifdef KEEP_OUR_CERT
7346
    WOLFSSL_X509*    ourCert;            /* keep alive a X509 struct of cert.
7347
                                            points to ctx if not owned (owned
7348
                                            flag found in buffers.weOwnCert) */
7349
#endif
7350
    byte             keepCert;           /* keep certificate after handshake */
7351
#ifdef HAVE_EX_DATA
7352
    WOLFSSL_CRYPTO_EX_DATA ex_data; /* external data, for Fortress */
7353
#endif
7354
    int              devId;             /* async device id to use */
7355
#ifdef HAVE_ONE_TIME_AUTH
7356
    OneTimeAuth     auth;
7357
#endif
7358
#ifdef HAVE_TLS_EXTENSIONS
7359
    TLSX* extensions;                  /* RFC 6066 TLS Extensions data */
7360
    #ifdef OPENSSL_EXTRA
7361
        /* Pre-built wire bytes for app-defined custom extensions in the
7362
         * ClientHello. Produced in TLSX_GetRequestSize and consumed (then
7363
         * freed) in TLSX_WriteRequest. See WOLFSSL_CustomExt. */
7364
        byte*   customExtData;
7365
        word16  customExtSz;
7366
        /* Custom extension types actually emitted in the ClientHello, so an
7367
         * unsolicited type echoed by the server can be rejected. Rebuilt with
7368
         * customExtData; persists until the connection is freed. */
7369
        word16* customExtSent;
7370
        word16  customExtSentCnt;
7371
    #endif
7372
    #ifdef HAVE_MAX_FRAGMENT
7373
        word16 max_fragment;
7374
    #endif
7375
    #ifdef HAVE_TRUNCATED_HMAC
7376
        byte truncated_hmac;
7377
    #endif
7378
    #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
7379
        byte status_request;
7380
    #endif
7381
    #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
7382
        byte status_request_v2;
7383
    #endif
7384
    #if defined(HAVE_CRL) && (defined(HAVE_CERTIFICATE_STATUS_REQUEST) || \
7385
                              defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2))
7386
        /* Leaf CRL verdict taken while the DecodedCert was alive, applied at
7387
         * ServerHelloDone only if no stapled response replaced it. */
7388
        int  deferredCrlRet;
7389
        byte deferredCrlDone;
7390
        /* Chain CRL verdicts, indexed like the staple list, applied at the
7391
         * fallback that runs for an entry no staple and no OCSP answered. */
7392
        int  deferredChainCrlRet[1 + MAX_CHAIN_DEPTH];
7393
    #ifdef WOLFSSL_CRL_ALLOW_MISSING_CDP
7394
        /* Entries whose CRL check was skipped for want of a CDP. */
7395
        byte deferredChainCrlSkipped[1 + MAX_CHAIN_DEPTH];
7396
    #endif
7397
    #endif
7398
    #if defined(HAVE_OCSP) && defined(WOLFSSL_NONBLOCK_OCSP) && \
7399
        (defined(HAVE_CERTIFICATE_STATUS_REQUEST) || \
7400
         defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2))
7401
        /* Staples and fallback lookups that passed, indexed like the staple
7402
         * list, so a retry after a later one blocked does not repeat them. */
7403
        byte csrLookupDone[1 + MAX_CHAIN_DEPTH];
7404
    #endif
7405
    #if defined(HAVE_SECURE_RENEGOTIATION) \
7406
        || defined(HAVE_SERVER_RENEGOTIATION_INFO)
7407
        int                  secure_rene_count;    /* how many times */
7408
        SecureRenegotiation* secure_renegotiation; /* valid pointer indicates */
7409
    #endif                                         /* user turned on */
7410
    #ifdef HAVE_ALPN
7411
        byte *alpn_peer_requested; /* the ALPN bytes requested by peer, sequence
7412
                                    * of length byte + chars */
7413
        word16 alpn_peer_requested_length; /* number of bytes total */
7414
        #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX)  || \
7415
            defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_QUIC)
7416
            CallbackALPNSelect alpnSelect;
7417
            void*              alpnSelectArg;
7418
        #endif
7419
    #endif                         /* of accepted protocols */
7420
    #if !defined(NO_WOLFSSL_CLIENT) && defined(HAVE_SESSION_TICKET)
7421
        CallbackSessionTicket session_ticket_cb;
7422
        void*                 session_ticket_ctx;
7423
        byte                  expect_session_ticket;
7424
    #endif
7425
        word16 hrr_keyshare_group;
7426
#endif /* HAVE_TLS_EXTENSIONS */
7427
#ifdef HAVE_OCSP
7428
        void*       ocspIOCtx;
7429
        byte ocspProducedDate[MAX_DATE_SIZE];
7430
        int ocspProducedDateFormat;
7431
        buffer      ocspCsrResp[1 + MAX_CHAIN_DEPTH];
7432
    #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
7433
        char*   url;
7434
    #endif
7435
#if defined(WOLFSSL_TLS13) && defined(HAVE_CERTIFICATE_STATUS_REQUEST)
7436
            word32 response_idx;
7437
#endif
7438
#endif
7439
#ifdef HAVE_NETX
7440
    NetX_Ctx        nxCtx;             /* NetX IO Context */
7441
#endif
7442
#ifdef WOLFSSL_GNRC
7443
    struct gnrc_wolfssl_ctx *gnrcCtx;  /* Riot-OS GNRC UDP/IP context */
7444
#endif
7445
#ifdef SESSION_INDEX
7446
    int sessionIndex;                  /* Session's location in the cache. */
7447
#endif
7448
#ifdef ATOMIC_USER
7449
    void*    MacEncryptCtx;    /* Atomic User Mac/Encrypt Callback Context */
7450
    void*    DecryptVerifyCtx; /* Atomic User Decrypt/Verify Callback Context */
7451
    #ifdef HAVE_ENCRYPT_THEN_MAC
7452
        void*    EncryptMacCtx;    /* Atomic User Encrypt/Mac Callback Ctx */
7453
        void*    VerifyDecryptCtx; /* Atomic User Verify/Decrypt Callback Ctx */
7454
    #endif
7455
#endif
7456
#ifdef HAVE_PK_CALLBACKS
7457
    #ifdef HAVE_ECC
7458
        void* EccKeyGenCtx;          /* EccKeyGen  Callback Context */
7459
        void* EccSignCtx;            /* Ecc Sign   Callback Context */
7460
        void* EccVerifyCtx;          /* Ecc Verify Callback Context */
7461
        void* EccSharedSecretCtx;    /* Ecc Pms    Callback Context */
7462
    #endif /* HAVE_ECC */
7463
    #ifdef HAVE_HKDF
7464
        void* HkdfExtractCtx;       /* Hkdf extract callback context */
7465
    #endif
7466
    #ifdef HAVE_ED25519
7467
        void* Ed25519SignCtx;        /* ED25519 Sign   Callback Context */
7468
        void* Ed25519VerifyCtx;      /* ED25519 Verify Callback Context */
7469
    #endif
7470
    #ifdef HAVE_CURVE25519
7471
        void* X25519KeyGenCtx;       /* X25519 KeyGen Callback Context */
7472
        void* X25519SharedSecretCtx; /* X25519 Pms    Callback Context */
7473
    #endif
7474
    #ifdef HAVE_ED448
7475
        void* Ed448SignCtx;          /* ED448 Sign   Callback Context */
7476
        void* Ed448VerifyCtx;        /* ED448 Verify Callback Context */
7477
    #endif
7478
    #ifdef HAVE_CURVE448
7479
        void* X448KeyGenCtx;         /* X448 KeyGen Callback Context */
7480
        void* X448SharedSecretCtx;   /* X448 Pms    Callback Context */
7481
    #endif
7482
    #ifndef NO_DH
7483
        void* DhAgreeCtx; /* DH Pms Callback Context */
7484
    #endif /* !NO_DH */
7485
    #ifndef NO_RSA
7486
        void* RsaSignCtx;     /* Rsa Sign   Callback Context */
7487
        void* RsaVerifyCtx;   /* Rsa Verify Callback Context */
7488
        #ifdef WC_RSA_PSS
7489
            void* RsaPssSignCtx;     /* Rsa PSS Sign   Callback Context */
7490
            void* RsaPssVerifyCtx;   /* Rsa PSS Verify Callback Context */
7491
        #endif
7492
        void* RsaEncCtx;      /* Rsa Public  Encrypt   Callback Context */
7493
        void* RsaDecCtx;      /* Rsa Private Decrypt   Callback Context */
7494
    #endif /* NO_RSA */
7495
    void* GenPreMasterCtx;   /* Generate Premaster Callback Context */
7496
    void* GenMasterCtx;      /* Generate Master Callback Context */
7497
    void* GenExtMasterCtx;   /* Generate Extended Master Callback Context */
7498
    void* GenSessionKeyCtx;  /* Generate Session Key Callback Context */
7499
    void* EncryptKeysCtx;    /* Set Encrypt keys Callback Context */
7500
    void* TlsFinishedCtx;    /* Generate Tls Finished Callback Context */
7501
    void* VerifyMacCtx;      /* Verify mac Callback Context */
7502
#endif /* HAVE_PK_CALLBACKS */
7503
#ifdef HAVE_SECRET_CALLBACK
7504
        SessionSecretCb sessionSecretCb;
7505
        void*           sessionSecretCtx;
7506
        TicketParseCb   ticketParseCb;
7507
        void*           ticketParseCtx;
7508
        TlsSecretCb     tlsSecretCb;
7509
        void*           tlsSecretCtx;
7510
    #ifdef WOLFSSL_TLS13
7511
        Tls13SecretCb   tls13SecretCb;
7512
        void*           tls13SecretCtx;
7513
    #endif
7514
    #ifdef OPENSSL_EXTRA
7515
        SessionSecretCb keyLogCb;
7516
    #ifdef WOLFSSL_TLS13
7517
        Tls13SecretCb   tls13KeyLogCb;
7518
    #endif
7519
    #endif
7520
#endif /* HAVE_SECRET_CALLBACK */
7521
#ifdef WOLFSSL_JNI
7522
        void* jObjectRef;     /* reference to WolfSSLSession in JNI wrapper */
7523
#endif /* WOLFSSL_JNI */
7524
#ifdef WOLFSSL_EARLY_DATA
7525
    EarlyDataState earlyData;
7526
    word32 earlyDataSz;
7527
    byte earlyDataStatus;
7528
#endif
7529
#if defined(OPENSSL_EXTRA)
7530
    WOLFSSL_STACK* supportedCiphers; /* Used in wolfSSL_get_ciphers_compat */
7531
    WOLFSSL_STACK* peerCertChain;    /* Used in wolfSSL_get_peer_cert_chain */
7532
    WOLFSSL_STACK* verifiedChain;    /* peer cert chain to CA */
7533
#ifdef KEEP_OUR_CERT
7534
    WOLFSSL_STACK* ourCertChain;    /* Used in wolfSSL_add1_chain_cert */
7535
#endif
7536
#endif
7537
#ifdef WOLFSSL_STATIC_EPHEMERAL
7538
    StaticKeyExchangeInfo_t staticKE;
7539
#endif
7540
#ifdef WOLFSSL_MAXQ10XX_TLS
7541
    maxq_ssl_t maxq_ctx;
7542
#endif
7543
#ifdef WOLFSSL_HAVE_TLS_UNIQUE
7544
    /* Added in libest port: allow applications to get the 'tls-unique' Channel
7545
     * Binding Type (https://tools.ietf.org/html/rfc5929#section-3). This is
7546
     * used in the EST protocol to bind an enrollment to a TLS session through
7547
     * 'proof-of-possession' (https://tools.ietf.org/html/rfc7030#section-3.4
7548
     * and https://tools.ietf.org/html/rfc7030#section-3.5). */
7549
    byte clientFinished[TLS_FINISHED_SZ_MAX];
7550
    byte serverFinished[TLS_FINISHED_SZ_MAX];
7551
    byte clientFinished_len;
7552
    byte serverFinished_len;
7553
#endif
7554
#if !defined(WOLFSSL_NO_CA_NAMES) && defined(OPENSSL_EXTRA)
7555
    WOLF_STACK_OF(WOLFSSL_X509_NAME)* client_ca_names; /* Used in *_set/get_client_CA_list
7556
                                                          (server only) */
7557
    WOLF_STACK_OF(WOLFSSL_X509_NAME)* ca_names;        /* Used in *_set0/get0_CA_list */
7558
    WOLF_STACK_OF(WOLFSSL_X509_NAME)* peer_ca_names;   /* Used in *_get0_peer_CA_list
7559
                                                          and (client only)
7560
                                                          wolfSSL_get_client_CA_list */
7561
#endif
7562
#if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES) && \
7563
    defined(WOLFSSL_TLS13)
7564
    /* wolfSSL native CA DN list sent in certificate_authorities. */
7565
    CertificateAuthority* ws_ca_names;
7566
    /* wolfSSL native CA DN list received from the peer. */
7567
    CertificateAuthority* ws_peer_ca_names;
7568
#endif
7569
#if defined(WOLFSSL_IOTSAFE) && defined(HAVE_PK_CALLBACKS)
7570
    IOTSAFE iotsafe;
7571
#endif
7572
#ifdef WOLFSSL_LWIP_NATIVE
7573
    WOLFSSL_LWIP_NATIVE_STATE      lwipCtx; /* LwIP native socket IO Context */
7574
#endif
7575
#ifdef WOLFSSL_QUIC
7576
    struct {
7577
        const WOLFSSL_QUIC_METHOD* method;
7578
        WOLFSSL_ENCRYPTION_LEVEL enc_level_read;
7579
        WOLFSSL_ENCRYPTION_LEVEL enc_level_read_next;
7580
        WOLFSSL_ENCRYPTION_LEVEL enc_level_latest_recvd;
7581
        WOLFSSL_ENCRYPTION_LEVEL enc_level_write;
7582
        WOLFSSL_ENCRYPTION_LEVEL enc_level_write_next;
7583
        int transport_version;
7584
        const QuicTransportParam* transport_local;
7585
        const QuicTransportParam* transport_peer;
7586
        const QuicTransportParam* transport_peer_draft;
7587
        QuicRecord* input_head;          /* we own, data for handshake */
7588
        QuicRecord* input_tail;          /* points to last element for append */
7589
        QuicRecord* scratch;             /* we own, record construction */
7590
        enum wolfssl_encryption_level_t output_rec_level;
7591
                                         /* encryption level of current output record */
7592
        word32 output_rec_remain;        /* how many bytes of output TLS record
7593
                                          * content have not been handled yet by quic */
7594
    } quic;
7595
#endif /* WOLFSSL_QUIC */
7596
#if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
7597
    WOLFSSL_EchConfig* echConfigs;
7598
    WOLFSSL_EchConfig* echRetryConfigs;
7599
#endif
7600
#if defined(WOLFSSL_TLS13) && defined(HAVE_ECH) && defined(WOLFSSL_TEST_ECH)
7601
    /* Test-only hook: called on the client before ECH encryption, after the
7602
     * inner ClientHello body is fully constructed. The callback may modify
7603
     * innerCh in-place (length stays the same). */
7604
    int (*echInnerHelloCb)(byte* innerCh, word32 innerChLen);
7605
#endif
7606
7607
#if defined(WOLFSSL_SNIFFER) && defined(WOLFSSL_SNIFFER_KEYLOGFILE)
7608
    SSLSnifferSecretCb snifferSecretCb;
7609
#endif /* WOLFSSL_SNIFFER && WOLFSSL_SNIFFER_KEYLOGFILE */
7610
#ifdef WOLFSSL_DUAL_ALG_CERTS
7611
    byte *sigSpec;         /* This pointer never owns the memory. */
7612
    word16 sigSpecSz;
7613
    byte *peerSigSpec;     /* This pointer always owns the memory. */
7614
    word16 peerSigSpecSz;
7615
#endif
7616
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
7617
    int secLevel; /* The security level of system-wide crypto policy. */
7618
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
7619
#if !defined(NO_WOLFSSL_CLIENT) && !defined(WOLFSSL_NO_TLS12) && \
7620
    defined(HAVE_SERVER_RENEGOTIATION_INFO) && \
7621
    !defined(WOLFSSL_HARDEN_TLS_NO_SCR_CHECK)
7622
    WC_BITFIELD          scr_check_enabled:1;  /* enable/disable SCR check */
7623
#endif
7624
#ifdef HAVE_WRITE_DUP
7625
#ifdef WOLFSSL_TLS13
7626
#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
7627
    WC_BITFIELD postHandshakeAuthPending:1;
7628
    WC_BITFIELD postHandshakeAuthPublish:1;
7629
#endif
7630
#endif
7631
#endif
7632
    /* Cached BuildMessage(sizeOnly) overhead (recordSz - payloadSz) for AEAD
7633
     * ciphers; 0 means uncached and is never a valid AEAD overhead. EtM does
7634
     * not apply to AEAD. */
7635
    word32 recordSzOverhead;
7636
#ifdef WOLFSSL_ASYNC_CRYPT
7637
    /* Async device for the TLS 1.3 key schedule: HKDF has no key object
7638
     * to carry one. Event bookkeeping only, for the callback re-invoke
7639
     * path (never wolfAsync_DevCtxInit'd, no hardware context). */
7640
    WC_ASYNC_DEV kdfAsyncDev;
7641
#endif
7642
    /* Key-schedule resume steps: completed derives must not re-run (e.g.
7643
     * the extract is in place over preMasterSecret). Unconditional so the
7644
     * schedule needs no ifdefs; without async they stay 0. */
7645
    byte kdfDeriveStep;  /* enum Tls13KdfSendStep (send side) */
7646
    byte kdfMsgStep;     /* enum Tls13KdfMsgStep (receive side) */
7647
    byte kdfMsgType;     /* handshake type kdfMsgStep belongs to */
7648
#if defined(WOLFSSL_ASYNC_REINVOKE) && defined(WOLFSSL_TLS13) && \
7649
    !defined(NO_HMAC)
7650
    /* Transcript HMAC (Finished verify_data, PSK binders) held across a
7651
     * WC_PENDING_E so the retry re-invokes the same object and arguments,
7652
     * bound to its output buffer. */
7653
    Hmac* hsHmac;
7654
    byte* hsHmacOut;
7655
    byte  hsHmacStep;
7656
#endif
7657
};
7658
7659
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
7660
#define WOLFSSL_SECLEVEL_STR "@SECLEVEL="
7661
struct SystemCryptoPolicy {
7662
    int    enabled;
7663
    int    secLevel;
7664
    char   str[MAX_WOLFSSL_CRYPTO_POLICY_SIZE + 1]; /* + 1 for null term */
7665
};
7666
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
7667
7668
/*
7669
 * wolfSSL_PEM_read_bio_X509 pushes an ASN_NO_PEM_HEADER error
7670
 * to the error queue on file end. This should not be left
7671
 * for the caller to find so we clear the last error.
7672
 */
7673
#if defined(OPENSSL_EXTRA) && defined(WOLFSSL_HAVE_ERROR_QUEUE)
7674
#define CLEAR_ASN_NO_PEM_HEADER_ERROR(err)                                     \
7675
do {                                                                           \
7676
    (err) = wolfSSL_ERR_peek_last_error();                                     \
7677
    if (wolfSSL_ERR_GET_LIB(err) == WOLFSSL_ERR_LIB_PEM &&                     \
7678
        wolfSSL_ERR_GET_REASON(err) ==                                         \
7679
            -WC_NO_ERR_TRACE(WOLFSSL_PEM_R_NO_START_LINE_E)) {                 \
7680
        unsigned long peekErr;                                                 \
7681
        do {                                                                   \
7682
            wc_RemoveErrorNode(-1);                                            \
7683
            peekErr = wolfSSL_ERR_peek_last_error();                           \
7684
        } while (wolfSSL_ERR_GET_LIB(peekErr) == WOLFSSL_ERR_LIB_PEM &&        \
7685
                 wolfSSL_ERR_GET_REASON(peekErr) ==                            \
7686
                 -WC_NO_ERR_TRACE(WOLFSSL_PEM_R_NO_START_LINE_E));             \
7687
    }                                                                          \
7688
} while(0)
7689
#else
7690
0
#define CLEAR_ASN_NO_PEM_HEADER_ERROR(err) (void)(err);
7691
#endif
7692
7693
/*
7694
 * The SSL object may have its own certificate store. The below macros simplify
7695
 * logic for choosing which WOLFSSL_CERT_MANAGER and WOLFSSL_X509_STORE to use.
7696
 * Always use SSL specific objects when available and revert to CTX otherwise.
7697
 */
7698
#ifdef WOLFSSL_LOCAL_X509_STORE
7699
#define SSL_CM(ssl) ((ssl)->x509_store_pt ? (ssl)->x509_store_pt->cm : \
7700
                     ((ssl)->ctx->x509_store_pt ? (ssl)->ctx->x509_store_pt->cm : \
7701
                                            (ssl)->ctx->cm))
7702
#define SSL_STORE(ssl) ((ssl)->x509_store_pt ? (ssl)->x509_store_pt : \
7703
                  ((ssl)->ctx->x509_store_pt ? (ssl)->ctx->x509_store_pt : \
7704
                                            &(ssl)->ctx->x509_store))
7705
#define CTX_STORE(ctx) ((ctx)->x509_store_pt ? (ctx)->x509_store_pt : \
7706
                                            &(ctx)->x509_store)
7707
#else
7708
0
#define SSL_CM(ssl) (ssl)->ctx->cm
7709
#endif
7710
/* Issue warning when we are modifying the overall context CM */
7711
#define SSL_CM_WARNING(ssl) \
7712
0
    do {                                                             \
7713
0
        if (SSL_CM( (ssl) ) == (ssl)->ctx->cm) {                     \
7714
0
            WOLFSSL_MSG("Modifying SSL_CTX CM not SSL specific CM"); \
7715
0
        }                                                            \
7716
0
    } while (0)
7717
7718
WOLFSSL_LOCAL int  SetSSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup);
7719
WOLFSSL_LOCAL int  InitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup);
7720
WOLFSSL_LOCAL int  ReinitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup);
7721
WOLFSSL_LOCAL void FreeSSL(WOLFSSL* ssl, void* heap);
7722
WOLFSSL_TEST_VIS   void wolfSSL_ResourceFree(WOLFSSL* ssl);   /* Micrium uses */
7723
#ifndef OPENSSL_COEXIST
7724
#define SSL_ResourceFree wolfSSL_ResourceFree
7725
#endif
7726
7727
7728
#ifndef NO_CERTS
7729
7730
    WOLFSSL_LOCAL int ProcessBuffer(WOLFSSL_CTX* ctx, const unsigned char* buff,
7731
                                    long sz, int format, int type, WOLFSSL* ssl,
7732
                                    long* used, int userChain, int verify,
7733
                                    const char *source_name);
7734
    WOLFSSL_LOCAL int ProcessFile(WOLFSSL_CTX* ctx, const char* fname, int format,
7735
                                 int type, WOLFSSL* ssl, int userChain,
7736
                                WOLFSSL_CRL* crl, int verify);
7737
7738
    #ifndef NO_ASN
7739
    WOLFSSL_LOCAL int CheckHostName(DecodedCert* dCert, const char *domainName,
7740
                                    size_t domainNameLen, unsigned int flags,
7741
                                    byte isIP);
7742
    #endif
7743
#endif
7744
7745
7746
#if defined(WOLFSSL_CALLBACKS) || defined(OPENSSL_EXTRA)
7747
    WOLFSSL_LOCAL void InitHandShakeInfo(HandShakeInfo* info, WOLFSSL* ssl);
7748
    WOLFSSL_LOCAL void FinishHandShakeInfo(HandShakeInfo* info);
7749
    WOLFSSL_LOCAL void AddPacketName(WOLFSSL* ssl, const char* name);
7750
7751
    WOLFSSL_LOCAL void InitTimeoutInfo(TimeoutInfo* info);
7752
    WOLFSSL_LOCAL void FreeTimeoutInfo(TimeoutInfo* info, void* heap);
7753
    WOLFSSL_LOCAL int AddPacketInfo(WOLFSSL* ssl, const char* name, int type,
7754
                             const byte* data, int sz, int written, int lateRL,
7755
                             void* heap);
7756
    WOLFSSL_LOCAL void AddLateName(const char* name, TimeoutInfo* info);
7757
    WOLFSSL_LOCAL void AddLateRecordHeader(const RecordLayerHeader* rl,
7758
                                           TimeoutInfo* info);
7759
#endif
7760
7761
7762
/* Record Layer Header identifier from page 12 */
7763
enum ContentType {
7764
    no_type            = 0,
7765
    change_cipher_spec = 20,
7766
    alert              = 21,
7767
    handshake          = 22,
7768
    application_data   = 23,
7769
    dtls12_cid         = 25,
7770
#ifdef WOLFSSL_DTLS13
7771
    ack                = 26,
7772
#endif /* WOLFSSL_DTLS13 */
7773
    WOLF_ENUM_DUMMY_LAST_ELEMENT(ContentType)
7774
};
7775
7776
7777
/* handshake header, same for each message type, pgs 20/21 */
7778
typedef struct HandShakeHeader {
7779
    byte            type;
7780
    word24          length;
7781
} HandShakeHeader;
7782
7783
7784
/* DTLS handshake header, same for each message type */
7785
typedef struct DtlsHandShakeHeader {
7786
    byte            type;
7787
    word24          length;
7788
    byte            message_seq[2];    /* start at 0, retransmit gets same # */
7789
    word24          fragment_offset;   /* bytes in previous fragments */
7790
    word24          fragment_length;   /* length of this fragment */
7791
} DtlsHandShakeHeader;
7792
7793
7794
enum HandShakeType {
7795
    hello_request        =   0,
7796
    client_hello         =   1,
7797
    server_hello         =   2,
7798
    hello_verify_request =   3,    /* DTLS addition */
7799
    session_ticket       =   4,
7800
    end_of_early_data    =   5,
7801
    hello_retry_request  =   6,
7802
    encrypted_extensions =   8,
7803
    request_connection_id =  9,    /* DTLS v1.3 addition (RFC 9147) */
7804
    new_connection_id    =  10,    /* DTLS v1.3 addition (RFC 9147) */
7805
    certificate          =  11,
7806
    server_key_exchange  =  12,
7807
    certificate_request  =  13,
7808
    server_hello_done    =  14,
7809
    certificate_verify   =  15,
7810
    client_key_exchange  =  16,
7811
    finished             =  20,
7812
    certificate_status   =  22,
7813
    key_update           =  24,
7814
    change_cipher_hs     =  55,    /* simulate unique handshake type for sanity
7815
                                      checks.  record layer change_cipher
7816
                                      conflicts with handshake finished */
7817
    message_hash         = 254,    /* synthetic message type for TLS v1.3 */
7818
    no_shake             = 255     /* used to initialize the DtlsMsg record */
7819
};
7820
7821
enum ProvisionSide {
7822
    PROVISION_CLIENT = 1,
7823
    PROVISION_SERVER = 2,
7824
    PROVISION_CLIENT_SERVER = 3
7825
};
7826
7827
/* cipher requirements */
7828
enum {
7829
    REQUIRES_RSA,
7830
    REQUIRES_DHE,
7831
    REQUIRES_ECC,
7832
    REQUIRES_ECC_STATIC,
7833
    REQUIRES_PSK,
7834
    REQUIRES_RSA_SIG,
7835
    REQUIRES_AEAD
7836
};
7837
7838
static const byte kTlsClientStr[SIZEOF_SENDER+1] = { 0x43, 0x4C, 0x4E, 0x54, 0x00 }; /* CLNT */
7839
static const byte kTlsServerStr[SIZEOF_SENDER+1] = { 0x53, 0x52, 0x56, 0x52, 0x00 }; /* SRVR */
7840
7841
static const byte kTlsClientFinStr[FINISHED_LABEL_SZ + 1] = "client finished";
7842
static const byte kTlsServerFinStr[FINISHED_LABEL_SZ + 1] = "server finished";
7843
7844
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || defined(HAVE_CURL)
7845
typedef struct {
7846
    int name_len;
7847
    const char *name;
7848
    int nid;
7849
    word16 curve;
7850
} WOLF_EC_NIST_NAME;
7851
extern const WOLF_EC_NIST_NAME kNistCurves[];
7852
WOLFSSL_LOCAL int set_curves_list(WOLFSSL* ssl, WOLFSSL_CTX *ctx,
7853
        const char* names, byte curves_only);
7854
#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL || HAVE_CURL */
7855
7856
/* internal functions */
7857
WOLFSSL_LOCAL int SendChangeCipher(WOLFSSL* ssl);
7858
WOLFSSL_LOCAL int SendTicket(WOLFSSL* ssl);
7859
#ifdef HAVE_SESSION_TICKET
7860
WOLFSSL_LOCAL int DoDecryptTicket(const WOLFSSL* ssl, const byte* input,
7861
        word32 len, InternalTicket **it);
7862
/* Return 0 when check successful. <0 on failure. */
7863
WOLFSSL_LOCAL void DoClientTicketFinalize(WOLFSSL* ssl, InternalTicket* it,
7864
                                          const WOLFSSL_SESSION* sess);
7865
7866
#ifdef WOLFSSL_TLS13
7867
WOLFSSL_LOCAL int DoClientTicketCheck(const WOLFSSL* ssl,
7868
        const PreSharedKey* psk, sword64 timeout, const byte* suite);
7869
WOLFSSL_LOCAL void CleanupClientTickets(PreSharedKey* psk);
7870
WOLFSSL_LOCAL int DoClientTicket_ex(const WOLFSSL* ssl, PreSharedKey* psk,
7871
                                    int retainSess);
7872
#endif
7873
7874
WOLFSSL_LOCAL int DoClientTicket(WOLFSSL* ssl, const byte* input, word32 len);
7875
#endif /* HAVE_SESSION_TICKET */
7876
/* TicketSniHash, TicketAlpnHash, and VerifyTicketBinding are defined in
7877
 * internal.c only when !NO_WOLFSSL_SERVER && !NO_TLS - gate the
7878
 * declarations to match so client-only or no-TLS builds don't compile in
7879
 * call sites that would fail to link. */
7880
#if !defined(NO_WOLFSSL_SERVER) && !defined(NO_TLS)
7881
#ifdef HAVE_SNI
7882
WOLFSSL_LOCAL int TicketSniHash(WOLFSSL* ssl, byte* dst);
7883
#endif
7884
#ifdef HAVE_ALPN
7885
WOLFSSL_LOCAL int TicketAlpnHash(WOLFSSL* ssl, byte* dst);
7886
#endif
7887
#if defined(HAVE_SNI) || defined(HAVE_ALPN)
7888
WOLFSSL_LOCAL int VerifyTicketBinding(WOLFSSL* ssl);
7889
#endif
7890
#endif /* !NO_WOLFSSL_SERVER && !NO_TLS */
7891
WOLFSSL_LOCAL int SendData(WOLFSSL* ssl, const void* data, size_t sz);
7892
#ifdef WOLFSSL_THREADED_CRYPT
7893
WOLFSSL_LOCAL int SendAsyncData(WOLFSSL* ssl);
7894
#endif
7895
#ifdef WOLFSSL_TLS13
7896
WOLFSSL_LOCAL int SendTls13ServerHello(WOLFSSL* ssl, byte extMsgType);
7897
#endif
7898
WOLFSSL_LOCAL int SendCertificate(WOLFSSL* ssl);
7899
WOLFSSL_LOCAL int SendCertificateRequest(WOLFSSL* ssl);
7900
#if defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
7901
 || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
7902
WOLFSSL_LOCAL int CreateOcspResponse(WOLFSSL* ssl, OcspRequest** ocspRequest,
7903
                       buffer* response);
7904
#endif
7905
#if !defined(NO_WOLFSSL_SERVER) && \
7906
    (defined(HAVE_CERTIFICATE_STATUS_REQUEST) || \
7907
     defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2))
7908
#ifdef WOLFSSL_API_PREFIX_MAP
7909
    #define FreeCtxOcspRequestCache wolfSSL_FreeCtxOcspRequestCache
7910
#endif
7911
WOLFSSL_TEST_VIS void FreeCtxOcspRequestCache(WOLFSSL_CTX* ctx);
7912
#else
7913
0
    #define FreeCtxOcspRequestCache(ctx) WC_DO_NOTHING
7914
#endif
7915
#if defined(HAVE_SECURE_RENEGOTIATION) && \
7916
    !defined(NO_WOLFSSL_SERVER)
7917
WOLFSSL_LOCAL int SendHelloRequest(WOLFSSL* ssl);
7918
#endif
7919
WOLFSSL_LOCAL int SendCertificateStatus(WOLFSSL* ssl);
7920
WOLFSSL_LOCAL int SendServerKeyExchange(WOLFSSL* ssl);
7921
WOLFSSL_LOCAL int SendBuffered(WOLFSSL* ssl);
7922
WOLFSSL_LOCAL int ReceiveData(WOLFSSL* ssl, byte* output, size_t sz, int peek);
7923
WOLFSSL_LOCAL int SendFinished(WOLFSSL* ssl);
7924
WOLFSSL_LOCAL int RetrySendAlert(WOLFSSL* ssl);
7925
WOLFSSL_LOCAL int SendAlert(WOLFSSL* ssl, int severity, int type);
7926
WOLFSSL_LOCAL int SendFatalAlertOnly(WOLFSSL *ssl, int error);
7927
WOLFSSL_LOCAL int ProcessReply(WOLFSSL* ssl);
7928
WOLFSSL_LOCAL int ProcessReplyEx(WOLFSSL* ssl, int allowSocketErr);
7929
7930
WOLFSSL_LOCAL const char* AlertTypeToString(int type);
7931
7932
WOLFSSL_LOCAL int SetCipherSpecs(WOLFSSL* ssl);
7933
WOLFSSL_LOCAL int GetCipherSpec(word16 side, byte cipherSuite0,
7934
        byte cipherSuite, CipherSpecs* specs, Options* opts);
7935
WOLFSSL_LOCAL int MakeMasterSecret(WOLFSSL* ssl);
7936
7937
WOLFSSL_LOCAL int DeriveKeys(WOLFSSL* ssl);
7938
WOLFSSL_LOCAL int StoreKeys(WOLFSSL* ssl, const byte* keyData, int side);
7939
7940
WOLFSSL_LOCAL int IsTLS(const WOLFSSL* ssl);
7941
WOLFSSL_LOCAL int IsTLS_ex(const ProtocolVersion pv);
7942
WOLFSSL_LOCAL int IsAtLeastTLSv1_2(const WOLFSSL* ssl);
7943
WOLFSSL_LOCAL int IsAtLeastTLSv1_3(const ProtocolVersion pv);
7944
WOLFSSL_LOCAL int IsWriteClosed(const WOLFSSL* ssl);
7945
WOLFSSL_LOCAL int IsEncryptionOn(const WOLFSSL* ssl, int isSend);
7946
WOLFSSL_LOCAL int TLSv1_3_Capable(WOLFSSL* ssl);
7947
7948
WOLFSSL_LOCAL void FreeHandshakeResources(WOLFSSL* ssl);
7949
WOLFSSL_LOCAL void ShrinkInputBuffer(WOLFSSL* ssl, int forcedFree);
7950
WOLFSSL_LOCAL void ShrinkOutputBuffer(WOLFSSL* ssl);
7951
WOLFSSL_LOCAL byte* GetOutputBuffer(WOLFSSL* ssl);
7952
7953
WOLFSSL_LOCAL int CipherRequires(byte first, byte second, int requirement);
7954
WOLFSSL_LOCAL int VerifyClientSuite(word16 havePSK, byte cipherSuite0,
7955
                                    byte cipherSuite);
7956
7957
WOLFSSL_LOCAL int SetTicket(WOLFSSL* ssl, const byte* ticket, word32 length);
7958
WOLFSSL_TEST_VIS int wolfssl_local_GetRecordSize(WOLFSSL *ssl, int payloadSz,
7959
        int isEncrypted);
7960
WOLFSSL_LOCAL int wolfssl_local_GetMaxPlaintextSize(WOLFSSL *ssl);
7961
WOLFSSL_LOCAL int wolfSSL_GetMaxFragSize(WOLFSSL* ssl);
7962
WOLFSSL_LOCAL int wolfssl_local_GetMaxSendFragSize(WOLFSSL* ssl);
7963
7964
#if defined(WOLFSSL_IOTSAFE) && defined(HAVE_PK_CALLBACKS)
7965
WOLFSSL_LOCAL IOTSAFE *wolfSSL_get_iotsafe_ctx(WOLFSSL *ssl);
7966
WOLFSSL_LOCAL int wolfSSL_set_iotsafe_ctx(WOLFSSL *ssl, IOTSAFE *iotsafe);
7967
#endif
7968
7969
#if (defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)) && defined(HAVE_ECC)
7970
WOLFSSL_LOCAL int SetECKeyInternal(WOLFSSL_EC_KEY* eckey);
7971
WOLFSSL_LOCAL int SetECKeyExternal(WOLFSSL_EC_KEY* eckey);
7972
#endif
7973
7974
#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL)
7975
WOLFSSL_LOCAL int wolfSSL_curve_is_disabled(const WOLFSSL* ssl,
7976
                                            word16 curve_id);
7977
#else
7978
static WC_INLINE int wolfSSL_curve_is_disabled(const WOLFSSL* ssl,
7979
                                               word16 curve_id)
7980
0
{
7981
0
    (void)ssl;
7982
0
    (void)curve_id;
7983
0
    return 0;
7984
0
}
Unexecuted instantiation: asn.c:wolfSSL_curve_is_disabled
Unexecuted instantiation: ssl.c:wolfSSL_curve_is_disabled
Unexecuted instantiation: tls.c:wolfSSL_curve_is_disabled
Unexecuted instantiation: tls13.c:wolfSSL_curve_is_disabled
Unexecuted instantiation: internal.c:wolfSSL_curve_is_disabled
Unexecuted instantiation: keys.c:wolfSSL_curve_is_disabled
Unexecuted instantiation: wolfio.c:wolfSSL_curve_is_disabled
7985
#endif
7986
7987
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
7988
WOLFSSL_LOCAL WC_RNG* WOLFSSL_RSA_GetRNG(WOLFSSL_RSA *rsa, WC_RNG **tmpRNG,
7989
                                         int *initTmpRng);
7990
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
7991
7992
    #ifndef NO_RSA
7993
        #ifdef WC_RSA_PSS
7994
            WOLFSSL_LOCAL int CheckRsaPssPadding(const byte* plain, word32 plainSz,
7995
                byte* out, word32 sigSz, enum wc_HashType hashType);
7996
            WOLFSSL_LOCAL int ConvertHashPss(int hashAlgo,
7997
                enum wc_HashType* hashType, int* mgf);
7998
        #endif
7999
        WOLFSSL_LOCAL int VerifyRsaSign(WOLFSSL* ssl, byte* verifySig,
8000
            word32 sigSz, const byte* plain, word32 plainSz, int sigAlgo,
8001
            int hashAlgo, RsaKey* key, DerBuffer* keyBufInfo);
8002
        WOLFSSL_LOCAL int RsaSign(WOLFSSL* ssl, const byte* in, word32 inSz,
8003
            byte* out, word32* outSz, int sigAlgo, int hashAlgo, RsaKey* key,
8004
            DerBuffer* keyBufInfo);
8005
        WOLFSSL_LOCAL int RsaVerify(WOLFSSL* ssl, byte* in, word32 inSz,
8006
            byte** out, int sigAlgo, int hashAlgo, RsaKey* key,
8007
            buffer* keyBufInfo);
8008
        WOLFSSL_LOCAL int RsaDec(WOLFSSL* ssl, byte* in, word32 inSz, byte** out,
8009
            word32* outSz, RsaKey* key, DerBuffer* keyBufInfo);
8010
        WOLFSSL_LOCAL int RsaEnc(WOLFSSL* ssl, const byte* in, word32 inSz, byte* out,
8011
            word32* outSz, RsaKey* key, buffer* keyBufInfo);
8012
    #endif /* !NO_RSA */
8013
8014
    #ifdef HAVE_ECC
8015
        WOLFSSL_LOCAL int EccSign(WOLFSSL* ssl, const byte* in, word32 inSz,
8016
            byte* out, word32* outSz, ecc_key* key, DerBuffer* keyBufInfo);
8017
        WOLFSSL_LOCAL int EccVerify(WOLFSSL* ssl, const byte* in, word32 inSz,
8018
            const byte* out, word32 outSz, ecc_key* key, buffer* keyBufInfo);
8019
        WOLFSSL_LOCAL int EccSharedSecret(WOLFSSL* ssl, ecc_key* priv_key,
8020
            ecc_key* pub_key, byte* pubKeyDer, word32* pubKeySz, byte* out,
8021
            word32* outlen, int side);
8022
    #endif /* HAVE_ECC */
8023
    #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
8024
        WOLFSSL_LOCAL int Sm2wSm3Sign(WOLFSSL* ssl, const byte* id, word32 idSz,
8025
            const byte* in, word32 inSz, byte* out, word32* outSz, ecc_key* key,
8026
            DerBuffer* keyBufInfo);
8027
        WOLFSSL_LOCAL int Sm2wSm3Verify(WOLFSSL* ssl, const byte* id,
8028
            word32 idSz, const byte* in, word32 inSz, const byte* out,
8029
            word32 outSz, ecc_key* key, buffer* keyBufInfo);
8030
    #endif /* WOLFSSL_SM2 && WOLFSSL_SM3 */
8031
    #ifdef HAVE_ED25519
8032
        WOLFSSL_LOCAL int Ed25519CheckPubKey(WOLFSSL* ssl);
8033
        WOLFSSL_LOCAL int Ed25519Sign(WOLFSSL* ssl, const byte* in, word32 inSz,
8034
            byte* out, word32* outSz, ed25519_key* key, DerBuffer* keyBufInfo);
8035
        WOLFSSL_LOCAL int Ed25519Verify(WOLFSSL* ssl, const byte* in,
8036
            word32 inSz, const byte* msg, word32 msgSz, ed25519_key* key,
8037
            buffer* keyBufInfo);
8038
    #endif /* HAVE_ED25519 */
8039
    #ifdef HAVE_ED448
8040
        WOLFSSL_LOCAL int Ed448CheckPubKey(WOLFSSL* ssl);
8041
        WOLFSSL_LOCAL int Ed448Sign(WOLFSSL* ssl, const byte* in, word32 inSz,
8042
            byte* out, word32* outSz, ed448_key* key, DerBuffer* keyBufInfo);
8043
        WOLFSSL_LOCAL int Ed448Verify(WOLFSSL* ssl, const byte* in,
8044
            word32 inSz, const byte* msg, word32 msgSz, ed448_key* key,
8045
            buffer* keyBufInfo);
8046
    #endif /* HAVE_ED448 */
8047
8048
#ifndef NO_CERTS
8049
    #ifdef WOLFSSL_TRUST_PEER_CERT
8050
8051
        /* options for searching hash table for a matching trusted peer cert */
8052
        #define WC_MATCH_SKID 0
8053
        #define WC_MATCH_NAME 1
8054
8055
        WOLFSSL_LOCAL TrustedPeerCert* GetTrustedPeer(WOLFSSL_CERT_MANAGER* cm,
8056
                DecodedCert* cert);
8057
    #endif
8058
8059
8060
    #ifndef GetCA
8061
        WOLFSSL_LOCAL Signer* GetCA(WOLFSSL_CERT_MANAGER* cm, byte* hash);
8062
    #endif
8063
    #if defined(WOLFSSL_AKID_NAME) && !defined(WC_SYM_RELOC_TABLES)
8064
        /* note WOLFSSL_API_PREFIX_MAPping is in asn.h, and if
8065
         * WC_SYM_RELOC_TABLES, the prototype is in the port layer
8066
         * (e.g. linuxkm_wc_port.h), to allow shimming.
8067
         */
8068
        WOLFSSL_TEST_VIS Signer* GetCAByAKID(WOLFSSL_CERT_MANAGER* cm,
8069
                const byte* issuer, word32 issuerSz, const byte* serial,
8070
                word32 serialSz);
8071
    #endif
8072
    #if defined(HAVE_OCSP) && !defined(GetCAByKeyHash)
8073
        WOLFSSL_LOCAL Signer* GetCAByKeyHash(WOLFSSL_CERT_MANAGER* cm,
8074
                const byte* keyHash);
8075
    #endif
8076
    #if !defined(NO_SKID) && !defined(GetCAByName)
8077
        WOLFSSL_LOCAL Signer* GetCAByName(WOLFSSL_CERT_MANAGER* cm,
8078
                byte* hash);
8079
    #endif
8080
#endif /* !NO_CERTS */
8081
WOLFSSL_LOCAL int  BuildTlsHandshakeHash(WOLFSSL* ssl, byte* hash,
8082
                                   word32* hashLen);
8083
WOLFSSL_LOCAL int  BuildTlsFinished(WOLFSSL* ssl, Hashes* hashes,
8084
                                   const byte* sender);
8085
WOLFSSL_LOCAL void FreeArrays(WOLFSSL* ssl, int keep);
8086
WOLFSSL_LOCAL  int CheckAvailableSize(WOLFSSL *ssl, int size);
8087
WOLFSSL_LOCAL  int GrowInputBuffer(WOLFSSL* ssl, int size, int usedLength);
8088
WOLFSSL_LOCAL  int MsgCheckEncryption(WOLFSSL* ssl, byte type, byte encrypted);
8089
WOLFSSL_LOCAL  int EarlySanityCheckMsgReceived(WOLFSSL* ssl, byte type,
8090
        word32 msgSz);
8091
WOLFSSL_LOCAL int GetHandshakeHeader(WOLFSSL* ssl, const byte* input,
8092
        word32* inOutIdx, byte* type, word32* size, word32 totalSz);
8093
#if !defined(NO_WOLFSSL_CLIENT) || !defined(WOLFSSL_NO_CLIENT_AUTH)
8094
WOLFSSL_LOCAL void DoCertFatalAlert(WOLFSSL* ssl, int ret);
8095
#endif
8096
#ifndef NO_TLS
8097
    WOLFSSL_LOCAL int  MakeTlsMasterSecret(WOLFSSL* ssl);
8098
#ifndef WOLFSSL_AEAD_ONLY
8099
    WOLFSSL_LOCAL int  TLS_hmac(WOLFSSL* ssl, byte* digest, const byte* in,
8100
                                word32 sz, int padSz, int content, int verify, int epochOrder);
8101
#endif
8102
#endif
8103
8104
WOLFSSL_LOCAL int cipherExtraData(WOLFSSL* ssl);
8105
WOLFSSL_LOCAL word32 MacSize(const WOLFSSL* ssl);
8106
8107
#ifndef NO_WOLFSSL_CLIENT
8108
    WOLFSSL_LOCAL int HaveUniqueSessionObj(WOLFSSL* ssl);
8109
    WOLFSSL_LOCAL int SendClientHello(WOLFSSL* ssl);
8110
    WOLFSSL_LOCAL int DoHelloVerifyRequest(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
8111
        word32 size);
8112
    #ifdef WOLFSSL_TLS13
8113
    WOLFSSL_LOCAL int SendTls13ClientHello(WOLFSSL* ssl);
8114
    #endif
8115
    WOLFSSL_LOCAL int SendClientKeyExchange(WOLFSSL* ssl);
8116
    WOLFSSL_LOCAL int SendCertificateVerify(WOLFSSL* ssl);
8117
#endif /* NO_WOLFSSL_CLIENT */
8118
8119
#ifndef NO_WOLFSSL_SERVER
8120
    WOLFSSL_LOCAL int SendServerHello(WOLFSSL* ssl);
8121
    WOLFSSL_LOCAL int SendServerHelloDone(WOLFSSL* ssl);
8122
#endif /* NO_WOLFSSL_SERVER */
8123
8124
#ifdef WOLFSSL_TLS13
8125
    WOLFSSL_LOCAL int SendTls13KeyUpdate(WOLFSSL* ssl);
8126
WOLFSSL_LOCAL int Tls13KeyUpdateLimitReached(WOLFSSL* ssl);
8127
#endif
8128
8129
#ifdef WOLFSSL_DTLS
8130
    #ifdef WOLFSSL_API_PREFIX_MAP
8131
        #define DtlsMsgListDelete wolfSSL_DtlsMsgListDelete
8132
        #define DtlsMsgListPurge wolfSSL_DtlsMsgListPurge
8133
        #define DtlsMsgListNextReady wolfSSL_DtlsMsgListNextReady
8134
        #define DtlsMsgFind wolfSSL_DtlsMsgFind
8135
        #define DtlsMsgStore wolfSSL_DtlsMsgStore
8136
    #endif /* WOLFSSL_API_PREFIX_MAP */
8137
    WOLFSSL_LOCAL DtlsMsg* DtlsMsgNew(word32 sz, byte tx, void* heap);
8138
    WOLFSSL_LOCAL void DtlsMsgDelete(DtlsMsg* item, void* heap);
8139
    WOLFSSL_TEST_VIS void DtlsMsgListDelete(DtlsMsg* head, void* heap);
8140
    WOLFSSL_TEST_VIS void DtlsMsgListPurge(WOLFSSL* ssl);
8141
    WOLFSSL_TEST_VIS DtlsMsg* DtlsMsgListNextReady(WOLFSSL* ssl);
8142
    WOLFSSL_LOCAL void DtlsMsgListRemove(WOLFSSL* ssl, DtlsMsg* item);
8143
    WOLFSSL_LOCAL void DtlsTxMsgListClean(WOLFSSL* ssl);
8144
    WOLFSSL_LOCAL int  DtlsMsgSet(DtlsMsg* msg, word32 seq, word16 epoch,
8145
                                  const byte* data, byte type,
8146
                                  word32 fragOffset, word32 fragSz, void* heap,
8147
                                  word32 totalLen, byte encrypted);
8148
    WOLFSSL_TEST_VIS DtlsMsg* DtlsMsgFind(DtlsMsg* head, word16 epoch, word32 seq);
8149
8150
    WOLFSSL_TEST_VIS int DtlsMsgStore(WOLFSSL* ssl, word16 epoch, word32 seq,
8151
                                    const byte* data, word32 dataSz, byte type,
8152
                                    word32 fragOffset, word32 fragSz,
8153
                                    void* heap);
8154
    WOLFSSL_LOCAL DtlsMsg* DtlsMsgInsert(DtlsMsg* head, DtlsMsg* item);
8155
8156
    WOLFSSL_LOCAL int  DtlsMsgPoolSave(WOLFSSL* ssl, const byte* data,
8157
                                       word32 dataSz, enum HandShakeType type);
8158
    WOLFSSL_LOCAL int  DtlsMsgPoolTimeout(WOLFSSL* ssl);
8159
    WOLFSSL_LOCAL int  VerifyForDtlsMsgPoolSend(WOLFSSL* ssl, byte type,
8160
                                                word32 fragOffset);
8161
    WOLFSSL_LOCAL int  VerifyForTxDtlsMsgDelete(WOLFSSL* ssl, DtlsMsg* item);
8162
    WOLFSSL_LOCAL void DtlsMsgPoolReset(WOLFSSL* ssl);
8163
    WOLFSSL_LOCAL int  wolfssl_local_SockAddrSet(WOLFSSL_SOCKADDR* sockAddr,
8164
                                                 void* peer,
8165
                                                 unsigned int peerSz,
8166
                                                 void* heap);
8167
    WOLFSSL_LOCAL int  DtlsMsgPoolSend(WOLFSSL* ssl, int sendOnlyFirstPacket);
8168
    WOLFSSL_LOCAL void DtlsMsgDestroyFragBucket(DtlsFragBucket* fragBucket, void* heap);
8169
    WOLFSSL_LOCAL int GetDtlsHandShakeHeader(WOLFSSL *ssl, const byte *input,
8170
        word32 *inOutIdx, byte *type, word32 *size, word32 *fragOffset,
8171
        word32 *fragSz, word32 totalSz);
8172
    WOLFSSL_LOCAL int DtlsMsgDrain(WOLFSSL *ssl);
8173
    WOLFSSL_LOCAL int SendHelloVerifyRequest(WOLFSSL* ssl,
8174
        const byte* cookie, byte cookieSz);
8175
8176
#if !defined(NO_WOLFSSL_SERVER)
8177
    WOLFSSL_LOCAL int DoClientHelloStateless(WOLFSSL* ssl,
8178
            const byte* input, word32 helloSz, byte isFirstCHFrag, byte* tls13);
8179
#endif /* !defined(NO_WOLFSSL_SERVER) */
8180
#if !defined(WOLFCRYPT_ONLY) && !defined(WOLFSSL_NO_SOCK) && \
8181
    (defined(USE_WOLFSSL_IO) || defined(WOLFSSL_USER_IO))
8182
    WOLFSSL_LOCAL int sockAddrEqual(SOCKADDR_S *a, XSOCKLENT aLen,
8183
                                    SOCKADDR_S *b, XSOCKLENT bLen);
8184
#endif
8185
#endif /* WOLFSSL_DTLS */
8186
8187
#if defined(HAVE_SECURE_RENEGOTIATION) && defined(WOLFSSL_DTLS)
8188
    WOLFSSL_LOCAL int DtlsSCRKeysSet(WOLFSSL* ssl);
8189
    WOLFSSL_LOCAL int IsDtlsMsgSCRKeys(WOLFSSL* ssl);
8190
    WOLFSSL_LOCAL int DtlsUseSCRKeys(WOLFSSL* ssl);
8191
    WOLFSSL_LOCAL int DtlsCheckOrder(WOLFSSL* ssl, int order);
8192
#endif
8193
    WOLFSSL_LOCAL int IsSCR(WOLFSSL* ssl);
8194
#ifdef HAVE_SECURE_RENEGOTIATION
8195
    WOLFSSL_LOCAL void ScrPeerCertToSession(const WOLFSSL* ssl, byte* state,
8196
                                            byte* hash);
8197
    WOLFSSL_LOCAL void ScrPeerCertFromSession(WOLFSSL* ssl);
8198
#endif
8199
    WOLFSSL_LOCAL int IsDtlsNotSctpMode(WOLFSSL* ssl);
8200
    WOLFSSL_LOCAL int IsDtlsNotSrtpMode(WOLFSSL* ssl);
8201
8202
    WOLFSSL_LOCAL void WriteSEQ(WOLFSSL* ssl, int verifyOrder, byte* out);
8203
8204
#if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || \
8205
        !defined(NO_PSK) || defined(WOLFSSL_DTLS13))
8206
#ifdef WOLFSSL_32BIT_MILLI_TIME
8207
    WOLFSSL_LOCAL word32 TimeNowInMilliseconds(void);
8208
#else
8209
    WOLFSSL_LOCAL sword64 TimeNowInMilliseconds(void);
8210
#endif
8211
8212
#endif
8213
WOLFSSL_LOCAL word32  LowResTimer(void);
8214
8215
WOLFSSL_LOCAL int FindSuiteSSL(const WOLFSSL* ssl, byte* suite);
8216
WOLFSSL_LOCAL int FindSuite(const Suites* suites, byte first, byte second);
8217
8218
WOLFSSL_LOCAL void DecodeSigAlg(const byte* input, byte* hashAlgo,
8219
        byte* hsType);
8220
#ifdef WOLFSSL_HAVE_SLHDSA
8221
WOLFSSL_LOCAL byte SlhDsaSigMinorToType(byte minor);
8222
WOLFSSL_LOCAL int SlhDsaTypeToParam(byte hsType);
8223
WOLFSSL_LOCAL int IsSlhDsaSigAlgo(byte hsType);
8224
WOLFSSL_LOCAL byte SlhDsaParamToType(int param);
8225
#endif
8226
WOLFSSL_LOCAL enum wc_HashType HashAlgoToType(int hashAlgo);
8227
8228
#ifndef NO_CERTS
8229
    WOLFSSL_LOCAL void InitX509Name(WOLFSSL_X509_NAME* name, int dynamicFlag,
8230
                                    void* heap);
8231
    WOLFSSL_LOCAL void FreeX509Name(WOLFSSL_X509_NAME* name);
8232
#if !defined(WOLFSSL_NO_CA_NAMES) && defined(OPENSSL_EXTRA)
8233
    WOLFSSL_LOCAL int SetX509NameRaw(WOLFSSL_X509_NAME* name, const byte* raw,
8234
                                     int rawLen);
8235
    WOLFSSL_LOCAL int SetX509NameRawFromDer(WOLFSSL_X509_NAME* name,
8236
                                            const byte* der, word32 derSz);
8237
    WOLFSSL_LOCAL void ClearX509NameRaw(WOLFSSL_X509_NAME* name);
8238
#endif
8239
    WOLFSSL_LOCAL void InitX509(WOLFSSL_X509* x509, int dynamicFlag,
8240
                                void* heap);
8241
    WOLFSSL_LOCAL void FreeX509(WOLFSSL_X509* x509);
8242
    WOLFSSL_LOCAL void ReinitX509(WOLFSSL_X509* x509);
8243
    #ifndef NO_ASN
8244
    WOLFSSL_LOCAL int  CopyDecodedToX509(WOLFSSL_X509* x509,
8245
                                         DecodedCert* dCert);
8246
    #endif
8247
    #ifdef KEEP_PEER_CERT
8248
        #ifdef WOLFSSL_DYNAMIC_PEER_CERT
8249
    WOLFSSL_LOCAL WOLFSSL_X509* GetPeerCert(WOLFSSL* ssl);
8250
        #else
8251
    /* The kept peer certificate object. */
8252
    static WC_INLINE WOLFSSL_X509* GetPeerCert(const WOLFSSL* ssl)
8253
    {
8254
        return (WOLFSSL_X509*)&ssl->peerCert;
8255
    }
8256
        #endif
8257
    /* The encoding of the kept peer certificate, without building the X509
8258
     * object. NULL when no certificate is kept. */
8259
    static WC_INLINE const DerBuffer* GetPeerCertDer(const WOLFSSL* ssl)
8260
    {
8261
        #ifdef WOLFSSL_DYNAMIC_PEER_CERT
8262
        if (ssl->peerCertDer != NULL)
8263
            return ssl->peerCertDer;
8264
        return (ssl->peerCert != NULL) ? ssl->peerCert->derCert : NULL;
8265
        #else
8266
        return ssl->peerCert.derCert;
8267
        #endif
8268
    }
8269
    WOLFSSL_LOCAL void FreePeerCert(WOLFSSL* ssl);
8270
        #ifndef NO_ASN
8271
    WOLFSSL_LOCAL int  SetPeerCert(WOLFSSL* ssl, DecodedCert* dCert);
8272
    WOLFSSL_LOCAL int  SetPeerCertDer(WOLFSSL* ssl, DecodedCert* dCert);
8273
        #endif
8274
    #endif
8275
#endif
8276
8277
#if defined(WOLFSSL_ACERT)
8278
    WOLFSSL_LOCAL int  CopyDecodedAcertToX509(WOLFSSL_X509_ACERT* x509,
8279
                                              DecodedAcert* dAcert);
8280
#endif /* WOLFSSL_ACERT */
8281
8282
8283
#ifndef MAX_CIPHER_NAME
8284
#define MAX_CIPHER_NAME 50
8285
#endif
8286
8287
#ifdef WOLFSSL_NAMES_STATIC
8288
typedef char cipher_name[MAX_CIPHER_NAME];
8289
#else
8290
typedef const char* cipher_name;
8291
#endif
8292
8293
typedef struct CipherSuiteInfo {
8294
    cipher_name name;
8295
#ifndef NO_ERROR_STRINGS
8296
    cipher_name name_iana;
8297
#endif
8298
    byte cipherSuite0;
8299
    byte cipherSuite;
8300
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_QT) || \
8301
    defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_NGINX)
8302
    byte minor;
8303
    byte major;
8304
#endif
8305
    byte flags;
8306
} CipherSuiteInfo;
8307
8308
#ifdef WOLFSSL_API_PREFIX_MAP
8309
    #define GetCipherNames wolfSSL_GetCipherNames
8310
    #define GetCipherNamesSize wolfSSL_GetCipherNamesSize
8311
#endif
8312
WOLFSSL_TEST_VIS const CipherSuiteInfo* GetCipherNames(void);
8313
WOLFSSL_TEST_VIS int GetCipherNamesSize(void);
8314
WOLFSSL_LOCAL int GetCipherNamesIdx(byte cipherSuite0, byte cipherSuite);
8315
WOLFSSL_LOCAL const char* GetCipherNameInternal(const byte cipherSuite0, const byte cipherSuite);
8316
#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
8317
/* used by the SSL_CIPHER NID accessors */
8318
#define MAX_SEGMENTS    5
8319
#define MAX_SEGMENT_SZ 20
8320
WOLFSSL_LOCAL const char* GetCipherSegment(const WOLFSSL_CIPHER* cipher,
8321
                                           char n[][MAX_SEGMENT_SZ]);
8322
WOLFSSL_LOCAL const char* GetCipherProtocol(byte minor);
8323
WOLFSSL_LOCAL const char* GetCipherKeaStr(char n[][MAX_SEGMENT_SZ]);
8324
WOLFSSL_LOCAL const char* GetCipherAuthStr(char n[][MAX_SEGMENT_SZ]);
8325
WOLFSSL_LOCAL const char* GetCipherEncStr(char n[][MAX_SEGMENT_SZ]);
8326
WOLFSSL_LOCAL const char* GetCipherMacStr(char n[][MAX_SEGMENT_SZ]);
8327
WOLFSSL_LOCAL int IsCipherAEAD(char n[][MAX_SEGMENT_SZ]);
8328
#endif
8329
WOLFSSL_LOCAL const char* GetCipherNameIana(const byte cipherSuite0, const byte cipherSuite);
8330
WOLFSSL_LOCAL const char* wolfSSL_get_cipher_name_internal(WOLFSSL* ssl);
8331
WOLFSSL_LOCAL const char* wolfSSL_get_cipher_name_iana(WOLFSSL* ssl);
8332
WOLFSSL_LOCAL int GetCipherSuiteFromName(const char* name, byte* cipherSuite0,
8333
                       byte* cipherSuite, byte* major, byte* minor, int* flags);
8334
8335
8336
enum encrypt_side {
8337
    ENCRYPT_SIDE_ONLY = 1,
8338
    DECRYPT_SIDE_ONLY,
8339
    ENCRYPT_AND_DECRYPT_SIDE
8340
};
8341
8342
WOLFSSL_LOCAL int SetKeys(Ciphers* enc, Ciphers* dec, Keys* keys,
8343
    CipherSpecs* specs, int side, void* heap, int devId, WC_RNG* rng,
8344
    int tls13);
8345
WOLFSSL_LOCAL int SetKeysSide(WOLFSSL* ssl, enum encrypt_side side);
8346
8347
/* Set*Internal and Set*External functions */
8348
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
8349
WOLFSSL_LOCAL int SetDsaInternal(WOLFSSL_DSA* dsa);
8350
WOLFSSL_LOCAL int SetDsaExternal(WOLFSSL_DSA* dsa);
8351
#ifndef NO_DSA
8352
WOLFSSL_LOCAL int wolfssl_local_dsa_do_sign(const unsigned char* d, int dLen,
8353
    unsigned char* sigRet, WOLFSSL_DSA* dsa);
8354
WOLFSSL_LOCAL int wolfssl_local_dsa_do_verify(const unsigned char* d, int dLen,
8355
    unsigned char* sig, WOLFSSL_DSA* dsa, int* dsacheck);
8356
#endif
8357
WOLFSSL_LOCAL int SetRsaExternal(WOLFSSL_RSA* rsa);
8358
WOLFSSL_LOCAL int SetRsaInternal(WOLFSSL_RSA* rsa);
8359
8360
typedef enum elem_set {
8361
    ELEMENT_P   = 0x01,
8362
    ELEMENT_Q   = 0x02,
8363
    ELEMENT_G   = 0x04,
8364
    ELEMENT_PUB = 0x08,
8365
    ELEMENT_PRV = 0x10,
8366
} Element_Set;
8367
WOLFSSL_LOCAL int SetDhExternal_ex(WOLFSSL_DH *dh, int elm );
8368
WOLFSSL_LOCAL int SetDhInternal(WOLFSSL_DH* dh);
8369
WOLFSSL_LOCAL int SetDhExternal(WOLFSSL_DH *dh);
8370
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
8371
8372
#if !defined(NO_DH) && (!defined(NO_CERTS) || !defined(NO_PSK))
8373
    WOLFSSL_LOCAL int DhGenKeyPair(WOLFSSL* ssl, DhKey* dhKey,
8374
        byte* priv, word32* privSz,
8375
        byte* pub, word32* pubSz);
8376
    WOLFSSL_LOCAL int DhAgree(WOLFSSL* ssl, DhKey* dhKey,
8377
        const byte* priv, word32 privSz,
8378
        const byte* otherPub, word32 otherPubSz,
8379
        byte* agree, word32* agreeSz,
8380
        const byte* prime, word32 primeSz);
8381
#endif /* !NO_DH */
8382
8383
#ifdef HAVE_ECC
8384
    WOLFSSL_LOCAL int EccMakeKey(WOLFSSL* ssl, ecc_key* key, ecc_key* peer);
8385
    WOLFSSL_LOCAL word16 GetCurveByOID(int oidSum);
8386
#endif
8387
8388
WOLFSSL_LOCAL int InitHandshakeHashes(WOLFSSL* ssl);
8389
WOLFSSL_LOCAL void Free_HS_Hashes(HS_Hashes* hsHashes, void* heap);
8390
WOLFSSL_LOCAL void FreeHandshakeHashes(WOLFSSL* ssl);
8391
WOLFSSL_LOCAL int InitHandshakeHashesAndCopy(WOLFSSL* ssl, HS_Hashes* source,
8392
    HS_Hashes** destination);
8393
8394
8395
#ifndef WOLFSSL_NO_TLS12
8396
WOLFSSL_LOCAL void FreeBuildMsgArgs(WOLFSSL* ssl, BuildMsgArgs* args);
8397
#endif
8398
#ifdef WOLFSSL_API_PREFIX_MAP
8399
    #define BuildMessage wolfSSL_BuildMessage
8400
#endif
8401
WOLFSSL_TEST_VIS int BuildMessage(WOLFSSL* ssl, byte* output, int outSz,
8402
                        const byte* input, int inSz, int type, int hashOutput,
8403
                        int sizeOnly, int asyncOkay, int epochOrder);
8404
8405
#ifdef WOLFSSL_TLS13
8406
#ifdef WOLFSSL_API_PREFIX_MAP
8407
    #define BuildTls13Message wolfSSL_BuildTls13Message
8408
#endif
8409
WOLFSSL_TEST_VIS int BuildTls13Message(WOLFSSL* ssl, byte* output, int outSz, const byte* input,
8410
               int inSz, int type, int hashOutput, int sizeOnly, int asyncOkay);
8411
WOLFSSL_LOCAL int Tls13UpdateKeys(WOLFSSL* ssl);
8412
#endif
8413
8414
WOLFSSL_LOCAL int AllocKey(WOLFSSL* ssl, int type, void** pKey);
8415
WOLFSSL_LOCAL void FreeKey(WOLFSSL* ssl, int type, void** pKey);
8416
8417
#ifdef WOLFSSL_ASYNC_CRYPT
8418
    WOLFSSL_LOCAL int wolfSSL_AsyncInit(WOLFSSL* ssl, WC_ASYNC_DEV* asyncDev, word32 flags);
8419
    WOLFSSL_LOCAL int wolfSSL_AsyncPop(WOLFSSL* ssl, byte* state);
8420
    WOLFSSL_LOCAL int wolfSSL_AsyncPush(WOLFSSL* ssl, WC_ASYNC_DEV* asyncDev);
8421
#endif
8422
8423
#if defined(OPENSSL_ALL) && defined(WOLFSSL_CERT_GEN) && \
8424
    (defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_EXT)) && \
8425
    !defined(NO_FILESYSTEM) && !defined(NO_WOLFSSL_DIR)
8426
WOLFSSL_LOCAL int LoadCertByIssuer(WOLFSSL_X509_STORE* store,
8427
                                           X509_NAME* issuer, int Type);
8428
#endif
8429
#if defined(OPENSSL_ALL) && !defined(NO_FILESYSTEM) && !defined(NO_WOLFSSL_DIR)
8430
WOLFSSL_LOCAL WOLFSSL_BY_DIR_HASH* wolfSSL_BY_DIR_HASH_new(void);
8431
WOLFSSL_LOCAL void wolfSSL_BY_DIR_HASH_free(WOLFSSL_BY_DIR_HASH* dir_hash);
8432
WOLFSSL_LOCAL WOLFSSL_STACK* wolfSSL_sk_BY_DIR_HASH_new_null(void);
8433
WOLFSSL_LOCAL int wolfSSL_sk_BY_DIR_HASH_find(
8434
   WOLF_STACK_OF(WOLFSSL_BY_DIR_HASH)* sk, const WOLFSSL_BY_DIR_HASH* toFind);
8435
WOLFSSL_LOCAL int wolfSSL_sk_BY_DIR_HASH_num(const WOLF_STACK_OF(WOLFSSL_BY_DIR_HASH) *sk);
8436
WOLFSSL_LOCAL WOLFSSL_BY_DIR_HASH* wolfSSL_sk_BY_DIR_HASH_value(
8437
                        const WOLF_STACK_OF(WOLFSSL_BY_DIR_HASH) *sk, int i);
8438
WOLFSSL_LOCAL WOLFSSL_BY_DIR_HASH* wolfSSL_sk_BY_DIR_HASH_pop(
8439
                                WOLF_STACK_OF(WOLFSSL_BY_DIR_HASH)* sk);
8440
WOLFSSL_LOCAL void wolfSSL_sk_BY_DIR_HASH_pop_free(WOLF_STACK_OF(WOLFSSL_BY_DIR_HASH)* sk,
8441
    void (*f) (WOLFSSL_BY_DIR_HASH*));
8442
WOLFSSL_LOCAL void wolfSSL_sk_BY_DIR_HASH_free(WOLF_STACK_OF(WOLFSSL_BY_DIR_HASH) *sk);
8443
WOLFSSL_LOCAL int wolfSSL_sk_BY_DIR_HASH_push(WOLF_STACK_OF(WOLFSSL_BY_DIR_HASH)* sk,
8444
                                               WOLFSSL_BY_DIR_HASH* in);
8445
/* WOLFSSL_BY_DIR_entry stuff */
8446
WOLFSSL_LOCAL WOLFSSL_BY_DIR_entry* wolfSSL_BY_DIR_entry_new(void);
8447
WOLFSSL_LOCAL void wolfSSL_BY_DIR_entry_free(WOLFSSL_BY_DIR_entry* entry);
8448
WOLFSSL_LOCAL WOLFSSL_STACK* wolfSSL_sk_BY_DIR_entry_new_null(void);
8449
WOLFSSL_LOCAL int wolfSSL_sk_BY_DIR_entry_num(const WOLF_STACK_OF(WOLFSSL_BY_DIR_entry) *sk);
8450
WOLFSSL_LOCAL WOLFSSL_BY_DIR_entry* wolfSSL_sk_BY_DIR_entry_value(
8451
                        const WOLF_STACK_OF(WOLFSSL_BY_DIR_entry) *sk, int i);
8452
WOLFSSL_LOCAL WOLFSSL_BY_DIR_entry* wolfSSL_sk_BY_DIR_entry_pop(
8453
                                WOLF_STACK_OF(WOLFSSL_BY_DIR_entry)* sk);
8454
WOLFSSL_LOCAL void wolfSSL_sk_BY_DIR_entry_pop_free(WOLF_STACK_OF(wolfSSL_BY_DIR_entry)* sk,
8455
    void (*f) (WOLFSSL_BY_DIR_entry*));
8456
WOLFSSL_LOCAL void wolfSSL_sk_BY_DIR_entry_free(WOLF_STACK_OF(wolfSSL_BY_DIR_entry) *sk);
8457
WOLFSSL_LOCAL int wolfSSL_sk_BY_DIR_entry_push(WOLF_STACK_OF(wolfSSL_BY_DIR_entry)* sk,
8458
                                               WOLFSSL_BY_DIR_entry* in);
8459
#endif /* OPENSSL_ALL && !NO_FILESYSTEM && !NO_WOLFSSL_DIR */
8460
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
8461
WOLFSSL_LOCAL int oid2nid(word32 oid, int grp);
8462
WOLFSSL_LOCAL word32 nid2oid(int nid, int grp);
8463
WOLFSSL_LOCAL void wolfssl_object_info_slice_init(void);
8464
#endif
8465
8466
#ifdef WOLFSSL_DTLS
8467
WOLFSSL_TEST_VIS int wolfSSL_DtlsUpdateWindow(word16 cur_hi, word32 cur_lo,
8468
        word16* next_hi, word32* next_lo, word32 *window);
8469
WOLFSSL_LOCAL int DtlsUpdateWindow(WOLFSSL* ssl);
8470
WOLFSSL_LOCAL void DtlsResetState(WOLFSSL *ssl);
8471
WOLFSSL_LOCAL int DtlsIgnoreError(int err);
8472
WOLFSSL_LOCAL void DtlsSetSeqNumForReply(WOLFSSL* ssl);
8473
#ifndef NO_WOLFSSL_SERVER
8474
WOLFSSL_LOCAL int DtlsNoCookieChGood(WOLFSSL* ssl);
8475
#endif
8476
#endif
8477
8478
#ifdef WOLFSSL_DTLS13
8479
    #ifdef WOLFSSL_API_PREFIX_MAP
8480
        #define Dtls13GetEpoch wolfSSL_Dtls13GetEpoch
8481
        #define Dtls13NewEpoch wolfSSL_Dtls13NewEpoch
8482
        #define Dtls13CheckEpoch wolfSSL_Dtls13CheckEpoch
8483
        #define Dtls13HandshakeRecv wolfSSL_Dtls13HandshakeRecv
8484
        #define Dtls13WriteAckMessage wolfSSL_Dtls13WriteAckMessage
8485
        #define Dtls13RtxAddAck wolfSSL_Dtls13RtxAddAck
8486
        #define Dtls13DoScheduledWork wolfSSL_Dtls13DoScheduledWork
8487
    #endif
8488
8489
WOLFSSL_TEST_VIS struct Dtls13Epoch* Dtls13GetEpoch(WOLFSSL* ssl,
8490
    w64wrapper epochNumber);
8491
WOLFSSL_LOCAL void Dtls13SetOlderEpochSide(WOLFSSL* ssl, w64wrapper epochNumber,
8492
    int side);
8493
WOLFSSL_TEST_VIS int Dtls13NewEpoch(WOLFSSL* ssl, w64wrapper epochNumber,
8494
    int side);
8495
WOLFSSL_LOCAL int Dtls13SetEpochKeys(WOLFSSL* ssl, w64wrapper epochNumber,
8496
    enum encrypt_side side);
8497
WOLFSSL_LOCAL int Dtls13GetSeq(WOLFSSL* ssl, int order, word32* seq,
8498
    byte increment);
8499
WOLFSSL_LOCAL void Dtls13RtxRemoveRecord(WOLFSSL* ssl, w64wrapper epoch,
8500
    w64wrapper seq);
8501
WOLFSSL_TEST_VIS int Dtls13DoScheduledWork(WOLFSSL* ssl);
8502
WOLFSSL_LOCAL int Dtls13DeriveSnKeys(WOLFSSL* ssl, int provision);
8503
WOLFSSL_LOCAL int Dtls13SetRecordNumberKeys(WOLFSSL* ssl,
8504
    enum encrypt_side side);
8505
#ifdef WOLFSSL_SESSION_EXPORT
8506
WOLFSSL_LOCAL int ExportDtls13State(WOLFSSL* ssl, byte* exp, word32 len);
8507
WOLFSSL_LOCAL int ImportDtls13State(WOLFSSL* ssl, const byte* exp, word32 len);
8508
#endif
8509
8510
WOLFSSL_LOCAL int Dtls13AddHeaders(byte* output, word32 length,
8511
    enum HandShakeType hs_type, WOLFSSL* ssl);
8512
WOLFSSL_LOCAL word16 Dtls13GetHeadersLength(WOLFSSL *ssl,
8513
    enum HandShakeType type);
8514
WOLFSSL_LOCAL word16 Dtls13GetRlHeaderLength(WOLFSSL *ssl, byte is_encrypted);
8515
WOLFSSL_LOCAL int Dtls13RlAddCiphertextHeader(WOLFSSL* ssl, byte* out,
8516
    word16 length);
8517
WOLFSSL_LOCAL int Dtls13RlAddPlaintextHeader(WOLFSSL* ssl, byte* out,
8518
    enum ContentType content_type, word16 length);
8519
WOLFSSL_LOCAL int Dtls13MinimumRecordLength(WOLFSSL* ssl);
8520
WOLFSSL_LOCAL int Dtls13EncryptRecordNumber(WOLFSSL* ssl, byte* hdr,
8521
    word16 recordLength);
8522
WOLFSSL_LOCAL int Dtls13IsUnifiedHeader(byte header_flags);
8523
WOLFSSL_LOCAL int Dtls13GetUnifiedHeaderSize(WOLFSSL* ssl, const byte input,
8524
    word16* size);
8525
WOLFSSL_LOCAL int Dtls13ParseUnifiedRecordLayer(WOLFSSL* ssl, const byte* input,
8526
    word16 input_size, Dtls13UnifiedHdrInfo* hdrInfo);
8527
WOLFSSL_LOCAL int Dtls13HandshakeSend(WOLFSSL* ssl, byte* output,
8528
    word16 output_size, word16 length, enum HandShakeType handshake_type,
8529
    int hash_output);
8530
WOLFSSL_LOCAL int Dtls13RecordRecvd(WOLFSSL* ssl);
8531
WOLFSSL_TEST_VIS int Dtls13CheckEpoch(WOLFSSL* ssl, enum HandShakeType type);
8532
WOLFSSL_TEST_VIS int Dtls13HandshakeRecv(WOLFSSL* ssl, byte* input,
8533
    word32* inOutIdx, word32 totalSz);
8534
WOLFSSL_LOCAL int Dtls13HandshakeAddHeader(WOLFSSL* ssl, byte* output,
8535
    enum HandShakeType msg_type, word32 length);
8536
#define EE_MASK 0x3
8537
WOLFSSL_LOCAL int Dtls13FragmentsContinue(WOLFSSL* ssl);
8538
WOLFSSL_LOCAL int DoDtls13KeyUpdateAck(WOLFSSL* ssl);
8539
#ifdef WOLFSSL_DTLS_CID
8540
WOLFSSL_LOCAL int DoDtls13RequestConnectionId(WOLFSSL* ssl, const byte* input,
8541
    word32* inOutIdx, word32 size);
8542
WOLFSSL_LOCAL int DoDtls13NewConnectionId(WOLFSSL* ssl, const byte* input,
8543
    word32* inOutIdx, word32 size);
8544
#endif /* WOLFSSL_DTLS_CID */
8545
WOLFSSL_LOCAL int DoDtls13Ack(WOLFSSL* ssl, const byte* input, word32 inputSize,
8546
    word32* processedSize);
8547
WOLFSSL_LOCAL int Dtls13ReconstructEpochNumber(WOLFSSL* ssl, byte epochBits,
8548
    w64wrapper* epoch);
8549
WOLFSSL_LOCAL int Dtls13ReconstructSeqNumber(WOLFSSL* ssl,
8550
    Dtls13UnifiedHdrInfo* hdrInfo, w64wrapper* out);
8551
WOLFSSL_TEST_VIS int Dtls13WriteAckMessage(WOLFSSL* ssl,
8552
    Dtls13RecordNumber* recordNumberList, word16 recordsCount, word32* length);
8553
WOLFSSL_LOCAL int SendDtls13Ack(WOLFSSL* ssl);
8554
WOLFSSL_TEST_VIS int Dtls13RtxAddAck(WOLFSSL* ssl, w64wrapper epoch, w64wrapper seq);
8555
WOLFSSL_LOCAL int Dtls13RtxProcessingCertificate(WOLFSSL* ssl, byte* input,
8556
    word32 inputSize);
8557
WOLFSSL_LOCAL int Dtls13HashHandshake(WOLFSSL* ssl, const byte* input,
8558
    word32 length);
8559
WOLFSSL_LOCAL int Dtls13HashClientHello(const WOLFSSL* ssl, byte* hash,
8560
        int* hashSz, const byte* body, word32 length, CipherSpecs* specs);
8561
WOLFSSL_LOCAL void Dtls13FreeFsmResources(WOLFSSL* ssl);
8562
WOLFSSL_LOCAL void Dtls13RtxFlushBuffered(WOLFSSL* ssl,
8563
        byte keepNewSessionTicket);
8564
WOLFSSL_LOCAL int Dtls13RtxTimeout(WOLFSSL* ssl);
8565
WOLFSSL_LOCAL int Dtls13ProcessBufferedMessages(WOLFSSL* ssl);
8566
WOLFSSL_LOCAL int Dtls13CheckAEADFailLimit(WOLFSSL* ssl);
8567
WOLFSSL_LOCAL int Dtls13UpdateWindowRecordRecvd(WOLFSSL* ssl);
8568
#endif /* WOLFSSL_DTLS13 */
8569
8570
#ifdef WOLFSSL_STATIC_EPHEMERAL
8571
WOLFSSL_LOCAL int wolfSSL_StaticEphemeralKeyLoad(WOLFSSL* ssl, int keyAlgo, void* keyPtr);
8572
#endif
8573
8574
#ifndef NO_CERTS
8575
#if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) || \
8576
    defined(OPENSSL_EXTRA_X509_SMALL)
8577
WOLFSSL_LOCAL int wolfSSL_ASN1_STRING_canon(WOLFSSL_ASN1_STRING* asn_out,
8578
    const WOLFSSL_ASN1_STRING* asn_in);
8579
#endif
8580
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
8581
WOLFSSL_LOCAL int GetX509Error(int e);
8582
#endif
8583
WOLFSSL_LOCAL void SetRevocationVerifyRet(WOLFSSL* ssl, int err);
8584
WOLFSSL_LOCAL int CrlErrWaived(const WOLFSSL* ssl, int err);
8585
#endif
8586
8587
#ifdef HAVE_EX_DATA_CRYPTO
8588
typedef struct CRYPTO_EX_cb_ctx {
8589
    long ctx_l;
8590
    void *ctx_ptr;
8591
    WOLFSSL_CRYPTO_EX_new* new_func;
8592
    WOLFSSL_CRYPTO_EX_free* free_func;
8593
    WOLFSSL_CRYPTO_EX_dup* dup_func;
8594
    struct CRYPTO_EX_cb_ctx* next;
8595
} CRYPTO_EX_cb_ctx;
8596
8597
WOLFSSL_TEST_VIS extern CRYPTO_EX_cb_ctx* crypto_ex_cb_ctx_session;
8598
#ifdef WOLFSSL_API_PREFIX_MAP
8599
    #define crypto_ex_cb_free wolfSSL_crypto_ex_cb_free
8600
#endif
8601
WOLFSSL_TEST_VIS void crypto_ex_cb_free(CRYPTO_EX_cb_ctx* cb_ctx);
8602
WOLFSSL_LOCAL void crypto_ex_cb_setup_new_data(void *new_obj,
8603
        CRYPTO_EX_cb_ctx* cb_ctx, WOLFSSL_CRYPTO_EX_DATA* ex_data);
8604
WOLFSSL_LOCAL void crypto_ex_cb_free_data(void *obj, CRYPTO_EX_cb_ctx* cb_ctx,
8605
        WOLFSSL_CRYPTO_EX_DATA* ex_data);
8606
WOLFSSL_LOCAL int crypto_ex_cb_dup_data(const WOLFSSL_CRYPTO_EX_DATA *in,
8607
        WOLFSSL_CRYPTO_EX_DATA *out, CRYPTO_EX_cb_ctx* cb_ctx);
8608
WOLFSSL_LOCAL int wolfssl_local_get_ex_new_index(int class_index, long ctx_l,
8609
        void* ctx_ptr, WOLFSSL_CRYPTO_EX_new* new_func,
8610
        WOLFSSL_CRYPTO_EX_dup* dup_func, WOLFSSL_CRYPTO_EX_free* free_func);
8611
#endif /* HAVE_EX_DATA_CRYPTO */
8612
8613
WOLFSSL_LOCAL WC_RNG* wolfssl_get_global_rng(void);
8614
WOLFSSL_LOCAL WC_RNG* wolfssl_make_global_rng(void);
8615
8616
#if !defined(WOLFCRYPT_ONLY) && defined(OPENSSL_EXTRA)
8617
#if defined(WOLFSSL_KEY_GEN) && defined(WOLFSSL_PEM_TO_DER)
8618
WOLFSSL_LOCAL int EncryptDerKey(byte *der, int *derSz,
8619
    const WOLFSSL_EVP_CIPHER* cipher, unsigned char* passwd, int passwdSz,
8620
    byte **cipherInfo, int maxDerSz, int hashType);
8621
#endif
8622
#endif
8623
8624
#if !defined(NO_RSA) && defined(OPENSSL_EXTRA)
8625
WOLFSSL_LOCAL int wolfSSL_RSA_To_Der(WOLFSSL_RSA* rsa, byte** outBuf,
8626
    int publicKey, void* heap);
8627
#endif
8628
8629
#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) \
8630
    || defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) || defined(HAVE_SECRET_CALLBACK)
8631
WOLFSSL_LOCAL int wolfSSL_SSL_do_handshake_internal(WOLFSSL *s);
8632
#endif
8633
8634
#ifdef WOLFSSL_QUIC
8635
#define WOLFSSL_IS_QUIC(s)  (((s) != NULL) && ((s)->quic.method != NULL))
8636
WOLFSSL_LOCAL int wolfSSL_quic_receive(WOLFSSL* ssl, byte* buf, word32 sz);
8637
WOLFSSL_LOCAL int wolfSSL_quic_send(WOLFSSL* ssl);
8638
WOLFSSL_LOCAL int wolfSSL_quic_send_alert(WOLFSSL* ssl, int severity, int code);
8639
WOLFSSL_LOCAL void wolfSSL_quic_clear(WOLFSSL* ssl);
8640
WOLFSSL_LOCAL void wolfSSL_quic_free(WOLFSSL* ssl);
8641
WOLFSSL_LOCAL int wolfSSL_quic_forward_secrets(WOLFSSL *ssl,
8642
                                               int ktype, int side);
8643
WOLFSSL_LOCAL int wolfSSL_quic_keys_active(WOLFSSL* ssl, enum encrypt_side side);
8644
8645
#else
8646
0
#define WOLFSSL_IS_QUIC(s) 0
8647
#endif /* WOLFSSL_QUIC (else) */
8648
8649
#if defined(SHOW_SECRETS) && defined(WOLFSSL_SSLKEYLOGFILE)
8650
WOLFSSL_LOCAL int tls13ShowSecrets(WOLFSSL* ssl, int id, const unsigned char* secret,
8651
    int secretSz, void* ctx);
8652
#endif
8653
8654
#if defined(SHOW_SECRETS)
8655
WOLFSSL_LOCAL int tlsShowSecrets(WOLFSSL* ssl, void* secret,
8656
        int secretSz, void* ctx);
8657
#endif
8658
8659
/* Optional Pre-Master-Secret logging for Wireshark */
8660
#if !defined(NO_FILESYSTEM) && defined(WOLFSSL_SSLKEYLOGFILE)
8661
#ifndef WOLFSSL_SSLKEYLOGFILE_OUTPUT
8662
    #define WOLFSSL_SSLKEYLOGFILE_OUTPUT "sslkeylog.log"
8663
#endif
8664
#endif
8665
8666
#if defined(WOLFSSL_TLS13) && !defined(NO_PSK)
8667
WOLFSSL_LOCAL int FindPskSuite(const WOLFSSL* ssl, PreSharedKey* psk,
8668
        byte* psk_key, word32* psk_keySz, const byte* suite, int* found,
8669
        byte* foundSuite);
8670
#endif
8671
8672
WOLFSSL_LOCAL int wolfSSL_GetHmacType_ex(CipherSpecs* specs);
8673
8674
#if defined(WOLFSSL_SEND_HRR_COOKIE) && !defined(NO_WOLFSSL_SERVER)
8675
WOLFSSL_LOCAL int CreateCookieExt(const WOLFSSL* ssl, byte* hash,
8676
                                  word16 hashSz, TLSX** exts,
8677
                                  byte cipherSuite0, byte cipherSuite);
8678
#endif
8679
8680
WOLFSSL_LOCAL int TranslateErrorToAlert(int err);
8681
WOLFSSL_LOCAL int RevocationAlert(int err);
8682
8683
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
8684
WOLFSSL_LOCAL void* wolfssl_sk_pop_type(WOLFSSL_STACK* sk,
8685
                                        WOLF_STACK_TYPE type);
8686
WOLFSSL_LOCAL void* wolfSSL_sk_pop_node(WOLFSSL_STACK* sk, int idx);
8687
WOLFSSL_LOCAL WOLFSSL_STACK* wolfssl_sk_new_type(WOLF_STACK_TYPE type);
8688
WOLFSSL_LOCAL WOLFSSL_STACK* wolfssl_sk_new_type_ex(WOLF_STACK_TYPE type,
8689
        void* heap);
8690
8691
WOLFSSL_LOCAL int wolfssl_asn1_obj_set(WOLFSSL_ASN1_OBJECT* obj,
8692
        const byte* der, word32 len, int addHdr);
8693
#endif
8694
8695
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
8696
WOLFSSL_LOCAL int pkcs8_encode(WOLFSSL_EVP_PKEY* pkey, byte* key,
8697
        word32* keySz);
8698
WOLFSSL_LOCAL int pkcs8_encrypt(WOLFSSL_EVP_PKEY* pkey,
8699
        const WOLFSSL_EVP_CIPHER* enc, char* passwd, int passwdSz, byte* key,
8700
        word32* keySz);
8701
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
8702
8703
#if (defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)) && !defined(NO_BIO)
8704
WOLFSSL_LOCAL int wolfSSL_PEM_X509_X509_CRL_X509_PKEY_read_bio(
8705
        WOLFSSL_BIO* bio, wc_pem_password_cb* cb, WOLFSSL_X509** x509,
8706
        WOLFSSL_X509_CRL** crl, WOLFSSL_X509_PKEY** x_pkey);
8707
#endif
8708
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)
8709
WOLFSSL_LOCAL void wolfSSL_X509_PKEY_free(WOLFSSL_X509_PKEY* xPkey);
8710
#endif
8711
8712
WOLFSSL_LOCAL void wolfssl_local_MaybeCheckAlertOnErr(WOLFSSL* ssl, int err);
8713
8714
#ifdef __cplusplus
8715
    }  /* extern "C" */
8716
#endif
8717
8718
#endif /* wolfSSL_INT_H */