Coverage Report

Created: 2026-10-31 07:16

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