Coverage Report

Created: 2026-12-01 07:02

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/wolfssl/src/ssl.c
Line
Count
Source
1
/* ssl.c
2
 *
3
 * Copyright (C) 2006-2026 wolfSSL Inc.
4
 *
5
 * This file is part of wolfSSL.
6
 *
7
 * wolfSSL is free software; you can redistribute it and/or modify
8
 * it under the terms of the GNU General Public License as published by
9
 * the Free Software Foundation; either version 3 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * wolfSSL is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License
18
 * along with this program; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
20
 */
21
22
#include <wolfssl/wolfcrypt/libwolfssl_sources.h>
23
24
#if defined(OPENSSL_EXTRA) && !defined(_WIN32) && !defined(_GNU_SOURCE)
25
    /* turn on GNU extensions for XISASCII */
26
    #define _GNU_SOURCE 1
27
#endif
28
29
#if !defined(WOLFCRYPT_ONLY) || defined(OPENSSL_EXTRA) || \
30
    defined(OPENSSL_EXTRA_X509_SMALL)
31
32
#include <wolfssl/internal.h>
33
#include <wolfssl/error-ssl.h>
34
#include <wolfssl/wolfcrypt/error-crypt.h>
35
#include <wolfssl/wolfcrypt/coding.h>
36
#include <wolfssl/wolfcrypt/kdf.h>
37
#ifdef NO_INLINE
38
    #include <wolfssl/wolfcrypt/misc.h>
39
#else
40
    #define WOLFSSL_MISC_INCLUDED
41
    #include <wolfcrypt/src/misc.c>
42
#endif
43
44
#ifdef HAVE_ERRNO_H
45
    #include <errno.h>
46
#endif
47
48
49
#if !defined(WOLFSSL_ALLOW_NO_SUITES) && !defined(WOLFCRYPT_ONLY)
50
    #if defined(NO_DH) && !defined(HAVE_ECC) && !defined(WOLFSSL_STATIC_RSA) \
51
                && !defined(WOLFSSL_STATIC_DH) && !defined(WOLFSSL_STATIC_PSK) \
52
                && !defined(HAVE_CURVE25519) && !defined(HAVE_CURVE448) \
53
                && (!defined(WOLFSSL_TLS13) \
54
                    || !defined(WOLFSSL_HAVE_MLKEM_CLIENT_SUPPORT) \
55
                    || defined(WOLFSSL_TLS_NO_MLKEM_STANDALONE))
56
        #error "No cipher suites defined because DH disabled, ECC disabled, " \
57
               "and no static suites defined. Please see top of README"
58
    #endif
59
    #ifdef WOLFSSL_CERT_GEN
60
        /* need access to Cert struct for creating certificate */
61
        #include <wolfssl/wolfcrypt/asn_public.h>
62
    #endif
63
#endif
64
65
#if !defined(WOLFCRYPT_ONLY) && (defined(OPENSSL_EXTRA)     \
66
    || defined(OPENSSL_EXTRA_X509_SMALL)                    \
67
    || defined(HAVE_WEBSERVER) || defined(WOLFSSL_KEY_GEN))
68
    #include <wolfssl/openssl/evp.h>
69
    /* ed25519 compat helpers (wolfSSL_ED25519_new/free) are used by the X509
70
     * Ed25519 paths, which also build under OPENSSL_EXTRA_X509_SMALL. */
71
    #include <wolfssl/openssl/ed25519.h>
72
    /* openssl headers end, wolfssl internal headers next */
73
#endif
74
75
#include <wolfssl/wolfcrypt/wc_encrypt.h>
76
77
#ifndef NO_RSA
78
    #include <wolfssl/wolfcrypt/rsa.h>
79
#endif
80
81
#ifdef OPENSSL_EXTRA
82
    /* openssl headers begin */
83
    #include <wolfssl/openssl/ssl.h>
84
    #include <wolfssl/openssl/aes.h>
85
#ifndef WOLFCRYPT_ONLY
86
    #include <wolfssl/openssl/hmac.h>
87
    #include <wolfssl/openssl/cmac.h>
88
#endif
89
    #include <wolfssl/openssl/crypto.h>
90
    #include <wolfssl/openssl/des.h>
91
    #include <wolfssl/openssl/bn.h>
92
    #include <wolfssl/openssl/buffer.h>
93
    #include <wolfssl/openssl/dh.h>
94
    #include <wolfssl/openssl/rsa.h>
95
    #include <wolfssl/openssl/fips_rand.h>
96
    #include <wolfssl/openssl/pem.h>
97
    #include <wolfssl/openssl/ec.h>
98
    #include <wolfssl/openssl/ec25519.h>
99
    #include <wolfssl/openssl/ec448.h>
100
    #include <wolfssl/openssl/ed448.h>
101
    #include <wolfssl/openssl/ecdsa.h>
102
    #include <wolfssl/openssl/ecdh.h>
103
    #include <wolfssl/openssl/err.h>
104
    #include <wolfssl/openssl/modes.h>
105
    #include <wolfssl/openssl/opensslv.h>
106
    #include <wolfssl/openssl/rc4.h>
107
    #include <wolfssl/openssl/stack.h>
108
    #include <wolfssl/openssl/x509_vfy.h>
109
    /* openssl headers end, wolfssl internal headers next */
110
    #include <wolfssl/wolfcrypt/hmac.h>
111
    #include <wolfssl/wolfcrypt/random.h>
112
    #include <wolfssl/wolfcrypt/rng_bank.h>
113
    #include <wolfssl/wolfcrypt/des3.h>
114
    #include <wolfssl/wolfcrypt/ecc.h>
115
    #include <wolfssl/wolfcrypt/md4.h>
116
    #include <wolfssl/wolfcrypt/md5.h>
117
    #include <wolfssl/wolfcrypt/arc4.h>
118
    #include <wolfssl/wolfcrypt/curve25519.h>
119
    #include <wolfssl/wolfcrypt/ed25519.h>
120
    #include <wolfssl/wolfcrypt/curve448.h>
121
    #if defined(HAVE_FALCON)
122
        #include <wolfssl/wolfcrypt/falcon.h>
123
    #endif /* HAVE_FALCON */
124
    #if defined(WOLFSSL_HAVE_MLDSA)
125
        #include <wolfssl/wolfcrypt/wc_mldsa.h>
126
    #endif /* WOLFSSL_HAVE_MLDSA */
127
    #if defined(OPENSSL_ALL) || defined(HAVE_STUNNEL)
128
        #ifdef HAVE_OCSP
129
            #include <wolfssl/openssl/ocsp.h>
130
        #endif
131
        #include <wolfssl/openssl/lhash.h>
132
        #include <wolfssl/openssl/txt_db.h>
133
    #endif /* WITH_STUNNEL */
134
    #if defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA384)
135
        #include <wolfssl/wolfcrypt/sha512.h>
136
    #endif
137
    #if defined(WOLFCRYPT_HAVE_SRP) && !defined(NO_SHA256) \
138
        && !defined(WC_NO_RNG)
139
        #include <wolfssl/wolfcrypt/srp.h>
140
    #endif
141
#endif
142
143
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
144
    #include <wolfssl/openssl/x509v3.h>
145
    int wolfssl_bn_get_value(WOLFSSL_BIGNUM* bn, mp_int* mpi);
146
    int wolfssl_bn_set_value(WOLFSSL_BIGNUM** bn, mp_int* mpi);
147
#endif
148
149
#if defined(WOLFSSL_QT)
150
    #include <wolfssl/wolfcrypt/sha.h>
151
#endif
152
153
#ifdef NO_ASN
154
    #include <wolfssl/wolfcrypt/dh.h>
155
#endif
156
#endif /* !WOLFCRYPT_ONLY || OPENSSL_EXTRA */
157
158
#if !defined(WOLFCRYPT_ONLY) && defined(WOLFSSL_SYS_CRYPTO_POLICY)
159
/* The system wide crypto-policy. Configured by wolfSSL_crypto_policy_enable.
160
 * */
161
static struct SystemCryptoPolicy crypto_policy;
162
#endif /* !WOLFCRYPT_ONLY && WOLFSSL_SYS_CRYPTO_POLICY */
163
164
/*
165
 * ssl.c Build Options:
166
 *
167
 * See also: tls.c for TLS extension/protocol options, tls13.c for TLS 1.3,
168
 *           internal.c for handshake internals, wc_port.c for platform/memory.
169
 *
170
 * OpenSSL Compatibility:
171
 * OPENSSL_EXTRA:              Enable OpenSSL compatibility API        default: off
172
 * OPENSSL_ALL:                Enable all OpenSSL compat APIs          default: off
173
 * OPENSSL_EXTRA_X509_SMALL:   Minimal OpenSSL X509 compat APIs       default: off
174
 * OPENSSL_EXTRA_NO_ASN1:      OpenSSL extra without ASN1 objects      default: off
175
 * OPENSSL_COMPATIBLE_DEFAULTS:
176
 *                  Default behavior compatible with OpenSSL           default: off
177
 * NO_WOLFSSL_STUB:            Disable stubs for unimplemented funcs   default: off
178
 * WOLFSSL_DEBUG_OPENSSL:
179
 *                  Alias for WOLFSSL_VERBOSE_LOGGING                  default: off
180
 * WOLFSSL_HAVE_ERROR_QUEUE:   OpenSSL-compatible error queue          default: off
181
 * WOLFSSL_ERROR_CODE_OPENSSL: Use OpenSSL-compatible error codes      default: off
182
 * WOLFSSL_CIPHER_INTERNALNAME:
183
 *                  Use wolfSSL internal cipher suite names             default: off
184
 * NO_CIPHER_SUITE_ALIASES:    Disable cipher suite name aliases       default: off
185
 * WOLFSSL_SET_CIPHER_BYTES:   Set cipher suites by raw byte values    default: off
186
 * WOLFSSL_OLD_SET_CURVES_LIST:
187
 *                  Old-style curve list parsing for compat             default: off
188
 * WOLFSSL_NO_OPENSSL_RAND_CB: Disable OpenSSL RAND callback compat   default: off
189
 * NO_ERROR_STRINGS:           Disable human-readable error strings    default: off
190
 * WOLFSSL_PUBLIC_ASN:         Make ASN parsing functions public        default: off
191
 *
192
 * Extra Data / BIO:
193
 * HAVE_EX_DATA:               Enable ex_data on SSL/CTX/X509 objects  default: off
194
 * HAVE_EX_DATA_CLEANUP_HOOKS: Cleanup callbacks for ex_data           default: off
195
 * HAVE_EX_DATA_CRYPTO:        ex_data support for wolfCrypt objects   default: off
196
 * MAX_EX_DATA:                Max ex_data entries per object           default: 5
197
 * NO_BIO:                     Disable BIO abstraction layer           default: off
198
 *
199
 * Session & Cache:
200
 * NO_SESSION_CACHE:           Disable server session cache            default: off
201
 * NO_SESSION_CACHE_REF:       wolfSSL_get_session returns ssl->session
202
 *                             reference instead of ClientCache ref    default: on
203
 * WOLFSSL_SESSION_CACHE_REF:  Opt back into the deprecated
204
 *                             ClientCache reference                   default: off
205
 * CLIENT_SESSIONS_MULTIPLIER: ClientCache size relative to the
206
 *                             session cache                           default: 1
207
 * SESSION_CACHE_DYNAMIC_MEM:  Dynamically allocate session cache      default: off
208
 * NO_CLIENT_CACHE:            Disable client-side session cache       default: off
209
 * SESSION_CERTS:              Store full cert chain in session         default: off
210
 * WOLFSSL_SESSION_ID_CTX:     Session ID context for cache sharing    default: off
211
 *
212
 * I/O & Transport:
213
 * USE_WOLFSSL_IO:             Use built-in I/O callbacks              default: on
214
 * WOLFSSL_USER_IO:            Application provides custom I/O         default: off
215
 * WOLFSSL_NO_SOCK:            Build without socket support            default: off
216
 * NO_WRITEV:                  Disable writev() scatter/gather I/O     default: off
217
 * WOLFSSL_DTLS_MTU:           Enable DTLS MTU management APIs         default: off
218
 * WOLFSSL_DTLS_DROP_STATS:    Track DTLS packet drop statistics       default: off
219
 * WOLFSSL_MULTICAST:          Enable DTLS multicast support           default: off
220
 *
221
 * Callbacks & Features:
222
 * WOLFSSL_CHECK_ALERT_ON_ERR: Check alerts on handshake error         default: off
223
 * ATOMIC_USER:                User-defined record layer callbacks      default: off
224
 * HAVE_WRITE_DUP:             Separate threads for SSL read/write     default: off
225
 * WOLFSSL_CALLBACKS:          Handshake monitoring callbacks           default: off
226
 * NO_HANDSHAKE_DONE_CB:       Disable handshake completion callback   default: off
227
 * WOLFSSL_SHUTDOWNONCE:       Send close_notify only once             default: off
228
 * WOLFSSL_COPY_CERT:          SSL keeps CTX cert if CTX replaces it   default: off
229
 *                             (on with OPENSSL_ALL)
230
 * WOLFSSL_COPY_KEY:           SSL keeps CTX key if CTX replaces it    default: off
231
 *                             (on with OPENSSL_ALL)
232
 * WOLF_PRIVATE_KEY_ID:        Reference private keys by ID            default: off
233
 * WOLFSSL_REFCNT_ERROR_RETURN:
234
 *                  Return errors on ref counting failures             default: off
235
 * WOLFSSL_ALLOW_MAX_FRAGMENT_ADJUST:
236
 *                  Allow runtime max fragment size adjustment          default: off
237
 * WOLFSSL_ALLOW_NO_SUITES:    Allow SSL objects with no cipher suites default: off
238
 *
239
 * Certificates & Keys:
240
 * KEEP_PEER_CERT:             Keep peer cert after handshake          default: off
241
 * KEEP_OUR_CERT:              Keep our cert after handshake           default: off
242
 * WOLFSSL_STATIC_RSA:         Enable static RSA key exchange          default: off
243
 * WOLFSSL_HAVE_CERT_SERVICE:  Certificate service callbacks           default: off
244
 * WOLFSSL_SYS_CA_CERTS:       Load system CA certs from OS            default: off
245
 *
246
 * Application Compatibility:
247
 * HAVE_CURL:                  APIs for libcurl compatibility          default: off
248
 * HAVE_LIGHTY:                APIs for lighttpd compatibility         default: off
249
 * HAVE_MEMCACHED:             APIs for memcached compatibility        default: off
250
 * WOLFSSL_APACHE_HTTPD:       APIs for Apache httpd compatibility     default: off
251
 * WOLFSSL_NGINX:              APIs for nginx compatibility            default: off
252
 * WOLFSSL_HAPROXY:            APIs for HAProxy compatibility          default: off
253
 * WOLFSSL_ASIO:               APIs for Boost.Asio compatibility       default: off
254
 * WOLFSSL_PYTHON:             APIs for Python module compatibility    default: off
255
 * WOLFSSL_QT:                 APIs for Qt framework compatibility     default: off
256
 * WOLFSSL_JNI:                APIs for Java JNI/JSSE compatibility    default: off
257
 *
258
 * Protocol Features:
259
 * WOLFSSL_HAVE_WOLFSCEP:      Enable wolfSCEP protocol support        default: off
260
 * WOLFCRYPT_HAVE_SRP:         Enable SRP protocol support             default: off
261
 * HAVE_LIBZ:                  Enable zlib TLS compression             default: off
262
 * WOLFSSL_EXTRA:              Extra SSL session info APIs              default: off
263
 * WOLFSSL_WPAS_SMALL:         Minimal wpa_supplicant/hostapd APIs     default: off
264
 * HAVE_FUZZER:                Fuzzing callback support                 default: off
265
 *
266
 * Memory & Threading:
267
 * WOLFSSL_STATIC_MEMORY_LEAN: Lean static memory allocation           default: off
268
 * WOLFSSL_THREADED_CRYPT:     Multi-threaded crypto operations         default: off
269
 * WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS:
270
 *                  Thread-safe cleanup via atomics                     default: off
271
 * WOLFSSL_ATOMIC_INITIALIZER: Static init for atomic variables        default: off
272
 * WOLFSSL_DEBUG_MEMORY:       Log malloc/free with file/line info     default: off
273
 * WOLFSSL_NO_REALLOC:         Disable realloc, use malloc+copy+free   default: off
274
 * WOLFSSL_HEAP_TEST:          Heap-related testing utilities           default: off
275
 *
276
 * Debugging & Build:
277
 * SHOW_SIZES:                 Display struct sizes at init             default: off
278
 * WOLFSSL_DEBUG_TRACE_ERROR_CODES:
279
 *                  Trace error code origins for debugging              default: off
280
 * HAVE_ATEXIT:                Register wolfSSL_Cleanup via atexit     default: off
281
 * WOLFSSL_SYS_CRYPTO_POLICY:  Honor system crypto policy settings     default: off
282
 *
283
 * Hardware TLS:
284
 * WOLFSSL_RENESAS_TSIP_TLS:   Renesas TSIP hardware crypto for TLS   default: off
285
 * WOLFSSL_RENESAS_FSPSM_TLS:  Renesas FSP Security Module for TLS    default: off
286
 * WOLFSSL_EGD_NBLOCK:         Non-blocking EGD entropy support        default: off
287
 */
288
289
#ifndef WOLFCRYPT_ONLY
290
291
#if !defined(NO_RSA) || !defined(NO_DH) || defined(HAVE_ECC) || \
292
    (defined(OPENSSL_EXTRA) && defined(WOLFSSL_KEY_GEN) && !defined(NO_DSA))
293
294
#define HAVE_GLOBAL_RNG /* consolidate flags for using globalRNG */
295
static WC_RNG globalRNG;
296
static wolfSSL_Atomic_Int initGlobalRNG = WOLFSSL_ATOMIC_INITIALIZER(0);
297
298
#if defined(OPENSSL_EXTRA) || !defined(WOLFSSL_MUTEX_INITIALIZER)
299
static WC_MAYBE_UNUSED wolfSSL_Mutex globalRNGMutex
300
    WOLFSSL_MUTEX_INITIALIZER_CLAUSE(globalRNGMutex);
301
#endif
302
#ifndef WOLFSSL_MUTEX_INITIALIZER
303
static int globalRNGMutex_valid = 0;
304
#endif
305
306
#ifdef OPENSSL_EXTRA
307
/* Serialise use of globalRNG. The mutex is not needed when the RNG locks
308
 * itself. A crypto callback found by WOLF_CRYPTO_CB_FIND runs outside the RNG
309
 * lock, so keep the mutex then. globalRNGMutex still guards init and free.
310
 * Only for the helpers below. */
311
#if defined(WC_RNG_HAVE_AUTO_LOCK) && \
312
    !defined(WC_RNG_AUTO_LOCK_DEFAULT_OFF) && \
313
    !defined(WOLF_CRYPTO_CB_FIND) && !defined(WOLFSSL_NO_ATOMICS)
314
static int wolfssl_global_rng_lock(void)
315
{
316
    return 0;
317
}
318
319
static void wolfssl_global_rng_unlock(void)
320
{
321
}
322
#else
323
static int wolfssl_global_rng_lock(void)
324
{
325
    return (wc_LockMutex(&globalRNGMutex) == 0) ? 0 : BAD_MUTEX_E;
326
}
327
328
static void wolfssl_global_rng_unlock(void)
329
{
330
    wc_UnLockMutex(&globalRNGMutex);
331
}
332
#endif
333
334
/* Init the global RNG if needed. Call without the lock held:
335
 * wolfSSL_RAND_Init() takes globalRNGMutex. Returns 0 on success. */
336
WC_MAYBE_UNUSED static int wolfssl_global_rng_init(void)
337
{
338
    if (WOLFSSL_ATOMIC_LOAD(initGlobalRNG) != 0)
339
        return 0;
340
    return (wolfSSL_RAND_Init() == WOLFSSL_SUCCESS) ? 0 : BAD_STATE_E;
341
}
342
343
/* Fill out with sz bytes from the global RNG. Inits it if needed.
344
 * Returns 0 on success. */
345
WC_MAYBE_UNUSED static int wolfssl_global_rng_generate(byte* out, word32 sz)
346
{
347
    int ret = wolfssl_global_rng_init();
348
349
    if (ret == 0)
350
        ret = wolfssl_global_rng_lock();
351
    if (ret != 0)
352
        return ret;
353
    /* Pairs with the store in wolfSSL_RAND_Init(). */
354
    if (WOLFSSL_ATOMIC_LOAD(initGlobalRNG) == 0) {
355
        wolfssl_global_rng_unlock();
356
        return BAD_STATE_E;
357
    }
358
    while ((ret == 0) && (sz > 0)) {
359
        word32 len = min(sz, (word32)RNG_MAX_BLOCK_LEN);
360
361
        ret = wc_RNG_GenerateBlock(&globalRNG, out, len);
362
        out += len;
363
        sz -= len;
364
    }
365
    wolfssl_global_rng_unlock();
366
367
    return ret;
368
}
369
370
#ifdef HAVE_HASHDRBG
371
/* Mix caller material into the global RNG. It gets no entropy credit.
372
 * Inits the RNG if needed. Returns 0 on success. */
373
WC_MAYBE_UNUSED static int wolfssl_global_rng_mix(const byte* in, word32 sz)
374
{
375
    int ret = wolfssl_global_rng_init();
376
377
    if (ret == 0)
378
        ret = wolfssl_global_rng_lock();
379
    if (ret != 0)
380
        return ret;
381
    /* Pairs with the store in wolfSSL_RAND_Init(). */
382
    if (WOLFSSL_ATOMIC_LOAD(initGlobalRNG) == 0) {
383
        wolfssl_global_rng_unlock();
384
        return BAD_STATE_E;
385
    }
386
#ifdef WC_RNG_HAVE_STIR
387
    /* An uncredited stir: credited user-class reseeds of conformant
388
     * instances are refused with WC_RNG_RBGC_STRATUM_IMMUTABLE. A standing
389
     * reseed or recovery obligation (NEEDS_RECOVERY_E: credited reseed due,
390
     * invalidation latched, or epoch stale; NOT_READY_E: the reseed interval
391
     * tripped within the call) outranks advisory material and is not a
392
     * failure: the next generate performs the credited reseed. */
393
    ret = wc_RNG_DRBG_Stir(&globalRNG, in, sz);
394
    if ((ret == WC_NO_ERR_TRACE(NOT_READY_E)) ||
395
            (ret == WC_NO_ERR_TRACE(NEEDS_RECOVERY_E))) {
396
        ret = 0;
397
    }
398
#else
399
    ret = wc_RNG_DRBG_Reseed(&globalRNG, in, sz);
400
#endif
401
    wolfssl_global_rng_unlock();
402
403
    return ret;
404
}
405
406
/* Reseed the global RNG from the system. Returns 0 on success. */
407
WC_MAYBE_UNUSED static int wolfssl_global_rng_reseed(void)
408
{
409
    /* The lock also covers wc_GenerateSeed(), which writes globalRNG.seed. */
410
    int ret = wolfssl_global_rng_lock();
411
412
    if (ret != 0)
413
        return ret;
414
    /* Pairs with the store in wolfSSL_RAND_Init(). */
415
    if (WOLFSSL_ATOMIC_LOAD(initGlobalRNG) == 0) {
416
        wolfssl_global_rng_unlock();
417
        return BAD_STATE_E;
418
    }
419
#ifdef WC_RNG_HAVE_RESEED_NOW
420
    ret = wc_RNG_DRBG_Reseed_Now(&globalRNG, NULL, 0);
421
    if (ret != 0) {
422
        WOLFSSL_MSG("Bad wc_RNG_DRBG_Reseed_Now");
423
    }
424
#else /* random.h predates wc_RNG_DRBG_Reseed_Now() */
425
    {
426
        byte   entropy[16];
427
        word32 entropy_sz = 16;
428
429
        ret = wc_GenerateSeed(&globalRNG.seed, entropy, entropy_sz);
430
        if (ret != 0) {
431
            WOLFSSL_MSG("Bad wc_GenerateSeed");
432
        }
433
        else {
434
            ret = wc_RNG_DRBG_Reseed(&globalRNG, entropy, entropy_sz);
435
            if (ret != 0) {
436
                WOLFSSL_MSG("Error reseeding DRBG");
437
            }
438
        }
439
        ForceZero(entropy, sizeof(entropy));
440
    }
441
#endif /* WC_RNG_HAVE_RESEED_NOW */
442
    wolfssl_global_rng_unlock();
443
444
    return ret;
445
}
446
#endif /* HAVE_HASHDRBG */
447
#endif /* OPENSSL_EXTRA */
448
449
#if defined(OPENSSL_EXTRA) && defined(HAVE_HASHDRBG)
450
static WOLFSSL_DRBG_CTX* gDrbgDefCtx = NULL;
451
#endif
452
453
WC_RNG* wolfssl_get_global_rng(void)
454
0
{
455
0
    WC_RNG* ret = NULL;
456
457
0
    if (WOLFSSL_ATOMIC_LOAD(initGlobalRNG) == 0)
458
0
        WOLFSSL_MSG("Global RNG no Init");
459
0
    else
460
0
        ret = &globalRNG;
461
462
0
    return ret;
463
0
}
464
465
/* Make a global RNG and return.
466
 *
467
 * @return  Global RNG on success.
468
 * @return  NULL on error.
469
 */
470
WC_RNG* wolfssl_make_global_rng(void)
471
0
{
472
0
    WC_RNG* ret;
473
474
0
#ifdef HAVE_GLOBAL_RNG
475
    /* Get the global random number generator instead. */
476
0
    ret = wolfssl_get_global_rng();
477
#ifdef OPENSSL_EXTRA
478
    if (ret == NULL) {
479
        /* Create a global random if possible. */
480
        (void)wolfSSL_RAND_Init();
481
        ret = wolfssl_get_global_rng();
482
    }
483
#endif
484
#else
485
    WOLFSSL_ERROR_MSG("Bad RNG Init");
486
    ret = NULL;
487
#endif
488
489
0
    return ret;
490
0
}
491
492
/* Too many defines to check explicitly - prototype it and always include
493
 * for RSA, DH, ECC and DSA for BN. */
494
WC_RNG* wolfssl_make_rng(WC_RNG* rng, int* local);
495
496
/* Make a random number generator or get global if possible.
497
 *
498
 * Global may not be available and NULL will be returned.
499
 *
500
 * @param [in, out] rng    Local random number generator.
501
 * @param [out]     local  Local random number generator returned.
502
 * @return  NULL on failure.
503
 * @return  A random number generator object.
504
 */
505
WC_RNG* wolfssl_make_rng(WC_RNG* rng, int* local)
506
0
{
507
0
    WC_RNG* ret = NULL;
508
#ifdef WOLFSSL_SMALL_STACK
509
    int freeRng = 0;
510
511
    /* Allocate RNG object . */
512
    if (rng == NULL) {
513
        rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
514
        freeRng = 1;
515
    }
516
#endif
517
518
0
    if (rng != NULL) {
519
0
        if (wc_InitRng(rng) == 0) {
520
0
            ret = rng;
521
0
            *local = 1;
522
0
        }
523
0
        else {
524
0
            WOLFSSL_MSG("Bad RNG Init");
525
#ifdef WOLFSSL_SMALL_STACK
526
            if (freeRng) {
527
                XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
528
                rng = NULL;
529
            }
530
#endif
531
0
        }
532
0
    }
533
0
    if (ret == NULL) {
534
0
#ifdef HAVE_GLOBAL_RNG
535
0
        WOLFSSL_MSG("trying global RNG");
536
0
#endif
537
0
        ret = wolfssl_make_global_rng();
538
0
    }
539
540
0
    return ret;
541
0
}
542
#endif
543
544
#ifdef OPENSSL_EXTRA
545
    /* WOLFSSL_NO_OPENSSL_RAND_CB: Allows way to reduce code size for
546
     *                OPENSSL_EXTRA where RAND callbacks are not used */
547
    #ifndef WOLFSSL_NO_OPENSSL_RAND_CB
548
        static const WOLFSSL_RAND_METHOD* gRandMethods = NULL;
549
        static wolfSSL_Mutex gRandMethodMutex
550
            WOLFSSL_MUTEX_INITIALIZER_CLAUSE(gRandMethodMutex);
551
        #ifndef WOLFSSL_MUTEX_INITIALIZER
552
        static int gRandMethodsInit = 0;
553
        #endif
554
    #endif /* !WOLFSSL_NO_OPENSSL_RAND_CB */
555
#endif /* OPENSSL_EXTRA */
556
557
#endif /* !WOLFCRYPT_ONLY */
558
559
#define WOLFSSL_SSL_MISC_INCLUDED
560
#include "src/ssl_misc.c"
561
562
#define WOLFSSL_EVP_INCLUDED
563
#include "wolfcrypt/src/evp.c"
564
565
/* Crypto code uses EVP APIs. */
566
#define WOLFSSL_SSL_CRYPTO_INCLUDED
567
#include "src/ssl_crypto.c"
568
569
#ifndef WOLFCRYPT_ONLY
570
#define WOLFSSL_SSL_CERTMAN_INCLUDED
571
#include "src/ssl_certman.c"
572
573
#define WOLFSSL_SSL_SESS_INCLUDED
574
#include "src/ssl_sess.c"
575
576
/* Forward declarations for static functions that are defined in a file
577
 * included later in this amalgamation but used by one included earlier. Keep
578
 * them here, next to the includes, rather than inside the files that need
579
 * them.
580
 *
581
 * x509GetIssuerFromCM() is defined in src/x509_str.c, which also requires
582
 * NO_CERTS to be undefined. */
583
#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA) && !defined(NO_CERTS)
584
static int x509GetIssuerFromCM(WOLFSSL_X509 **issuer, WOLFSSL_CERT_MANAGER* cm,
585
        WOLFSSL_X509 *x);
586
#endif
587
588
#define WOLFSSL_SSL_API_CERT_INCLUDED
589
#include "src/ssl_api_cert.c"
590
591
#define WOLFSSL_SSL_API_PK_INCLUDED
592
#include "src/ssl_api_pk.c"
593
#endif
594
595
596
#ifndef WOLFCRYPT_ONLY
597
598
599
600
#define WOLFSSL_SSL_BN_INCLUDED
601
#include "src/ssl_bn.c"
602
603
#define WOLFSSL_SSL_ASN1_INCLUDED
604
#include "src/ssl_asn1.c"
605
606
#define WOLFSSL_SSL_TSP_INCLUDED
607
#include "src/ssl_tsp.c"
608
609
#define WOLFSSL_PK_INCLUDED
610
#include "src/pk.c"
611
612
#define WOLFSSL_EVP_PK_INCLUDED
613
#include "wolfcrypt/src/evp_pk.c"
614
615
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
616
/* copies over data of "in" to "out" */
617
static void wolfSSL_CIPHER_copy(WOLFSSL_CIPHER* in, WOLFSSL_CIPHER* out)
618
{
619
    if (in == NULL || out == NULL)
620
        return;
621
622
    *out = *in;
623
}
624
625
626
#if defined(OPENSSL_ALL)
627
static WOLFSSL_X509_OBJECT* wolfSSL_X509_OBJECT_dup(WOLFSSL_X509_OBJECT* obj)
628
{
629
    WOLFSSL_X509_OBJECT* ret = NULL;
630
    if (obj) {
631
        ret = wolfSSL_X509_OBJECT_new();
632
        if (ret) {
633
            ret->type = obj->type;
634
            switch (ret->type) {
635
                case WOLFSSL_X509_LU_NONE:
636
                    break;
637
                case WOLFSSL_X509_LU_X509:
638
                    ret->data.x509 = wolfSSL_X509_dup(obj->data.x509);
639
                    break;
640
                case WOLFSSL_X509_LU_CRL:
641
            #if defined(HAVE_CRL)
642
                    ret->data.crl = wolfSSL_X509_CRL_dup(obj->data.crl);
643
            #endif
644
                    break;
645
            }
646
        }
647
    }
648
    return ret;
649
}
650
#endif /* OPENSSL_ALL */
651
652
#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
653
654
#define WOLFSSL_SSL_SK_INCLUDED
655
#include "src/ssl_sk.c"
656
657
658
#include <wolfssl/wolfcrypt/hpke.h>
659
660
#define WOLFSSL_SSL_ECH_INCLUDED
661
#include "src/ssl_ech.c"
662
663
#ifdef OPENSSL_EXTRA
664
static int wolfSSL_parse_cipher_list(WOLFSSL_CTX* ctx, WOLFSSL* ssl,
665
        Suites* suites, const char* list);
666
#endif
667
668
#if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_FSPSM_TLS)
669
#include <wolfssl/wolfcrypt/port/Renesas/renesas_cmn.h>
670
#endif
671
672
/* prevent multiple mutex initializations */
673
674
/* note, initRefCount is not used for thread synchronization, only for
675
 * bookkeeping while inits_count_mutex is held.
676
 */
677
static volatile WC_THREADSHARED int initRefCount = 0;
678
679
/* init ref count mutex */
680
static WC_THREADSHARED wolfSSL_Mutex inits_count_mutex
681
    WOLFSSL_MUTEX_INITIALIZER_CLAUSE(inits_count_mutex);
682
#ifndef WOLFSSL_MUTEX_INITIALIZER
683
static WC_THREADSHARED volatile int inits_count_mutex_valid = 0;
684
#endif
685
686
#ifdef NO_TLS
687
static const WOLFSSL_METHOD gNoTlsMethod;
688
#endif
689
690
/* Create a new WOLFSSL_CTX struct and return the pointer to created struct.
691
   WOLFSSL_METHOD pointer passed in is given to ctx to manage.
692
   This function frees the passed in WOLFSSL_METHOD struct on failure and on
693
   success is freed when ctx is freed.
694
 */
695
WOLFSSL_CTX* wolfSSL_CTX_new_ex(WOLFSSL_METHOD* method, void* heap)
696
0
{
697
0
    WOLFSSL_CTX* ctx = NULL;
698
699
0
    WOLFSSL_ENTER("wolfSSL_CTX_new_ex");
700
701
0
    if (initRefCount == 0) {
702
        /* user no longer forced to call Init themselves */
703
0
        int ret = wolfSSL_Init();
704
0
        if (ret != WOLFSSL_SUCCESS) {
705
0
            WOLFSSL_MSG("wolfSSL_Init failed");
706
0
            WOLFSSL_LEAVE("wolfSSL_CTX_new_ex", 0);
707
0
            XFREE(method, heap, DYNAMIC_TYPE_METHOD);
708
0
            return NULL;
709
0
        }
710
0
    }
711
712
0
#ifndef NO_TLS
713
0
    if (method == NULL)
714
0
        return ctx;
715
#else
716
    /* a blank TLS method */
717
    method = (WOLFSSL_METHOD*)&gNoTlsMethod;
718
#endif
719
720
0
    ctx = (WOLFSSL_CTX*)XMALLOC(sizeof(WOLFSSL_CTX), heap, DYNAMIC_TYPE_CTX);
721
0
    if (ctx) {
722
0
        int ret;
723
724
0
        ret = InitSSL_Ctx(ctx, method, heap);
725
    #ifdef WOLFSSL_STATIC_MEMORY
726
        if (heap != NULL) {
727
            ctx->onHeapHint = 1; /* free the memory back to heap when done */
728
        }
729
    #endif
730
0
        if (ret < 0) {
731
0
            WOLFSSL_MSG("Init CTX failed");
732
0
            wolfSSL_CTX_free(ctx);
733
0
            ctx = NULL;
734
0
        }
735
#if defined(OPENSSL_EXTRA) && defined(WOLFCRYPT_HAVE_SRP) \
736
                           && !defined(NO_SHA256) && !defined(WC_NO_RNG)
737
        else {
738
            ctx->srp = (Srp*)XMALLOC(sizeof(Srp), heap, DYNAMIC_TYPE_SRP);
739
            if (ctx->srp == NULL){
740
                WOLFSSL_MSG("Init CTX failed");
741
                wolfSSL_CTX_free(ctx);
742
                return NULL;
743
            }
744
            XMEMSET(ctx->srp, 0, sizeof(Srp));
745
        }
746
#endif
747
0
    }
748
0
    else {
749
0
        WOLFSSL_MSG("Alloc CTX failed, method freed");
750
0
        XFREE(method, heap, DYNAMIC_TYPE_METHOD);
751
0
    }
752
753
#ifdef OPENSSL_COMPATIBLE_DEFAULTS
754
    if (ctx) {
755
        wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, NULL);
756
        wolfSSL_CTX_set_mode(ctx, WOLFSSL_MODE_AUTO_RETRY);
757
        if (wolfSSL_CTX_set_min_proto_version(ctx,
758
                (method->version.major == DTLS_MAJOR) ?
759
                DTLS1_VERSION : SSL3_VERSION) != WOLFSSL_SUCCESS ||
760
#ifdef HAVE_ANON
761
                wolfSSL_CTX_allow_anon_cipher(ctx) != WOLFSSL_SUCCESS ||
762
#endif
763
                wolfSSL_CTX_set_group_messages(ctx) != WOLFSSL_SUCCESS) {
764
            WOLFSSL_MSG("Setting OpenSSL CTX defaults failed");
765
            wolfSSL_CTX_free(ctx);
766
            ctx = NULL;
767
        }
768
        else {
769
            /* a default, not a minimum the user asked for */
770
            ctx->minVersionSet = 0;
771
        }
772
    }
773
#endif
774
775
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
776
    /* Load the crypto-policy ciphers if configured. */
777
    if (ctx && wolfSSL_crypto_policy_is_enabled()) {
778
        const char * list = wolfSSL_crypto_policy_get_ciphers();
779
        int          ret = 0;
780
781
        if (list != NULL && *list != '\0') {
782
            if (AllocateCtxSuites(ctx) != 0) {
783
                WOLFSSL_MSG("allocate ctx suites failed");
784
                wolfSSL_CTX_free(ctx);
785
                ctx = NULL;
786
            }
787
            else {
788
                ret = wolfSSL_parse_cipher_list(ctx, NULL, ctx->suites, list);
789
                if (ret != WOLFSSL_SUCCESS) {
790
                    WOLFSSL_MSG("parse cipher list failed");
791
                    wolfSSL_CTX_free(ctx);
792
                    ctx = NULL;
793
                }
794
            }
795
        }
796
    }
797
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
798
799
0
    WOLFSSL_LEAVE("wolfSSL_CTX_new_ex", 0);
800
0
    return ctx;
801
0
}
802
803
804
WOLFSSL_ABI
805
WOLFSSL_CTX* wolfSSL_CTX_new(WOLFSSL_METHOD* method)
806
0
{
807
#ifdef WOLFSSL_HEAP_TEST
808
    /* if testing the heap hint then set top level CTX to have test value */
809
    return wolfSSL_CTX_new_ex(method, (void*)WOLFSSL_HEAP_TEST);
810
#else
811
0
    return wolfSSL_CTX_new_ex(method, NULL);
812
0
#endif
813
0
}
814
815
/* increases CTX reference count to track proper time to "free" */
816
int wolfSSL_CTX_up_ref(WOLFSSL_CTX* ctx)
817
0
{
818
0
    int ret;
819
0
    wolfSSL_RefWithMutexInc(&ctx->ref, &ret);
820
#ifdef WOLFSSL_REFCNT_ERROR_RETURN
821
    return ((ret == 0) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE);
822
#else
823
0
    (void)ret;
824
0
    return WOLFSSL_SUCCESS;
825
0
#endif
826
0
}
827
828
WOLFSSL_ABI
829
void wolfSSL_CTX_free(WOLFSSL_CTX* ctx)
830
0
{
831
0
    WOLFSSL_ENTER("wolfSSL_CTX_free");
832
0
    if (ctx) {
833
0
        FreeSSL_Ctx(ctx);
834
0
    }
835
836
0
    WOLFSSL_LEAVE("wolfSSL_CTX_free", 0);
837
0
}
838
839
840
#ifdef HAVE_ENCRYPT_THEN_MAC
841
/**
842
 * Sets whether Encrypt-Then-MAC extension can be negotiated against context.
843
 * The default value: enabled.
844
 *
845
 * ctx  SSL/TLS context.
846
 * set  Whether to allow or not: 1 is allow and 0 is disallow.
847
 * returns WOLFSSL_SUCCESS
848
 */
849
int wolfSSL_CTX_AllowEncryptThenMac(WOLFSSL_CTX *ctx, int set)
850
0
{
851
0
    ctx->disallowEncThenMac = !set;
852
0
    return WOLFSSL_SUCCESS;
853
0
}
854
855
/**
856
 * Sets whether Encrypt-Then-MAC extension can be negotiated against context.
857
 * The default value comes from context.
858
 *
859
 * ctx  SSL/TLS context.
860
 * set  Whether to allow or not: 1 is allow and 0 is disallow.
861
 * returns WOLFSSL_SUCCESS
862
 */
863
int wolfSSL_AllowEncryptThenMac(WOLFSSL *ssl, int set)
864
0
{
865
0
    ssl->options.disallowEncThenMac = !set;
866
0
    return WOLFSSL_SUCCESS;
867
0
}
868
#endif
869
870
#ifdef SINGLE_THREADED
871
/* no locking in single threaded mode, allow a CTX level rng to be shared with
872
 * WOLFSSL objects, WOLFSSL_SUCCESS on ok */
873
int wolfSSL_CTX_new_rng(WOLFSSL_CTX* ctx)
874
{
875
    WC_RNG* rng;
876
    int     ret;
877
878
    if (ctx == NULL) {
879
        return BAD_FUNC_ARG;
880
    }
881
882
    rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), ctx->heap, DYNAMIC_TYPE_RNG);
883
    if (rng == NULL) {
884
        return MEMORY_E;
885
    }
886
887
#ifndef HAVE_FIPS
888
    ret = wc_InitRng_ex(rng, ctx->heap, ctx->devId);
889
#else
890
    ret = wc_InitRng(rng);
891
#endif
892
    if (ret != 0) {
893
        XFREE(rng, ctx->heap, DYNAMIC_TYPE_RNG);
894
        return ret;
895
    }
896
897
    ctx->rng = rng;
898
    return WOLFSSL_SUCCESS;
899
}
900
#endif
901
902
903
WOLFSSL_ABI
904
WOLFSSL* wolfSSL_new(WOLFSSL_CTX* ctx)
905
0
{
906
0
    WOLFSSL* ssl = NULL;
907
0
    int ret = 0;
908
909
0
    WOLFSSL_ENTER("wolfSSL_new");
910
911
0
    if (ctx == NULL) {
912
0
        WOLFSSL_MSG("wolfSSL_new ctx is null");
913
0
        return NULL;
914
0
    }
915
916
0
    ssl = (WOLFSSL*) XMALLOC(sizeof(WOLFSSL), ctx->heap, DYNAMIC_TYPE_SSL);
917
918
0
    if (ssl == NULL) {
919
0
        WOLFSSL_MSG_EX("ssl xmalloc failed to allocate %d bytes",
920
0
                        (int)sizeof(WOLFSSL));
921
0
    }
922
0
    else {
923
0
        ret = InitSSL(ssl, ctx, 0);
924
0
        if (ret < 0) {
925
0
            WOLFSSL_MSG_EX("wolfSSL_new failed during InitSSL. err = %d", ret);
926
0
            FreeSSL(ssl, ctx->heap);
927
0
            ssl = NULL;
928
0
        }
929
0
        else if (ret == 0) {
930
0
            WOLFSSL_MSG("wolfSSL_new InitSSL success");
931
0
        }
932
0
        else {
933
            /* Only success (0) or negative values should ever be seen. */
934
0
            WOLFSSL_MSG_EX("WARNING: wolfSSL_new unexpected InitSSL return"
935
0
                           " value = %d", ret);
936
0
        } /* InitSSL check */
937
0
    } /* ssl XMALLOC success */
938
939
0
    WOLFSSL_LEAVE("wolfSSL_new InitSSL =", ret);
940
0
    (void)ret;
941
942
0
    return ssl;
943
0
}
944
945
946
WOLFSSL_ABI
947
void wolfSSL_free(WOLFSSL* ssl)
948
0
{
949
0
    void *heap = NULL;
950
0
    WOLFSSL_ENTER("wolfSSL_free");
951
952
0
    if (ssl) {
953
0
        WOLFSSL_MSG_EX("Free SSL: %p", (wc_ptr_t)ssl);
954
0
        if (ssl->ctx != NULL) {
955
0
            heap = ssl->ctx->heap;
956
0
        }
957
0
        FreeSSL(ssl, heap);
958
0
    }
959
0
    else {
960
0
        WOLFSSL_MSG("Free SSL: wolfSSL_free already null");
961
0
    }
962
0
    WOLFSSL_LEAVE("wolfSSL_free", 0);
963
0
}
964
965
966
int wolfSSL_is_server(WOLFSSL* ssl)
967
0
{
968
0
    if (ssl == NULL)
969
0
        return BAD_FUNC_ARG;
970
0
    return ssl->options.side == WOLFSSL_SERVER_END;
971
0
}
972
973
#ifdef HAVE_WRITE_DUP
974
975
/*
976
 * Release resources around WriteDup object
977
 *
978
 * ssl WOLFSSL object
979
 *
980
 * no return, destruction so make best attempt
981
*/
982
void FreeWriteDup(WOLFSSL* ssl)
983
{
984
    int doFree = 0;
985
986
    WOLFSSL_ENTER("FreeWriteDup");
987
988
    if (ssl->dupWrite) {
989
        if (wc_LockMutex(&ssl->dupWrite->dupMutex) == 0) {
990
            ssl->dupWrite->dupCount--;
991
            if (ssl->dupWrite->dupCount == 0) {
992
                doFree = 1;
993
            } else {
994
                WOLFSSL_MSG("WriteDup count not zero, no full free");
995
            }
996
            wc_UnLockMutex(&ssl->dupWrite->dupMutex);
997
        }
998
    }
999
1000
    if (doFree) {
1001
#ifdef WOLFSSL_DTLS13
1002
        struct Dtls13RecordNumber* rn = ssl->dupWrite->sendAckList;
1003
        while (rn != NULL) {
1004
            struct Dtls13RecordNumber* next = rn->next;
1005
            XFREE(rn, ssl->heap, DYNAMIC_TYPE_DTLS_MSG);
1006
            rn = next;
1007
        }
1008
#endif
1009
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
1010
        Free_HS_Hashes(ssl->dupWrite->postHandshakeHashState, ssl->heap);
1011
        Free_HS_Hashes(ssl->dupWrite->postHandshakeSyncedHashState, ssl->heap);
1012
        {
1013
            CertReqCtx* ctx = ssl->dupWrite->postHandshakeCertReqCtx;
1014
            while (ctx != NULL) {
1015
                CertReqCtx* nxt = ctx->next;
1016
                XFREE(ctx, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
1017
                ctx = nxt;
1018
            }
1019
        }
1020
#endif /* WOLFSSL_TLS13 && WOLFSSL_POST_HANDSHAKE_AUTH */
1021
        wc_FreeMutex(&ssl->dupWrite->dupMutex);
1022
        XFREE(ssl->dupWrite, ssl->heap, DYNAMIC_TYPE_WRITEDUP);
1023
        ssl->dupWrite = NULL;
1024
        WOLFSSL_MSG("Did WriteDup full free, count to zero");
1025
    }
1026
}
1027
1028
1029
/*
1030
 * duplicate existing ssl members into dup needed for writing
1031
 *
1032
 * dup write only WOLFSSL
1033
 * ssl existing WOLFSSL
1034
 *
1035
 * 0 on success
1036
*/
1037
static int DupSSL(WOLFSSL* dup, WOLFSSL* ssl)
1038
{
1039
    word16 tmp_weOwnRng;
1040
#ifdef HAVE_ONE_TIME_AUTH
1041
#ifdef HAVE_POLY1305
1042
    Poly1305* tmp_poly1305 = NULL;
1043
#endif
1044
#endif
1045
1046
    /* shared dupWrite setup */
1047
    ssl->dupWrite = (WriteDup*)XMALLOC(sizeof(WriteDup), ssl->heap,
1048
                                       DYNAMIC_TYPE_WRITEDUP);
1049
    if (ssl->dupWrite == NULL) {
1050
        return MEMORY_E;
1051
    }
1052
    XMEMSET(ssl->dupWrite, 0, sizeof(WriteDup));
1053
1054
    if (wc_InitMutex(&ssl->dupWrite->dupMutex) != 0) {
1055
        XFREE(ssl->dupWrite, ssl->heap, DYNAMIC_TYPE_WRITEDUP);
1056
        ssl->dupWrite = NULL;
1057
        return BAD_MUTEX_E;
1058
    }
1059
1060
    /* Pre-allocate any objects that can fail BEFORE performing destructive
1061
     * state mutations on ssl, so an allocation failure cannot leave ssl
1062
     * with a zeroed encrypt context and a poisoned dupWrite.
1063
     * dup->heap == ssl->heap here because dup was initialised with ssl->ctx;
1064
     * use ssl->heap consistently for cleanup symmetry. */
1065
#ifdef HAVE_ONE_TIME_AUTH
1066
#ifdef HAVE_POLY1305
1067
    if (ssl->auth.setup && ssl->auth.poly1305 != NULL) {
1068
        tmp_poly1305 = (Poly1305*)XMALLOC(sizeof(Poly1305), ssl->heap,
1069
            DYNAMIC_TYPE_CIPHER);
1070
        if (tmp_poly1305 == NULL) {
1071
            wc_FreeMutex(&ssl->dupWrite->dupMutex);
1072
            XFREE(ssl->dupWrite, ssl->heap, DYNAMIC_TYPE_WRITEDUP);
1073
            ssl->dupWrite = NULL;
1074
            return MEMORY_E;
1075
        }
1076
    }
1077
#endif
1078
#endif
1079
1080
    ssl->dupWrite->dupCount = 2;    /* both sides have a count to start */
1081
    dup->dupWrite = ssl->dupWrite; /* each side uses */
1082
1083
    tmp_weOwnRng = dup->options.weOwnRng;
1084
1085
    /* copy write parts over to dup writer */
1086
    XMEMCPY(&dup->specs,   &ssl->specs,   sizeof(CipherSpecs));
1087
    XMEMCPY(&dup->options, &ssl->options, sizeof(Options));
1088
    XMEMCPY(&dup->keys,    &ssl->keys,    sizeof(Keys));
1089
    XMEMCPY(&dup->encrypt, &ssl->encrypt, sizeof(Ciphers));
1090
    XMEMCPY(&dup->version, &ssl->version, sizeof(ProtocolVersion));
1091
    XMEMCPY(&dup->chVersion, &ssl->chVersion, sizeof(ProtocolVersion));
1092
#ifdef HAVE_MAX_FRAGMENT
1093
    /* The negotiated limit applies to the records the writer sends. */
1094
    dup->max_fragment = ssl->max_fragment;
1095
#endif
1096
1097
    /* dup side now owns encrypt/write ciphers */
1098
    XMEMSET(&ssl->encrypt, 0, sizeof(Ciphers));
1099
1100
#ifdef HAVE_ONE_TIME_AUTH
1101
#ifdef HAVE_POLY1305
1102
    if (tmp_poly1305 != NULL) {
1103
        dup->auth.poly1305 = tmp_poly1305;
1104
        dup->auth.setup = 1;
1105
    }
1106
#endif
1107
#endif
1108
1109
#ifdef WOLFSSL_TLS13
1110
    if (IsAtLeastTLSv1_3(ssl->version)) {
1111
        /* Copy TLS 1.3 application traffic secrets so the write side can
1112
         * derive updated keys when wolfSSL_update_keys() is called. */
1113
        XMEMCPY(dup->clientSecret, ssl->clientSecret, SECRET_LEN);
1114
        XMEMCPY(dup->serverSecret, ssl->serverSecret, SECRET_LEN);
1115
1116
#ifdef WOLFSSL_DTLS13
1117
        if (ssl->options.dtls) {
1118
            /* Copy epoch array (contains only value types -- safe to memcpy). */
1119
            XMEMCPY(dup->dtls13Epochs, ssl->dtls13Epochs,
1120
                    sizeof(ssl->dtls13Epochs));
1121
1122
            /* Re-point dtls13EncryptEpoch into dup's own epoch array. */
1123
            if (ssl->dtls13EncryptEpoch != NULL) {
1124
                dup->dtls13EncryptEpoch =
1125
                    &dup->dtls13Epochs[ssl->dtls13EncryptEpoch -
1126
                                       ssl->dtls13Epochs];
1127
            }
1128
1129
            /* Copy current write epoch number. */
1130
            dup->dtls13Epoch = ssl->dtls13Epoch;
1131
1132
            /* Transfer record-number encryption cipher ownership to dup. */
1133
            XMEMCPY(&dup->dtlsRecordNumberEncrypt,
1134
                    &ssl->dtlsRecordNumberEncrypt, sizeof(RecordNumberCiphers));
1135
            XMEMSET(&ssl->dtlsRecordNumberEncrypt,
1136
                    0, sizeof(RecordNumberCiphers));
1137
        }
1138
#endif /* WOLFSSL_DTLS13 */
1139
    }
1140
#endif /* WOLFSSL_TLS13 */
1141
1142
1143
    dup->IOCB_WriteCtx = ssl->IOCB_WriteCtx;
1144
    dup->CBIOSend = ssl->CBIOSend;
1145
#ifdef OPENSSL_EXTRA
1146
    dup->cbioFlag = ssl->cbioFlag;
1147
    dup->maxSendFragment = ssl->maxSendFragment;
1148
#endif
1149
    dup->wfd    = ssl->wfd;
1150
    dup->wflags = ssl->wflags;
1151
#ifndef WOLFSSL_AEAD_ONLY
1152
    dup->hmac   = ssl->hmac;
1153
#endif
1154
#ifdef HAVE_TRUNCATED_HMAC
1155
    dup->truncated_hmac = ssl->truncated_hmac;
1156
#endif
1157
1158
    /* Restore rng option */
1159
    dup->options.weOwnRng = tmp_weOwnRng;
1160
1161
    /* unique side dup setup */
1162
    dup->dupSide = WRITE_DUP_SIDE;
1163
    ssl->dupSide = READ_DUP_SIDE;
1164
1165
    return 0;
1166
}
1167
1168
1169
/*
1170
 * duplicate a WOLFSSL object post handshake for writing only
1171
 * turn existing object into read only.  Allows concurrent access from two
1172
 * different threads.
1173
 *
1174
 * ssl existing WOLFSSL object
1175
 *
1176
 * return dup'd WOLFSSL object on success
1177
*/
1178
WOLFSSL* wolfSSL_write_dup(WOLFSSL* ssl)
1179
{
1180
    WOLFSSL* dup = NULL;
1181
    int ret = 0;
1182
1183
    (void)ret;
1184
    WOLFSSL_ENTER("wolfSSL_write_dup");
1185
1186
    if (ssl == NULL) {
1187
        return ssl;
1188
    }
1189
1190
    if (ssl->options.handShakeDone == 0) {
1191
        WOLFSSL_MSG("wolfSSL_write_dup called before handshake complete");
1192
        return NULL;
1193
    }
1194
1195
    if (ssl->dupWrite) {
1196
        WOLFSSL_MSG("wolfSSL_write_dup already called once");
1197
        return NULL;
1198
    }
1199
1200
    dup = (WOLFSSL*) XMALLOC(sizeof(WOLFSSL), ssl->ctx->heap, DYNAMIC_TYPE_SSL);
1201
    if (dup) {
1202
        if ( (ret = InitSSL(dup, ssl->ctx, 1)) < 0) {
1203
            FreeSSL(dup, ssl->ctx->heap);
1204
            dup = NULL;
1205
        } else if ( (ret = DupSSL(dup, ssl)) < 0) {
1206
            FreeSSL(dup, ssl->ctx->heap);
1207
            dup = NULL;
1208
        }
1209
    }
1210
1211
    WOLFSSL_LEAVE("wolfSSL_write_dup", ret);
1212
1213
    return dup;
1214
}
1215
1216
1217
/*
1218
 * Notify write dup side of fatal error or close notify
1219
 *
1220
 * ssl WOLFSSL object
1221
 * err Notify err
1222
 *
1223
 * 0 on success
1224
*/
1225
int NotifyWriteSide(WOLFSSL* ssl, int err)
1226
{
1227
    int ret;
1228
1229
    WOLFSSL_ENTER("NotifyWriteSide");
1230
1231
    ret = wc_LockMutex(&ssl->dupWrite->dupMutex);
1232
    if (ret == 0) {
1233
        ssl->dupWrite->dupErr = err;
1234
        ret = wc_UnLockMutex(&ssl->dupWrite->dupMutex);
1235
    }
1236
1237
    return ret;
1238
}
1239
1240
1241
#endif /* HAVE_WRITE_DUP */
1242
1243
1244
#ifdef HAVE_POLY1305
1245
/* set if to use old poly 1 for yes 0 to use new poly */
1246
int wolfSSL_use_old_poly(WOLFSSL* ssl, int value)
1247
0
{
1248
0
    (void)ssl;
1249
0
    (void)value;
1250
1251
0
#ifndef WOLFSSL_NO_TLS12
1252
0
    WOLFSSL_ENTER("wolfSSL_use_old_poly");
1253
0
    WOLFSSL_MSG("Warning SSL connection auto detects old/new and this function"
1254
0
            "is depreciated");
1255
0
    ssl->options.oldPoly = (word16)value;
1256
0
    WOLFSSL_LEAVE("wolfSSL_use_old_poly", 0);
1257
0
#endif
1258
0
    return 0;
1259
0
}
1260
#endif
1261
1262
1263
WOLFSSL_ABI
1264
int wolfSSL_set_fd(WOLFSSL* ssl, int fd)
1265
0
{
1266
0
    int ret;
1267
1268
0
    WOLFSSL_ENTER("wolfSSL_set_fd");
1269
1270
0
    if (ssl == NULL) {
1271
0
        return BAD_FUNC_ARG;
1272
0
    }
1273
1274
0
    ret = wolfSSL_set_read_fd(ssl, fd);
1275
0
    if (ret == WOLFSSL_SUCCESS) {
1276
0
        ret = wolfSSL_set_write_fd(ssl, fd);
1277
0
    }
1278
1279
0
    return ret;
1280
0
}
1281
1282
1283
int wolfSSL_set_read_fd(WOLFSSL* ssl, int fd)
1284
0
{
1285
0
    WOLFSSL_ENTER("wolfSSL_set_read_fd");
1286
1287
0
    if (ssl == NULL) {
1288
0
        return BAD_FUNC_ARG;
1289
0
    }
1290
1291
0
    ssl->rfd = fd;      /* not used directly to allow IO callbacks */
1292
0
    ssl->IOCB_ReadCtx  = &ssl->rfd;
1293
1294
    #ifdef WOLFSSL_DTLS
1295
        ssl->buffers.dtlsCtx.connected = 0;
1296
        if (ssl->options.dtls) {
1297
            ssl->IOCB_ReadCtx = &ssl->buffers.dtlsCtx;
1298
            ssl->buffers.dtlsCtx.rfd = fd;
1299
        #ifdef USE_WOLFSSL_IO
1300
            ssl->buffers.dtlsCtx.rfdIsDGram =
1301
                (byte)(wolfIO_SockIsDGram(fd) != 0);
1302
        #endif
1303
        }
1304
    #endif
1305
1306
0
    WOLFSSL_LEAVE("wolfSSL_set_read_fd", WOLFSSL_SUCCESS);
1307
0
    return WOLFSSL_SUCCESS;
1308
0
}
1309
1310
1311
int wolfSSL_set_write_fd(WOLFSSL* ssl, int fd)
1312
0
{
1313
0
    WOLFSSL_ENTER("wolfSSL_set_write_fd");
1314
1315
0
    if (ssl == NULL) {
1316
0
        return BAD_FUNC_ARG;
1317
0
    }
1318
1319
0
    ssl->wfd = fd;      /* not used directly to allow IO callbacks */
1320
0
    ssl->IOCB_WriteCtx  = &ssl->wfd;
1321
1322
    #ifdef WOLFSSL_DTLS
1323
        ssl->buffers.dtlsCtx.connected = 0;
1324
        if (ssl->options.dtls) {
1325
            ssl->IOCB_WriteCtx = &ssl->buffers.dtlsCtx;
1326
            ssl->buffers.dtlsCtx.wfd = fd;
1327
        #ifdef USE_WOLFSSL_IO
1328
            ssl->buffers.dtlsCtx.wfdIsDGram =
1329
                (byte)(wolfIO_SockIsDGram(fd) != 0);
1330
        #endif
1331
        }
1332
    #endif
1333
1334
0
    WOLFSSL_LEAVE("wolfSSL_set_write_fd", WOLFSSL_SUCCESS);
1335
0
    return WOLFSSL_SUCCESS;
1336
0
}
1337
1338
1339
/**
1340
  * Get the name of cipher at priority level passed in.
1341
  */
1342
char* wolfSSL_get_cipher_list(int priority)
1343
0
{
1344
0
    const CipherSuiteInfo* ciphers = GetCipherNames();
1345
1346
0
    if (priority >= GetCipherNamesSize() || priority < 0) {
1347
0
        return 0;
1348
0
    }
1349
1350
0
    return (char*)ciphers[priority].name;
1351
0
}
1352
1353
1354
/**
1355
  * Get the name of cipher at priority level passed in.
1356
  */
1357
char* wolfSSL_get_cipher_list_ex(WOLFSSL* ssl, int priority)
1358
0
{
1359
1360
0
    if (ssl == NULL) {
1361
0
        return NULL;
1362
0
    }
1363
0
    else {
1364
0
        const char* cipher;
1365
1366
0
        if ((cipher = wolfSSL_get_cipher_name_internal(ssl)) != NULL) {
1367
0
            if (priority == 0) {
1368
0
                return (char*)cipher;
1369
0
            }
1370
0
            else {
1371
0
                return NULL;
1372
0
            }
1373
0
        }
1374
0
        else {
1375
0
            return wolfSSL_get_cipher_list(priority);
1376
0
        }
1377
0
    }
1378
0
}
1379
1380
1381
int wolfSSL_get_ciphers(char* buf, int len)
1382
0
{
1383
0
    const CipherSuiteInfo* ciphers = GetCipherNames();
1384
0
    int ciphersSz = GetCipherNamesSize();
1385
0
    int i;
1386
1387
0
    if (buf == NULL || len <= 0)
1388
0
        return BAD_FUNC_ARG;
1389
1390
    /* Add each member to the buffer delimited by a : */
1391
0
    for (i = 0; i < ciphersSz; i++) {
1392
0
        int cipherNameSz = (int)XSTRLEN(ciphers[i].name);
1393
0
        if (cipherNameSz + 1 < len) {
1394
0
            XSTRNCPY(buf, ciphers[i].name, (size_t)len);
1395
0
            buf += cipherNameSz;
1396
1397
0
            if (i < ciphersSz - 1)
1398
0
                *buf++ = ':';
1399
0
            *buf = 0;
1400
1401
0
            len -= cipherNameSz + 1;
1402
0
        }
1403
0
        else
1404
0
            return BUFFER_E;
1405
0
    }
1406
0
    return WOLFSSL_SUCCESS;
1407
0
}
1408
1409
1410
#ifndef NO_ERROR_STRINGS
1411
/* places a list of all supported cipher suites in TLS_* format into "buf"
1412
 * return WOLFSSL_SUCCESS on success */
1413
int wolfSSL_get_ciphers_iana(char* buf, int len)
1414
0
{
1415
0
    const CipherSuiteInfo* ciphers = GetCipherNames();
1416
0
    int ciphersSz = GetCipherNamesSize();
1417
0
    int i;
1418
0
    int cipherNameSz;
1419
1420
0
    if (buf == NULL || len <= 0)
1421
0
        return BAD_FUNC_ARG;
1422
1423
    /* Add each member to the buffer delimited by a : */
1424
0
    for (i = 0; i < ciphersSz; i++) {
1425
0
#ifndef NO_CIPHER_SUITE_ALIASES
1426
0
        if (ciphers[i].flags & WOLFSSL_CIPHER_SUITE_FLAG_NAMEALIAS)
1427
0
            continue;
1428
0
#endif
1429
0
        cipherNameSz = (int)XSTRLEN(ciphers[i].name_iana);
1430
0
        if (cipherNameSz + 1 < len) {
1431
0
            XSTRNCPY(buf, ciphers[i].name_iana, (size_t)len);
1432
0
            buf += cipherNameSz;
1433
1434
0
            if (i < ciphersSz - 1)
1435
0
                *buf++ = ':';
1436
0
            *buf = 0;
1437
1438
0
            len -= cipherNameSz + 1;
1439
0
        }
1440
0
        else
1441
0
            return BUFFER_E;
1442
0
    }
1443
0
    return WOLFSSL_SUCCESS;
1444
0
}
1445
#endif /* NO_ERROR_STRINGS */
1446
1447
1448
const char* wolfSSL_get_shared_ciphers(WOLFSSL* ssl, char* buf, int len)
1449
0
{
1450
0
    const char* cipher;
1451
1452
0
    if (ssl == NULL || buf == NULL || len <= 0)
1453
0
        return NULL;
1454
1455
0
    cipher = wolfSSL_get_cipher_name_iana(ssl);
1456
0
    if (cipher == NULL)
1457
0
        return NULL;
1458
0
    len = (int)min((word32)len, (word32)(XSTRLEN(cipher) + 1));
1459
0
    XMEMCPY(buf, cipher, (size_t)len);
1460
0
    return buf;
1461
0
}
1462
1463
int wolfSSL_get_fd(const WOLFSSL* ssl)
1464
0
{
1465
0
    int fd = -1;
1466
0
    WOLFSSL_ENTER("wolfSSL_get_fd");
1467
0
    if (ssl) {
1468
0
        fd = ssl->rfd;
1469
0
    }
1470
0
    WOLFSSL_LEAVE("wolfSSL_get_fd", fd);
1471
0
    return fd;
1472
0
}
1473
1474
int wolfSSL_get_wfd(const WOLFSSL* ssl)
1475
0
{
1476
0
    int fd = -1;
1477
0
    WOLFSSL_ENTER("wolfSSL_get_fd");
1478
0
    if (ssl) {
1479
0
        fd = ssl->wfd;
1480
0
    }
1481
0
    WOLFSSL_LEAVE("wolfSSL_get_fd", fd);
1482
0
    return fd;
1483
0
}
1484
1485
1486
#ifdef WOLFSSL_WOLFSENTRY_HOOKS
1487
1488
int wolfSSL_CTX_set_AcceptFilter(
1489
    WOLFSSL_CTX *ctx,
1490
    NetworkFilterCallback_t AcceptFilter,
1491
    void *AcceptFilter_arg)
1492
{
1493
    if (ctx == NULL)
1494
        return BAD_FUNC_ARG;
1495
    ctx->AcceptFilter = AcceptFilter;
1496
    ctx->AcceptFilter_arg = AcceptFilter_arg;
1497
    return 0;
1498
}
1499
1500
int wolfSSL_set_AcceptFilter(
1501
    WOLFSSL *ssl,
1502
    NetworkFilterCallback_t AcceptFilter,
1503
    void *AcceptFilter_arg)
1504
{
1505
    if (ssl == NULL)
1506
        return BAD_FUNC_ARG;
1507
    ssl->AcceptFilter = AcceptFilter;
1508
    ssl->AcceptFilter_arg = AcceptFilter_arg;
1509
    return 0;
1510
}
1511
1512
int wolfSSL_CTX_set_ConnectFilter(
1513
    WOLFSSL_CTX *ctx,
1514
    NetworkFilterCallback_t ConnectFilter,
1515
    void *ConnectFilter_arg)
1516
{
1517
    if (ctx == NULL)
1518
        return BAD_FUNC_ARG;
1519
    ctx->ConnectFilter = ConnectFilter;
1520
    ctx->ConnectFilter_arg = ConnectFilter_arg;
1521
    return 0;
1522
}
1523
1524
int wolfSSL_set_ConnectFilter(
1525
    WOLFSSL *ssl,
1526
    NetworkFilterCallback_t ConnectFilter,
1527
    void *ConnectFilter_arg)
1528
{
1529
    if (ssl == NULL)
1530
        return BAD_FUNC_ARG;
1531
    ssl->ConnectFilter = ConnectFilter;
1532
    ssl->ConnectFilter_arg = ConnectFilter_arg;
1533
    return 0;
1534
}
1535
1536
#endif /* WOLFSSL_WOLFSENTRY_HOOKS */
1537
1538
1539
1540
WOLFSSL_ABI
1541
WC_RNG* wolfSSL_GetRNG(WOLFSSL* ssl)
1542
0
{
1543
0
    if (ssl) {
1544
0
        return ssl->rng;
1545
0
    }
1546
1547
0
    return NULL;
1548
0
}
1549
1550
1551
#ifndef WOLFSSL_LEANPSK
1552
/* object size based on build */
1553
int wolfSSL_GetObjectSize(void)
1554
0
{
1555
#ifdef SHOW_SIZES
1556
    printf("sizeof suites           = %lu\n", (unsigned long)sizeof(Suites));
1557
    printf("sizeof ciphers(2)       = %lu\n", (unsigned long)sizeof(Ciphers));
1558
#ifndef NO_RC4
1559
    printf("\tsizeof arc4         = %lu\n", (unsigned long)sizeof(Arc4));
1560
#endif
1561
    printf("\tsizeof aes          = %lu\n", (unsigned long)sizeof(Aes));
1562
#ifndef NO_DES3
1563
    printf("\tsizeof des3         = %lu\n", (unsigned long)sizeof(Des3));
1564
#endif
1565
#ifdef HAVE_CHACHA
1566
    printf("\tsizeof chacha       = %lu\n", (unsigned long)sizeof(ChaCha));
1567
#endif
1568
#ifdef WOLFSSL_SM4
1569
    printf("\tsizeof sm4          = %lu\n", (unsigned long)sizeof(Sm4));
1570
#endif
1571
    printf("sizeof cipher specs     = %lu\n", (unsigned long)
1572
        sizeof(CipherSpecs));
1573
    printf("sizeof keys             = %lu\n", (unsigned long)sizeof(Keys));
1574
    printf("sizeof Hashes(2)        = %lu\n", (unsigned long)sizeof(Hashes));
1575
#ifndef NO_MD5
1576
    printf("\tsizeof MD5          = %lu\n", (unsigned long)sizeof(wc_Md5));
1577
#endif
1578
#ifndef NO_SHA
1579
    printf("\tsizeof SHA          = %lu\n", (unsigned long)sizeof(wc_Sha));
1580
#endif
1581
#ifdef WOLFSSL_SHA224
1582
    printf("\tsizeof SHA224       = %lu\n", (unsigned long)sizeof(wc_Sha224));
1583
#endif
1584
#ifndef NO_SHA256
1585
    printf("\tsizeof SHA256       = %lu\n", (unsigned long)sizeof(wc_Sha256));
1586
#endif
1587
#ifdef WOLFSSL_SHA384
1588
    printf("\tsizeof SHA384       = %lu\n", (unsigned long)sizeof(wc_Sha384));
1589
#endif
1590
#ifdef WOLFSSL_SHA384
1591
    printf("\tsizeof SHA512       = %lu\n", (unsigned long)sizeof(wc_Sha512));
1592
#endif
1593
#ifdef WOLFSSL_SM3
1594
    printf("\tsizeof sm3          = %lu\n", (unsigned long)sizeof(Sm3));
1595
#endif
1596
    printf("sizeof Buffers          = %lu\n", (unsigned long)sizeof(Buffers));
1597
    printf("sizeof Options          = %lu\n", (unsigned long)sizeof(Options));
1598
    printf("sizeof Arrays           = %lu\n", (unsigned long)sizeof(Arrays));
1599
#ifndef NO_RSA
1600
    printf("sizeof RsaKey           = %lu\n", (unsigned long)sizeof(RsaKey));
1601
#endif
1602
#ifdef HAVE_ECC
1603
    printf("sizeof ecc_key          = %lu\n", (unsigned long)sizeof(ecc_key));
1604
#endif
1605
    printf("sizeof WOLFSSL_CIPHER    = %lu\n", (unsigned long)
1606
        sizeof(WOLFSSL_CIPHER));
1607
    printf("sizeof WOLFSSL_SESSION   = %lu\n", (unsigned long)
1608
        sizeof(WOLFSSL_SESSION));
1609
    printf("sizeof WOLFSSL           = %lu\n", (unsigned long)sizeof(WOLFSSL));
1610
    printf("sizeof WOLFSSL_CTX       = %lu\n", (unsigned long)
1611
        sizeof(WOLFSSL_CTX));
1612
#endif
1613
1614
0
    return sizeof(WOLFSSL);
1615
0
}
1616
1617
int wolfSSL_CTX_GetObjectSize(void)
1618
0
{
1619
0
    return sizeof(WOLFSSL_CTX);
1620
0
}
1621
1622
int wolfSSL_METHOD_GetObjectSize(void)
1623
0
{
1624
0
    return sizeof(WOLFSSL_METHOD);
1625
0
}
1626
#endif
1627
1628
1629
#ifdef WOLFSSL_STATIC_MEMORY
1630
1631
int wolfSSL_CTX_load_static_memory(WOLFSSL_CTX** ctx,
1632
    wolfSSL_method_func method, unsigned char* buf, unsigned int sz, int flag,
1633
    int maxSz)
1634
{
1635
    WOLFSSL_HEAP_HINT* hint = NULL;
1636
1637
    if (ctx == NULL || buf == NULL) {
1638
        return BAD_FUNC_ARG;
1639
    }
1640
1641
    if (*ctx == NULL && method == NULL) {
1642
        return BAD_FUNC_ARG;
1643
    }
1644
1645
    /* If there is a heap already, capture it in hint. */
1646
    if (*ctx && (*ctx)->heap != NULL) {
1647
        hint = (*ctx)->heap;
1648
    }
1649
1650
    if (wc_LoadStaticMemory(&hint, buf, sz, flag, maxSz)) {
1651
        WOLFSSL_MSG("Error loading static memory");
1652
        return WOLFSSL_FAILURE;
1653
    }
1654
1655
    if (*ctx) {
1656
        if ((*ctx)->heap == NULL) {
1657
            (*ctx)->heap = (void*)hint;
1658
        }
1659
    }
1660
    else {
1661
        /* create ctx if needed */
1662
        *ctx = wolfSSL_CTX_new_ex(method(hint), hint);
1663
        if (*ctx == NULL) {
1664
            WOLFSSL_MSG("Error creating ctx");
1665
            return WOLFSSL_FAILURE;
1666
        }
1667
    }
1668
1669
    return WOLFSSL_SUCCESS;
1670
}
1671
1672
1673
int wolfSSL_is_static_memory(WOLFSSL* ssl, WOLFSSL_MEM_CONN_STATS* mem_stats)
1674
{
1675
    if (ssl == NULL) {
1676
        return BAD_FUNC_ARG;
1677
    }
1678
    WOLFSSL_ENTER("wolfSSL_is_static_memory");
1679
1680
#ifndef WOLFSSL_STATIC_MEMORY_LEAN
1681
    /* fill out statistics if wanted and WOLFMEM_TRACK_STATS flag */
1682
    if (mem_stats != NULL && ssl->heap != NULL) {
1683
        WOLFSSL_HEAP_HINT* hint = ((WOLFSSL_HEAP_HINT*)(ssl->heap));
1684
        WOLFSSL_HEAP* heap      = hint->memory;
1685
        if (heap->flag & WOLFMEM_TRACK_STATS && hint->stats != NULL) {
1686
            XMEMCPY(mem_stats, hint->stats, sizeof(WOLFSSL_MEM_CONN_STATS));
1687
        }
1688
    }
1689
#endif
1690
1691
    (void)mem_stats;
1692
    return (ssl->heap) ? 1 : 0;
1693
}
1694
1695
1696
int wolfSSL_CTX_is_static_memory(WOLFSSL_CTX* ctx, WOLFSSL_MEM_STATS* mem_stats)
1697
{
1698
    if (ctx == NULL) {
1699
        return BAD_FUNC_ARG;
1700
    }
1701
    WOLFSSL_ENTER("wolfSSL_CTX_is_static_memory");
1702
1703
#ifndef WOLFSSL_STATIC_MEMORY_LEAN
1704
    /* fill out statistics if wanted */
1705
    if (mem_stats != NULL && ctx->heap != NULL) {
1706
        WOLFSSL_HEAP* heap = ((WOLFSSL_HEAP_HINT*)(ctx->heap))->memory;
1707
        if (wolfSSL_GetMemStats(heap, mem_stats) != 1) {
1708
            return MEMORY_E;
1709
        }
1710
    }
1711
#endif
1712
1713
    (void)mem_stats;
1714
    return (ctx->heap) ? 1 : 0;
1715
}
1716
1717
#endif /* WOLFSSL_STATIC_MEMORY */
1718
1719
#ifndef NO_TLS
1720
/* return max record layer size plaintext input size */
1721
int wolfSSL_GetMaxOutputSize(WOLFSSL* ssl)
1722
0
{
1723
0
    WOLFSSL_ENTER("wolfSSL_GetMaxOutputSize");
1724
1725
0
    if (ssl == NULL)
1726
0
        return BAD_FUNC_ARG;
1727
1728
0
    if (ssl->options.handShakeState != HANDSHAKE_DONE) {
1729
0
        WOLFSSL_MSG("Handshake not complete yet");
1730
0
        return BAD_FUNC_ARG;
1731
0
    }
1732
1733
0
    return min(OUTPUT_RECORD_SIZE, wolfssl_local_GetMaxPlaintextSize(ssl));
1734
0
}
1735
1736
1737
/* return record layer size of plaintext input size */
1738
int wolfSSL_GetOutputSize(WOLFSSL* ssl, int inSz)
1739
0
{
1740
0
    int maxSize;
1741
1742
0
    WOLFSSL_ENTER("wolfSSL_GetOutputSize");
1743
1744
0
    if (inSz < 0)
1745
0
        return BAD_FUNC_ARG;
1746
1747
0
    maxSize = wolfSSL_GetMaxOutputSize(ssl);
1748
0
    if (maxSize < 0)
1749
0
        return maxSize;   /* error */
1750
0
    if (inSz > maxSize)
1751
0
        return INPUT_SIZE_E;
1752
1753
#ifdef HAVE_LIBZ
1754
    /* SendData() sizes the record for deflate's worst case, so report that
1755
     * same bound: an incompressible fragment emits more than its plaintext
1756
     * length. */
1757
    if (ssl->options.usingCompression)
1758
        inSz += MAX_COMP_EXTRA;
1759
#endif
1760
1761
0
    return wolfssl_local_GetRecordSize(ssl, inSz, 1);
1762
0
}
1763
1764
1765
#endif /* !NO_TLS */
1766
1767
#define WOLFSSL_SSL_API_RW_INCLUDED
1768
#include "src/ssl_api_rw.c"
1769
1770
#define WOLFSSL_SSL_API_DTLS_INCLUDED
1771
#include "src/ssl_api_dtls.c"
1772
1773
/* helpers to set the device id, WOLFSSL_SUCCESS on ok */
1774
WOLFSSL_ABI
1775
int wolfSSL_SetDevId(WOLFSSL* ssl, int devId)
1776
0
{
1777
0
    if (ssl == NULL)
1778
0
        return BAD_FUNC_ARG;
1779
1780
0
    ssl->devId = devId;
1781
1782
0
    return WOLFSSL_SUCCESS;
1783
0
}
1784
1785
WOLFSSL_ABI
1786
int wolfSSL_CTX_SetDevId(WOLFSSL_CTX* ctx, int devId)
1787
0
{
1788
0
    if (ctx == NULL)
1789
0
        return BAD_FUNC_ARG;
1790
1791
0
    ctx->devId = devId;
1792
1793
0
    return WOLFSSL_SUCCESS;
1794
0
}
1795
1796
/* helpers to get device id and heap */
1797
WOLFSSL_ABI
1798
int wolfSSL_CTX_GetDevId(WOLFSSL_CTX* ctx, WOLFSSL* ssl)
1799
0
{
1800
0
    int devId = INVALID_DEVID;
1801
0
    if (ssl != NULL)
1802
0
        devId = ssl->devId;
1803
0
    if (ctx != NULL && devId == INVALID_DEVID)
1804
0
        devId = ctx->devId;
1805
0
    return devId;
1806
0
}
1807
void* wolfSSL_CTX_GetHeap(WOLFSSL_CTX* ctx, WOLFSSL* ssl)
1808
0
{
1809
0
    void* heap = NULL;
1810
0
    if (ctx != NULL)
1811
0
        heap = ctx->heap;
1812
0
    else if (ssl != NULL)
1813
0
        heap = ssl->heap;
1814
0
    return heap;
1815
0
}
1816
1817
1818
1819
/* get current error state value */
1820
int wolfSSL_state(WOLFSSL* ssl)
1821
0
{
1822
0
    if (ssl == NULL) {
1823
0
        return BAD_FUNC_ARG;
1824
0
    }
1825
1826
0
    return ssl->error;
1827
0
}
1828
1829
1830
#ifdef OPENSSL_EXTRA
1831
/* Whether err is from a record that failed authentication or decryption.
1832
 * OpenSSL reports these as SSL_ERROR_SSL, with the detail on the error queue.
1833
 */
1834
static int IsRecordCorruptError(int err)
1835
{
1836
    switch (err) {
1837
        case WC_NO_ERR_TRACE(VERIFY_MAC_ERROR):
1838
        case WC_NO_ERR_TRACE(DECRYPT_ERROR):
1839
        case WC_NO_ERR_TRACE(SANITY_CIPHER_E):
1840
        case WC_NO_ERR_TRACE(AES_GCM_AUTH_E):
1841
        case WC_NO_ERR_TRACE(AES_CCM_AUTH_E):
1842
        case WC_NO_ERR_TRACE(MAC_CMP_FAILED_E):
1843
        case WC_NO_ERR_TRACE(SM4_GCM_AUTH_E):
1844
        case WC_NO_ERR_TRACE(SM4_CCM_AUTH_E):
1845
            return 1;
1846
        default:
1847
            return 0;
1848
    }
1849
}
1850
#endif
1851
1852
WOLFSSL_ABI
1853
int wolfSSL_get_error(WOLFSSL* ssl, int ret)
1854
0
{
1855
0
    WOLFSSL_ENTER("wolfSSL_get_error");
1856
1857
0
    if (ret > 0)
1858
0
        return WOLFSSL_ERROR_NONE;
1859
0
    if (ssl == NULL)
1860
0
        return BAD_FUNC_ARG;
1861
1862
0
    WOLFSSL_LEAVE("wolfSSL_get_error", ssl->error);
1863
1864
    /* make sure converted types are handled in SetErrorString() too */
1865
0
    if (ssl->error == WC_NO_ERR_TRACE(WANT_READ))
1866
0
        return WOLFSSL_ERROR_WANT_READ;         /* convert to OpenSSL type */
1867
0
    else if (ssl->error == WC_NO_ERR_TRACE(WANT_WRITE))
1868
0
        return WOLFSSL_ERROR_WANT_WRITE;        /* convert to OpenSSL type */
1869
0
    else if (ssl->error == WC_NO_ERR_TRACE(ZERO_RETURN) ||
1870
0
             ssl->options.shutdownDone)
1871
0
        return WOLFSSL_ERROR_ZERO_RETURN;       /* convert to OpenSSL type */
1872
#ifdef OPENSSL_EXTRA
1873
    else if (ssl->error == WC_NO_ERR_TRACE(MATCH_SUITE_ERROR))
1874
        return WOLFSSL_ERROR_SYSCALL;           /* convert to OpenSSL type */
1875
    else if (ssl->error == WC_NO_ERR_TRACE(SOCKET_PEER_CLOSED_E))
1876
        return WOLFSSL_ERROR_SYSCALL;           /* convert to OpenSSL type */
1877
    /* ssl->error keeps the detail. DTLS drops a bad record and goes on, so it
1878
     * keeps reporting the detail. */
1879
    else if (!ssl->options.dtls && IsRecordCorruptError(ssl->error))
1880
        return WOLFSSL_ERROR_SSL;               /* convert to OpenSSL type */
1881
#endif
1882
#ifdef WOLFSSL_ASYNC_CRYPT
1883
    else if (ssl->error == WC_NO_ERR_TRACE(MP_WOULDBLOCK))
1884
        return WC_PENDING_E;                    /* map non-blocking crypto */
1885
#endif
1886
0
    return ssl->error;
1887
0
}
1888
1889
1890
/* retrieve alert history, WOLFSSL_SUCCESS on ok */
1891
int wolfSSL_get_alert_history(WOLFSSL* ssl, WOLFSSL_ALERT_HISTORY *h)
1892
0
{
1893
0
    if (ssl && h) {
1894
0
        *h = ssl->alert_history;
1895
0
    }
1896
0
    return WOLFSSL_SUCCESS;
1897
0
}
1898
1899
1900
#define WOLFSSL_SSL_ERR_INCLUDED
1901
#include "src/ssl_err.c"
1902
1903
1904
/* don't free temporary arrays at end of handshake */
1905
void wolfSSL_KeepArrays(WOLFSSL* ssl)
1906
0
{
1907
0
    if (ssl)
1908
0
        ssl->options.saveArrays = 1;
1909
0
}
1910
1911
1912
/* user doesn't need temporary arrays anymore, Free */
1913
void wolfSSL_FreeArrays(WOLFSSL* ssl)
1914
0
{
1915
0
    if (ssl && ssl->options.handShakeState == HANDSHAKE_DONE) {
1916
0
        ssl->options.saveArrays = 0;
1917
0
        FreeArrays(ssl, 1);
1918
0
    }
1919
0
}
1920
1921
/* Set option to indicate that the resources are not to be freed after
1922
 * handshake.
1923
 *
1924
 * ssl  The SSL/TLS object.
1925
 * returns BAD_FUNC_ARG when ssl is NULL and 0 on success.
1926
 */
1927
int wolfSSL_KeepHandshakeResources(WOLFSSL* ssl)
1928
0
{
1929
0
    if (ssl == NULL)
1930
0
        return BAD_FUNC_ARG;
1931
1932
0
    ssl->options.keepResources = 1;
1933
1934
0
    return 0;
1935
0
}
1936
1937
/* Free the handshake resources after handshake.
1938
 *
1939
 * ssl  The SSL/TLS object.
1940
 * returns BAD_FUNC_ARG when ssl is NULL and 0 on success.
1941
 */
1942
int wolfSSL_FreeHandshakeResources(WOLFSSL* ssl)
1943
0
{
1944
0
    if (ssl == NULL)
1945
0
        return BAD_FUNC_ARG;
1946
1947
0
    FreeHandshakeResources(ssl);
1948
1949
0
    return 0;
1950
0
}
1951
1952
/* Use the client's order of preference when matching cipher suites.
1953
 *
1954
 * ssl  The SSL/TLS context object.
1955
 * returns BAD_FUNC_ARG when ssl is NULL and 0 on success.
1956
 */
1957
int wolfSSL_CTX_UseClientSuites(WOLFSSL_CTX* ctx)
1958
0
{
1959
0
    if (ctx == NULL)
1960
0
        return BAD_FUNC_ARG;
1961
1962
0
    ctx->useClientOrder = 1;
1963
1964
0
    return 0;
1965
0
}
1966
1967
/* Use the client's order of preference when matching cipher suites.
1968
 *
1969
 * ssl  The SSL/TLS object.
1970
 * returns BAD_FUNC_ARG when ssl is NULL and 0 on success.
1971
 */
1972
int wolfSSL_UseClientSuites(WOLFSSL* ssl)
1973
0
{
1974
0
    if (ssl == NULL)
1975
0
        return BAD_FUNC_ARG;
1976
1977
0
    ssl->options.useClientOrder = 1;
1978
1979
0
    return 0;
1980
0
}
1981
1982
1983
const byte* wolfSSL_GetMacSecret(WOLFSSL* ssl, int verify)
1984
0
{
1985
0
#ifndef WOLFSSL_AEAD_ONLY
1986
0
    if (ssl == NULL)
1987
0
        return NULL;
1988
1989
0
    if ( (ssl->options.side == WOLFSSL_CLIENT_END && !verify) ||
1990
0
         (ssl->options.side == WOLFSSL_SERVER_END &&  verify) )
1991
0
        return ssl->keys.client_write_MAC_secret;
1992
0
    else
1993
0
        return ssl->keys.server_write_MAC_secret;
1994
#else
1995
    (void)ssl;
1996
    (void)verify;
1997
1998
    return NULL;
1999
#endif
2000
0
}
2001
2002
int wolfSSL_GetSide(WOLFSSL* ssl)
2003
0
{
2004
0
    if (ssl)
2005
0
        return ssl->options.side;
2006
2007
0
    return BAD_FUNC_ARG;
2008
0
}
2009
2010
#ifdef ATOMIC_USER
2011
2012
void  wolfSSL_CTX_SetMacEncryptCb(WOLFSSL_CTX* ctx, CallbackMacEncrypt cb)
2013
{
2014
    if (ctx)
2015
        ctx->MacEncryptCb = cb;
2016
}
2017
2018
2019
void  wolfSSL_SetMacEncryptCtx(WOLFSSL* ssl, void *ctx)
2020
{
2021
    if (ssl)
2022
        ssl->MacEncryptCtx = ctx;
2023
}
2024
2025
2026
void* wolfSSL_GetMacEncryptCtx(WOLFSSL* ssl)
2027
{
2028
    if (ssl)
2029
        return ssl->MacEncryptCtx;
2030
2031
    return NULL;
2032
}
2033
2034
2035
void  wolfSSL_CTX_SetDecryptVerifyCb(WOLFSSL_CTX* ctx, CallbackDecryptVerify cb)
2036
{
2037
    if (ctx)
2038
        ctx->DecryptVerifyCb = cb;
2039
}
2040
2041
2042
void  wolfSSL_SetDecryptVerifyCtx(WOLFSSL* ssl, void *ctx)
2043
{
2044
    if (ssl)
2045
        ssl->DecryptVerifyCtx = ctx;
2046
}
2047
2048
2049
void* wolfSSL_GetDecryptVerifyCtx(WOLFSSL* ssl)
2050
{
2051
    if (ssl)
2052
        return ssl->DecryptVerifyCtx;
2053
2054
    return NULL;
2055
}
2056
2057
#if defined(HAVE_ENCRYPT_THEN_MAC) && !defined(WOLFSSL_AEAD_ONLY)
2058
/**
2059
 * Set the callback, against the context, that encrypts then MACs.
2060
 *
2061
 * ctx  SSL/TLS context.
2062
 * cb   Callback function to use with Encrypt-Then-MAC.
2063
 */
2064
void  wolfSSL_CTX_SetEncryptMacCb(WOLFSSL_CTX* ctx, CallbackEncryptMac cb)
2065
{
2066
    if (ctx)
2067
        ctx->EncryptMacCb = cb;
2068
}
2069
2070
/**
2071
 * Set the context to use with callback that encrypts then MACs.
2072
 *
2073
 * ssl  SSL/TLS object.
2074
 * ctx  Callback function's context.
2075
 */
2076
void  wolfSSL_SetEncryptMacCtx(WOLFSSL* ssl, void *ctx)
2077
{
2078
    if (ssl)
2079
        ssl->EncryptMacCtx = ctx;
2080
}
2081
2082
/**
2083
 * Get the context being used with callback that encrypts then MACs.
2084
 *
2085
 * ssl  SSL/TLS object.
2086
 * returns callback function's context or NULL if SSL/TLS object is NULL.
2087
 */
2088
void* wolfSSL_GetEncryptMacCtx(WOLFSSL* ssl)
2089
{
2090
    if (ssl)
2091
        return ssl->EncryptMacCtx;
2092
2093
    return NULL;
2094
}
2095
2096
2097
/**
2098
 * Set the callback, against the context, that MAC verifies then decrypts.
2099
 *
2100
 * ctx  SSL/TLS context.
2101
 * cb   Callback function to use with Encrypt-Then-MAC.
2102
 */
2103
void  wolfSSL_CTX_SetVerifyDecryptCb(WOLFSSL_CTX* ctx, CallbackVerifyDecrypt cb)
2104
{
2105
    if (ctx)
2106
        ctx->VerifyDecryptCb = cb;
2107
}
2108
2109
/**
2110
 * Set the context to use with callback that MAC verifies then decrypts.
2111
 *
2112
 * ssl  SSL/TLS object.
2113
 * ctx  Callback function's context.
2114
 */
2115
void  wolfSSL_SetVerifyDecryptCtx(WOLFSSL* ssl, void *ctx)
2116
{
2117
    if (ssl)
2118
        ssl->VerifyDecryptCtx = ctx;
2119
}
2120
2121
/**
2122
 * Get the context being used with callback that MAC verifies then decrypts.
2123
 *
2124
 * ssl  SSL/TLS object.
2125
 * returns callback function's context or NULL if SSL/TLS object is NULL.
2126
 */
2127
void* wolfSSL_GetVerifyDecryptCtx(WOLFSSL* ssl)
2128
{
2129
    if (ssl)
2130
        return ssl->VerifyDecryptCtx;
2131
2132
    return NULL;
2133
}
2134
#endif /* HAVE_ENCRYPT_THEN_MAC !WOLFSSL_AEAD_ONLY */
2135
2136
2137
2138
const byte* wolfSSL_GetClientWriteKey(WOLFSSL* ssl)
2139
{
2140
    if (ssl)
2141
        return ssl->keys.client_write_key;
2142
2143
    return NULL;
2144
}
2145
2146
2147
const byte* wolfSSL_GetClientWriteIV(WOLFSSL* ssl)
2148
{
2149
    if (ssl)
2150
        return ssl->keys.client_write_IV;
2151
2152
    return NULL;
2153
}
2154
2155
2156
const byte* wolfSSL_GetServerWriteKey(WOLFSSL* ssl)
2157
{
2158
    if (ssl)
2159
        return ssl->keys.server_write_key;
2160
2161
    return NULL;
2162
}
2163
2164
2165
const byte* wolfSSL_GetServerWriteIV(WOLFSSL* ssl)
2166
{
2167
    if (ssl)
2168
        return ssl->keys.server_write_IV;
2169
2170
    return NULL;
2171
}
2172
2173
int wolfSSL_GetKeySize(WOLFSSL* ssl)
2174
{
2175
    if (ssl)
2176
        return ssl->specs.key_size;
2177
2178
    return BAD_FUNC_ARG;
2179
}
2180
2181
2182
int wolfSSL_GetIVSize(WOLFSSL* ssl)
2183
{
2184
    if (ssl)
2185
        return ssl->specs.iv_size;
2186
2187
    return BAD_FUNC_ARG;
2188
}
2189
2190
2191
int wolfSSL_GetBulkCipher(WOLFSSL* ssl)
2192
{
2193
    if (ssl)
2194
        return ssl->specs.bulk_cipher_algorithm;
2195
2196
    return BAD_FUNC_ARG;
2197
}
2198
2199
2200
int wolfSSL_GetCipherType(WOLFSSL* ssl)
2201
{
2202
    if (ssl == NULL)
2203
        return BAD_FUNC_ARG;
2204
2205
#ifndef WOLFSSL_AEAD_ONLY
2206
    if (ssl->specs.cipher_type == block)
2207
        return WOLFSSL_BLOCK_TYPE;
2208
    if (ssl->specs.cipher_type == stream)
2209
        return WOLFSSL_STREAM_TYPE;
2210
#endif
2211
    if (ssl->specs.cipher_type == aead)
2212
        return WOLFSSL_AEAD_TYPE;
2213
2214
    return WOLFSSL_FATAL_ERROR;
2215
}
2216
2217
2218
int wolfSSL_GetCipherBlockSize(WOLFSSL* ssl)
2219
{
2220
    if (ssl == NULL)
2221
        return BAD_FUNC_ARG;
2222
2223
    return ssl->specs.block_size;
2224
}
2225
2226
2227
int wolfSSL_GetAeadMacSize(WOLFSSL* ssl)
2228
{
2229
    if (ssl == NULL)
2230
        return BAD_FUNC_ARG;
2231
2232
    return ssl->specs.aead_mac_size;
2233
}
2234
2235
2236
int wolfSSL_IsTLSv1_1(WOLFSSL* ssl)
2237
{
2238
    if (ssl == NULL)
2239
        return BAD_FUNC_ARG;
2240
2241
    if (ssl->options.tls1_1)
2242
        return 1;
2243
2244
    return 0;
2245
}
2246
2247
2248
2249
int wolfSSL_GetHmacSize(WOLFSSL* ssl)
2250
{
2251
    /* AEAD ciphers don't have HMAC keys */
2252
    if (ssl)
2253
        return (ssl->specs.cipher_type != aead) ? ssl->specs.hash_size : 0;
2254
2255
    return BAD_FUNC_ARG;
2256
}
2257
2258
#ifdef WORD64_AVAILABLE
2259
int wolfSSL_GetPeerSequenceNumber(WOLFSSL* ssl, word64 *seq)
2260
{
2261
    if ((ssl == NULL) || (seq == NULL))
2262
        return BAD_FUNC_ARG;
2263
2264
    *seq = ((word64)ssl->keys.peer_sequence_number_hi << 32) |
2265
                    ssl->keys.peer_sequence_number_lo;
2266
    return !(*seq);
2267
}
2268
2269
int wolfSSL_GetSequenceNumber(WOLFSSL* ssl, word64 *seq)
2270
{
2271
    if ((ssl == NULL) || (seq == NULL))
2272
        return BAD_FUNC_ARG;
2273
2274
    *seq = ((word64)ssl->keys.sequence_number_hi << 32) |
2275
                    ssl->keys.sequence_number_lo;
2276
    return !(*seq);
2277
}
2278
#endif
2279
2280
#endif /* ATOMIC_USER */
2281
2282
#if !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM) \
2283
    && defined(XFPRINTF)
2284
2285
2286
#if defined(OPENSSL_EXTRA) || defined(DEBUG_WOLFSSL_VERBOSE)
2287
#endif
2288
#endif /* !NO_FILESYSTEM && !NO_STDIO_FILESYSTEM && XFPRINTF */
2289
2290
#ifndef WOLFSSL_LEANPSK
2291
/* turn on handshake group messages for context */
2292
int wolfSSL_CTX_set_group_messages(WOLFSSL_CTX* ctx)
2293
0
{
2294
0
    if (ctx == NULL)
2295
0
       return BAD_FUNC_ARG;
2296
2297
0
    ctx->groupMessages = 1;
2298
2299
0
    return WOLFSSL_SUCCESS;
2300
0
}
2301
2302
int wolfSSL_CTX_clear_group_messages(WOLFSSL_CTX* ctx)
2303
0
{
2304
0
    if (ctx == NULL)
2305
0
       return BAD_FUNC_ARG;
2306
2307
0
    ctx->groupMessages = 0;
2308
2309
0
    return WOLFSSL_SUCCESS;
2310
0
}
2311
#endif
2312
2313
2314
#ifndef WOLFSSL_LEANPSK
2315
/* turn on handshake group messages for ssl object */
2316
int wolfSSL_set_group_messages(WOLFSSL* ssl)
2317
0
{
2318
0
    if (ssl == NULL)
2319
0
       return BAD_FUNC_ARG;
2320
2321
0
    ssl->options.groupMessages = 1;
2322
2323
0
    return WOLFSSL_SUCCESS;
2324
0
}
2325
2326
int wolfSSL_clear_group_messages(WOLFSSL* ssl)
2327
0
{
2328
0
    if (ssl == NULL)
2329
0
       return BAD_FUNC_ARG;
2330
2331
0
    ssl->options.groupMessages = 0;
2332
2333
0
    return WOLFSSL_SUCCESS;
2334
0
}
2335
2336
/* make minVersion the internal equivalent SSL version */
2337
static int SetMinVersionHelper(byte* minVersion, int version)
2338
0
{
2339
0
    (void)minVersion;
2340
2341
0
    switch (version) {
2342
#if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
2343
        case WOLFSSL_SSLV3:
2344
            *minVersion = SSLv3_MINOR;
2345
            break;
2346
#endif
2347
2348
0
#ifndef NO_TLS
2349
    #ifndef NO_OLD_TLS
2350
        #ifdef WOLFSSL_ALLOW_TLSV10
2351
        case WOLFSSL_TLSV1:
2352
            *minVersion = TLSv1_MINOR;
2353
            break;
2354
        #endif
2355
2356
        case WOLFSSL_TLSV1_1:
2357
            *minVersion = TLSv1_1_MINOR;
2358
            break;
2359
    #endif
2360
0
    #ifndef WOLFSSL_NO_TLS12
2361
0
        case WOLFSSL_TLSV1_2:
2362
0
            *minVersion = TLSv1_2_MINOR;
2363
0
            break;
2364
0
    #endif
2365
0
#endif
2366
0
    #ifdef WOLFSSL_TLS13
2367
0
        case WOLFSSL_TLSV1_3:
2368
0
            *minVersion = TLSv1_3_MINOR;
2369
0
            break;
2370
0
    #endif
2371
2372
#ifdef WOLFSSL_DTLS
2373
        case WOLFSSL_DTLSV1:
2374
            *minVersion = DTLS_MINOR;
2375
            break;
2376
        case WOLFSSL_DTLSV1_2:
2377
            *minVersion = DTLSv1_2_MINOR;
2378
            break;
2379
#ifdef WOLFSSL_DTLS13
2380
        case WOLFSSL_DTLSV1_3:
2381
            *minVersion = DTLSv1_3_MINOR;
2382
            break;
2383
#endif /* WOLFSSL_DTLS13 */
2384
#endif /* WOLFSSL_DTLS */
2385
2386
0
        default:
2387
0
            WOLFSSL_MSG("Bad function argument");
2388
0
            return BAD_FUNC_ARG;
2389
0
    }
2390
2391
0
    return WOLFSSL_SUCCESS;
2392
0
}
2393
2394
2395
/* Set minimum downgrade version allowed, WOLFSSL_SUCCESS on ok */
2396
WOLFSSL_ABI
2397
int wolfSSL_CTX_SetMinVersion(WOLFSSL_CTX* ctx, int version)
2398
0
{
2399
0
    int ret;
2400
2401
0
    WOLFSSL_ENTER("wolfSSL_CTX_SetMinVersion");
2402
2403
0
    if (ctx == NULL) {
2404
0
        WOLFSSL_MSG("Bad function argument");
2405
0
        return BAD_FUNC_ARG;
2406
0
    }
2407
2408
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
2409
    if (crypto_policy.enabled) {
2410
        return CRYPTO_POLICY_FORBIDDEN;
2411
    }
2412
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
2413
2414
0
    ret = SetMinVersionHelper(&ctx->minDowngrade, version);
2415
0
    if (ret == WOLFSSL_SUCCESS)
2416
0
        ctx->minVersionSet = 1;
2417
2418
0
    return ret;
2419
0
}
2420
2421
2422
/* Work out whether the version set by wolfSSL_SetVersion() is one pinned
2423
 * version or the top of a range. */
2424
static void RestoreDowngrade(WOLFSSL* ssl)
2425
0
{
2426
0
    if (ssl->options.versionSet && ssl->ctx != NULL) {
2427
0
        if (ssl->options.failNoPSK || !ssl->options.minVersionSet) {
2428
            /* A PSK requirement is TLS 1.3 only, and with no minimum there is
2429
             * one version, so both keep the version pinned */
2430
0
            ssl->options.downgrade = 0;
2431
0
        }
2432
0
        else {
2433
            /* Set the connection's downgrade option to the context's default */
2434
0
            ssl->options.downgrade = (word16)(ssl->ctx->method->downgrade);
2435
0
        }
2436
0
    }
2437
0
}
2438
2439
/* Set minimum downgrade version allowed, WOLFSSL_SUCCESS on ok */
2440
int wolfSSL_SetMinVersion(WOLFSSL* ssl, int version)
2441
0
{
2442
0
    int ret;
2443
2444
0
    WOLFSSL_ENTER("wolfSSL_SetMinVersion");
2445
2446
0
    if (ssl == NULL) {
2447
0
        WOLFSSL_MSG("Bad function argument");
2448
0
        return BAD_FUNC_ARG;
2449
0
    }
2450
2451
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
2452
    if (crypto_policy.enabled) {
2453
        return CRYPTO_POLICY_FORBIDDEN;
2454
    }
2455
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
2456
2457
0
    ret = SetMinVersionHelper(&ssl->options.minDowngrade, version);
2458
0
    if (ret == WOLFSSL_SUCCESS) {
2459
0
        ssl->options.minVersionSet = 1;
2460
0
        RestoreDowngrade(ssl);
2461
0
    }
2462
2463
0
    return ret;
2464
0
}
2465
2466
2467
/* Function to get version as WOLFSSL_ enum value for wolfSSL_SetVersion */
2468
int wolfSSL_GetVersion(const WOLFSSL* ssl)
2469
0
{
2470
0
    if (ssl == NULL)
2471
0
        return BAD_FUNC_ARG;
2472
2473
0
    if (ssl->version.major == SSLv3_MAJOR) {
2474
0
        switch (ssl->version.minor) {
2475
0
            case SSLv3_MINOR :
2476
0
                return WOLFSSL_SSLV3;
2477
0
            case TLSv1_MINOR :
2478
0
                return WOLFSSL_TLSV1;
2479
0
            case TLSv1_1_MINOR :
2480
0
                return WOLFSSL_TLSV1_1;
2481
0
            case TLSv1_2_MINOR :
2482
0
                return WOLFSSL_TLSV1_2;
2483
0
            case TLSv1_3_MINOR :
2484
0
                return WOLFSSL_TLSV1_3;
2485
0
            default:
2486
0
                break;
2487
0
        }
2488
0
    }
2489
#ifdef WOLFSSL_DTLS
2490
    if (ssl->version.major == DTLS_MAJOR) {
2491
        switch (ssl->version.minor) {
2492
            case DTLS_MINOR :
2493
                return WOLFSSL_DTLSV1;
2494
            case DTLSv1_2_MINOR :
2495
                return WOLFSSL_DTLSV1_2;
2496
            case DTLSv1_3_MINOR :
2497
                return WOLFSSL_DTLSV1_3;
2498
            default:
2499
                break;
2500
        }
2501
    }
2502
#endif /* WOLFSSL_DTLS */
2503
2504
0
    return VERSION_ERROR;
2505
0
}
2506
2507
int wolfSSL_SetVersion(WOLFSSL* ssl, int version)
2508
0
{
2509
0
    word16 haveRSA = 1;
2510
0
    word16 havePSK = 0;
2511
0
    int    keySz   = 0;
2512
2513
0
    WOLFSSL_ENTER("wolfSSL_SetVersion");
2514
2515
0
    if (ssl == NULL) {
2516
0
        WOLFSSL_MSG("Bad function argument");
2517
0
        return BAD_FUNC_ARG;
2518
0
    }
2519
2520
0
    switch (version) {
2521
#if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
2522
        case WOLFSSL_SSLV3:
2523
            ssl->version = MakeSSLv3();
2524
            break;
2525
#endif
2526
2527
0
#ifndef NO_TLS
2528
    #ifndef NO_OLD_TLS
2529
        #ifdef WOLFSSL_ALLOW_TLSV10
2530
        case WOLFSSL_TLSV1:
2531
            ssl->version = MakeTLSv1();
2532
            break;
2533
        #endif
2534
2535
        case WOLFSSL_TLSV1_1:
2536
            ssl->version = MakeTLSv1_1();
2537
            break;
2538
    #endif
2539
0
    #ifndef WOLFSSL_NO_TLS12
2540
0
        case WOLFSSL_TLSV1_2:
2541
0
            ssl->version = MakeTLSv1_2();
2542
0
            break;
2543
0
    #endif
2544
2545
0
    #ifdef WOLFSSL_TLS13
2546
0
        case WOLFSSL_TLSV1_3:
2547
0
            ssl->version = MakeTLSv1_3();
2548
0
            break;
2549
0
    #endif /* WOLFSSL_TLS13 */
2550
0
#endif
2551
2552
0
        default:
2553
0
            WOLFSSL_MSG("Bad function argument");
2554
0
            return BAD_FUNC_ARG;
2555
0
    }
2556
2557
0
    ssl->options.versionSet = 1;
2558
0
    ssl->options.maxVersionMinor = ssl->version.minor;
2559
0
    if (!ssl->options.minVersionSet) {
2560
        /* no minimum asked for, so this version is the whole range */
2561
0
        ssl->options.downgrade = 0;
2562
0
    }
2563
2564
    #ifdef NO_RSA
2565
        haveRSA = 0;
2566
    #endif
2567
    #ifndef NO_PSK
2568
        havePSK = ssl->options.havePSK;
2569
    #endif
2570
0
    #ifndef NO_CERTS
2571
0
        keySz = ssl->buffers.keySz;
2572
0
    #endif
2573
2574
0
    if (AllocateSuites(ssl) != 0)
2575
0
        return WOLFSSL_FAILURE;
2576
0
    InitSuites(ssl->suites, ssl->version, keySz, haveRSA, havePSK,
2577
0
               ssl->options.haveDH, ssl->options.haveECDSAsig,
2578
0
               ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
2579
0
               ssl->options.useAnon, TRUE, TRUE, TRUE, TRUE, ssl->options.side);
2580
0
    return WOLFSSL_SUCCESS;
2581
0
}
2582
#endif /* !leanpsk */
2583
2584
/* If we don't have static mutex initializers, but we do have static atomic
2585
 * initializers, activate WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS to leverage
2586
 * the latter.
2587
 *
2588
 * See further explanation below in wolfSSL_Init().
2589
 */
2590
#ifndef WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS
2591
    #if !defined(WOLFSSL_MUTEX_INITIALIZER) && !defined(SINGLE_THREADED) && \
2592
            defined(WOLFSSL_ATOMIC_OPS) && defined(WOLFSSL_ATOMIC_INITIALIZER)
2593
        #define WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS 1
2594
    #else
2595
        #define WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS 0
2596
    #endif
2597
#elif defined(WOLFSSL_MUTEX_INITIALIZER) || defined(SINGLE_THREADED)
2598
    #undef WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS
2599
    #define WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS 0
2600
#endif
2601
2602
#if WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS
2603
    #ifndef WOLFSSL_ATOMIC_OPS
2604
        #error WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS requires WOLFSSL_ATOMIC_OPS
2605
    #endif
2606
    #ifndef WOLFSSL_ATOMIC_INITIALIZER
2607
        #error WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS requires WOLFSSL_ATOMIC_INITIALIZER
2608
    #endif
2609
    static wolfSSL_Atomic_Int inits_count_mutex_atomic_initing_flag =
2610
        WOLFSSL_ATOMIC_INITIALIZER(0);
2611
#endif /* WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS && !WOLFSSL_MUTEX_INITIALIZER */
2612
2613
#if defined(OPENSSL_EXTRA) && defined(HAVE_ATEXIT)
2614
static void AtExitCleanup(void)
2615
{
2616
    if (initRefCount > 0) {
2617
        initRefCount = 1;
2618
        (void)wolfSSL_Cleanup();
2619
#if WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS
2620
        if (inits_count_mutex_valid == 1) {
2621
            (void)wc_FreeMutex(&inits_count_mutex);
2622
            inits_count_mutex_valid = 0;
2623
            inits_count_mutex_atomic_initing_flag = 0;
2624
        }
2625
#endif
2626
    }
2627
}
2628
#endif
2629
2630
WOLFSSL_ABI
2631
int wolfSSL_Init(void)
2632
0
{
2633
0
    int ret = WOLFSSL_SUCCESS;
2634
#if !defined(NO_SESSION_CACHE) && defined(ENABLE_SESSION_CACHE_ROW_LOCK)
2635
    int i;
2636
#endif
2637
2638
0
    WOLFSSL_ENTER("wolfSSL_Init");
2639
2640
0
#if defined(LIBWOLFSSL_CMAKE_OUTPUT)
2641
0
    WOLFSSL_MSG(LIBWOLFSSL_CMAKE_OUTPUT);
2642
#else
2643
    WOLFSSL_MSG("No extra wolfSSL cmake messages found");
2644
#endif
2645
2646
#ifndef WOLFSSL_MUTEX_INITIALIZER
2647
    if (inits_count_mutex_valid == 0) {
2648
    #if WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS
2649
2650
        /* Without this mitigation, if two threads enter wolfSSL_Init() at the
2651
         * same time, and both see zero inits_count_mutex_valid, then both will
2652
         * run wc_InitMutex(&inits_count_mutex), leading to process corruption
2653
         * or (best case) a resource leak.
2654
         *
2655
         * When WOLFSSL_ATOMIC_INITIALIZER() is available, we can mitigate this
2656
         * by use an atomic counting int as a mutex.
2657
         */
2658
2659
        if (wolfSSL_Atomic_Int_FetchAdd(&inits_count_mutex_atomic_initing_flag,
2660
                                        1) != 0)
2661
        {
2662
            (void)wolfSSL_Atomic_Int_FetchSub(
2663
                &inits_count_mutex_atomic_initing_flag, 1);
2664
            return DEADLOCK_AVERTED_E;
2665
        }
2666
    #endif /* WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS */
2667
        if (wc_InitMutex(&inits_count_mutex) != 0) {
2668
            WOLFSSL_MSG("Bad Init Mutex count");
2669
    #if WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS
2670
            (void)wolfSSL_Atomic_Int_FetchSub(
2671
                &inits_count_mutex_atomic_initing_flag, 1);
2672
    #endif
2673
            return BAD_MUTEX_E;
2674
        }
2675
        else {
2676
            inits_count_mutex_valid = 1;
2677
        }
2678
    }
2679
#endif /* !WOLFSSL_MUTEX_INITIALIZER */
2680
2681
0
    if (wc_LockMutex(&inits_count_mutex) != 0) {
2682
0
        WOLFSSL_MSG("Bad Lock Mutex count");
2683
0
        return BAD_MUTEX_E;
2684
0
    }
2685
2686
#if FIPS_VERSION_GE(5,1)
2687
    if ((ret == WOLFSSL_SUCCESS) && (initRefCount == 0)) {
2688
        ret = wolfCrypt_SetPrivateKeyReadEnable_fips(1, WC_KEYTYPE_ALL);
2689
        if (ret == 0)
2690
            ret = WOLFSSL_SUCCESS;
2691
    }
2692
#endif
2693
2694
0
    if ((ret == WOLFSSL_SUCCESS) && (initRefCount == 0)) {
2695
        /* Initialize crypto for use with TLS connection */
2696
2697
0
        if (wolfCrypt_Init() != 0) {
2698
0
            WOLFSSL_MSG("Bad wolfCrypt Init");
2699
0
            ret = WC_INIT_E;
2700
0
        }
2701
2702
#if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
2703
    !defined(WOLFCRYPT_ONLY)
2704
        /* Calculate the index of OID groups in wolfssl_object_info[]. */
2705
        wolfssl_object_info_slice_init();
2706
#endif
2707
2708
#if defined(HAVE_GLOBAL_RNG) && !defined(WOLFSSL_MUTEX_INITIALIZER)
2709
        if (ret == WOLFSSL_SUCCESS) {
2710
            if (wc_InitMutex(&globalRNGMutex) != 0) {
2711
                WOLFSSL_MSG("Bad Init Mutex rng");
2712
                ret = BAD_MUTEX_E;
2713
            }
2714
            else {
2715
                globalRNGMutex_valid = 1;
2716
            }
2717
        }
2718
#endif
2719
2720
    #ifdef WC_RNG_SEED_CB
2721
        wc_SetSeed_Cb(WC_GENERATE_SEED_DEFAULT);
2722
    #endif
2723
2724
#ifdef OPENSSL_EXTRA
2725
    #ifndef WOLFSSL_NO_OPENSSL_RAND_CB
2726
        if ((ret == WOLFSSL_SUCCESS) && (wolfSSL_RAND_InitMutex() != 0)) {
2727
            ret = BAD_MUTEX_E;
2728
        }
2729
    #endif
2730
        if ((ret == WOLFSSL_SUCCESS) &&
2731
            (wolfSSL_RAND_seed(NULL, 0) != WOLFSSL_SUCCESS)) {
2732
            WOLFSSL_MSG("wolfSSL_RAND_seed failed");
2733
            ret = WC_INIT_E;
2734
        }
2735
#endif
2736
2737
0
#ifndef NO_SESSION_CACHE
2738
    #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
2739
        for (i = 0; i < SESSION_ROWS; ++i) {
2740
            SessionCache[i].lock_valid = 0;
2741
        }
2742
        for (i = 0; (ret == WOLFSSL_SUCCESS) && (i < SESSION_ROWS); ++i) {
2743
            if (wc_InitRwLock(&SessionCache[i].row_lock) != 0) {
2744
                WOLFSSL_MSG("Bad Init Mutex session");
2745
                ret = BAD_MUTEX_E;
2746
            }
2747
            else {
2748
                SessionCache[i].lock_valid = 1;
2749
            }
2750
        }
2751
    #else
2752
0
        if (ret == WOLFSSL_SUCCESS) {
2753
0
            if (wc_InitRwLock(&session_lock) != 0) {
2754
0
                WOLFSSL_MSG("Bad Init Mutex session");
2755
0
                ret = BAD_MUTEX_E;
2756
0
            }
2757
0
            else {
2758
0
                session_lock_valid = 1;
2759
0
            }
2760
0
        }
2761
0
    #endif
2762
0
    #ifndef NO_CLIENT_CACHE
2763
        #ifndef WOLFSSL_MUTEX_INITIALIZER
2764
        if (ret == WOLFSSL_SUCCESS) {
2765
            if (wc_InitMutex(&clisession_mutex) != 0) {
2766
                WOLFSSL_MSG("Bad Init Mutex session");
2767
                ret = BAD_MUTEX_E;
2768
            }
2769
            else {
2770
                clisession_mutex_valid = 1;
2771
            }
2772
        }
2773
        #endif
2774
0
    #endif
2775
0
#endif
2776
#if defined(OPENSSL_EXTRA) && defined(HAVE_ATEXIT)
2777
        /* OpenSSL registers cleanup using atexit */
2778
        if ((ret == WOLFSSL_SUCCESS) && (atexit(AtExitCleanup) != 0)) {
2779
            WOLFSSL_MSG("Bad atexit registration");
2780
            ret = WC_INIT_E;
2781
        }
2782
#endif
2783
0
    }
2784
2785
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
2786
    /* System wide crypto policy disabled by default. */
2787
    XMEMSET(&crypto_policy, 0, sizeof(crypto_policy));
2788
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
2789
2790
0
    if (ret == WOLFSSL_SUCCESS) {
2791
0
        initRefCount = initRefCount + 1;
2792
0
    }
2793
0
    else {
2794
0
        initRefCount = 1; /* Force cleanup */
2795
0
    }
2796
2797
0
    wc_UnLockMutex(&inits_count_mutex);
2798
2799
0
    if (ret != WOLFSSL_SUCCESS) {
2800
0
        (void)wolfSSL_Cleanup(); /* Ignore any error from cleanup */
2801
0
    }
2802
2803
0
    return ret;
2804
0
}
2805
2806
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
2807
/* Helper function for wolfSSL_crypto_policy_enable and
2808
 * wolfSSL_crypto_policy_enable_buffer.
2809
 *
2810
 * Parses the crypto policy string, verifies values,
2811
 * and sets in global crypto policy struct. Not thread
2812
 * safe. String length has already been verified.
2813
 *
2814
 * Returns WOLFSSL_SUCCESS on success.
2815
 * Returns CRYPTO_POLICY_FORBIDDEN if already enabled.
2816
 * Returns < 0 on misc error.
2817
 * */
2818
static int crypto_policy_parse(void)
2819
{
2820
    const char * hdr = WOLFSSL_SECLEVEL_STR;
2821
    int          sec_level = 0;
2822
    size_t       i = 0;
2823
2824
    /* All policies should begin with "@SECLEVEL=<N>" (N={0..5}) followed
2825
     * by bulk cipher list. */
2826
    if (XMEMCMP(crypto_policy.str, hdr, strlen(hdr)) != 0) {
2827
        WOLFSSL_MSG("error: crypto policy: invalid header");
2828
        return WOLFSSL_BAD_FILE;
2829
    }
2830
2831
    {
2832
        /* Extract the security level. */
2833
        char *       policy_mem = crypto_policy.str;
2834
        policy_mem += strlen(hdr);
2835
        sec_level = (int) (*policy_mem - '0');
2836
    }
2837
2838
    if (sec_level < MIN_WOLFSSL_SEC_LEVEL ||
2839
        sec_level > MAX_WOLFSSL_SEC_LEVEL) {
2840
        WOLFSSL_MSG_EX("error: invalid SECLEVEL: %d", sec_level);
2841
        return WOLFSSL_BAD_FILE;
2842
    }
2843
2844
    /* Remove trailing '\r' or '\n'. */
2845
    for (i = 0; i < MAX_WOLFSSL_CRYPTO_POLICY_SIZE; ++i) {
2846
        if (crypto_policy.str[i] == '\0') {
2847
            break;
2848
        }
2849
2850
        if (crypto_policy.str[i] == '\r' || crypto_policy.str[i] == '\n') {
2851
            crypto_policy.str[i] = '\0';
2852
            break;
2853
        }
2854
    }
2855
2856
    #if defined(DEBUG_WOLFSSL_VERBOSE)
2857
    WOLFSSL_MSG_EX("info: SECLEVEL=%d", sec_level);
2858
    WOLFSSL_MSG_EX("info: using crypto-policy file: %s, %ld", policy_file, sz);
2859
    #endif /* DEBUG_WOLFSSL_VERBOSE */
2860
2861
    crypto_policy.secLevel = sec_level;
2862
    crypto_policy.enabled = 1;
2863
2864
    return WOLFSSL_SUCCESS;
2865
}
2866
2867
#ifndef NO_FILESYSTEM
2868
/* Enables wolfSSL system wide crypto-policy, using the given policy
2869
 * file arg. If NULL is passed, then the default system crypto-policy
2870
 * file that was set at configure time will be used instead.
2871
 *
2872
 * While enabled:
2873
 *   - TLS methods, min key sizes, and cipher lists are all configured
2874
 *     automatically by the policy.
2875
 *   - Attempting to use lesser strength parameters will fail with
2876
 *     error CRYPTO_POLICY_FORBIDDEN.
2877
 *
2878
 * Disable with wolfSSL_crypto_policy_disable.
2879
 *
2880
 * Note: the wolfSSL_crypto_policy_X API are not thread safe, and should
2881
 * only be called at program init time.
2882
 *
2883
 * Returns WOLFSSL_SUCCESS on success.
2884
 * Returns CRYPTO_POLICY_FORBIDDEN if already enabled.
2885
 * Returns < 0 on misc error.
2886
 * */
2887
int wolfSSL_crypto_policy_enable(const char * policy_file)
2888
{
2889
    XFILE   file;
2890
    long    sz = 0;
2891
    size_t  n_read = 0;
2892
2893
    WOLFSSL_ENTER("wolfSSL_crypto_policy_enable");
2894
2895
    if (wolfSSL_crypto_policy_is_enabled()) {
2896
        WOLFSSL_MSG_EX("error: crypto policy already enabled: %s",
2897
                       policy_file);
2898
        return CRYPTO_POLICY_FORBIDDEN;
2899
    }
2900
2901
    if (policy_file == NULL) {
2902
        /* Use the configure-time default if NULL passed. */
2903
        policy_file = WC_STRINGIFY(WOLFSSL_CRYPTO_POLICY_FILE);
2904
    }
2905
2906
    if (policy_file == NULL || *policy_file == '\0') {
2907
        WOLFSSL_MSG("error: crypto policy empty file");
2908
        return BAD_FUNC_ARG;
2909
    }
2910
2911
    XMEMSET(&crypto_policy, 0, sizeof(crypto_policy));
2912
2913
    file = XFOPEN(policy_file, "rb");
2914
2915
    if (file == XBADFILE) {
2916
        WOLFSSL_MSG_EX("error: crypto policy file open failed: %s",
2917
                       policy_file);
2918
        return WOLFSSL_BAD_FILE;
2919
    }
2920
2921
    if (XFSEEK(file, 0, XSEEK_END) != 0) {
2922
        WOLFSSL_MSG_EX("error: crypto policy file seek end failed: %s",
2923
                       policy_file);
2924
        XFCLOSE(file);
2925
        return WOLFSSL_BAD_FILE;
2926
    }
2927
2928
    sz = XFTELL(file);
2929
2930
    if (XFSEEK(file, 0, XSEEK_SET) != 0) {
2931
        WOLFSSL_MSG_EX("error: crypto policy file seek failed: %s",
2932
                       policy_file);
2933
        XFCLOSE(file);
2934
        return WOLFSSL_BAD_FILE;
2935
    }
2936
2937
    if (sz <= 0 || sz > MAX_WOLFSSL_CRYPTO_POLICY_SIZE) {
2938
        WOLFSSL_MSG_EX("error: crypto policy file %s, invalid size: %ld",
2939
                       policy_file, sz);
2940
        XFCLOSE(file);
2941
        return WOLFSSL_BAD_FILE;
2942
    }
2943
2944
    n_read = XFREAD(crypto_policy.str, 1, sz, file);
2945
    XFCLOSE(file);
2946
2947
    if (n_read != (size_t) sz) {
2948
        WOLFSSL_MSG_EX("error: crypto policy file %s: read %zu, "
2949
                       "expected %ld", policy_file, n_read, sz);
2950
        return WOLFSSL_BAD_FILE;
2951
    }
2952
2953
    crypto_policy.str[n_read] = '\0';
2954
2955
    return crypto_policy_parse();
2956
}
2957
#endif /* ! NO_FILESYSTEM */
2958
2959
/* Same behavior as wolfSSL_crypto_policy_enable, but loads
2960
 * via memory buf instead of file.
2961
 *
2962
 * Returns WOLFSSL_SUCCESS on success.
2963
 * Returns CRYPTO_POLICY_FORBIDDEN if already enabled.
2964
 * Returns < 0 on misc error.
2965
 * */
2966
int wolfSSL_crypto_policy_enable_buffer(const char * buf)
2967
{
2968
    size_t sz = 0;
2969
2970
    WOLFSSL_ENTER("wolfSSL_crypto_policy_enable_buffer");
2971
2972
    if (wolfSSL_crypto_policy_is_enabled()) {
2973
        WOLFSSL_MSG_EX("error: crypto policy already enabled");
2974
        return CRYPTO_POLICY_FORBIDDEN;
2975
    }
2976
2977
    if (buf == NULL || *buf == '\0') {
2978
        return BAD_FUNC_ARG;
2979
    }
2980
2981
    sz = XSTRLEN(buf);
2982
2983
    if (sz == 0 || sz > MAX_WOLFSSL_CRYPTO_POLICY_SIZE) {
2984
        return BAD_FUNC_ARG;
2985
    }
2986
2987
    XMEMSET(&crypto_policy, 0, sizeof(crypto_policy));
2988
    XMEMCPY(crypto_policy.str, buf, sz);
2989
2990
    return crypto_policy_parse();
2991
}
2992
2993
/* Returns whether the system wide crypto-policy is enabled.
2994
 *
2995
 * Returns 1 if enabled.
2996
 *         0 if disabled.
2997
 * */
2998
int wolfSSL_crypto_policy_is_enabled(void)
2999
{
3000
    WOLFSSL_ENTER("wolfSSL_crypto_policy_is_enabled");
3001
3002
    return crypto_policy.enabled == 1;
3003
}
3004
3005
/* Disables the system wide crypto-policy.
3006
 * note: SSL and CTX structures already instantiated will
3007
 * keep their security policy parameters. This will only
3008
 * affect new instantiations.
3009
 * */
3010
void wolfSSL_crypto_policy_disable(void)
3011
{
3012
    WOLFSSL_ENTER("wolfSSL_crypto_policy_disable");
3013
    crypto_policy.enabled = 0;
3014
    XMEMSET(&crypto_policy, 0, sizeof(crypto_policy));
3015
    return;
3016
}
3017
3018
/* Get the crypto-policy bulk cipher list string.
3019
 * String is not owned by caller, should not be freed.
3020
 *
3021
 * Returns pointer to bulk cipher list string.
3022
 * Returns NULL if NOT enabled, or on error.
3023
 * */
3024
const char * wolfSSL_crypto_policy_get_ciphers(void)
3025
{
3026
    WOLFSSL_ENTER("wolfSSL_crypto_policy_get_ciphers");
3027
3028
    if (crypto_policy.enabled == 1) {
3029
        /* The crypto policy config will have
3030
         * this form:
3031
         *   "@SECLEVEL=2:kEECDH:kRSA..." */
3032
        return crypto_policy.str;
3033
    }
3034
3035
    return NULL;
3036
}
3037
3038
/* Get the configured crypto-policy security level.
3039
 * A security level of 0 does not impose any additional
3040
 * restrictions.
3041
 *
3042
 * Returns 1 - 5 if enabled.
3043
 * Returns 0 if NOT enabled.
3044
 * */
3045
int wolfSSL_crypto_policy_get_level(void)
3046
{
3047
    if (crypto_policy.enabled == 1) {
3048
        return crypto_policy.secLevel;
3049
    }
3050
3051
    return 0;
3052
}
3053
3054
/* Get security level from ssl structure.
3055
 * @param ssl  a pointer to WOLFSSL structure
3056
 */
3057
int wolfSSL_get_security_level(const WOLFSSL * ssl)
3058
{
3059
    if (ssl == NULL) {
3060
        return BAD_FUNC_ARG;
3061
    }
3062
3063
    return ssl->secLevel;
3064
}
3065
3066
#ifndef NO_WOLFSSL_STUB
3067
/*
3068
 * Set security level (wolfSSL doesn't support setting the security level).
3069
 *
3070
 * The security level can only be set through a system wide crypto-policy
3071
 * with wolfSSL_crypto_policy_enable().
3072
 *
3073
 * @param ssl  a pointer to WOLFSSL structure
3074
 * @param level security level
3075
 */
3076
void wolfSSL_set_security_level(WOLFSSL * ssl, int level)
3077
{
3078
    WOLFSSL_ENTER("wolfSSL_set_security_level");
3079
    (void)ssl;
3080
    (void)level;
3081
}
3082
#endif /* !NO_WOLFSSL_STUB */
3083
3084
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
3085
3086
3087
#define WOLFSSL_SSL_LOAD_INCLUDED
3088
#include <src/ssl_load.c>
3089
3090
#define WOLFSSL_SSL_API_CRL_OCSP_INCLUDED
3091
#include "src/ssl_api_crl_ocsp.c"
3092
3093
3094
void wolfSSL_load_error_strings(void)
3095
0
{
3096
    /* compatibility only */
3097
0
}
3098
3099
3100
int wolfSSL_library_init(void)
3101
0
{
3102
0
    WOLFSSL_ENTER("wolfSSL_library_init");
3103
0
    if (wolfSSL_Init() == WOLFSSL_SUCCESS)
3104
0
        return WOLFSSL_SUCCESS;
3105
0
    else
3106
0
        return WOLFSSL_FATAL_ERROR;
3107
0
}
3108
3109
3110
#ifdef HAVE_SECRET_CALLBACK
3111
3112
int wolfSSL_set_session_secret_cb(WOLFSSL* ssl, SessionSecretCb cb, void* ctx)
3113
{
3114
    WOLFSSL_ENTER("wolfSSL_set_session_secret_cb");
3115
    if (ssl == NULL)
3116
        return WOLFSSL_FAILURE;
3117
3118
    ssl->sessionSecretCb = cb;
3119
    ssl->sessionSecretCtx = ctx;
3120
    if (cb != NULL) {
3121
        /* If using a pre-set key, assume session resumption. */
3122
        ssl->session->sessionIDSz = 0;
3123
        ssl->options.resuming = 1;
3124
    }
3125
3126
    return WOLFSSL_SUCCESS;
3127
}
3128
3129
int wolfSSL_set_session_ticket_ext_cb(WOLFSSL* ssl, TicketParseCb cb,
3130
        void *ctx)
3131
{
3132
    WOLFSSL_ENTER("wolfSSL_set_session_ticket_ext_cb");
3133
    if (ssl == NULL)
3134
        return WOLFSSL_FAILURE;
3135
3136
    ssl->ticketParseCb = cb;
3137
    ssl->ticketParseCtx = ctx;
3138
3139
    return WOLFSSL_SUCCESS;
3140
}
3141
3142
int wolfSSL_set_secret_cb(WOLFSSL* ssl, TlsSecretCb cb, void* ctx)
3143
{
3144
    WOLFSSL_ENTER("wolfSSL_set_secret_cb");
3145
    if (ssl == NULL)
3146
        return WOLFSSL_FATAL_ERROR;
3147
3148
    ssl->tlsSecretCb = cb;
3149
    ssl->tlsSecretCtx = ctx;
3150
3151
    return WOLFSSL_SUCCESS;
3152
}
3153
3154
#ifdef SHOW_SECRETS
3155
int tlsShowSecrets(WOLFSSL* ssl, void* secret, int secretSz,
3156
        void* ctx)
3157
{
3158
    /* Wireshark Pre-Master-Secret Format:
3159
     *  CLIENT_RANDOM <clientrandom> <mastersecret>
3160
     */
3161
    const char* CLIENT_RANDOM_LABEL = "CLIENT_RANDOM";
3162
    int i, pmsPos = 0;
3163
    char pmsBuf[13 + 1 + 64 + 1 + 96 + 1 + 1];
3164
    byte clientRandom[RAN_LEN];
3165
    int clientRandomSz;
3166
3167
    (void)ctx;
3168
3169
    clientRandomSz = (int)wolfSSL_get_client_random(ssl, clientRandom,
3170
        sizeof(clientRandom));
3171
3172
    if (clientRandomSz <= 0) {
3173
        printf("Error getting server random %d\n", clientRandomSz);
3174
        return BAD_FUNC_ARG;
3175
    }
3176
3177
    XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "%s ",
3178
        CLIENT_RANDOM_LABEL);
3179
    pmsPos += XSTRLEN(CLIENT_RANDOM_LABEL) + 1;
3180
    for (i = 0; i < clientRandomSz; i++) {
3181
        XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "%02x",
3182
            clientRandom[i]);
3183
        pmsPos += 2;
3184
    }
3185
    XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, " ");
3186
    pmsPos += 1;
3187
    for (i = 0; i < secretSz; i++) {
3188
        XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "%02x",
3189
            ((byte*)secret)[i]);
3190
        pmsPos += 2;
3191
    }
3192
    XSNPRINTF(&pmsBuf[pmsPos], sizeof(pmsBuf) - pmsPos, "\n");
3193
    pmsPos += 1;
3194
3195
    /* print master secret */
3196
    puts(pmsBuf);
3197
3198
    #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_SSLKEYLOGFILE)
3199
    {
3200
        const char* keyLogFile = WOLFSSL_SSLKEYLOGFILE_OUTPUT;
3201
        FILE* f;
3202
    #ifdef WOLFSSL_SSLKEYLOGFILE_USE_ENV
3203
        /* RFC 9850: prefer the SSLKEYLOGFILE environment variable so other
3204
         * tools can share the path, else use the compile-time path. XGETENV is
3205
         * NULL where environment access is unavailable. Opt-in so a build with
3206
         * the variable exported for other applications is not affected. */
3207
        const char* keyLogEnv = XGETENV("SSLKEYLOGFILE");
3208
        if (keyLogEnv != NULL && keyLogEnv[0] != '\0')
3209
            keyLogFile = keyLogEnv;
3210
    #endif
3211
        f = XFOPEN(keyLogFile, "a");
3212
        if (f != XBADFILE) {
3213
            XFWRITE(pmsBuf, 1, pmsPos, f);
3214
            XFCLOSE(f);
3215
        }
3216
    }
3217
    #endif
3218
    return 0;
3219
}
3220
#endif /* SHOW_SECRETS */
3221
3222
#endif
3223
3224
3225
#ifdef OPENSSL_EXTRA
3226
3227
/*
3228
 * check if the list has TLS13 and pre-TLS13 suites
3229
 * @param list cipher suite list that user want to set
3230
 *         (caller required to check for NULL)
3231
 * @return mixed: 0, only pre-TLS13: 1, only TLS13: 2
3232
 */
3233
static int CheckcipherList(const char* list)
3234
{
3235
    int ret;
3236
    int findTLSv13Suites = 0;
3237
    int findbeforeSuites = 0;
3238
    byte cipherSuite0;
3239
    byte cipherSuite1;
3240
    int flags;
3241
    char* next = (char*)list;
3242
3243
    do {
3244
        char*  current = next;
3245
        char   name[MAX_SUITE_NAME + 1];
3246
        word32 length = MAX_SUITE_NAME;
3247
        word32 current_length;
3248
        byte major = INVALID_BYTE;
3249
        byte minor = INVALID_BYTE;
3250
3251
        next   = XSTRSTR(next, ":");
3252
3253
        if (next) {
3254
            current_length = (word32)(next - current);
3255
            ++next; /* increment to skip ':' */
3256
        }
3257
        else {
3258
            current_length = (word32)XSTRLEN(current);
3259
        }
3260
3261
        if (current_length == 0) {
3262
            break;
3263
        }
3264
3265
        if (current_length < length) {
3266
            length = current_length;
3267
        }
3268
        XMEMCPY(name, current, length);
3269
        name[length] = 0;
3270
3271
        if (XSTRCMP(name, "ALL") == 0 ||
3272
            XSTRCMP(name, "DEFAULT") == 0 ||
3273
            XSTRCMP(name, "HIGH") == 0)
3274
        {
3275
            findTLSv13Suites = 1;
3276
            findbeforeSuites = 1;
3277
            break;
3278
        }
3279
3280
        ret = GetCipherSuiteFromName(name, &cipherSuite0,
3281
                &cipherSuite1, &major, &minor, &flags);
3282
        if (ret == 0) {
3283
            if (cipherSuite0 == TLS13_BYTE || minor == TLSv1_3_MINOR) {
3284
                /* TLSv13 suite */
3285
                findTLSv13Suites = 1;
3286
            }
3287
            else {
3288
                findbeforeSuites = 1;
3289
            }
3290
        }
3291
3292
    #if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)
3293
        /* check if mixed due to names like RSA:ECDHE+AESGCM etc. */
3294
        if (ret != 0) {
3295
            char* subStr = name;
3296
            char* subStrNext;
3297
3298
            do {
3299
                subStrNext = XSTRSTR(subStr, "+");
3300
3301
                if ((XSTRCMP(subStr, "ECDHE") == 0) ||
3302
                    (XSTRCMP(subStr, "RSA") == 0)) {
3303
                    return 0;
3304
                }
3305
3306
                if (subStrNext && (XSTRLEN(subStrNext) > 0)) {
3307
                    subStr = subStrNext + 1; /* +1 to skip past '+' */
3308
                }
3309
            } while (subStrNext != NULL);
3310
        }
3311
    #endif
3312
3313
        if (findTLSv13Suites == 1 && findbeforeSuites == 1) {
3314
            /* list has mixed suites */
3315
            return 0;
3316
        }
3317
    } while (next);
3318
3319
    if (findTLSv13Suites == 0 && findbeforeSuites == 1) {
3320
        ret = 1;/* only before TLSv13 suites */
3321
    }
3322
    else if (findTLSv13Suites == 1 && findbeforeSuites == 0) {
3323
        ret = 2;/* only TLSv13 suties */
3324
    }
3325
    else {
3326
        ret = 0;/* handle as mixed */
3327
    }
3328
    return ret;
3329
}
3330
3331
/* parse some bulk lists like !eNULL / !aNULL
3332
 *
3333
 * returns WOLFSSL_SUCCESS on success and sets the cipher suite list
3334
 */
3335
static int wolfSSL_parse_cipher_list(WOLFSSL_CTX* ctx, WOLFSSL* ssl,
3336
        Suites* suites, const char* list)
3337
{
3338
    int     ret = 0;
3339
    int     listattribute = 0;
3340
    int     tls13Only = 0;
3341
    WC_DECLARE_VAR(suitesCpy, byte, WOLFSSL_MAX_SUITE_SZ, 0);
3342
    word16  suitesCpySz = 0;
3343
    word16  i = 0;
3344
    word16  j = 0;
3345
3346
    if (suites == NULL || list == NULL) {
3347
        WOLFSSL_MSG("NULL argument");
3348
        return WOLFSSL_FAILURE;
3349
    }
3350
3351
    listattribute = CheckcipherList(list);
3352
3353
    if (listattribute == 0) {
3354
       /* list has mixed(pre-TLSv13 and TLSv13) suites
3355
        * update cipher suites the same as before
3356
        */
3357
        return (SetCipherList_ex(ctx, ssl, suites, list)) ? WOLFSSL_SUCCESS :
3358
        WOLFSSL_FAILURE;
3359
    }
3360
    else if (listattribute == 1) {
3361
       /* list has only pre-TLSv13 suites.
3362
        * Only update before TLSv13 suites.
3363
        */
3364
        tls13Only = 0;
3365
    }
3366
    else if (listattribute == 2) {
3367
       /* list has only TLSv13 suites. Only update TLv13 suites
3368
        * simulate set_ciphersuites() compatibility layer API
3369
        */
3370
        tls13Only = 1;
3371
        if ((ctx != NULL && !IsAtLeastTLSv1_3(ctx->method->version) &&
3372
                !ctx->method->downgrade) ||
3373
                (ssl != NULL && !IsAtLeastTLSv1_3(ssl->version) &&
3374
                (!ssl->options.downgrade || ssl->options.versionSet))) {
3375
            /* Fail only for methods that can never reach TLS 1.3 (downgrade
3376
             * disabled) or when SetVersion() put the maximum below TLS 1.3.
3377
             * A minimum version does not raise the maximum, so it is not
3378
             * considered here. A version merely capped via
3379
             * set_max_proto_version() still silently ignores the list,
3380
             * matching OpenSSL. */
3381
            WOLFSSL_MSG("Cipher list has only TLS 1.3 suites but TLS 1.3 "
3382
                        "is not negotiable");
3383
            return WOLFSSL_FAILURE;
3384
        }
3385
    }
3386
3387
    /* list contains ciphers either only for TLS 1.3 or <= TLS 1.2 */
3388
#ifdef WOLFSSL_SMALL_STACK
3389
    if (suites->suiteSz > 0) {
3390
        suitesCpy = (byte*)XMALLOC(suites->suiteSz, NULL,
3391
                DYNAMIC_TYPE_TMP_BUFFER);
3392
        if (suitesCpy == NULL) {
3393
            return WOLFSSL_FAILURE;
3394
        }
3395
3396
        XMEMSET(suitesCpy, 0, suites->suiteSz);
3397
    }
3398
#else
3399
        XMEMSET(suitesCpy, 0, sizeof(suitesCpy));
3400
#endif
3401
3402
    if (suites->suiteSz > 0)
3403
        XMEMCPY(suitesCpy, suites->suites, suites->suiteSz);
3404
    suitesCpySz = suites->suiteSz;
3405
3406
    ret = SetCipherList_ex(ctx, ssl, suites, list);
3407
    if (ret != 1) {
3408
        WC_FREE_VAR_EX(suitesCpy, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3409
        return WOLFSSL_FAILURE;
3410
    }
3411
3412
    /* The idea in this section is that OpenSSL has two API to set ciphersuites.
3413
     *   - SSL_CTX_set_cipher_list for setting TLS <= 1.2 suites
3414
     *   - SSL_CTX_set_ciphersuites for setting TLS 1.3 suites
3415
     * Since we direct both API here we attempt to provide API compatibility. If
3416
     * we only get suites from <= 1.2 or == 1.3 then we will only update those
3417
     * suites and keep the suites from the other group.
3418
     * If a single version is in use, skip preserving the other group's
3419
     * suites. A min version makes it a range again, so both groups are kept. */
3420
    if ((ssl != NULL && (!ssl->options.downgrade ||
3421
            (ssl->options.versionSet && !ssl->options.minVersionSet))) ||
3422
        (ctx != NULL && !ctx->method->downgrade)) {
3423
        /* One version only - don't preserve the other group's suites */
3424
        WC_FREE_VAR_EX(suitesCpy, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3425
        return ret;
3426
    }
3427
3428
    for (i = 0; i < suitesCpySz &&
3429
                suites->suiteSz <= (WOLFSSL_MAX_SUITE_SZ - SUITE_LEN); i += 2) {
3430
        /* Check for duplicates */
3431
        int duplicate = 0;
3432
        for (j = 0; j < suites->suiteSz; j += 2) {
3433
            if (suitesCpy[i] == suites->suites[j] &&
3434
                    suitesCpy[i+1] == suites->suites[j+1]) {
3435
                duplicate = 1;
3436
                break;
3437
            }
3438
        }
3439
        if (!duplicate) {
3440
            if (tls13Only) {
3441
                /* Updating TLS 1.3 ciphers */
3442
                if (suitesCpy[i] != TLS13_BYTE) {
3443
                    /* Only copy over <= TLS 1.2 ciphers */
3444
                    /* TLS 1.3 ciphers take precedence */
3445
                    suites->suites[suites->suiteSz++] = suitesCpy[i];
3446
                    suites->suites[suites->suiteSz++] = suitesCpy[i+1];
3447
                }
3448
            }
3449
            else {
3450
                /* Updating <= TLS 1.2 ciphers */
3451
                if (suitesCpy[i] == TLS13_BYTE) {
3452
                    /* Only copy over TLS 1.3 ciphers */
3453
                    /* TLS 1.3 ciphers take precedence */
3454
                    XMEMMOVE(suites->suites + SUITE_LEN, suites->suites,
3455
                             suites->suiteSz);
3456
                    suites->suites[0] = suitesCpy[i];
3457
                    suites->suites[1] = suitesCpy[i+1];
3458
                    suites->suiteSz += 2;
3459
                }
3460
            }
3461
        }
3462
    }
3463
3464
    WC_FREE_VAR_EX(suitesCpy, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3465
    return ret;
3466
}
3467
3468
#endif
3469
3470
3471
int wolfSSL_CTX_set_cipher_list(WOLFSSL_CTX* ctx, const char* list)
3472
0
{
3473
0
    WOLFSSL_ENTER("wolfSSL_CTX_set_cipher_list");
3474
3475
0
    if (ctx == NULL)
3476
0
        return WOLFSSL_FAILURE;
3477
3478
0
    if (AllocateCtxSuites(ctx) != 0)
3479
0
        return WOLFSSL_FAILURE;
3480
3481
#ifdef OPENSSL_EXTRA
3482
    return wolfSSL_parse_cipher_list(ctx, NULL, ctx->suites, list);
3483
#else
3484
0
    return (SetCipherList(ctx, ctx->suites, list)) ?
3485
0
        WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
3486
0
#endif
3487
0
}
3488
3489
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_SET_CIPHER_BYTES)
3490
int wolfSSL_CTX_set_cipher_list_bytes(WOLFSSL_CTX* ctx, const byte* list,
3491
                                      const int listSz)
3492
{
3493
    WOLFSSL_ENTER("wolfSSL_CTX_set_cipher_list_bytes");
3494
3495
    if (ctx == NULL)
3496
        return WOLFSSL_FAILURE;
3497
3498
    if (AllocateCtxSuites(ctx) != 0)
3499
        return WOLFSSL_FAILURE;
3500
3501
    return (SetCipherListFromBytes(ctx, ctx->suites, list, listSz)) ?
3502
        WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
3503
}
3504
#endif /* OPENSSL_EXTRA || WOLFSSL_SET_CIPHER_BYTES */
3505
3506
int wolfSSL_set_cipher_list(WOLFSSL* ssl, const char* list)
3507
0
{
3508
0
    WOLFSSL_ENTER("wolfSSL_set_cipher_list");
3509
3510
0
    if (ssl == NULL || ssl->ctx == NULL) {
3511
0
        return WOLFSSL_FAILURE;
3512
0
    }
3513
3514
0
    if (AllocateSuites(ssl) != 0)
3515
0
        return WOLFSSL_FAILURE;
3516
3517
#ifdef OPENSSL_EXTRA
3518
    return wolfSSL_parse_cipher_list(NULL, ssl, ssl->suites, list);
3519
#else
3520
0
    return (SetCipherList_ex(NULL, ssl, ssl->suites, list)) ?
3521
0
        WOLFSSL_SUCCESS :
3522
0
        WOLFSSL_FAILURE;
3523
0
#endif
3524
0
}
3525
3526
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_SET_CIPHER_BYTES)
3527
int wolfSSL_set_cipher_list_bytes(WOLFSSL* ssl, const byte* list,
3528
                                  const int listSz)
3529
{
3530
    WOLFSSL_ENTER("wolfSSL_set_cipher_list_bytes");
3531
3532
    if (ssl == NULL || ssl->ctx == NULL) {
3533
        return WOLFSSL_FAILURE;
3534
    }
3535
3536
    if (AllocateSuites(ssl) != 0)
3537
        return WOLFSSL_FAILURE;
3538
3539
    return (SetCipherListFromBytes(ssl->ctx, ssl->suites, list, listSz))
3540
           ? WOLFSSL_SUCCESS
3541
           : WOLFSSL_FAILURE;
3542
}
3543
#endif /* OPENSSL_EXTRA || WOLFSSL_SET_CIPHER_BYTES */
3544
3545
3546
#ifdef HAVE_KEYING_MATERIAL
3547
3548
#define TLS_PRF_LABEL_CLIENT_FINISHED     "client finished"
3549
#define TLS_PRF_LABEL_SERVER_FINISHED     "server finished"
3550
#define TLS_PRF_LABEL_MASTER_SECRET       "master secret"
3551
#define TLS_PRF_LABEL_EXT_MASTER_SECRET   "extended master secret"
3552
#define TLS_PRF_LABEL_KEY_EXPANSION       "key expansion"
3553
3554
static const struct ForbiddenLabels {
3555
    const char* label;
3556
    size_t labelLen;
3557
} forbiddenLabels[] = {
3558
    {TLS_PRF_LABEL_CLIENT_FINISHED, XSTR_SIZEOF(TLS_PRF_LABEL_CLIENT_FINISHED)},
3559
    {TLS_PRF_LABEL_SERVER_FINISHED, XSTR_SIZEOF(TLS_PRF_LABEL_SERVER_FINISHED)},
3560
    {TLS_PRF_LABEL_MASTER_SECRET, XSTR_SIZEOF(TLS_PRF_LABEL_MASTER_SECRET)},
3561
    {TLS_PRF_LABEL_EXT_MASTER_SECRET,
3562
     XSTR_SIZEOF(TLS_PRF_LABEL_EXT_MASTER_SECRET)},
3563
    {TLS_PRF_LABEL_KEY_EXPANSION, XSTR_SIZEOF(TLS_PRF_LABEL_KEY_EXPANSION)},
3564
    {NULL, 0},
3565
};
3566
3567
/**
3568
 * Implement RFC 5705
3569
 * TLS 1.3 uses a different exporter definition (section 7.5 of RFC 8446)
3570
 * @return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on error
3571
 */
3572
int wolfSSL_export_keying_material(WOLFSSL *ssl,
3573
        unsigned char *out, size_t outLen,
3574
        const char *label, size_t labelLen,
3575
        const unsigned char *context, size_t contextLen,
3576
        int use_context)
3577
{
3578
    byte*  seed = NULL;
3579
    word32 seedLen;
3580
    const struct ForbiddenLabels* fl;
3581
3582
    WOLFSSL_ENTER("wolfSSL_export_keying_material");
3583
3584
    if (ssl == NULL || out == NULL || label == NULL ||
3585
            (use_context && contextLen && context == NULL)) {
3586
        WOLFSSL_MSG("Bad argument");
3587
        return WOLFSSL_FAILURE;
3588
    }
3589
3590
    /* RFC 8446 Section 7.5 / RFC 5705: keying-material exporters derive from
3591
     * exporter_master_secret, which exists only after the handshake is
3592
     * complete. Refuse the export until the handshake has completed so that
3593
     * a premature call cannot derive material from an uninitialised
3594
     * exporterSecret buffer. */
3595
    if (ssl->options.handShakeDone == 0) {
3596
        WOLFSSL_MSG("Handshake not complete; refusing keying-material export");
3597
        return WOLFSSL_FAILURE;
3598
    }
3599
3600
    /* Sanity check contextLen to prevent integer overflow when cast to word32
3601
     * and to ensure it fits in the 2-byte length encoding (max 65535). */
3602
    if (use_context && contextLen > WOLFSSL_MAX_16BIT) {
3603
        WOLFSSL_MSG("contextLen too large");
3604
        return WOLFSSL_FAILURE;
3605
    }
3606
3607
    /* clientRandom + serverRandom
3608
     * OR
3609
     * clientRandom + serverRandom + ctx len encoding + ctx */
3610
    seedLen = !use_context ? (word32)SEED_LEN :
3611
                             (word32)SEED_LEN + 2 + (word32)contextLen;
3612
3613
    if (ssl->options.saveArrays == 0 || ssl->arrays == NULL) {
3614
        WOLFSSL_MSG("To export keying material wolfSSL needs to keep handshake "
3615
                    "data. Call wolfSSL_KeepArrays before attempting to "
3616
                    "export keyid material.");
3617
        return WOLFSSL_FAILURE;
3618
    }
3619
3620
    /* check forbidden labels */
3621
    for (fl = &forbiddenLabels[0]; fl->label != NULL; fl++) {
3622
        if (labelLen >= fl->labelLen &&
3623
                XMEMCMP(label, fl->label, fl->labelLen) == 0) {
3624
            WOLFSSL_MSG("Forbidden label");
3625
            return WOLFSSL_FAILURE;
3626
        }
3627
    }
3628
3629
#ifdef WOLFSSL_TLS13
3630
    if (IsAtLeastTLSv1_3(ssl->version)) {
3631
        /* Path for TLS 1.3 */
3632
        if (!use_context) {
3633
            contextLen = 0;
3634
            context = (byte*)""; /* Give valid pointer for 0 length memcpy */
3635
        }
3636
3637
        if (Tls13_Exporter(ssl, out, (word32)outLen, label, labelLen,
3638
                context, contextLen) != 0) {
3639
            WOLFSSL_MSG("Tls13_Exporter error");
3640
            return WOLFSSL_FAILURE;
3641
        }
3642
        return WOLFSSL_SUCCESS;
3643
    }
3644
#endif
3645
3646
    /* Path for <=TLS 1.2 */
3647
    seed = (byte*)XMALLOC(seedLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3648
    if (seed == NULL) {
3649
        WOLFSSL_MSG("malloc error");
3650
        return WOLFSSL_FAILURE;
3651
    }
3652
3653
    XMEMCPY(seed,           ssl->arrays->clientRandom, RAN_LEN);
3654
    XMEMCPY(seed + RAN_LEN, ssl->arrays->serverRandom, RAN_LEN);
3655
3656
    if (use_context) {
3657
        /* Encode len in big endian */
3658
        seed[SEED_LEN    ] = (contextLen >> 8) & 0xFF;
3659
        seed[SEED_LEN + 1] = (contextLen) & 0xFF;
3660
        if (contextLen) {
3661
            /* 0 length context is allowed */
3662
            XMEMCPY(seed + SEED_LEN + 2, context, contextLen);
3663
        }
3664
    }
3665
3666
    PRIVATE_KEY_UNLOCK();
3667
    if (wc_PRF_TLS(out, (word32)outLen, ssl->arrays->masterSecret, SECRET_LEN,
3668
            (byte*)label, (word32)labelLen, seed, seedLen,
3669
            IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm, ssl->heap,
3670
            ssl->devId) != 0) {
3671
        WOLFSSL_MSG("wc_PRF_TLS error");
3672
        PRIVATE_KEY_LOCK();
3673
        XFREE(seed, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3674
        return WOLFSSL_FAILURE;
3675
    }
3676
    PRIVATE_KEY_LOCK();
3677
3678
    XFREE(seed, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3679
    return WOLFSSL_SUCCESS;
3680
}
3681
#endif /* HAVE_KEYING_MATERIAL */
3682
3683
3684
/* EITHER SIDE METHODS */
3685
#if !defined(NO_TLS) && (defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE))
3686
    WOLFSSL_METHOD* wolfSSLv23_method(void)
3687
    {
3688
        return wolfSSLv23_method_ex(NULL);
3689
    }
3690
    WOLFSSL_METHOD* wolfSSLv23_method_ex(void* heap)
3691
    {
3692
        WOLFSSL_METHOD* m = NULL;
3693
        WOLFSSL_ENTER("wolfSSLv23_method");
3694
    #if !defined(NO_WOLFSSL_CLIENT)
3695
        m = wolfSSLv23_client_method_ex(heap);
3696
    #elif !defined(NO_WOLFSSL_SERVER)
3697
        m = wolfSSLv23_server_method_ex(heap);
3698
    #else
3699
        (void)heap;
3700
    #endif
3701
        if (m != NULL) {
3702
            m->side = WOLFSSL_NEITHER_END;
3703
        }
3704
3705
        return m;
3706
    }
3707
3708
    #ifndef NO_OLD_TLS
3709
    #ifdef WOLFSSL_ALLOW_SSLV3
3710
    WOLFSSL_METHOD* wolfSSLv3_method(void)
3711
    {
3712
        return wolfSSLv3_method_ex(NULL);
3713
    }
3714
    WOLFSSL_METHOD* wolfSSLv3_method_ex(void* heap)
3715
    {
3716
        WOLFSSL_METHOD* m = NULL;
3717
        WOLFSSL_ENTER("wolfSSLv3_method_ex");
3718
    #if !defined(NO_WOLFSSL_CLIENT)
3719
        m = wolfSSLv3_client_method_ex(heap);
3720
    #elif !defined(NO_WOLFSSL_SERVER)
3721
        m = wolfSSLv3_server_method_ex(heap);
3722
    #endif
3723
        if (m != NULL) {
3724
            m->side = WOLFSSL_NEITHER_END;
3725
        }
3726
3727
        return m;
3728
    }
3729
    #endif
3730
    #endif
3731
#endif /* !NO_TLS && (OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE) */
3732
3733
/* client only parts */
3734
#if !defined(NO_WOLFSSL_CLIENT) && !defined(NO_TLS)
3735
3736
    #if defined(OPENSSL_EXTRA) && !defined(NO_OLD_TLS)
3737
    WOLFSSL_METHOD* wolfSSLv2_client_method(void)
3738
    {
3739
        WOLFSSL_STUB("wolfSSLv2_client_method");
3740
        return NULL;
3741
    }
3742
    #endif
3743
3744
    #if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
3745
    WOLFSSL_METHOD* wolfSSLv3_client_method(void)
3746
    {
3747
        return wolfSSLv3_client_method_ex(NULL);
3748
    }
3749
    WOLFSSL_METHOD* wolfSSLv3_client_method_ex(void* heap)
3750
    {
3751
        WOLFSSL_METHOD* method =
3752
                              (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
3753
                                                     heap, DYNAMIC_TYPE_METHOD);
3754
        (void)heap;
3755
        WOLFSSL_ENTER("wolfSSLv3_client_method_ex");
3756
        if (method)
3757
            InitSSL_Method(method, MakeSSLv3());
3758
        return method;
3759
    }
3760
    #endif /* WOLFSSL_ALLOW_SSLV3 && !NO_OLD_TLS */
3761
3762
3763
    WOLFSSL_METHOD* wolfSSLv23_client_method(void)
3764
0
    {
3765
0
        return wolfSSLv23_client_method_ex(NULL);
3766
0
    }
3767
    WOLFSSL_METHOD* wolfSSLv23_client_method_ex(void* heap)
3768
0
    {
3769
0
        WOLFSSL_METHOD* method =
3770
0
                              (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
3771
0
                                                     heap, DYNAMIC_TYPE_METHOD);
3772
0
        (void)heap;
3773
0
        WOLFSSL_ENTER("wolfSSLv23_client_method_ex");
3774
0
        if (method) {
3775
0
    #if !defined(NO_SHA256) || defined(WOLFSSL_SHA384) || \
3776
0
        defined(WOLFSSL_SHA512)
3777
0
        #if defined(WOLFSSL_TLS13)
3778
0
            InitSSL_Method(method, MakeTLSv1_3());
3779
        #elif !defined(WOLFSSL_NO_TLS12)
3780
            InitSSL_Method(method, MakeTLSv1_2());
3781
        #elif !defined(NO_OLD_TLS)
3782
            InitSSL_Method(method, MakeTLSv1_1());
3783
        #endif
3784
    #else
3785
        #ifndef NO_OLD_TLS
3786
            InitSSL_Method(method, MakeTLSv1_1());
3787
        #endif
3788
    #endif
3789
0
    #if !defined(NO_OLD_TLS) || defined(WOLFSSL_TLS13)
3790
0
            method->downgrade = 1;
3791
0
    #endif
3792
0
        }
3793
0
        return method;
3794
0
    }
3795
3796
3797
#endif /* !NO_WOLFSSL_CLIENT && !NO_TLS */
3798
/* end client only parts */
3799
3800
/* server only parts */
3801
#if !defined(NO_WOLFSSL_SERVER) && !defined(NO_TLS)
3802
3803
    #if defined(OPENSSL_EXTRA) && !defined(NO_OLD_TLS)
3804
    WOLFSSL_METHOD* wolfSSLv2_server_method(void)
3805
    {
3806
        WOLFSSL_STUB("wolfSSLv2_server_method");
3807
        return 0;
3808
    }
3809
    #endif
3810
3811
    #if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
3812
    WOLFSSL_METHOD* wolfSSLv3_server_method(void)
3813
    {
3814
        return wolfSSLv3_server_method_ex(NULL);
3815
    }
3816
    WOLFSSL_METHOD* wolfSSLv3_server_method_ex(void* heap)
3817
    {
3818
        WOLFSSL_METHOD* method =
3819
                              (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
3820
                                                     heap, DYNAMIC_TYPE_METHOD);
3821
        (void)heap;
3822
        WOLFSSL_ENTER("wolfSSLv3_server_method_ex");
3823
        if (method) {
3824
            InitSSL_Method(method, MakeSSLv3());
3825
            method->side = WOLFSSL_SERVER_END;
3826
        }
3827
        return method;
3828
    }
3829
    #endif /* WOLFSSL_ALLOW_SSLV3 && !NO_OLD_TLS */
3830
3831
    WOLFSSL_METHOD* wolfSSLv23_server_method(void)
3832
0
    {
3833
0
        return wolfSSLv23_server_method_ex(NULL);
3834
0
    }
3835
3836
    WOLFSSL_METHOD* wolfSSLv23_server_method_ex(void* heap)
3837
0
    {
3838
0
        WOLFSSL_METHOD* method =
3839
0
                              (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
3840
0
                                                     heap, DYNAMIC_TYPE_METHOD);
3841
0
        (void)heap;
3842
0
        WOLFSSL_ENTER("wolfSSLv23_server_method_ex");
3843
0
        if (method) {
3844
0
    #if !defined(NO_SHA256) || defined(WOLFSSL_SHA384) || \
3845
0
        defined(WOLFSSL_SHA512)
3846
0
        #ifdef WOLFSSL_TLS13
3847
0
            InitSSL_Method(method, MakeTLSv1_3());
3848
        #elif !defined(WOLFSSL_NO_TLS12)
3849
            InitSSL_Method(method, MakeTLSv1_2());
3850
        #elif !defined(NO_OLD_TLS)
3851
            InitSSL_Method(method, MakeTLSv1_1());
3852
        #endif
3853
    #else
3854
        #ifndef NO_OLD_TLS
3855
            InitSSL_Method(method, MakeTLSv1_1());
3856
        #else
3857
            #error Must have SHA256, SHA384 or SHA512 enabled for TLS 1.2
3858
        #endif
3859
    #endif
3860
0
    #if !defined(NO_OLD_TLS) || defined(WOLFSSL_TLS13)
3861
0
            method->downgrade = 1;
3862
0
    #endif
3863
0
            method->side      = WOLFSSL_SERVER_END;
3864
0
        }
3865
0
        return method;
3866
0
    }
3867
3868
3869
3870
#endif /* !NO_WOLFSSL_SERVER && !NO_TLS */
3871
/* end server only parts */
3872
3873
#define WOLFSSL_SSL_API_HS_INCLUDED
3874
#include "src/ssl_api_hs.c"
3875
3876
3877
3878
WOLFSSL_ABI
3879
int wolfSSL_Cleanup(void)
3880
0
{
3881
0
    int ret = WOLFSSL_SUCCESS; /* Only the first error will be returned */
3882
0
    int release = 0;
3883
0
#if !defined(NO_SESSION_CACHE)
3884
0
    int i;
3885
0
    int j;
3886
0
#endif
3887
3888
0
    WOLFSSL_ENTER("wolfSSL_Cleanup");
3889
3890
#ifndef WOLFSSL_MUTEX_INITIALIZER
3891
    if (inits_count_mutex_valid == 1) {
3892
#endif
3893
0
        if (wc_LockMutex(&inits_count_mutex) != 0) {
3894
0
            WOLFSSL_MSG("Bad Lock Mutex count");
3895
0
            return BAD_MUTEX_E;
3896
0
        }
3897
#ifndef WOLFSSL_MUTEX_INITIALIZER
3898
    }
3899
#endif
3900
3901
0
    if (initRefCount > 0) {
3902
0
        initRefCount = initRefCount - 1;
3903
0
        if (initRefCount == 0)
3904
0
            release = 1;
3905
0
    }
3906
3907
#ifndef WOLFSSL_MUTEX_INITIALIZER
3908
    if (inits_count_mutex_valid == 1) {
3909
#endif
3910
0
        wc_UnLockMutex(&inits_count_mutex);
3911
#ifndef WOLFSSL_MUTEX_INITIALIZER
3912
    }
3913
#endif
3914
3915
0
    if (!release)
3916
0
        return ret;
3917
3918
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
3919
    wolfSSL_crypto_policy_disable();
3920
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
3921
3922
#ifdef OPENSSL_EXTRA
3923
    wolfSSL_BN_free_one();
3924
#endif
3925
3926
0
#ifndef NO_SESSION_CACHE
3927
    #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
3928
    for (i = 0; i < SESSION_ROWS; ++i) {
3929
        if ((SessionCache[i].lock_valid == 1) &&
3930
            (wc_FreeRwLock(&SessionCache[i].row_lock) != 0)) {
3931
            if (ret == WOLFSSL_SUCCESS)
3932
                ret = BAD_MUTEX_E;
3933
        }
3934
        SessionCache[i].lock_valid = 0;
3935
    }
3936
    #else
3937
0
    if ((session_lock_valid == 1) && (wc_FreeRwLock(&session_lock) != 0)) {
3938
0
        if (ret == WOLFSSL_SUCCESS)
3939
0
            ret = BAD_MUTEX_E;
3940
0
    }
3941
0
    session_lock_valid = 0;
3942
0
    #endif
3943
0
    for (i = 0; i < SESSION_ROWS; i++) {
3944
0
        for (j = 0; j < SESSIONS_PER_ROW; j++) {
3945
    #ifdef SESSION_CACHE_DYNAMIC_MEM
3946
            if (SessionCache[i].Sessions[j]) {
3947
                EvictSessionFromCache(SessionCache[i].Sessions[j]);
3948
                XFREE(SessionCache[i].Sessions[j], SessionCache[i].heap,
3949
                      DYNAMIC_TYPE_SESSION);
3950
                SessionCache[i].Sessions[j] = NULL;
3951
            }
3952
    #else
3953
0
            EvictSessionFromCache(&SessionCache[i].Sessions[j]);
3954
0
    #endif
3955
0
        }
3956
0
    }
3957
0
    #ifndef NO_CLIENT_CACHE
3958
    #ifndef WOLFSSL_MUTEX_INITIALIZER
3959
    if ((clisession_mutex_valid == 1) &&
3960
        (wc_FreeMutex(&clisession_mutex) != 0)) {
3961
        if (ret == WOLFSSL_SUCCESS)
3962
            ret = BAD_MUTEX_E;
3963
    }
3964
    clisession_mutex_valid = 0;
3965
    #endif
3966
0
    #endif
3967
0
#endif /* !NO_SESSION_CACHE */
3968
3969
#if !defined(WOLFSSL_MUTEX_INITIALIZER) && \
3970
      !WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS
3971
    if ((inits_count_mutex_valid == 1) &&
3972
            (wc_FreeMutex(&inits_count_mutex) != 0)) {
3973
        if (ret == WOLFSSL_SUCCESS)
3974
            ret = BAD_MUTEX_E;
3975
    }
3976
    inits_count_mutex_valid = 0;
3977
#endif
3978
3979
#ifdef OPENSSL_EXTRA
3980
    wolfssl_rand_cleanup();
3981
#endif
3982
3983
0
    if (wolfCrypt_Cleanup() != 0) {
3984
0
        WOLFSSL_MSG("Error with wolfCrypt_Cleanup call");
3985
0
        if (ret == WOLFSSL_SUCCESS)
3986
0
            ret = WC_CLEANUP_E;
3987
0
    }
3988
3989
#if FIPS_VERSION_GE(5,1)
3990
    if (wolfCrypt_SetPrivateKeyReadEnable_fips(0, WC_KEYTYPE_ALL) < 0) {
3991
        if (ret == WOLFSSL_SUCCESS)
3992
            ret = WC_CLEANUP_E;
3993
    }
3994
#endif
3995
3996
0
#ifdef HAVE_GLOBAL_RNG
3997
#ifndef WOLFSSL_MUTEX_INITIALIZER
3998
    if ((globalRNGMutex_valid == 1) && (wc_FreeMutex(&globalRNGMutex) != 0)) {
3999
        if (ret == WOLFSSL_SUCCESS)
4000
            ret = BAD_MUTEX_E;
4001
    }
4002
    globalRNGMutex_valid = 0;
4003
#endif /* !WOLFSSL_MUTEX_INITIALIZER */
4004
4005
    #if defined(OPENSSL_EXTRA) && defined(HAVE_HASHDRBG)
4006
    wolfSSL_FIPS_drbg_free(gDrbgDefCtx);
4007
    gDrbgDefCtx = NULL;
4008
    #endif
4009
0
#endif
4010
4011
#ifdef HAVE_EX_DATA_CRYPTO
4012
    crypto_ex_cb_free(crypto_ex_cb_ctx_session);
4013
    crypto_ex_cb_ctx_session = NULL;
4014
#endif
4015
4016
#ifdef WOLFSSL_MEM_FAIL_COUNT
4017
    wc_MemFailCount_Free();
4018
#endif
4019
4020
0
    return ret;
4021
0
}
4022
4023
/* Returns 1 if name is a syntactically valid DNS FQDN per RFC 952/1123.
4024
 *
4025
 * Rules enforced:
4026
 *   - Total effective length (excluding optional trailing dot) in [1, 253]
4027
 *   - Each label is 1-63 octets of [a-zA-Z0-9-], with _ allowed in all but
4028
 *     the last label.
4029
 *   - No label starts or ends with '-'
4030
 *   - At least two labels (single-label names are not "fully qualified")
4031
 *   - Final label (TLD) contains at least one letter (rejects all-numeric
4032
 *     strings that could be confused with IPv4 literals, and matches the
4033
 *     ICANN constraint that TLDs are alphabetic)
4034
 *   - Optional trailing dot is accepted (absolute FQDN form)
4035
 *   - Internationalized names are valid in their ACE/punycode (xn--) form
4036
 */
4037
int wolfssl_local_IsValidFQDN(const char* name, word32 nameSz)
4038
0
{
4039
0
    word32 i;
4040
0
    int labelLen = 0;
4041
0
    int labelCount = 0;
4042
0
    int curLabelHasAlpha = 0;
4043
0
    int curLabelHasUnderscore = 0;
4044
4045
0
    if (name == NULL || nameSz == 0 || nameSz > 254)
4046
0
        return 0;
4047
4048
    /* Bound before touching name[]: a valid name is at most 253 octets
4049
     * plus an optional trailing dot, so longer sizes are rejected here
4050
     * without reading past the caller's buffer.
4051
     */
4052
    /* Strip a single optional trailing dot before measuring.  "example.com."
4053
     * is the absolute form of the same FQDN.
4054
     */
4055
0
    if (name[nameSz - 1] == '.')
4056
0
        --nameSz;
4057
4058
0
    if (nameSz > 253)
4059
0
        return 0;
4060
4061
0
    for (i = 0; i < nameSz; i++) {
4062
0
        byte c = (byte)name[i];
4063
4064
0
        if (c == '.') {
4065
0
            if (labelLen == 0 || name[i - 1] == '-')
4066
0
                return 0;
4067
0
            ++labelCount;
4068
0
            labelLen = 0;
4069
0
            curLabelHasAlpha = 0;
4070
0
            curLabelHasUnderscore = 0;
4071
0
            continue;
4072
0
        }
4073
4074
0
        if (++labelLen > 63)
4075
0
            return 0;
4076
4077
0
        if (c == '-') {
4078
0
            if (labelLen == 1)
4079
0
                return 0;
4080
0
        }
4081
0
        else if (((c | 0x20) >= 'a') && ((c | 0x20) <= 'z')) {
4082
0
            curLabelHasAlpha = 1;
4083
0
        }
4084
0
        else if (c == '_') {
4085
0
            curLabelHasUnderscore = 1;
4086
0
        }
4087
0
        else if ((c < '0') || (c > '9')) {
4088
0
            return 0;
4089
0
        }
4090
0
    }
4091
4092
    /* Final label (no trailing dot in the effective range to close it) */
4093
0
    if ((labelLen == 0) || (name[nameSz - 1] == '-') || curLabelHasUnderscore)
4094
0
        return 0;
4095
0
    ++labelCount;
4096
4097
#ifdef WOLFSSL_ALLOW_SINGLE_LABEL_HOSTNAME
4098
    (void)labelCount;
4099
    return curLabelHasAlpha;
4100
#else
4101
0
    return ((labelCount > 1) && curLabelHasAlpha);
4102
0
#endif
4103
0
}
4104
4105
/* call before SSL_connect, if verifying will add name check to
4106
   date check and signature check */
4107
WOLFSSL_ABI
4108
int wolfSSL_check_domain_name(WOLFSSL* ssl, const char* dn)
4109
0
{
4110
0
    size_t dn_len;
4111
4112
0
    WOLFSSL_ENTER("wolfSSL_check_domain_name");
4113
4114
0
    if (ssl == NULL || dn == NULL) {
4115
0
        WOLFSSL_MSG("Bad function argument: NULL");
4116
0
        return WOLFSSL_FAILURE;
4117
0
    }
4118
4119
0
    dn_len = XSTRLEN(dn);
4120
4121
0
    if ((! wolfssl_local_IsValidFQDN(dn, (word32)dn_len)) &&
4122
0
        (XSTRCMP(dn, "localhost") != 0))
4123
0
    {
4124
0
        WOLFSSL_MSG("Bad function argument: fails wolfssl_local_IsValidFQDN");
4125
0
        return WOLFSSL_FAILURE;
4126
0
    }
4127
4128
0
    if (ssl->buffers.domainName.buffer)
4129
0
        XFREE(ssl->buffers.domainName.buffer, ssl->heap, DYNAMIC_TYPE_DOMAIN);
4130
4131
0
    ssl->buffers.domainName.length = (word32)XSTRLEN(dn);
4132
0
    ssl->buffers.domainName.buffer = (byte*)XMALLOC(
4133
0
            ssl->buffers.domainName.length + 1, ssl->heap, DYNAMIC_TYPE_DOMAIN);
4134
4135
0
    if (ssl->buffers.domainName.buffer) {
4136
0
        unsigned char* domainName = ssl->buffers.domainName.buffer;
4137
0
        XMEMCPY(domainName, dn, ssl->buffers.domainName.length);
4138
0
        domainName[ssl->buffers.domainName.length] = '\0';
4139
0
        return WOLFSSL_SUCCESS;
4140
0
    }
4141
0
    else {
4142
0
        ssl->error = MEMORY_ERROR;
4143
0
        return WOLFSSL_FAILURE;
4144
0
    }
4145
0
}
4146
4147
/* call before SSL_connect, if verifying will add IP SAN check to
4148
   date check and signature check */
4149
WOLFSSL_ABI
4150
int wolfSSL_check_ip_address(WOLFSSL* ssl, const char* ipaddr)
4151
0
{
4152
0
    WOLFSSL_ENTER("wolfSSL_check_ip_address");
4153
4154
0
    if (ssl == NULL || ipaddr == NULL) {
4155
0
        WOLFSSL_MSG("Bad function argument: NULL");
4156
0
        return WOLFSSL_FAILURE;
4157
0
    }
4158
4159
0
    if (ssl->buffers.ipasc.buffer != NULL) {
4160
0
        XFREE(ssl->buffers.ipasc.buffer, ssl->heap, DYNAMIC_TYPE_DOMAIN);
4161
0
        ssl->buffers.ipasc.buffer = NULL;
4162
0
        ssl->buffers.ipasc.length = 0;
4163
0
    }
4164
4165
0
    ssl->buffers.ipasc.length = (word32)XSTRLEN(ipaddr);
4166
0
    ssl->buffers.ipasc.buffer = (byte*)XMALLOC(ssl->buffers.ipasc.length + 1,
4167
0
                                               ssl->heap, DYNAMIC_TYPE_DOMAIN);
4168
0
    if (ssl->buffers.ipasc.buffer == NULL) {
4169
0
        ssl->error = MEMORY_ERROR;
4170
0
        return WOLFSSL_FAILURE;
4171
0
    }
4172
4173
0
    XMEMCPY(ssl->buffers.ipasc.buffer, ipaddr, ssl->buffers.ipasc.length);
4174
0
    ssl->buffers.ipasc.buffer[ssl->buffers.ipasc.length] = '\0';
4175
4176
#ifdef OPENSSL_EXTRA
4177
    if (ssl->param == NULL) {
4178
        return WOLFSSL_FAILURE;
4179
    }
4180
    if (wolfSSL_X509_VERIFY_PARAM_set1_ip_asc(ssl->param, ipaddr) !=
4181
            WOLFSSL_SUCCESS) {
4182
        return WOLFSSL_FAILURE;
4183
    }
4184
#endif
4185
4186
0
    return WOLFSSL_SUCCESS;
4187
0
}
4188
4189
#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
4190
const char *wolfSSL_get0_peername(WOLFSSL *ssl) {
4191
    if (ssl == NULL) {
4192
        return NULL;
4193
    }
4194
4195
    if (ssl->buffers.domainName.buffer)
4196
        return (const char *)ssl->buffers.domainName.buffer;
4197
    else if (ssl->session && ssl->session->peer)
4198
        return ssl->session->peer->subjectCN;
4199
#ifdef KEEP_PEER_CERT
4200
    else if (GetPeerCert(ssl) != NULL && GetPeerCert(ssl)->subjectCN[0])
4201
        return GetPeerCert(ssl)->subjectCN;
4202
#endif
4203
    else {
4204
        ssl->error = NO_PEER_CERT;
4205
        return NULL;
4206
    }
4207
}
4208
4209
#endif /* SESSION_CERTS && OPENSSL_EXTRA */
4210
4211
/* turn on wolfSSL zlib compression
4212
   returns WOLFSSL_SUCCESS for success, else error (not built in)
4213
*/
4214
int wolfSSL_set_compression(WOLFSSL* ssl)
4215
0
{
4216
0
    WOLFSSL_ENTER("wolfSSL_set_compression");
4217
0
    (void)ssl;
4218
#ifdef HAVE_LIBZ
4219
    if (ssl == NULL)
4220
        return BAD_FUNC_ARG;
4221
#ifdef WOLFSSL_DTLS
4222
    /* zlib keeps one deflate stream running across records, so a datagram
4223
     * that is lost, duplicated or reordered desyncs the peer's inflate state
4224
     * for the rest of the connection. */
4225
    if (ssl->options.dtls) {
4226
        WOLFSSL_MSG("Compression not supported over DTLS");
4227
        return BAD_FUNC_ARG;
4228
    }
4229
#endif
4230
    ssl->options.usingCompression = 1;
4231
    return WOLFSSL_SUCCESS;
4232
#else
4233
0
    return NOT_COMPILED_IN;
4234
0
#endif
4235
0
}
4236
4237
4238
#ifndef NO_PSK
4239
4240
    void wolfSSL_CTX_set_psk_client_callback(WOLFSSL_CTX* ctx,
4241
                                         wc_psk_client_callback cb)
4242
    {
4243
        WOLFSSL_ENTER("wolfSSL_CTX_set_psk_client_callback");
4244
4245
        if (ctx == NULL)
4246
            return;
4247
4248
        ctx->havePSK = 1;
4249
        ctx->client_psk_cb = cb;
4250
    }
4251
4252
    void wolfSSL_set_psk_client_callback(WOLFSSL* ssl,wc_psk_client_callback cb)
4253
    {
4254
        byte haveRSA = 1;
4255
        int  keySz   = 0;
4256
4257
        WOLFSSL_ENTER("wolfSSL_set_psk_client_callback");
4258
4259
        if (ssl == NULL)
4260
            return;
4261
4262
        ssl->options.havePSK = 1;
4263
        ssl->options.client_psk_cb = cb;
4264
4265
        #ifdef NO_RSA
4266
            haveRSA = 0;
4267
        #endif
4268
        #ifndef NO_CERTS
4269
            keySz = ssl->buffers.keySz;
4270
        #endif
4271
        if (AllocateSuites(ssl) != 0)
4272
            return;
4273
        InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE,
4274
                   ssl->options.haveDH, ssl->options.haveECDSAsig,
4275
                   ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
4276
                   ssl->options.useAnon, TRUE, TRUE, TRUE, TRUE, ssl->options.side);
4277
    }
4278
4279
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_CERT_WITH_EXTERN_PSK)
4280
    int wolfSSL_CTX_set_cert_with_extern_psk(WOLFSSL_CTX* ctx, int state)
4281
    {
4282
        WOLFSSL_ENTER("wolfSSL_CTX_set_cert_with_extern_psk");
4283
        if (ctx == NULL)
4284
            return WOLFSSL_FAILURE;
4285
        ctx->certWithExternPsk = (byte)(state != 0);
4286
        return WOLFSSL_SUCCESS;
4287
    }
4288
4289
    int wolfSSL_set_cert_with_extern_psk(WOLFSSL* ssl, int state)
4290
    {
4291
        WOLFSSL_ENTER("wolfSSL_set_cert_with_extern_psk");
4292
        if (ssl == NULL)
4293
            return WOLFSSL_FAILURE;
4294
        ssl->options.certWithExternPsk = (word16)(state != 0);
4295
        return WOLFSSL_SUCCESS;
4296
    }
4297
#endif
4298
4299
    #ifdef OPENSSL_EXTRA
4300
    /**
4301
     * set call back function for psk session use
4302
     * @param ssl  a pointer to WOLFSSL structure
4303
     * @param cb   a function pointer to wc_psk_use_session_cb
4304
     * @return none
4305
     */
4306
    void wolfSSL_set_psk_use_session_callback(WOLFSSL* ssl,
4307
                                                wc_psk_use_session_cb_func cb)
4308
    {
4309
        WOLFSSL_ENTER("wolfSSL_set_psk_use_session_callback");
4310
4311
        if (ssl != NULL) {
4312
            ssl->options.havePSK = 1;
4313
            ssl->options.session_psk_cb = cb;
4314
        }
4315
4316
        WOLFSSL_LEAVE("wolfSSL_set_psk_use_session_callback", WOLFSSL_SUCCESS);
4317
    }
4318
    #endif
4319
4320
    void wolfSSL_CTX_set_psk_server_callback(WOLFSSL_CTX* ctx,
4321
                                         wc_psk_server_callback cb)
4322
    {
4323
        WOLFSSL_ENTER("wolfSSL_CTX_set_psk_server_callback");
4324
        if (ctx == NULL)
4325
            return;
4326
        ctx->havePSK = 1;
4327
        ctx->server_psk_cb = cb;
4328
    }
4329
4330
    void wolfSSL_set_psk_server_callback(WOLFSSL* ssl,wc_psk_server_callback cb)
4331
    {
4332
        byte haveRSA = 1;
4333
        int  keySz   = 0;
4334
4335
        WOLFSSL_ENTER("wolfSSL_set_psk_server_callback");
4336
        if (ssl == NULL)
4337
            return;
4338
4339
        ssl->options.havePSK = 1;
4340
        ssl->options.server_psk_cb = cb;
4341
4342
        #ifdef NO_RSA
4343
            haveRSA = 0;
4344
        #endif
4345
        #ifndef NO_CERTS
4346
            keySz = ssl->buffers.keySz;
4347
        #endif
4348
        if (AllocateSuites(ssl) != 0)
4349
            return;
4350
        InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE,
4351
                   ssl->options.haveDH, ssl->options.haveECDSAsig,
4352
                   ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
4353
                   ssl->options.useAnon, TRUE, TRUE, TRUE, TRUE, ssl->options.side);
4354
    }
4355
4356
    const char* wolfSSL_get_psk_identity_hint(const WOLFSSL* ssl)
4357
    {
4358
        WOLFSSL_ENTER("wolfSSL_get_psk_identity_hint");
4359
4360
        if (ssl == NULL || ssl->arrays == NULL)
4361
            return NULL;
4362
4363
        return ssl->arrays->server_hint;
4364
    }
4365
4366
4367
    const char* wolfSSL_get_psk_identity(const WOLFSSL* ssl)
4368
    {
4369
        WOLFSSL_ENTER("wolfSSL_get_psk_identity");
4370
4371
        if (ssl == NULL || ssl->arrays == NULL)
4372
            return NULL;
4373
4374
        return ssl->arrays->client_identity;
4375
    }
4376
4377
    int wolfSSL_CTX_use_psk_identity_hint(WOLFSSL_CTX* ctx, const char* hint)
4378
    {
4379
        WOLFSSL_ENTER("wolfSSL_CTX_use_psk_identity_hint");
4380
        if (hint == 0)
4381
            ctx->server_hint[0] = '\0';
4382
        else {
4383
            /* Qt does not call CTX_set_*_psk_callbacks where havePSK is set */
4384
            #ifdef WOLFSSL_QT
4385
            ctx->havePSK=1;
4386
            #endif
4387
            XSTRNCPY(ctx->server_hint, hint, MAX_PSK_ID_LEN);
4388
            ctx->server_hint[MAX_PSK_ID_LEN] = '\0'; /* null term */
4389
        }
4390
        return WOLFSSL_SUCCESS;
4391
    }
4392
4393
    int wolfSSL_use_psk_identity_hint(WOLFSSL* ssl, const char* hint)
4394
    {
4395
        WOLFSSL_ENTER("wolfSSL_use_psk_identity_hint");
4396
4397
        if (ssl == NULL || ssl->arrays == NULL)
4398
            return WOLFSSL_FAILURE;
4399
4400
        if (hint == 0)
4401
            ssl->arrays->server_hint[0] = 0;
4402
        else {
4403
            XSTRNCPY(ssl->arrays->server_hint, hint,
4404
                                            sizeof(ssl->arrays->server_hint)-1);
4405
            ssl->arrays->server_hint[sizeof(ssl->arrays->server_hint)-1] = '\0';
4406
        }
4407
        return WOLFSSL_SUCCESS;
4408
    }
4409
4410
    void* wolfSSL_get_psk_callback_ctx(WOLFSSL* ssl)
4411
    {
4412
        return ssl ? ssl->options.psk_ctx : NULL;
4413
    }
4414
    void* wolfSSL_CTX_get_psk_callback_ctx(WOLFSSL_CTX* ctx)
4415
    {
4416
        return ctx ? ctx->psk_ctx : NULL;
4417
    }
4418
    int wolfSSL_set_psk_callback_ctx(WOLFSSL* ssl, void* psk_ctx)
4419
    {
4420
        if (ssl == NULL)
4421
            return WOLFSSL_FAILURE;
4422
        ssl->options.psk_ctx = psk_ctx;
4423
        return WOLFSSL_SUCCESS;
4424
    }
4425
    int wolfSSL_CTX_set_psk_callback_ctx(WOLFSSL_CTX* ctx, void* psk_ctx)
4426
    {
4427
        if (ctx == NULL)
4428
            return WOLFSSL_FAILURE;
4429
        ctx->psk_ctx = psk_ctx;
4430
        return WOLFSSL_SUCCESS;
4431
    }
4432
#endif /* NO_PSK */
4433
4434
4435
#ifdef HAVE_ANON
4436
4437
    int wolfSSL_CTX_allow_anon_cipher(WOLFSSL_CTX* ctx)
4438
    {
4439
        WOLFSSL_ENTER("wolfSSL_CTX_allow_anon_cipher");
4440
4441
        if (ctx == NULL)
4442
            return WOLFSSL_FAILURE;
4443
4444
        ctx->useAnon = 1;
4445
4446
        return WOLFSSL_SUCCESS;
4447
    }
4448
4449
#endif /* HAVE_ANON */
4450
4451
#ifdef OPENSSL_EXTRA
4452
4453
    int wolfSSL_add_all_algorithms(void)
4454
    {
4455
        WOLFSSL_ENTER("wolfSSL_add_all_algorithms");
4456
        if (initRefCount != 0 || wolfSSL_Init() == WOLFSSL_SUCCESS)
4457
            return WOLFSSL_SUCCESS;
4458
        else
4459
            return WOLFSSL_FATAL_ERROR;
4460
    }
4461
4462
    int wolfSSL_OpenSSL_add_all_algorithms_noconf(void)
4463
    {
4464
        WOLFSSL_ENTER("wolfSSL_OpenSSL_add_all_algorithms_noconf");
4465
4466
        if  (wolfSSL_add_all_algorithms() ==
4467
             WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR))
4468
        {
4469
            return WOLFSSL_FATAL_ERROR;
4470
        }
4471
4472
        return  WOLFSSL_SUCCESS;
4473
    }
4474
4475
    int wolfSSL_OpenSSL_add_all_algorithms_conf(void)
4476
    {
4477
        WOLFSSL_ENTER("wolfSSL_OpenSSL_add_all_algorithms_conf");
4478
        /* This function is currently the same as
4479
        wolfSSL_OpenSSL_add_all_algorithms_noconf since we do not employ
4480
        the use of a wolfssl.cnf type configuration file and is only used for
4481
        OpenSSL compatibility. */
4482
4483
        if (wolfSSL_add_all_algorithms() ==
4484
            WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR))
4485
        {
4486
            return WOLFSSL_FATAL_ERROR;
4487
        }
4488
        return WOLFSSL_SUCCESS;
4489
    }
4490
4491
#endif
4492
4493
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
4494
    defined(WOLFSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
4495
    void wolfSSL_CTX_set_quiet_shutdown(WOLFSSL_CTX* ctx, int mode)
4496
    {
4497
        WOLFSSL_ENTER("wolfSSL_CTX_set_quiet_shutdown");
4498
        if (mode)
4499
            ctx->quietShutdown = 1;
4500
    }
4501
4502
4503
    void wolfSSL_set_quiet_shutdown(WOLFSSL* ssl, int mode)
4504
    {
4505
        WOLFSSL_ENTER("wolfSSL_set_quiet_shutdown");
4506
        if (mode)
4507
            ssl->options.quietShutdown = 1;
4508
    }
4509
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL ||
4510
          WOLFSSL_EXTRA || WOLFSSL_WPAS_SMALL */
4511
4512
#ifdef OPENSSL_EXTRA
4513
#ifndef NO_BIO
4514
    static void ssl_set_bio(WOLFSSL* ssl, WOLFSSL_BIO* rd, WOLFSSL_BIO* wr, int flags)
4515
    {
4516
        WOLFSSL_ENTER("wolfSSL_set_bio");
4517
4518
        if (ssl == NULL) {
4519
            WOLFSSL_MSG("Bad argument, ssl was NULL");
4520
            return;
4521
        }
4522
4523
        /* free any existing WOLFSSL_BIOs in use but don't free those in
4524
         * a chain */
4525
        if ((flags & WOLFSSL_BIO_FLAG_READ) && (ssl->biord != NULL)) {
4526
            if ((flags & WOLFSSL_BIO_FLAG_WRITE) && (ssl->biord != ssl->biowr)) {
4527
                if (ssl->biowr != NULL && ssl->biowr->prev == NULL)
4528
                    wolfSSL_BIO_free(ssl->biowr);
4529
                ssl->biowr = NULL;
4530
            }
4531
            if (ssl->biord->prev == NULL)
4532
                wolfSSL_BIO_free(ssl->biord);
4533
            ssl->biord = NULL;
4534
        }
4535
        else if ((flags & WOLFSSL_BIO_FLAG_WRITE) && (ssl->biowr != NULL)) {
4536
            if (ssl->biowr->prev == NULL)
4537
                wolfSSL_BIO_free(ssl->biowr);
4538
            ssl->biowr = NULL;
4539
        }
4540
4541
        /* set flag obviously */
4542
        if (rd && !(rd->flags & WOLFSSL_BIO_FLAG_READ))
4543
            rd->flags |= WOLFSSL_BIO_FLAG_READ;
4544
        if (wr && !(wr->flags & WOLFSSL_BIO_FLAG_WRITE))
4545
            wr->flags |= WOLFSSL_BIO_FLAG_WRITE;
4546
4547
        if (flags & WOLFSSL_BIO_FLAG_READ)
4548
            ssl->biord = rd;
4549
        if (flags & WOLFSSL_BIO_FLAG_WRITE)
4550
            ssl->biowr = wr;
4551
4552
        /* set SSL to use BIO callbacks instead */
4553
        if ((flags & WOLFSSL_BIO_FLAG_READ) &&
4554
            (((ssl->cbioFlag & WOLFSSL_CBIO_RECV) == 0)))
4555
        {
4556
            ssl->CBIORecv = SslBioReceive;
4557
        }
4558
        if ((flags & WOLFSSL_BIO_FLAG_WRITE) &&
4559
            (((ssl->cbioFlag & WOLFSSL_CBIO_SEND) == 0)))
4560
        {
4561
            ssl->CBIOSend = SslBioSend;
4562
        }
4563
4564
        /* User programs should always retry reading from these BIOs */
4565
        if (rd) {
4566
            /* User writes to rd */
4567
            wolfSSL_BIO_set_retry_write(rd);
4568
        }
4569
        if (wr) {
4570
            /* User reads from wr */
4571
            wolfSSL_BIO_set_retry_read(wr);
4572
        }
4573
    }
4574
4575
    void wolfSSL_set_bio(WOLFSSL* ssl, WOLFSSL_BIO* rd, WOLFSSL_BIO* wr)
4576
    {
4577
        ssl_set_bio(ssl, rd, wr, WOLFSSL_BIO_FLAG_READ | WOLFSSL_BIO_FLAG_WRITE);
4578
    }
4579
4580
    void wolfSSL_set_rbio(WOLFSSL* ssl, WOLFSSL_BIO* rd)
4581
    {
4582
        ssl_set_bio(ssl, rd, NULL, WOLFSSL_BIO_FLAG_READ);
4583
    }
4584
4585
    void wolfSSL_set_wbio(WOLFSSL* ssl, WOLFSSL_BIO* wr)
4586
    {
4587
        ssl_set_bio(ssl, NULL, wr, WOLFSSL_BIO_FLAG_WRITE);
4588
    }
4589
4590
#endif /* !NO_BIO */
4591
#endif /* OPENSSL_EXTRA */
4592
4593
#ifdef WOLFSSL_CERT_SETUP_CB
4594
    int wolfSSL_get_client_suites_sigalgs(const WOLFSSL* ssl,
4595
            const byte** suites, word16* suiteSz,
4596
            const byte** hashSigAlgo, word16* hashSigAlgoSz)
4597
    {
4598
        WOLFSSL_ENTER("wolfSSL_get_client_suites_sigalgs");
4599
4600
        if (suites != NULL)
4601
            *suites = NULL;
4602
        if (suiteSz != NULL)
4603
            *suiteSz = 0;
4604
        if (hashSigAlgo != NULL)
4605
            *hashSigAlgo = NULL;
4606
        if (hashSigAlgoSz != NULL)
4607
            *hashSigAlgoSz = 0;
4608
4609
        if (ssl != NULL && ssl->clSuites != NULL) {
4610
            if (suites != NULL && suiteSz != NULL) {
4611
                *suites = ssl->clSuites->suites;
4612
                *suiteSz = ssl->clSuites->suiteSz;
4613
            }
4614
            if (hashSigAlgo != NULL && hashSigAlgoSz != NULL) {
4615
                *hashSigAlgo = ssl->clSuites->hashSigAlgo;
4616
                *hashSigAlgoSz = ssl->clSuites->hashSigAlgoSz;
4617
            }
4618
            return WOLFSSL_SUCCESS;
4619
        }
4620
        return WOLFSSL_FAILURE;
4621
    }
4622
4623
#ifndef NO_TLS
4624
    WOLFSSL_CIPHERSUITE_INFO wolfSSL_get_ciphersuite_info(byte first,
4625
            byte second)
4626
    {
4627
        WOLFSSL_CIPHERSUITE_INFO info;
4628
        info.rsaAuth = (byte)(CipherRequires(first, second, REQUIRES_RSA) ||
4629
                CipherRequires(first, second, REQUIRES_RSA_SIG));
4630
        info.eccAuth = (byte)(CipherRequires(first, second, REQUIRES_ECC) ||
4631
                /* Static ECC ciphers may require RSA for authentication */
4632
                (CipherRequires(first, second, REQUIRES_ECC_STATIC) &&
4633
                        !CipherRequires(first, second, REQUIRES_RSA_SIG)));
4634
        info.eccStatic =
4635
                (byte)CipherRequires(first, second, REQUIRES_ECC_STATIC);
4636
        info.psk = (byte)CipherRequires(first, second, REQUIRES_PSK);
4637
        return info;
4638
    }
4639
#endif
4640
4641
    /**
4642
     * @param first First byte of the hash and signature algorithm
4643
     * @param second Second byte of the hash and signature algorithm
4644
     * @param hashAlgo The enum wc_HashType of the MAC algorithm
4645
     * @param sigAlgo The enum Key_Sum of the authentication algorithm
4646
     */
4647
    int wolfSSL_get_sigalg_info(byte first, byte second,
4648
            int* hashAlgo, int* sigAlgo)
4649
    {
4650
        byte input[2];
4651
        byte hashType;
4652
        byte sigType;
4653
4654
        if (hashAlgo == NULL || sigAlgo == NULL)
4655
            return BAD_FUNC_ARG;
4656
4657
        input[0] = first;
4658
        input[1] = second;
4659
        DecodeSigAlg(input, &hashType, &sigType);
4660
4661
        /* cast so that compiler reminds us of unimplemented values */
4662
        switch ((enum SignatureAlgorithm)sigType) {
4663
        case anonymous_sa_algo:
4664
            *sigAlgo = ANONk;
4665
            break;
4666
        case rsa_sa_algo:
4667
            *sigAlgo = RSAk;
4668
            break;
4669
        case dsa_sa_algo:
4670
            *sigAlgo = DSAk;
4671
            break;
4672
        case ecc_dsa_sa_algo:
4673
        case ecc_brainpool_sa_algo:
4674
            *sigAlgo = ECDSAk;
4675
            break;
4676
        case rsa_pss_sa_algo:
4677
            *sigAlgo = RSAPSSk;
4678
            break;
4679
        case ed25519_sa_algo:
4680
            *sigAlgo = ED25519k;
4681
            break;
4682
        case rsa_pss_pss_algo:
4683
            *sigAlgo = RSAPSSk;
4684
            break;
4685
        case ed448_sa_algo:
4686
            *sigAlgo = ED448k;
4687
            break;
4688
        case falcon_level1_sa_algo:
4689
            *sigAlgo = FALCON_LEVEL1k;
4690
            break;
4691
        case falcon_level5_sa_algo:
4692
            *sigAlgo = FALCON_LEVEL5k;
4693
            break;
4694
        case mldsa_44_sa_algo:
4695
            *sigAlgo = ML_DSA_44k;
4696
            break;
4697
        case mldsa_65_sa_algo:
4698
            *sigAlgo = ML_DSA_65k;
4699
            break;
4700
        case mldsa_87_sa_algo:
4701
            *sigAlgo = ML_DSA_87k;
4702
            break;
4703
        case slhdsa_sha2_128s_sa_algo:
4704
            *sigAlgo = SLH_DSA_SHA2_128Sk;
4705
            break;
4706
        case slhdsa_sha2_128f_sa_algo:
4707
            *sigAlgo = SLH_DSA_SHA2_128Fk;
4708
            break;
4709
        case slhdsa_sha2_192s_sa_algo:
4710
            *sigAlgo = SLH_DSA_SHA2_192Sk;
4711
            break;
4712
        case slhdsa_sha2_192f_sa_algo:
4713
            *sigAlgo = SLH_DSA_SHA2_192Fk;
4714
            break;
4715
        case slhdsa_sha2_256s_sa_algo:
4716
            *sigAlgo = SLH_DSA_SHA2_256Sk;
4717
            break;
4718
        case slhdsa_sha2_256f_sa_algo:
4719
            *sigAlgo = SLH_DSA_SHA2_256Fk;
4720
            break;
4721
        case slhdsa_shake_128s_sa_algo:
4722
            *sigAlgo = SLH_DSA_SHAKE_128Sk;
4723
            break;
4724
        case slhdsa_shake_128f_sa_algo:
4725
            *sigAlgo = SLH_DSA_SHAKE_128Fk;
4726
            break;
4727
        case slhdsa_shake_192s_sa_algo:
4728
            *sigAlgo = SLH_DSA_SHAKE_192Sk;
4729
            break;
4730
        case slhdsa_shake_192f_sa_algo:
4731
            *sigAlgo = SLH_DSA_SHAKE_192Fk;
4732
            break;
4733
        case slhdsa_shake_256s_sa_algo:
4734
            *sigAlgo = SLH_DSA_SHAKE_256Sk;
4735
            break;
4736
        case slhdsa_shake_256f_sa_algo:
4737
            *sigAlgo = SLH_DSA_SHAKE_256Fk;
4738
            break;
4739
        case sm2_sa_algo:
4740
            *sigAlgo = SM2k;
4741
            break;
4742
        case invalid_sa_algo:
4743
        case any_sa_algo:
4744
        default:
4745
            *hashAlgo = WC_HASH_TYPE_NONE;
4746
            *sigAlgo = 0;
4747
            return BAD_FUNC_ARG;
4748
        }
4749
4750
        /* cast so that compiler reminds us of unimplemented values */
4751
        switch((enum wc_MACAlgorithm)hashType) {
4752
        case no_mac:
4753
        case rmd_mac: /* Don't have a RIPEMD type in wc_HashType */
4754
            *hashAlgo = WC_HASH_TYPE_NONE;
4755
            break;
4756
        case md5_mac:
4757
            *hashAlgo = WC_HASH_TYPE_MD5;
4758
            break;
4759
        case sha_mac:
4760
            *hashAlgo = WC_HASH_TYPE_SHA;
4761
            break;
4762
        case sha224_mac:
4763
            *hashAlgo = WC_HASH_TYPE_SHA224;
4764
            break;
4765
        case sha256_mac:
4766
            *hashAlgo = WC_HASH_TYPE_SHA256;
4767
            break;
4768
        case sha384_mac:
4769
            *hashAlgo = WC_HASH_TYPE_SHA384;
4770
            break;
4771
        case sha512_mac:
4772
            *hashAlgo = WC_HASH_TYPE_SHA512;
4773
            break;
4774
        case blake2b_mac:
4775
            *hashAlgo = WC_HASH_TYPE_BLAKE2B;
4776
            break;
4777
        case sm3_mac:
4778
#ifdef WOLFSSL_SM3
4779
            *hashAlgo = WC_HASH_TYPE_SM3;
4780
#else
4781
            *hashAlgo = WC_HASH_TYPE_NONE;
4782
#endif
4783
            break;
4784
        default:
4785
            *hashAlgo = WC_HASH_TYPE_NONE;
4786
            *sigAlgo = 0;
4787
            return BAD_FUNC_ARG;
4788
        }
4789
        return 0;
4790
    }
4791
#endif /* WOLFSSL_CERT_SETUP_CB */
4792
4793
#ifdef OPENSSL_EXTRA
4794
4795
    /* keyblock size in bytes or -1 */
4796
    int wolfSSL_get_keyblock_size(WOLFSSL* ssl)
4797
    {
4798
        if (ssl == NULL)
4799
            return WOLFSSL_FATAL_ERROR;
4800
4801
        return 2 * (ssl->specs.key_size + ssl->specs.iv_size +
4802
                    ssl->specs.hash_size);
4803
    }
4804
4805
#endif /* OPENSSL_EXTRA */
4806
4807
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EXTRA) || \
4808
    defined(WOLFSSL_WPAS_SMALL)
4809
4810
    /* store keys returns WOLFSSL_SUCCESS or -1 on error */
4811
    int wolfSSL_get_keys(WOLFSSL* ssl, unsigned char** ms, unsigned int* msLen,
4812
                                     unsigned char** sr, unsigned int* srLen,
4813
                                     unsigned char** cr, unsigned int* crLen)
4814
    {
4815
        if (ssl == NULL || ssl->arrays == NULL)
4816
            return WOLFSSL_FATAL_ERROR;
4817
4818
        *ms = ssl->arrays->masterSecret;
4819
        *sr = ssl->arrays->serverRandom;
4820
        *cr = ssl->arrays->clientRandom;
4821
4822
        *msLen = SECRET_LEN;
4823
        *srLen = RAN_LEN;
4824
        *crLen = RAN_LEN;
4825
4826
        return WOLFSSL_SUCCESS;
4827
    }
4828
4829
4830
#endif /* OPENSSL_EXTRA || WOLFSSL_EXTRA || WOLFSSL_WPAS_SMALL */
4831
4832
4833
#ifdef OPENSSL_EXTRA
4834
    void wolfSSL_CTX_set_tmp_rsa_callback(WOLFSSL_CTX* ctx,
4835
                                      WOLFSSL_RSA*(*f)(WOLFSSL*, int, int))
4836
    {
4837
        /* wolfSSL verifies all these internally */
4838
        (void)ctx;
4839
        (void)f;
4840
    }
4841
4842
4843
    void wolfSSL_set_shutdown(WOLFSSL* ssl, int opt)
4844
    {
4845
        WOLFSSL_ENTER("wolfSSL_set_shutdown");
4846
        if(ssl==NULL) {
4847
            WOLFSSL_MSG("Shutdown not set. ssl is null");
4848
            return;
4849
        }
4850
4851
        ssl->options.sentNotify =  (opt&WOLFSSL_SENT_SHUTDOWN) > 0;
4852
        ssl->options.closeNotify = (opt&WOLFSSL_RECEIVED_SHUTDOWN) > 0;
4853
    }
4854
#endif
4855
4856
    long wolfSSL_CTX_get_options(WOLFSSL_CTX* ctx)
4857
0
    {
4858
0
        WOLFSSL_ENTER("wolfSSL_CTX_get_options");
4859
0
        WOLFSSL_MSG("wolfSSL options are set through API calls and macros");
4860
0
        if(ctx == NULL)
4861
0
            return BAD_FUNC_ARG;
4862
0
        return (long)ctx->mask;
4863
0
    }
4864
4865
    /* forward declaration */
4866
    static long wolf_set_options(long old_op, long op);
4867
4868
    long wolfSSL_CTX_set_options(WOLFSSL_CTX* ctx, long opt)
4869
0
    {
4870
0
        WOLFSSL_ENTER("wolfSSL_CTX_set_options");
4871
4872
0
        if (ctx == NULL)
4873
0
            return BAD_FUNC_ARG;
4874
4875
0
        ctx->mask = (unsigned long)wolf_set_options((long)ctx->mask, opt);
4876
#if defined(HAVE_SESSION_TICKET) && (defined(OPENSSL_EXTRA) \
4877
        || defined(HAVE_WEBSERVER) || defined(WOLFSSL_WPAS_SMALL))
4878
        if ((ctx->mask & WOLFSSL_OP_NO_TICKET) == WOLFSSL_OP_NO_TICKET) {
4879
          ctx->noTicketTls12 = 1;
4880
        }
4881
        /* This code is here for documentation purpose. You must not turn off
4882
         * session tickets with the WOLFSSL_OP_NO_TICKET option for TLSv1.3.
4883
         * Because we need to support both stateful and stateless tickets.
4884
        #ifdef WOLFSSL_TLS13
4885
            if ((ctx->mask & WOLFSSL_OP_NO_TICKET) == WOLFSSL_OP_NO_TICKET) {
4886
                ctx->noTicketTls13 = 1;
4887
            }
4888
        #endif
4889
        */
4890
#endif
4891
0
        return (long)ctx->mask;
4892
0
    }
4893
4894
    long wolfSSL_CTX_clear_options(WOLFSSL_CTX* ctx, long opt)
4895
0
    {
4896
0
        WOLFSSL_ENTER("wolfSSL_CTX_clear_options");
4897
0
        if(ctx == NULL)
4898
0
            return BAD_FUNC_ARG;
4899
0
        ctx->mask &= (unsigned long)~opt;
4900
0
        return (long)ctx->mask;
4901
0
    }
4902
4903
#ifdef OPENSSL_EXTRA
4904
4905
    int wolfSSL_set_rfd(WOLFSSL* ssl, int rfd)
4906
    {
4907
        WOLFSSL_ENTER("wolfSSL_set_rfd");
4908
        return wolfSSL_set_read_fd(ssl, rfd);
4909
    }
4910
4911
4912
    int wolfSSL_set_wfd(WOLFSSL* ssl, int wfd)
4913
    {
4914
        WOLFSSL_ENTER("wolfSSL_set_wfd");
4915
        return wolfSSL_set_write_fd(ssl, wfd);
4916
    }
4917
#endif /* OPENSSL_EXTRA */
4918
4919
#ifdef WOLFSSL_ENCRYPTED_KEYS
4920
4921
    void wolfSSL_CTX_set_default_passwd_cb_userdata(WOLFSSL_CTX* ctx,
4922
                                                   void* userdata)
4923
    {
4924
        WOLFSSL_ENTER("wolfSSL_CTX_set_default_passwd_cb_userdata");
4925
        if (ctx)
4926
            ctx->passwd_userdata = userdata;
4927
    }
4928
4929
4930
    void wolfSSL_CTX_set_default_passwd_cb(WOLFSSL_CTX* ctx, wc_pem_password_cb*
4931
                                           cb)
4932
    {
4933
        WOLFSSL_ENTER("wolfSSL_CTX_set_default_passwd_cb");
4934
        if (ctx)
4935
            ctx->passwd_cb = cb;
4936
    }
4937
4938
    wc_pem_password_cb* wolfSSL_CTX_get_default_passwd_cb(WOLFSSL_CTX *ctx)
4939
    {
4940
        if (ctx == NULL || ctx->passwd_cb == NULL) {
4941
            return NULL;
4942
        }
4943
4944
        return ctx->passwd_cb;
4945
    }
4946
4947
4948
    void* wolfSSL_CTX_get_default_passwd_cb_userdata(WOLFSSL_CTX *ctx)
4949
    {
4950
        if (ctx == NULL) {
4951
            return NULL;
4952
        }
4953
4954
        return ctx->passwd_userdata;
4955
    }
4956
4957
#endif /* WOLFSSL_ENCRYPTED_KEYS */
4958
4959
4960
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || defined(HAVE_MEMCACHED)
4961
#endif
4962
4963
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
4964
4965
    int wolfSSL_num_locks(void)
4966
    {
4967
        return 0;
4968
    }
4969
4970
    void wolfSSL_set_locking_callback(mutex_cb* f)
4971
    {
4972
        WOLFSSL_ENTER("wolfSSL_set_locking_callback");
4973
4974
        if (wc_SetMutexCb(f) != 0) {
4975
            WOLFSSL_MSG("Error when setting mutex call back");
4976
        }
4977
    }
4978
4979
    mutex_cb* wolfSSL_get_locking_callback(void)
4980
    {
4981
        WOLFSSL_ENTER("wolfSSL_get_locking_callback");
4982
4983
        return wc_GetMutexCb();
4984
    }
4985
4986
4987
    typedef unsigned long (idCb)(void);
4988
    static idCb* inner_idCb = NULL;
4989
4990
    unsigned long wolfSSL_thread_id(void)
4991
    {
4992
        if (inner_idCb != NULL) {
4993
            return inner_idCb();
4994
        }
4995
        else {
4996
            return 0;
4997
        }
4998
    }
4999
5000
5001
    void wolfSSL_set_id_callback(unsigned long (*f)(void))
5002
    {
5003
        inner_idCb = f;
5004
    }
5005
5006
#ifdef WOLFSSL_HAVE_ERROR_QUEUE
5007
#ifndef NO_BIO
5008
    /* print out and clear all errors */
5009
#endif /* !NO_BIO */
5010
#endif /* WOLFSSL_HAVE_ERROR_QUEUE */
5011
5012
#endif /* OPENSSL_EXTRA || HAVE_WEBSERVER */
5013
5014
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || \
5015
    defined(HAVE_SECRET_CALLBACK)
5016
#if !defined(NO_WOLFSSL_SERVER)
5017
/* Return the amount of random bytes copied over or error case.
5018
 * ssl : ssl struct after handshake
5019
 * out : buffer to hold random bytes
5020
 * outSz : either 0 (return max buffer sz) or size of out buffer
5021
 */
5022
size_t wolfSSL_get_server_random(const WOLFSSL *ssl, unsigned char *out,
5023
                                                                   size_t outSz)
5024
{
5025
    size_t size;
5026
5027
    /* return max size of buffer */
5028
    if (outSz == 0) {
5029
        return RAN_LEN;
5030
    }
5031
5032
    if (ssl == NULL || out == NULL) {
5033
        return 0;
5034
    }
5035
5036
    if (ssl->arrays == NULL) {
5037
        WOLFSSL_MSG("Arrays struct not saved after handshake");
5038
        return 0;
5039
    }
5040
5041
    if (outSz > RAN_LEN) {
5042
        size = RAN_LEN;
5043
    }
5044
    else {
5045
        size = outSz;
5046
    }
5047
5048
    XMEMCPY(out, ssl->arrays->serverRandom, size);
5049
    return size;
5050
}
5051
#endif /* !NO_WOLFSSL_SERVER */
5052
#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL || HAVE_SECRET_CALLBACK */
5053
5054
#ifdef OPENSSL_EXTRA
5055
#if !defined(NO_WOLFSSL_SERVER)
5056
/* Used to get the peer ephemeral public key sent during the connection
5057
 * NOTE: currently wolfSSL_KeepHandshakeResources(WOLFSSL* ssl) must be called
5058
 *       before the ephemeral key is stored.
5059
 * return WOLFSSL_SUCCESS on success */
5060
int wolfSSL_get_peer_tmp_key(const WOLFSSL* ssl, WOLFSSL_EVP_PKEY** pkey)
5061
{
5062
    WOLFSSL_EVP_PKEY* ret = NULL;
5063
5064
    WOLFSSL_ENTER("wolfSSL_get_server_tmp_key");
5065
5066
    if (ssl == NULL || pkey == NULL) {
5067
        WOLFSSL_MSG("Bad argument passed in");
5068
        return WOLFSSL_FAILURE;
5069
    }
5070
5071
    /* Clear up front: the per-curve export failures below return early, and a
5072
     * caller reusing one variable across calls must not see a stale pointer. */
5073
    *pkey = NULL;
5074
5075
#ifdef HAVE_ECC
5076
    /* Keys kept for this call outlive the connection they came from, so pick
5077
     * the one the current key exchange used rather than the first one set. */
5078
    if ((ssl->peerEccKey != NULL) && ssl->peerEccKeyPresent
5079
#ifdef HAVE_CURVE25519
5080
        && (ssl->ecdhCurveOID != ECC_X25519_OID)
5081
#endif
5082
#ifdef HAVE_CURVE448
5083
        && (ssl->ecdhCurveOID != ECC_X448_OID)
5084
#endif
5085
        ) {
5086
        unsigned char* der;
5087
        const unsigned char* pt;
5088
        unsigned int   derSz = 0;
5089
        int sz;
5090
5091
        PRIVATE_KEY_UNLOCK();
5092
        if (wc_ecc_export_x963(ssl->peerEccKey, NULL, &derSz)
5093
              != WC_NO_ERR_TRACE(LENGTH_ONLY_E))
5094
        {
5095
            WOLFSSL_MSG("get ecc der size failed");
5096
            PRIVATE_KEY_LOCK();
5097
            return WOLFSSL_FAILURE;
5098
        }
5099
        PRIVATE_KEY_LOCK();
5100
5101
        derSz += MAX_SEQ_SZ + (2 * MAX_ALGO_SZ) + MAX_SEQ_SZ + TRAILING_ZERO;
5102
        der = (unsigned char*)XMALLOC(derSz, ssl->heap, DYNAMIC_TYPE_KEY);
5103
        if (der == NULL) {
5104
            WOLFSSL_MSG("Memory error");
5105
            return WOLFSSL_FAILURE;
5106
        }
5107
5108
        if ((sz = wc_EccPublicKeyToDer(ssl->peerEccKey, der, derSz, 1)) <= 0) {
5109
            WOLFSSL_MSG("get ecc der failed");
5110
            XFREE(der, ssl->heap, DYNAMIC_TYPE_KEY);
5111
            return WOLFSSL_FAILURE;
5112
        }
5113
        pt = der; /* in case pointer gets advanced */
5114
        ret = wolfSSL_d2i_PUBKEY(NULL, &pt, sz);
5115
        XFREE(der, ssl->heap, DYNAMIC_TYPE_KEY);
5116
    }
5117
#endif
5118
5119
#ifdef HAVE_CURVE25519
5120
    if ((ret == NULL) && (ssl->ecdhCurveOID == ECC_X25519_OID) &&
5121
            (ssl->peerX25519Key != NULL) && ssl->peerX25519KeyPresent) {
5122
        byte pub[CURVE25519_PUB_KEY_SIZE];
5123
        word32 pubSz = (word32)sizeof(pub);
5124
5125
        /* Raw X25519 keys are little-endian (RFC 7748). */
5126
        if (wc_curve25519_export_public_ex(ssl->peerX25519Key, pub, &pubSz,
5127
                EC25519_LITTLE_ENDIAN) != 0) {
5128
            WOLFSSL_MSG("get curve25519 public key failed");
5129
            return WOLFSSL_FAILURE;
5130
        }
5131
        ret = wolfSSL_EVP_PKEY_new_raw_public_key(WC_EVP_PKEY_X25519, NULL,
5132
            pub, (size_t)pubSz);
5133
    }
5134
#endif
5135
5136
#ifdef HAVE_CURVE448
5137
    if ((ret == NULL) && (ssl->ecdhCurveOID == ECC_X448_OID) &&
5138
            (ssl->peerX448Key != NULL) && ssl->peerX448KeyPresent) {
5139
        byte pub[CURVE448_PUB_KEY_SIZE];
5140
        word32 pubSz = (word32)sizeof(pub);
5141
5142
        /* Raw X448 keys are little-endian (RFC 7748). */
5143
        if (wc_curve448_export_public_ex(ssl->peerX448Key, pub, &pubSz,
5144
                EC448_LITTLE_ENDIAN) != 0) {
5145
            WOLFSSL_MSG("get curve448 public key failed");
5146
            return WOLFSSL_FAILURE;
5147
        }
5148
        ret = wolfSSL_EVP_PKEY_new_raw_public_key(WC_EVP_PKEY_X448, NULL,
5149
            pub, (size_t)pubSz);
5150
    }
5151
#endif
5152
5153
    *pkey = ret;
5154
5155
    return (ret != NULL) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
5156
}
5157
5158
#endif /* !NO_WOLFSSL_SERVER */
5159
5160
/**
5161
 * This function checks if any compiled in protocol versions are
5162
 * left enabled after calls to set_min or set_max API.
5163
 * @param major The SSL/TLS major version
5164
 * @return WOLFSSL_SUCCESS on valid settings and WOLFSSL_FAILURE when no
5165
 *         protocol versions are left enabled.
5166
 */
5167
static int CheckSslMethodVersion(byte major, unsigned long options)
5168
{
5169
    int sanityConfirmed = 0;
5170
5171
    (void)options;
5172
5173
    switch (major) {
5174
    #ifndef NO_TLS
5175
        case SSLv3_MAJOR:
5176
            #ifdef WOLFSSL_ALLOW_SSLV3
5177
                if (!(options & WOLFSSL_OP_NO_SSLv3)) {
5178
                    sanityConfirmed = 1;
5179
                }
5180
            #endif
5181
            #ifndef NO_OLD_TLS
5182
                if (!(options & WOLFSSL_OP_NO_TLSv1))
5183
                    sanityConfirmed = 1;
5184
                if (!(options & WOLFSSL_OP_NO_TLSv1_1))
5185
                    sanityConfirmed = 1;
5186
            #endif
5187
            #ifndef WOLFSSL_NO_TLS12
5188
                if (!(options & WOLFSSL_OP_NO_TLSv1_2))
5189
                    sanityConfirmed = 1;
5190
            #endif
5191
            #ifdef WOLFSSL_TLS13
5192
                if (!(options & WOLFSSL_OP_NO_TLSv1_3))
5193
                    sanityConfirmed = 1;
5194
            #endif
5195
            break;
5196
    #endif
5197
    #ifdef WOLFSSL_DTLS
5198
        case DTLS_MAJOR:
5199
            sanityConfirmed = 1;
5200
            break;
5201
    #endif
5202
        default:
5203
            WOLFSSL_MSG("Invalid major version");
5204
            return WOLFSSL_FAILURE;
5205
    }
5206
    if (!sanityConfirmed) {
5207
        WOLFSSL_MSG("All compiled in TLS versions disabled");
5208
        return WOLFSSL_FAILURE;
5209
    }
5210
    return WOLFSSL_SUCCESS;
5211
}
5212
5213
/**
5214
 * protoVerTbl holds (D)TLS version numbers in ascending order.
5215
 * Except DTLS versions, the newer version is located in the latter part of
5216
 * the table. This table is referred by wolfSSL_CTX_set_min_proto_version and
5217
 * wolfSSL_CTX_set_max_proto_version.
5218
 */
5219
static const int protoVerTbl[] = {
5220
    SSL3_VERSION,
5221
    TLS1_VERSION,
5222
    TLS1_1_VERSION,
5223
    TLS1_2_VERSION,
5224
    TLS1_3_VERSION,
5225
    DTLS1_VERSION,
5226
    DTLS1_2_VERSION
5227
};
5228
/* number of protocol versions listed in protoVerTbl */
5229
#define NUMBER_OF_PROTOCOLS (sizeof(protoVerTbl)/sizeof(int))
5230
5231
/**
5232
 * wolfSSL_CTX_set_min_proto_version attempts to set the minimum protocol
5233
 * version to use by SSL objects created from this WOLFSSL_CTX.
5234
 * This API guarantees that a version of SSL/TLS lower than specified
5235
 * here will not be allowed. If the version specified is not compiled in
5236
 * then this API sets the lowest compiled in protocol version.
5237
 * This API also accept 0 as version, to set the minimum version automatically.
5238
 * CheckSslMethodVersion() is called to check if any remaining protocol versions
5239
 * are enabled.
5240
 * @param ctx The wolfSSL CONTEXT factory for spawning SSL/TLS objects
5241
 * @param version Any of the following
5242
 *          * 0
5243
 *          * SSL3_VERSION
5244
 *          * TLS1_VERSION
5245
 *          * TLS1_1_VERSION
5246
 *          * TLS1_2_VERSION
5247
 *          * TLS1_3_VERSION
5248
 *          * DTLS1_VERSION
5249
 *          * DTLS1_2_VERSION
5250
 * @return WOLFSSL_SUCCESS on valid settings and WOLFSSL_FAILURE when no
5251
 *         protocol versions are left enabled.
5252
 */
5253
static int Set_CTX_min_proto_version(WOLFSSL_CTX* ctx, int version)
5254
{
5255
    WOLFSSL_ENTER("wolfSSL_CTX_set_min_proto_version_ex");
5256
5257
    if (ctx == NULL) {
5258
        return WOLFSSL_FAILURE;
5259
    }
5260
5261
    switch (version) {
5262
#ifndef NO_TLS
5263
        case SSL3_VERSION:
5264
#if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
5265
            ctx->minDowngrade = SSLv3_MINOR;
5266
            break;
5267
#endif
5268
        case TLS1_VERSION:
5269
        #ifdef WOLFSSL_ALLOW_TLSV10
5270
            ctx->minDowngrade = TLSv1_MINOR;
5271
            break;
5272
        #endif
5273
        case TLS1_1_VERSION:
5274
        #ifndef NO_OLD_TLS
5275
            ctx->minDowngrade = TLSv1_1_MINOR;
5276
            break;
5277
        #endif
5278
        case TLS1_2_VERSION:
5279
        #ifndef WOLFSSL_NO_TLS12
5280
            ctx->minDowngrade = TLSv1_2_MINOR;
5281
            break;
5282
        #endif
5283
        case TLS1_3_VERSION:
5284
        #ifdef WOLFSSL_TLS13
5285
            ctx->minDowngrade = TLSv1_3_MINOR;
5286
            break;
5287
        #endif
5288
#endif
5289
#ifdef WOLFSSL_DTLS
5290
        case DTLS1_VERSION:
5291
    #ifndef NO_OLD_TLS
5292
            ctx->minDowngrade = DTLS_MINOR;
5293
            break;
5294
    #endif
5295
        case DTLS1_2_VERSION:
5296
            ctx->minDowngrade = DTLSv1_2_MINOR;
5297
            break;
5298
#endif
5299
        default:
5300
            WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
5301
            return WOLFSSL_FAILURE;
5302
    }
5303
5304
    switch (version) {
5305
#ifndef NO_TLS
5306
    case TLS1_3_VERSION:
5307
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_2);
5308
        FALL_THROUGH;
5309
    case TLS1_2_VERSION:
5310
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_1);
5311
        FALL_THROUGH;
5312
    case TLS1_1_VERSION:
5313
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1);
5314
        FALL_THROUGH;
5315
    case TLS1_VERSION:
5316
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_SSLv3);
5317
        break;
5318
    case SSL3_VERSION:
5319
    case SSL2_VERSION:
5320
        /* Nothing to do here */
5321
        break;
5322
#endif
5323
#ifdef WOLFSSL_DTLS
5324
    case DTLS1_VERSION:
5325
    case DTLS1_2_VERSION:
5326
        break;
5327
#endif
5328
    default:
5329
        WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
5330
        return WOLFSSL_FAILURE;
5331
    }
5332
5333
    return CheckSslMethodVersion(ctx->method->version.major, ctx->mask);
5334
}
5335
5336
/* Sets the min protocol version allowed with WOLFSSL_CTX
5337
 * returns WOLFSSL_SUCCESS on success */
5338
int wolfSSL_CTX_set_min_proto_version(WOLFSSL_CTX* ctx, int version)
5339
{
5340
    int ret;
5341
    int proto    = 0;
5342
    int maxProto = 0;
5343
    int i;
5344
    int idx = 0;
5345
5346
    WOLFSSL_ENTER("wolfSSL_CTX_set_min_proto_version");
5347
5348
    if (ctx == NULL) {
5349
        return WOLFSSL_FAILURE;
5350
    }
5351
5352
    if (version != 0) {
5353
        proto = version;
5354
        ctx->minProto = 0; /* turn min proto flag off */
5355
        for (i = 0; (unsigned)i < NUMBER_OF_PROTOCOLS; i++) {
5356
            if (protoVerTbl[i] == version) {
5357
                break;
5358
            }
5359
        }
5360
    }
5361
    else {
5362
        /* when 0 is specified as version, try to find out the min version */
5363
        for (i = 0; (unsigned)i < NUMBER_OF_PROTOCOLS; i++) {
5364
            ret = Set_CTX_min_proto_version(ctx, protoVerTbl[i]);
5365
            if (ret == WOLFSSL_SUCCESS) {
5366
                proto = protoVerTbl[i];
5367
                ctx->minProto = 1; /* turn min proto flag on */
5368
                break;
5369
            }
5370
        }
5371
    }
5372
5373
    /* check case where max > min , if so then clear the NO_* options
5374
     * i is the index into the table for proto version used, see if the max
5375
     * proto version index found is smaller */
5376
    maxProto = wolfSSL_CTX_get_max_proto_version(ctx);
5377
    for (idx = 0; (unsigned)idx < NUMBER_OF_PROTOCOLS; idx++) {
5378
        if (protoVerTbl[idx] == maxProto) {
5379
            break;
5380
        }
5381
    }
5382
    if (idx < i) {
5383
        wolfSSL_CTX_clear_options(ctx, WOLFSSL_OP_NO_TLSv1 |
5384
                WOLFSSL_OP_NO_TLSv1_1 | WOLFSSL_OP_NO_TLSv1_2 |
5385
                WOLFSSL_OP_NO_TLSv1_3);
5386
    }
5387
5388
    ret = Set_CTX_min_proto_version(ctx, proto);
5389
    if (ret == WOLFSSL_SUCCESS) {
5390
        /* Version 0 picks the lowest, so the user set no minimum */
5391
        ctx->minVersionSet = (version != 0);
5392
    }
5393
5394
    return ret;
5395
}
5396
5397
/**
5398
 * wolfSSL_CTX_set_max_proto_version attempts to set the maximum protocol
5399
 * version to use by SSL objects created from this WOLFSSL_CTX.
5400
 * This API guarantees that a version of SSL/TLS higher than specified
5401
 * here will not be allowed. If the version specified is not compiled in
5402
 * then this API sets the highest compiled in protocol version.
5403
 * This API also accept 0 as version, to set the maximum version automatically.
5404
 * CheckSslMethodVersion() is called to check if any remaining protocol versions
5405
 * are enabled.
5406
 * @param ctx The wolfSSL CONTEXT factory for spawning SSL/TLS objects
5407
 * @param ver Any of the following
5408
 *          * 0
5409
 *          * SSL3_VERSION
5410
 *          * TLS1_VERSION
5411
 *          * TLS1_1_VERSION
5412
 *          * TLS1_2_VERSION
5413
 *          * TLS1_3_VERSION
5414
 *          * DTLS1_VERSION
5415
 *          * DTLS1_2_VERSION
5416
 * @return WOLFSSL_SUCCESS on valid settings and WOLFSSL_FAILURE when no
5417
 *         protocol versions are left enabled.
5418
 */
5419
static int Set_CTX_max_proto_version(WOLFSSL_CTX* ctx, int ver)
5420
{
5421
    int ret;
5422
    WOLFSSL_ENTER("Set_CTX_max_proto_version");
5423
5424
    if (!ctx || !ctx->method) {
5425
        WOLFSSL_MSG("Bad parameter");
5426
        return WOLFSSL_FAILURE;
5427
    }
5428
5429
    switch (ver) {
5430
#ifndef NO_TLS
5431
#ifndef NO_OLD_TLS
5432
    case SSL2_VERSION:
5433
        WOLFSSL_MSG("wolfSSL does not support SSLv2");
5434
        return WOLFSSL_FAILURE;
5435
#endif
5436
    case SSL3_VERSION:
5437
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1);
5438
        FALL_THROUGH;
5439
    case TLS1_VERSION:
5440
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_1);
5441
        FALL_THROUGH;
5442
    case TLS1_1_VERSION:
5443
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_2);
5444
        FALL_THROUGH;
5445
    case TLS1_2_VERSION:
5446
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_3);
5447
        FALL_THROUGH;
5448
    case TLS1_3_VERSION:
5449
        /* Nothing to do here */
5450
        break;
5451
#endif
5452
#ifdef WOLFSSL_DTLS
5453
    case DTLS1_VERSION:
5454
    case DTLS1_2_VERSION:
5455
        break;
5456
#endif
5457
    default:
5458
        WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
5459
        return WOLFSSL_FAILURE;
5460
    }
5461
5462
    ret = CheckSslMethodVersion(ctx->method->version.major, ctx->mask);
5463
    if (ret == WOLFSSL_SUCCESS) {
5464
        /* Check the major */
5465
        switch (ver) {
5466
    #ifndef NO_TLS
5467
        case SSL3_VERSION:
5468
        case TLS1_VERSION:
5469
        case TLS1_1_VERSION:
5470
        case TLS1_2_VERSION:
5471
        case TLS1_3_VERSION:
5472
            if (ctx->method->version.major != SSLv3_MAJOR) {
5473
                WOLFSSL_MSG("Mismatched protocol version");
5474
                return WOLFSSL_FAILURE;
5475
            }
5476
            break;
5477
    #endif
5478
    #ifdef WOLFSSL_DTLS
5479
        case DTLS1_VERSION:
5480
        case DTLS1_2_VERSION:
5481
            if (ctx->method->version.major != DTLS_MAJOR) {
5482
                WOLFSSL_MSG("Mismatched protocol version");
5483
                return WOLFSSL_FAILURE;
5484
            }
5485
            break;
5486
    #endif
5487
        }
5488
        /* Update the method */
5489
        switch (ver) {
5490
    #ifndef NO_TLS
5491
        case SSL3_VERSION:
5492
            ctx->method->version.minor = SSLv3_MINOR;
5493
            break;
5494
        case TLS1_VERSION:
5495
            ctx->method->version.minor = TLSv1_MINOR;
5496
            break;
5497
        case TLS1_1_VERSION:
5498
            ctx->method->version.minor = TLSv1_1_MINOR;
5499
            break;
5500
        case TLS1_2_VERSION:
5501
            ctx->method->version.minor = TLSv1_2_MINOR;
5502
            break;
5503
        case TLS1_3_VERSION:
5504
            ctx->method->version.minor = TLSv1_3_MINOR;
5505
            break;
5506
    #endif
5507
    #ifdef WOLFSSL_DTLS
5508
        case DTLS1_VERSION:
5509
            ctx->method->version.minor = DTLS_MINOR;
5510
            break;
5511
        case DTLS1_2_VERSION:
5512
            ctx->method->version.minor = DTLSv1_2_MINOR;
5513
            break;
5514
    #endif
5515
        default:
5516
            WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
5517
            return WOLFSSL_FAILURE;
5518
        }
5519
    }
5520
    return ret;
5521
}
5522
5523
5524
/* Sets the max protocol version allowed with WOLFSSL_CTX
5525
 * returns WOLFSSL_SUCCESS on success */
5526
int wolfSSL_CTX_set_max_proto_version(WOLFSSL_CTX* ctx, int version)
5527
{
5528
    int i;
5529
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
5530
    int minProto;
5531
    byte minVersionSet;
5532
5533
    WOLFSSL_ENTER("wolfSSL_CTX_set_max_proto_version");
5534
5535
    if (ctx == NULL) {
5536
        return ret;
5537
    }
5538
5539
    /* clear out flags and reset min protocol version */
5540
    minProto = wolfSSL_CTX_get_min_proto_version(ctx);
5541
    wolfSSL_CTX_clear_options(ctx,
5542
            WOLFSSL_OP_NO_TLSv1 | WOLFSSL_OP_NO_TLSv1_1 |
5543
            WOLFSSL_OP_NO_TLSv1_2 | WOLFSSL_OP_NO_TLSv1_3);
5544
    minVersionSet = ctx->minVersionSet;
5545
    wolfSSL_CTX_set_min_proto_version(ctx, minProto);
5546
    ctx->minVersionSet = minVersionSet; /* restoring, not setting, a minimum */
5547
    if (version != 0) {
5548
        ctx->maxProto = 0; /* turn max proto flag off */
5549
        return Set_CTX_max_proto_version(ctx, version);
5550
    }
5551
5552
    /* when 0 is specified as version, try to find out the min version from
5553
     * the bottom to top of the protoverTbl.
5554
     */
5555
    for (i = NUMBER_OF_PROTOCOLS -1; i >= 0; i--) {
5556
        ret = Set_CTX_max_proto_version(ctx, protoVerTbl[i]);
5557
        if (ret == WOLFSSL_SUCCESS) {
5558
            ctx->maxProto = 1; /* turn max proto flag on */
5559
            break;
5560
        }
5561
    }
5562
5563
    return ret;
5564
}
5565
5566
5567
static int Set_SSL_min_proto_version(WOLFSSL* ssl, int ver)
5568
{
5569
    WOLFSSL_ENTER("Set_SSL_min_proto_version");
5570
5571
    if (ssl == NULL) {
5572
        return WOLFSSL_FAILURE;
5573
    }
5574
5575
    switch (ver) {
5576
#ifndef NO_TLS
5577
        case SSL3_VERSION:
5578
#if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
5579
            ssl->options.minDowngrade = SSLv3_MINOR;
5580
            break;
5581
#endif
5582
        case TLS1_VERSION:
5583
        #ifdef WOLFSSL_ALLOW_TLSV10
5584
            ssl->options.minDowngrade = TLSv1_MINOR;
5585
            break;
5586
        #endif
5587
        case TLS1_1_VERSION:
5588
        #ifndef NO_OLD_TLS
5589
            ssl->options.minDowngrade = TLSv1_1_MINOR;
5590
            break;
5591
        #endif
5592
        case TLS1_2_VERSION:
5593
        #ifndef WOLFSSL_NO_TLS12
5594
            ssl->options.minDowngrade = TLSv1_2_MINOR;
5595
            break;
5596
        #endif
5597
        case TLS1_3_VERSION:
5598
        #ifdef WOLFSSL_TLS13
5599
            ssl->options.minDowngrade = TLSv1_3_MINOR;
5600
            break;
5601
        #endif
5602
#endif
5603
#ifdef WOLFSSL_DTLS
5604
        case DTLS1_VERSION:
5605
    #ifndef NO_OLD_TLS
5606
            ssl->options.minDowngrade = DTLS_MINOR;
5607
            break;
5608
    #endif
5609
        case DTLS1_2_VERSION:
5610
            ssl->options.minDowngrade = DTLSv1_2_MINOR;
5611
            break;
5612
#endif
5613
        default:
5614
            WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
5615
            return WOLFSSL_FAILURE;
5616
    }
5617
5618
    switch (ver) {
5619
#ifndef NO_TLS
5620
    case TLS1_3_VERSION:
5621
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_2;
5622
        FALL_THROUGH;
5623
    case TLS1_2_VERSION:
5624
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_1;
5625
        FALL_THROUGH;
5626
    case TLS1_1_VERSION:
5627
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1;
5628
        FALL_THROUGH;
5629
    case TLS1_VERSION:
5630
        ssl->options.mask |= WOLFSSL_OP_NO_SSLv3;
5631
        break;
5632
    case SSL3_VERSION:
5633
    case SSL2_VERSION:
5634
        /* Nothing to do here */
5635
        break;
5636
#endif
5637
#ifdef WOLFSSL_DTLS
5638
    case DTLS1_VERSION:
5639
    case DTLS1_2_VERSION:
5640
        break;
5641
#endif
5642
    default:
5643
        WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
5644
        return WOLFSSL_FAILURE;
5645
    }
5646
5647
    return CheckSslMethodVersion(ssl->version.major, ssl->options.mask);
5648
}
5649
5650
int wolfSSL_set_min_proto_version(WOLFSSL* ssl, int version)
5651
{
5652
    int i;
5653
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);;
5654
5655
    WOLFSSL_ENTER("wolfSSL_set_min_proto_version");
5656
5657
    if (ssl == NULL) {
5658
        return WOLFSSL_FAILURE;
5659
    }
5660
    if (version != 0) {
5661
        ret = Set_SSL_min_proto_version(ssl, version);
5662
    }
5663
    else {
5664
        /* when 0 is specified as version, try to find out the min version */
5665
        for (i= 0; (unsigned)i < NUMBER_OF_PROTOCOLS; i++) {
5666
            ret = Set_SSL_min_proto_version(ssl, protoVerTbl[i]);
5667
            if (ret == WOLFSSL_SUCCESS)
5668
                break;
5669
        }
5670
    }
5671
5672
    if (ret == WOLFSSL_SUCCESS) {
5673
        /* Version 0 picks the lowest, so the user set no minimum */
5674
        ssl->options.minVersionSet = (version != 0);
5675
        RestoreDowngrade(ssl);
5676
    }
5677
5678
    return ret;
5679
}
5680
5681
static int Set_SSL_max_proto_version(WOLFSSL* ssl, int ver)
5682
{
5683
5684
    WOLFSSL_ENTER("Set_SSL_max_proto_version");
5685
5686
    if (!ssl) {
5687
        WOLFSSL_MSG("Bad parameter");
5688
        return WOLFSSL_FAILURE;
5689
    }
5690
5691
    switch (ver) {
5692
    case SSL2_VERSION:
5693
        WOLFSSL_MSG("wolfSSL does not support SSLv2");
5694
        return WOLFSSL_FAILURE;
5695
#ifndef NO_TLS
5696
    case SSL3_VERSION:
5697
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1;
5698
        FALL_THROUGH;
5699
    case TLS1_VERSION:
5700
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_1;
5701
        FALL_THROUGH;
5702
    case TLS1_1_VERSION:
5703
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_2;
5704
        FALL_THROUGH;
5705
    case TLS1_2_VERSION:
5706
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_3;
5707
        FALL_THROUGH;
5708
    case TLS1_3_VERSION:
5709
        /* Nothing to do here */
5710
        break;
5711
#endif
5712
#ifdef WOLFSSL_DTLS
5713
    case DTLS1_VERSION:
5714
    case DTLS1_2_VERSION:
5715
        break;
5716
#endif
5717
    default:
5718
        WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
5719
        return WOLFSSL_FAILURE;
5720
    }
5721
5722
    return CheckSslMethodVersion(ssl->version.major, ssl->options.mask);
5723
}
5724
5725
int wolfSSL_set_max_proto_version(WOLFSSL* ssl, int version)
5726
{
5727
    int i;
5728
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);;
5729
5730
    WOLFSSL_ENTER("wolfSSL_set_max_proto_version");
5731
5732
    if (ssl == NULL) {
5733
        return WOLFSSL_FAILURE;
5734
    }
5735
    if (version != 0) {
5736
        return Set_SSL_max_proto_version(ssl, version);
5737
    }
5738
5739
    /* when 0 is specified as version, try to find out the min version from
5740
     * the bottom to top of the protoverTbl.
5741
     */
5742
    for (i = NUMBER_OF_PROTOCOLS -1; i >= 0; i--) {
5743
        ret = Set_SSL_max_proto_version(ssl, protoVerTbl[i]);
5744
        if (ret == WOLFSSL_SUCCESS)
5745
            break;
5746
    }
5747
5748
    return ret;
5749
}
5750
5751
static int GetMinProtoVersion(int minDowngrade)
5752
{
5753
    int ret;
5754
5755
    switch (minDowngrade) {
5756
#ifndef NO_OLD_TLS
5757
    #ifdef WOLFSSL_ALLOW_SSLV3
5758
        case SSLv3_MINOR:
5759
            ret = SSL3_VERSION;
5760
            break;
5761
    #endif
5762
    #ifdef WOLFSSL_ALLOW_TLSV10
5763
        case TLSv1_MINOR:
5764
            ret = TLS1_VERSION;
5765
            break;
5766
    #endif
5767
        case TLSv1_1_MINOR:
5768
            ret = TLS1_1_VERSION;
5769
            break;
5770
#endif
5771
#ifndef WOLFSSL_NO_TLS12
5772
        case TLSv1_2_MINOR:
5773
            ret = TLS1_2_VERSION;
5774
            break;
5775
#endif
5776
#ifdef WOLFSSL_TLS13
5777
        case TLSv1_3_MINOR:
5778
            ret = TLS1_3_VERSION;
5779
            break;
5780
#endif
5781
        default:
5782
            ret = 0;
5783
            break;
5784
    }
5785
5786
    return ret;
5787
}
5788
5789
int wolfSSL_CTX_get_min_proto_version(WOLFSSL_CTX* ctx)
5790
{
5791
    int ret = 0;
5792
5793
    WOLFSSL_ENTER("wolfSSL_CTX_get_min_proto_version");
5794
5795
    if (ctx != NULL) {
5796
        if (ctx->minProto) {
5797
            ret = 0;
5798
        }
5799
        else {
5800
            ret = GetMinProtoVersion(ctx->minDowngrade);
5801
        }
5802
    }
5803
    else {
5804
        ret = GetMinProtoVersion(WOLFSSL_MIN_DOWNGRADE);
5805
    }
5806
5807
    WOLFSSL_LEAVE("wolfSSL_CTX_get_min_proto_version", ret);
5808
5809
    return ret;
5810
}
5811
5812
5813
/* returns the maximum allowed protocol version given the 'options' used
5814
 * returns WOLFSSL_FATAL_ERROR on no match */
5815
static int GetMaxProtoVersion(long options)
5816
{
5817
#ifndef NO_TLS
5818
#ifdef WOLFSSL_TLS13
5819
    if (!(options & WOLFSSL_OP_NO_TLSv1_3))
5820
        return TLS1_3_VERSION;
5821
#endif
5822
#ifndef WOLFSSL_NO_TLS12
5823
    if (!(options & WOLFSSL_OP_NO_TLSv1_2))
5824
        return TLS1_2_VERSION;
5825
#endif
5826
#ifndef NO_OLD_TLS
5827
    if (!(options & WOLFSSL_OP_NO_TLSv1_1))
5828
        return TLS1_1_VERSION;
5829
    #ifdef WOLFSSL_ALLOW_TLSV10
5830
    if (!(options & WOLFSSL_OP_NO_TLSv1))
5831
        return TLS1_VERSION;
5832
    #endif
5833
    #ifdef WOLFSSL_ALLOW_SSLV3
5834
    if (!(options & WOLFSSL_OP_NO_SSLv3))
5835
        return SSL3_VERSION;
5836
    #endif
5837
#endif
5838
#else
5839
    (void)options;
5840
#endif /* NO_TLS */
5841
    return WOLFSSL_FATAL_ERROR;
5842
}
5843
5844
5845
/* returns the maximum protocol version for 'ctx' */
5846
int wolfSSL_CTX_get_max_proto_version(WOLFSSL_CTX* ctx)
5847
{
5848
    int ret = 0;
5849
    long options = 0; /* default to nothing set */
5850
5851
    WOLFSSL_ENTER("wolfSSL_CTX_get_max_proto_version");
5852
5853
    if (ctx != NULL) {
5854
        options = wolfSSL_CTX_get_options(ctx);
5855
    }
5856
5857
    if ((ctx != NULL) && ctx->maxProto) {
5858
        ret = 0;
5859
    }
5860
    else {
5861
        ret = GetMaxProtoVersion(options);
5862
    }
5863
5864
    WOLFSSL_LEAVE("wolfSSL_CTX_get_max_proto_version", ret);
5865
5866
    if (ret == WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR)) {
5867
        WOLFSSL_MSG("Error getting max proto version");
5868
        ret = 0; /* setting ret to 0 to match compat return */
5869
    }
5870
    return ret;
5871
}
5872
#endif /* OPENSSL_EXTRA */
5873
5874
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || \
5875
    defined(HAVE_SECRET_CALLBACK)
5876
#if !defined(NO_WOLFSSL_CLIENT)
5877
/* Return the amount of random bytes copied over or error case.
5878
 * ssl : ssl struct after handshake
5879
 * out : buffer to hold random bytes
5880
 * outSz : either 0 (return max buffer sz) or size of out buffer
5881
 */
5882
size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out,
5883
                                                                   size_t outSz)
5884
{
5885
    size_t size;
5886
5887
    /* return max size of buffer */
5888
    if (outSz == 0) {
5889
        return RAN_LEN;
5890
    }
5891
5892
    if (ssl == NULL || out == NULL) {
5893
        return 0;
5894
    }
5895
5896
    if (ssl->arrays == NULL) {
5897
        WOLFSSL_MSG("Arrays struct not saved after handshake");
5898
        return 0;
5899
    }
5900
5901
    if (outSz > RAN_LEN) {
5902
        size = RAN_LEN;
5903
    }
5904
    else {
5905
        size = outSz;
5906
    }
5907
5908
    XMEMCPY(out, ssl->arrays->clientRandom, size);
5909
    return size;
5910
}
5911
#endif /* !NO_WOLFSSL_CLIENT */
5912
#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL || HAVE_SECRET_CALLBACK */
5913
5914
#ifdef OPENSSL_EXTRA
5915
5916
    unsigned long wolfSSLeay(void)
5917
    {
5918
#ifdef SSLEAY_VERSION_NUMBER
5919
        return SSLEAY_VERSION_NUMBER;
5920
#else
5921
        return OPENSSL_VERSION_NUMBER;
5922
#endif
5923
    }
5924
5925
    unsigned long wolfSSL_OpenSSL_version_num(void)
5926
    {
5927
        return OPENSSL_VERSION_NUMBER;
5928
    }
5929
5930
    const char* wolfSSLeay_version(int type)
5931
    {
5932
        return wolfSSL_OpenSSL_version(type);
5933
    }
5934
#endif /* OPENSSL_EXTRA */
5935
5936
#ifdef OPENSSL_EXTRA
5937
5938
    void wolfSSL_cleanup_all_ex_data(void)
5939
    {
5940
        /* nothing to do here */
5941
    }
5942
5943
#endif /* OPENSSL_EXTRA */
5944
5945
#if defined(OPENSSL_EXTRA) || defined(DEBUG_WOLFSSL_VERBOSE) || \
5946
    defined(HAVE_CURL)
5947
#endif
5948
5949
    int wolfSSL_clear(WOLFSSL* ssl)
5950
0
    {
5951
0
        WOLFSSL_ENTER("wolfSSL_clear");
5952
5953
0
        if (ssl == NULL) {
5954
0
            return WOLFSSL_FAILURE;
5955
0
        }
5956
5957
        /* A client keeps the session it may resume. A server's is per
5958
         * connection: take a new one when the application holds a reference,
5959
         * else reset ours, as wolfSSL_get_session() hands out a pointer
5960
         * without taking one. */
5961
0
        if (!ssl->options.handShakeDone ||
5962
0
                ((ssl->options.side == WOLFSSL_SERVER_END) &&
5963
0
                 (wolfSSL_RefCur(ssl->session->ref) > 1))) {
5964
0
            wolfSSL_FreeSession(ssl->ctx, ssl->session);
5965
0
            ssl->session = wolfSSL_NewSession(ssl->heap);
5966
0
            if (ssl->session == NULL) {
5967
0
                return WOLFSSL_FAILURE;
5968
0
            }
5969
0
        }
5970
0
        else if (ssl->options.side == WOLFSSL_SERVER_END) {
5971
0
            ssl->session->haveAltSessionID = 0;
5972
0
            ForceZero(ssl->session->altSessionID, ID_LEN);
5973
0
#ifndef NO_WOLFSSL_SERVER
5974
0
            ssl->session->peerAuthOk = 0;
5975
0
            ssl->session->isPSK = 0;
5976
0
#endif
5977
        #if defined(HAVE_SESSION_TICKET) && defined(WOLFSSL_TLS13)
5978
            ssl->session->ticketNonce.len = 0;
5979
        #endif
5980
0
        }
5981
5982
0
#ifndef NO_CERTS
5983
        /* Trust for the previous peer must not carry into the next. */
5984
0
        SslWaivedCAsFree(ssl);
5985
0
#endif
5986
5987
        /* reset error */
5988
0
        ssl->error = 0;
5989
5990
        /* reset option bits */
5991
0
        ssl->options.isClosed = 0;
5992
0
        ssl->options.fatalAlert = 0;
5993
0
        ssl->options.connReset = 0;
5994
0
        ssl->options.sentNotify = 0;
5995
0
        ssl->options.closeNotify = 0;
5996
        /* Per-connection budgets, not cumulative across a reused object. */
5997
0
        ssl->options.alertCount = 0;
5998
0
        ssl->options.emptyRecordCount = 0;
5999
0
        ssl->options.sendVerify = 0;
6000
0
        ssl->options.serverState = NULL_STATE;
6001
0
        ssl->options.clientState = NULL_STATE;
6002
0
        ssl->options.connectState = CONNECT_BEGIN;
6003
0
        ssl->options.acceptState  = ACCEPT_BEGIN;
6004
0
        ssl->options.handShakeState  = NULL_STATE;
6005
0
        ssl->options.handShakeDone = 0;
6006
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WOLFSSL_ASYNC_CERT_YIELD)
6007
        /* A per-certificate yield (WOLFSSL_ASYNC_CERT_YIELD) sets this and it is
6008
         * normally cleared on the next ProcessPeerCerts re-entry. Clear it here
6009
         * so reusing this object after abandoning a yielded handshake cannot
6010
         * skip the ProcessPeerCerts state reset on the next fresh entry. */
6011
        ssl->options.certYieldPending = 0;
6012
#endif
6013
0
        ssl->recordSzOverhead = 0;
6014
#ifdef WOLFSSL_TLS13_STREAM_CERT_VERIFY
6015
        /* Drop any half-sent streamed CertificateVerify. Left in place, the
6016
         * resume guard in SendTls13CertificateVerify would fire on the next
6017
         * handshake and re-send the previous one's signature. */
6018
        XFREE(ssl->buffers.certVerifyMsg.buffer, ssl->heap,
6019
              DYNAMIC_TYPE_TMP_BUFFER);
6020
        ssl->buffers.certVerifyMsg.buffer = NULL;
6021
        ssl->buffers.certVerifyMsg.length = 0;
6022
#endif
6023
0
        ssl->fragOffset = 0;
6024
0
        ssl->options.buildingMsg = 0;
6025
0
        ssl->options.processReply = 0; /* doProcessInit */
6026
0
        ssl->options.havePeerVerify = 0;
6027
0
        ssl->options.havePeerCert = 0;
6028
0
        ssl->options.peerAuthGood = 0;
6029
0
        ssl->options.usingPSK_cipher = 0;
6030
0
        ssl->options.usingAnon_cipher = 0;
6031
#if defined(WOLFSSL_TLS13) && (defined(HAVE_SESSION_TICKET) || !defined(NO_PSK))
6032
        ssl->options.pskNegotiated = 0;
6033
#endif
6034
0
        ssl->options.tls1_3 = 0;
6035
0
        ssl->options.haveSessionId = 0;
6036
0
        ssl->options.tls = 0;
6037
0
        ssl->options.tls1_1 = 0;
6038
0
#ifdef HAVE_EXTENDED_MASTER
6039
        /* haveEMS is negotiated per handshake: re-arm an EMS-capable client
6040
         * unless the user disabled EMS, and clear a server until the next
6041
         * ClientHello. The requireEMS/disableEMS policy persists. */
6042
0
        ssl->options.haveEMS = 0;
6043
0
        if (ssl->options.side == WOLFSSL_CLIENT_END &&
6044
0
                !ssl->options.disableEMS) {
6045
0
            if (ssl->ctx->method->version.major == SSLv3_MAJOR &&
6046
0
                    ssl->ctx->method->version.minor >= TLSv1_MINOR) {
6047
0
                ssl->options.haveEMS = 1;
6048
0
            }
6049
        #ifdef WOLFSSL_DTLS
6050
            if (ssl->ctx->method->version.major == DTLS_MAJOR)
6051
                ssl->options.haveEMS = 1;
6052
        #endif
6053
0
        }
6054
0
#endif
6055
0
    #ifdef WOLFSSL_TLS13
6056
0
    #ifdef WOLFSSL_TLS13_COOKIE
6057
0
        ssl->options.hrrSentCookie = 0;
6058
0
    #endif
6059
0
        ssl->options.hrrSentKeyShare = 0;
6060
0
        ssl->options.sentChangeCipher = 0;
6061
0
        ssl->options.ccsIgnoredCount = 0;
6062
        /* Matches InitSSL_Tls13Options(); the server clears it again when the
6063
         * next ClientHello carries an empty session id. */
6064
0
        ssl->options.tls13MiddleBoxCompat = 1;
6065
0
        ssl->options.shSentKeyShare = 0;
6066
0
        XFREE(ssl->certHashSigAlgo, ssl->heap, DYNAMIC_TYPE_TLSX);
6067
0
        ssl->certHashSigAlgo = NULL;
6068
0
        ssl->certHashSigAlgoSz = 0;
6069
0
    #endif
6070
0
    #if defined(WOLFSSL_TLS13) || defined(HAVE_FFDHE)
6071
        /* The group the previous connection negotiated. Nothing else clears
6072
         * it, and a handshake that negotiates none - TLS 1.3 psk_ke - would
6073
         * leave it readable as this connection's. */
6074
0
        ssl->namedGroup = 0;
6075
0
    #endif
6076
0
    #if defined(HAVE_ECC) || defined(HAVE_ED25519) || \
6077
0
        defined(HAVE_CURVE25519) || defined(HAVE_ED448) || \
6078
0
        defined(HAVE_CURVE448)
6079
        /* The peer's ephemeral key is now kept past the handshake for
6080
         * wolfSSL_get_peer_tmp_key(). A next handshake that negotiates no
6081
         * (EC)DH would otherwise report the previous connection's key.
6082
         * Back to what SetSSL_CTX() starts from, so a curve set with
6083
         * wolfSSL_CTX_set_tmp_ecdh() survives. */
6084
0
        ssl->ecdhCurveOID = ssl->ctx->ecdhCurveOID;
6085
0
        ssl->peerEccKeyPresent = 0;
6086
0
    #endif
6087
    #ifdef HAVE_CURVE25519
6088
        ssl->peerX25519KeyPresent = 0;
6089
    #endif
6090
    #ifdef HAVE_CURVE448
6091
        ssl->peerX448KeyPresent = 0;
6092
    #endif
6093
        /* Drop the peer certificate public key left by an abandoned handshake. */
6094
0
        FreePeerCertKeys(ssl);
6095
    #ifdef WOLFSSL_DTLS
6096
        ssl->options.dtlsStateful = 0;
6097
        #ifndef NO_ASN_TIME
6098
        ssl->dtls_timer_len = 0;
6099
        #endif
6100
    #endif
6101
0
    #ifdef WOLFSSL_TLS13
6102
    #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
6103
        ssl->options.pskNegotiated = 0;
6104
        ssl->options.noPskDheKe = ssl->ctx->noPskDheKe;
6105
        ssl->options.noPskDheKePolicy = ssl->ctx->noPskDheKe;
6106
        #ifdef HAVE_SUPPORTED_CURVES
6107
        ssl->options.onlyPskDheKe = ssl->ctx->onlyPskDheKe;
6108
        #endif
6109
    #endif
6110
        /* An abandoned handshake can leave a key-schedule or record-build
6111
         * resume marker set; a reused object must not resume into the new
6112
         * handshake. */
6113
0
        ssl->kdfDeriveStep = TLS13_SEND_KDF_NONE;
6114
0
        ssl->kdfMsgStep = TLS13_MSG_KDF_NONE;
6115
0
        ssl->kdfMsgType = 0;
6116
        #if defined(WOLFSSL_ASYNC_REINVOKE) && !defined(NO_HMAC)
6117
        Tls13FreeHsHmac(ssl);
6118
        #endif
6119
        #ifdef WOLFSSL_ASYNC_CRYPT
6120
        ssl->options.buildArgs13Set = 0;
6121
        /* An abandoned handshake can leave a mid-flight handler resume
6122
         * state and a queued key-schedule event behind; a reused object
6123
         * must start fresh. */
6124
        ssl->options.asyncState = TLS_ASYNC_BEGIN;
6125
        if (ssl->asyncDev == &ssl->kdfAsyncDev) {
6126
            if (ssl->kdfAsyncDev.event.state == WOLF_EVENT_STATE_PENDING &&
6127
                    ssl->ctx != NULL) {
6128
                (void)wolfEventQueue_Remove(&ssl->ctx->event_queue,
6129
                                            &ssl->kdfAsyncDev.event);
6130
            }
6131
            XMEMSET(&ssl->kdfAsyncDev.event, 0, sizeof(WOLF_EVENT));
6132
            ssl->asyncDev = NULL;
6133
        }
6134
        #endif
6135
0
    #endif
6136
    #ifdef HAVE_SESSION_TICKET
6137
        #ifdef WOLFSSL_TLS13
6138
        ssl->options.ticketsSent = 0;
6139
        #if !defined(NO_WOLFSSL_SERVER) && \
6140
            defined(WOLFSSL_TLS13_TICKET_CHECK_PSK_MODES)
6141
        /* Recorded from the ClientHello, so it must not carry into the next
6142
         * connection on a reused object. */
6143
        ssl->options.pskKeModes = 0;
6144
        ssl->options.pskKeModesRecvd = 0;
6145
        #endif
6146
        #if defined(WOLFSSL_EARLY_DATA) && !defined(NO_SESSION_CACHE)
6147
        ssl->options.ticketCacheHit = 0;
6148
        #endif
6149
        #endif
6150
        ssl->options.rejectTicket = 0;
6151
        ssl->options.useTicket = 0;
6152
        ssl->options.createTicket = 0;
6153
    #endif
6154
    #ifdef WOLFSSL_EARLY_DATA
6155
        ssl->earlyData = no_early_data;
6156
        ssl->earlyDataSz = 0;
6157
    #endif
6158
    #ifdef HAVE_RPK
6159
        /* Drop the negotiated cert types so one peer's choice cannot carry into
6160
         * the next handshake. Clearing the counts is enough: every read of the
6161
         * type arrays is gated on its count. */
6162
        ssl->options.rpkState.sending_ClientCertTypeCnt = 0;
6163
        ssl->options.rpkState.sending_ServerCertTypeCnt = 0;
6164
        ssl->options.rpkState.received_ClientCertTypeCnt = 0;
6165
        ssl->options.rpkState.received_ServerCertTypeCnt = 0;
6166
    #endif
6167
6168
0
    #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CA_NAMES) && \
6169
0
        defined(WOLFSSL_TLS13)
6170
        /* The peer list belongs to the connection that just ended. Left in
6171
         * place, the getters report the previous peer's authorities when the
6172
         * next one sends no certificate_authorities extension. */
6173
0
        TLSX_CertificateAuthorities_FreeAll(ssl->ws_peer_ca_names, ssl->heap);
6174
0
        ssl->ws_peer_ca_names = NULL;
6175
0
    #endif
6176
6177
0
    #if defined(HAVE_TLS_EXTENSIONS) && !defined(NO_TLS)
6178
0
        TLSX_FreeAll(ssl->extensions, ssl->heap);
6179
0
        ssl->extensions = NULL;
6180
0
      #if defined(HAVE_SECURE_RENEGOTIATION) \
6181
0
       || defined(HAVE_SERVER_RENEGOTIATION_INFO)
6182
0
        ssl->secure_renegotiation = NULL;
6183
        /* The renegotiation_info advertising is re-established when the next
6184
         * ClientHello is built (SendClientHello), so a reused client object
6185
         * keeps the "advertise implies enforce" invariant (RFC 5746). */
6186
0
      #endif
6187
0
    #endif
6188
6189
0
        if (ssl->keys.encryptionOn) {
6190
0
            ForceZero(ssl->buffers.inputBuffer.buffer -
6191
0
                ssl->buffers.inputBuffer.offset,
6192
0
                ssl->buffers.inputBuffer.bufferSize);
6193
        #ifdef WOLFSSL_CHECK_MEM_ZERO
6194
            wc_MemZero_Check(ssl->buffers.inputBuffer.buffer -
6195
                ssl->buffers.inputBuffer.offset,
6196
                ssl->buffers.inputBuffer.bufferSize);
6197
        #endif
6198
0
        }
6199
0
        ssl->buffers.clearOutputBuffer.buffer = NULL;
6200
0
        ssl->buffers.clearOutputBuffer.length = 0;
6201
0
        ssl->buffers.inputBuffer.idx = 0;
6202
0
        ssl->buffers.inputBuffer.length = 0;
6203
0
        ssl->buffers.prevSent = 0;
6204
0
        ssl->buffers.plainSz = 0;
6205
        /* Recycling the object for a new connection must not carry the
6206
         * previous connection's key material along with it. A freshly
6207
         * created object has all of this zeroed. */
6208
0
        ForceZero(&ssl->keys, sizeof(Keys));
6209
    #ifdef WOLFSSL_MULTICAST
6210
        if (ssl->options.haveMcast) {
6211
            int i;
6212
6213
            for (i = 0; i < WOLFSSL_DTLS_PEERSEQ_SZ; i++)
6214
                ssl->keys.peerSeq[i].peerId = INVALID_PEER_ID;
6215
        }
6216
    #endif
6217
0
    #ifdef WOLFSSL_TLS13
6218
0
        ForceZero(ssl->clientSecret, sizeof(ssl->clientSecret));
6219
0
        ForceZero(ssl->serverSecret, sizeof(ssl->serverSecret));
6220
        /* A key update the previous connection asked for has nothing to say
6221
         * about the next one, and the keys it would rotate are gone. */
6222
0
        ssl->options.sendKeyUpdate = 0;
6223
0
    #endif
6224
    #ifdef WOLFSSL_HAVE_TLS_UNIQUE
6225
        /* The channel binding of the connection that just ended. Leaving it
6226
         * in place would let the next caller bind to the wrong session. */
6227
        ForceZero(ssl->clientFinished, TLS_FINISHED_SZ_MAX);
6228
        ForceZero(ssl->serverFinished, TLS_FINISHED_SZ_MAX);
6229
        ssl->clientFinished_len = 0;
6230
        ssl->serverFinished_len = 0;
6231
    #endif
6232
    #ifdef WOLFSSL_DTLS13
6233
        /* Per-epoch traffic keys, IVs and sequence number keys. */
6234
        ForceZero(ssl->dtls13Epochs, sizeof(ssl->dtls13Epochs));
6235
        /* Only InitSSL() sets up the unprotected epoch 0 and aims the epoch
6236
         * pointers at it, and this object is being reused rather than freed,
6237
         * so put it back or the next handshake has no valid epoch. */
6238
        ssl->dtls13Epochs[0].isValid = 1;
6239
        ssl->dtls13Epochs[0].side = ENCRYPT_AND_DECRYPT_SIDE;
6240
        ssl->dtls13EncryptEpoch = &ssl->dtls13Epochs[0];
6241
        ssl->dtls13DecryptEpoch = &ssl->dtls13Epochs[0];
6242
        /* The numbers that say which epoch to use sit outside the table and
6243
         * only ever move up, so wiping the table has to be matched here by
6244
         * hand. InitSSL() gets this for free from clearing the whole object.
6245
         * Left behind, they ask the next handshake to send under an epoch the
6246
         * table no longer holds, and Dtls13SetEpochKeys() fails the connection
6247
         * with BAD_STATE_E. */
6248
        w64Zero(&ssl->dtls13Epoch);
6249
        w64Zero(&ssl->dtls13PeerEpoch);
6250
        w64Zero(&ssl->dtls13InvalidateBefore);
6251
        ssl->dtls13WaitKeyUpdateAck = 0;
6252
        ssl->dtls13DoKeyUpdate = 0;
6253
        ssl->dtls13SendingAckOrRtx = 0;
6254
        /* Anything still queued for retransmission or acknowledgement is
6255
         * tagged with an epoch that no longer exists, so it can never be sent
6256
         * and would only be released when the object is freed. */
6257
        Dtls13FreeFsmResources(ssl);
6258
        ssl->dtls13Rtx.sendAcks = 0;
6259
        ssl->dtls13Rtx.retransmit = 0;
6260
    #endif
6261
        /* The handshake arrays hold the master and pre-master secrets. Wipe
6262
         * those in place rather than releasing the arrays, so that the
6263
         * allocation stays valid for wolfSSL_set_secret(), the exporter and
6264
         * the other accessors that read from it once a connection has ended.
6265
         * An application that asked to keep the arrays still gets back
6266
         * everything the API can hand it, so only the rest goes. */
6267
0
        if (ssl->arrays != NULL) {
6268
            /* The buffer lives as long as the arrays do. */
6269
0
            ForceZero(ssl->arrays->preMasterSecret, MAX_PREMASTER_SZ);
6270
            /* Key agreement reads this as the writable capacity. */
6271
0
            ssl->arrays->preMasterSz = MAX_PREMASTER_SZ;
6272
        #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
6273
            ForceZero(ssl->arrays->psk_key, MAX_PSK_KEY_LEN);
6274
            ssl->arrays->psk_keySz = 0;
6275
        #endif
6276
0
        #ifdef WOLFSSL_TLS13
6277
            /* The key schedule secret. No API hands this one back. */
6278
0
            ForceZero(ssl->arrays->secret, SECRET_LEN);
6279
0
        #endif
6280
0
            if (!ssl->options.saveArrays) {
6281
0
                ForceZero(ssl->arrays->masterSecret, SECRET_LEN);
6282
            #ifdef HAVE_KEYING_MATERIAL
6283
                /* Tls13_Exporter() reads this one, and exporting keying
6284
                 * material requires the arrays to be kept, so it only goes
6285
                 * when the application did not ask for that. */
6286
                ForceZero(ssl->arrays->exporterSecret, WC_MAX_DIGEST_SIZE);
6287
            #endif
6288
0
            }
6289
0
        }
6290
0
        XMEMSET(&ssl->msgsReceived, 0, sizeof(ssl->msgsReceived));
6291
6292
        /* Discard any partial handshake-message reassembly on reuse. */
6293
0
        XFREE(ssl->pendingMsg, ssl->heap, DYNAMIC_TYPE_ARRAYS);
6294
0
        ssl->pendingMsg = NULL;
6295
0
        ssl->pendingMsgSz = 0;
6296
0
        ssl->pendingMsgOffset = 0;
6297
0
        ssl->pendingMsgType = 0;
6298
6299
0
        FreeCiphers(ssl);
6300
0
        InitCiphers(ssl);
6301
0
        InitCipherSpecs(&ssl->specs);
6302
6303
0
        if (InitSSL_Suites(ssl) != WOLFSSL_SUCCESS)
6304
0
            return WOLFSSL_FAILURE;
6305
6306
0
        if (InitHandshakeHashes(ssl) != 0)
6307
0
            return WOLFSSL_FAILURE;
6308
6309
#ifdef KEEP_PEER_CERT
6310
        FreePeerCert(ssl);
6311
#endif
6312
6313
#ifdef WOLFSSL_QUIC
6314
        wolfSSL_quic_clear(ssl);
6315
#endif
6316
#ifdef HAVE_OCSP
6317
#if defined(WOLFSSL_TLS13) && defined(HAVE_CERTIFICATE_STATUS_REQUEST)
6318
        ssl->response_idx = 0;
6319
#endif
6320
#endif
6321
0
        return WOLFSSL_SUCCESS;
6322
0
    }
6323
6324
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || defined(HAVE_MEMCACHED)
6325
    long wolfSSL_CTX_set_mode(WOLFSSL_CTX* ctx, long mode)
6326
    {
6327
        /* WOLFSSL_MODE_ACCEPT_MOVING_WRITE_BUFFER is wolfSSL default mode */
6328
6329
        WOLFSSL_ENTER("wolfSSL_CTX_set_mode");
6330
        switch(mode) {
6331
            case WOLFSSL_MODE_ENABLE_PARTIAL_WRITE:
6332
                ctx->partialWrite = 1;
6333
                break;
6334
            #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
6335
            case SSL_MODE_RELEASE_BUFFERS:
6336
                WOLFSSL_MSG("SSL_MODE_RELEASE_BUFFERS not implemented.");
6337
                break;
6338
            #endif
6339
            case WOLFSSL_MODE_AUTO_RETRY:
6340
                ctx->autoRetry = 1;
6341
                break;
6342
            default:
6343
                WOLFSSL_MSG("Mode Not Implemented");
6344
        }
6345
6346
        /* WOLFSSL_MODE_AUTO_RETRY
6347
         * Should not return WOLFSSL_FATAL_ERROR with renegotiation on read/write */
6348
6349
        return mode;
6350
    }
6351
6352
    long wolfSSL_CTX_clear_mode(WOLFSSL_CTX* ctx, long mode)
6353
    {
6354
        /* WOLFSSL_MODE_ACCEPT_MOVING_WRITE_BUFFER is wolfSSL default mode */
6355
6356
        WOLFSSL_ENTER("wolfSSL_CTX_clear_mode");
6357
        switch(mode) {
6358
            case WOLFSSL_MODE_ENABLE_PARTIAL_WRITE:
6359
                ctx->partialWrite = 0;
6360
                break;
6361
            #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
6362
            case SSL_MODE_RELEASE_BUFFERS:
6363
                WOLFSSL_MSG("SSL_MODE_RELEASE_BUFFERS not implemented.");
6364
                break;
6365
            #endif
6366
            case WOLFSSL_MODE_AUTO_RETRY:
6367
                ctx->autoRetry = 0;
6368
                break;
6369
            default:
6370
                WOLFSSL_MSG("Mode Not Implemented");
6371
        }
6372
6373
        /* WOLFSSL_MODE_AUTO_RETRY
6374
         * Should not return WOLFSSL_FATAL_ERROR with renegotiation on read/write */
6375
6376
        return 0;
6377
    }
6378
#endif
6379
6380
#ifdef OPENSSL_EXTRA
6381
6382
    #ifndef NO_WOLFSSL_STUB
6383
    long wolfSSL_SSL_get_mode(WOLFSSL* ssl)
6384
    {
6385
        /* TODO: */
6386
        (void)ssl;
6387
        WOLFSSL_STUB("SSL_get_mode");
6388
        return 0;
6389
    }
6390
    #endif
6391
6392
    #ifndef NO_WOLFSSL_STUB
6393
    long wolfSSL_CTX_get_mode(WOLFSSL_CTX* ctx)
6394
    {
6395
        /* TODO: */
6396
        (void)ctx;
6397
        WOLFSSL_STUB("SSL_CTX_get_mode");
6398
        return 0;
6399
    }
6400
    #endif
6401
6402
    #ifndef NO_WOLFSSL_STUB
6403
    void wolfSSL_CTX_set_default_read_ahead(WOLFSSL_CTX* ctx, int m)
6404
    {
6405
        /* TODO: maybe? */
6406
        (void)ctx;
6407
        (void)m;
6408
        WOLFSSL_STUB("SSL_CTX_set_default_read_ahead");
6409
    }
6410
    #endif
6411
6412
6413
    /* returns the unsigned error value and increments the pointer into the
6414
     * error queue.
6415
     *
6416
     * file  pointer to file name
6417
     * line  gets set to line number of error when not NULL
6418
     */
6419
6420
6421
6422
6423
6424
#endif /* OPENSSL_EXTRA */
6425
6426
6427
6428
6429
6430
6431
6432
int wolfSSL_session_reused(WOLFSSL* ssl)
6433
0
{
6434
0
    int resuming = 0;
6435
0
    WOLFSSL_ENTER("wolfSSL_session_reused");
6436
0
    if (ssl) {
6437
0
#ifndef HAVE_SECURE_RENEGOTIATION
6438
0
        resuming = ssl->options.resuming;
6439
#else
6440
        resuming = ssl->options.resuming || ssl->options.resumed;
6441
#endif
6442
0
    }
6443
0
    WOLFSSL_LEAVE("wolfSSL_session_reused", resuming);
6444
0
    return resuming;
6445
0
}
6446
6447
/* helper function that takes in a protocol version struct and returns string */
6448
static const char* wolfSSL_internal_get_version(const ProtocolVersion* version)
6449
0
{
6450
0
    WOLFSSL_ENTER("wolfSSL_get_version");
6451
6452
0
    if (version == NULL) {
6453
0
        return "Bad arg";
6454
0
    }
6455
6456
0
    if (version->major == SSLv3_MAJOR) {
6457
0
        switch (version->minor) {
6458
0
            case SSLv3_MINOR :
6459
0
                return "SSLv3";
6460
0
            case TLSv1_MINOR :
6461
0
                return "TLSv1";
6462
0
            case TLSv1_1_MINOR :
6463
0
                return "TLSv1.1";
6464
0
            case TLSv1_2_MINOR :
6465
0
                return "TLSv1.2";
6466
0
            case TLSv1_3_MINOR :
6467
0
                return "TLSv1.3";
6468
0
            default:
6469
0
                return "unknown";
6470
0
        }
6471
0
    }
6472
#ifdef WOLFSSL_DTLS
6473
    else if (version->major == DTLS_MAJOR) {
6474
        switch (version->minor) {
6475
            case DTLS_MINOR :
6476
                return "DTLS";
6477
            case DTLSv1_2_MINOR :
6478
                return "DTLSv1.2";
6479
            case DTLSv1_3_MINOR :
6480
                return "DTLSv1.3";
6481
            default:
6482
                return "unknown";
6483
        }
6484
    }
6485
#endif /* WOLFSSL_DTLS */
6486
0
    return "unknown";
6487
0
}
6488
6489
6490
const char* wolfSSL_get_version(const WOLFSSL* ssl)
6491
0
{
6492
0
    if (ssl == NULL) {
6493
0
        WOLFSSL_MSG("Bad argument");
6494
0
        return "unknown";
6495
0
    }
6496
6497
0
    return wolfSSL_internal_get_version(&ssl->version);
6498
0
}
6499
6500
6501
/* current library version */
6502
const char* wolfSSL_lib_version(void)
6503
0
{
6504
0
    return LIBWOLFSSL_VERSION_STRING;
6505
0
}
6506
6507
#ifdef OPENSSL_EXTRA
6508
/* Signature deliberately does not depend on OPENSSL_VERSION_NUMBER. That macro
6509
 * can evaluate differently in the library and in the application (e.g. under
6510
 * OPENSSL_COEXIST the library also sees the real OpenSSL headers), which would
6511
 * make the caller and the definition disagree on the argument list. */
6512
const char* wolfSSL_OpenSSL_version(int type)
6513
{
6514
    WOLFSSL_ENTER("wolfSSL_OpenSSL_version");
6515
    switch (type) {
6516
        case OPENSSL_VERSION:
6517
            return "wolfSSL " LIBWOLFSSL_VERSION_STRING;
6518
        case OPENSSL_CFLAGS:
6519
            return "compiler: information not available";
6520
        case OPENSSL_BUILT_ON:
6521
        /* Kernel module builds compile with -Werror=date-time.  Define
6522
         * WOLFSSL_OPENSSL_NO_BUILD_DATE to drop the date without needing the
6523
         * full reproducible-build option. */
6524
#if defined(HAVE_REPRODUCIBLE_BUILD) || defined(WOLFSSL_LINUXKM) || \
6525
    defined(WOLFSSL_OPENSSL_NO_BUILD_DATE)
6526
            return "built on: date not available";
6527
#else
6528
            return "built on: " __DATE__ " " __TIME__;
6529
#endif
6530
        case OPENSSL_PLATFORM:
6531
            return "platform: information not available";
6532
        case OPENSSL_DIR:
6533
            return "OPENSSLDIR: N/A";
6534
        case OPENSSL_ENGINES_DIR:
6535
            return "ENGINESDIR: N/A";
6536
        default:
6537
            return "not available";
6538
    }
6539
}
6540
#endif /* OPENSSL_EXTRA */
6541
6542
6543
/* current library version in hex */
6544
word32 wolfSSL_lib_version_hex(void)
6545
0
{
6546
0
    return LIBWOLFSSL_VERSION_HEX;
6547
0
}
6548
6549
6550
int wolfSSL_get_current_cipher_suite(WOLFSSL* ssl)
6551
0
{
6552
0
    WOLFSSL_ENTER("wolfSSL_get_current_cipher_suite");
6553
0
    if (ssl)
6554
0
        return (ssl->options.cipherSuite0 << 8) | ssl->options.cipherSuite;
6555
0
    return 0;
6556
0
}
6557
6558
/* Fill in all of cipher. The accessors only read these fields. */
6559
static void wolfssl_cipher_set(WOLFSSL_CIPHER* cipher, byte suite0,
6560
    byte suite, const ProtocolVersion* pv)
6561
0
{
6562
0
    XMEMSET(cipher, 0, sizeof(*cipher));
6563
0
    cipher->cipherSuite0 = suite0;
6564
0
    cipher->cipherSuite  = suite;
6565
0
    cipher->pv           = *pv;
6566
0
}
6567
6568
#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
6569
    defined(WOLFSSL_HAPROXY) || defined(OPENSSL_EXTRA)
6570
/* Is the specified cipher suite a fake one used an an extension proxy? */
6571
static WC_INLINE int SCSV_Check(byte suite0, byte suite)
6572
{
6573
    (void)suite0;
6574
    (void)suite;
6575
#ifdef HAVE_RENEGOTIATION_INDICATION
6576
    if (suite0 == CIPHER_BYTE && suite == TLS_EMPTY_RENEGOTIATION_INFO_SCSV)
6577
        return 1;
6578
#endif
6579
    return 0;
6580
}
6581
6582
/* Fill in cipher as a cipher list entry. It describes the suite itself: its
6583
 * own version, not that of a session. */
6584
static void wolfssl_cipher_init_suite(WOLFSSL_CIPHER* cipher, byte suite0,
6585
    byte suite)
6586
{
6587
    const CipherSuiteInfo* names = GetCipherNames();
6588
    int idx = GetCipherNamesIdx(suite0, suite);
6589
    ProtocolVersion pv;
6590
6591
    pv.major = 0;
6592
    pv.minor = 0;
6593
    if (idx >= 0) {
6594
        pv.major = names[idx].major;
6595
        pv.minor = names[idx].minor;
6596
    }
6597
    wolfssl_cipher_set(cipher, suite0, suite, &pv);
6598
}
6599
#endif
6600
6601
/* The cipher of the session. Filled in from ssl on each call, so a pointer
6602
 * kept from an earlier call reports the session as it was then. */
6603
WOLFSSL_CIPHER* wolfSSL_get_current_cipher(WOLFSSL* ssl)
6604
0
{
6605
0
    WOLFSSL_ENTER("wolfSSL_get_current_cipher");
6606
0
    if (ssl) {
6607
0
        wolfssl_cipher_set(&ssl->cipher, ssl->options.cipherSuite0,
6608
0
            ssl->options.cipherSuite, &ssl->version);
6609
0
        return &ssl->cipher;
6610
0
    }
6611
0
    else
6612
0
        return NULL;
6613
0
}
6614
6615
6616
const char* wolfSSL_CIPHER_get_name(const WOLFSSL_CIPHER* cipher)
6617
0
{
6618
0
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_name");
6619
6620
0
    if (cipher == NULL) {
6621
0
        return NULL;
6622
0
    }
6623
6624
0
    #if !defined(WOLFSSL_CIPHER_INTERNALNAME) && !defined(NO_ERROR_STRINGS) && \
6625
0
        !defined(WOLFSSL_QT)
6626
0
        return GetCipherNameIana(cipher->cipherSuite0, cipher->cipherSuite);
6627
    #else
6628
        return wolfSSL_get_cipher_name_from_suite(cipher->cipherSuite0,
6629
                cipher->cipherSuite);
6630
    #endif
6631
0
}
6632
6633
const char*  wolfSSL_CIPHER_get_version(const WOLFSSL_CIPHER* cipher)
6634
0
{
6635
0
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_version");
6636
6637
0
    if (cipher == NULL) {
6638
0
        return NULL;
6639
0
    }
6640
6641
0
    return wolfSSL_internal_get_version(&cipher->pv);
6642
0
}
6643
6644
const char* wolfSSL_get_cipher(WOLFSSL* ssl)
6645
0
{
6646
0
    WOLFSSL_ENTER("wolfSSL_get_cipher");
6647
0
    return wolfSSL_CIPHER_get_name(wolfSSL_get_current_cipher(ssl));
6648
0
}
6649
6650
/* gets cipher name in the format DHE-RSA-... rather then TLS_DHE... */
6651
const char* wolfSSL_get_cipher_name(WOLFSSL* ssl)
6652
0
{
6653
    /* get access to cipher_name_idx in internal.c */
6654
0
    return wolfSSL_get_cipher_name_internal(ssl);
6655
0
}
6656
6657
const char* wolfSSL_get_cipher_name_from_suite(byte cipherSuite0,
6658
    byte cipherSuite)
6659
0
{
6660
0
    return GetCipherNameInternal(cipherSuite0, cipherSuite);
6661
0
}
6662
6663
const char* wolfSSL_get_cipher_name_iana_from_suite(byte cipherSuite0,
6664
        byte cipherSuite)
6665
0
{
6666
0
    return GetCipherNameIana(cipherSuite0, cipherSuite);
6667
0
}
6668
6669
int wolfSSL_get_cipher_suite_from_name(const char* name, byte* cipherSuite0,
6670
0
                                       byte* cipherSuite, int *flags) {
6671
0
    if ((name == NULL) ||
6672
0
        (cipherSuite0 == NULL) ||
6673
0
        (cipherSuite == NULL) ||
6674
0
        (flags == NULL))
6675
0
        return BAD_FUNC_ARG;
6676
0
    return GetCipherSuiteFromName(name, cipherSuite0, cipherSuite, NULL, NULL,
6677
0
                                  flags);
6678
0
}
6679
6680
6681
word32 wolfSSL_CIPHER_get_id(const WOLFSSL_CIPHER* cipher)
6682
0
{
6683
0
    word16 cipher_id = 0;
6684
6685
0
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_id");
6686
6687
    /* Read the suite of this entry: stack entries and SSL_CIPHER_find()
6688
     * results are not the negotiated suite. */
6689
0
    if (cipher != NULL) {
6690
0
        cipher_id = (word16)((word16)cipher->cipherSuite0 << 8) |
6691
0
                     cipher->cipherSuite;
6692
0
    }
6693
6694
0
    return cipher_id;
6695
0
}
6696
6697
const WOLFSSL_CIPHER* wolfSSL_get_cipher_by_value(word16 value)
6698
0
{
6699
0
    const WOLFSSL_CIPHER* cipher = NULL;
6700
0
    byte cipherSuite0, cipherSuite;
6701
0
    WOLFSSL_ENTER("wolfSSL_get_cipher_by_value");
6702
6703
    /* extract cipher id information */
6704
0
    cipherSuite =   (value       & 0xFF);
6705
0
    cipherSuite0 = ((value >> 8) & 0xFF);
6706
6707
    /* TODO: lookup by cipherSuite0 / cipherSuite */
6708
0
    (void)cipherSuite0;
6709
0
    (void)cipherSuite;
6710
6711
0
    return cipher;
6712
0
}
6713
6714
#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
6715
    defined(WOLFSSL_HAPROXY) || defined(OPENSSL_EXTRA)
6716
/* Locate a cipher in the SSL's cipher list by 2-byte wire-format suite id.
6717
 *
6718
 * Mirrors OpenSSL's SSL_CIPHER_find(): the SSL's configured cipher list is
6719
 * searched first, then all cipher suites known to the library are searched as
6720
 * a fallback. This lets callers decode a suite id seen on the wire even when
6721
 * it is not enabled on the SSL object.
6722
 *
6723
 * A match found in the SSL's cipher list returns storage owned by that list.
6724
 * A match found only in the library fallback is stored in the SSL object's
6725
 * scratch cipher (ssl->cipher), as wolfSSL_get_current_cipher does. In either
6726
 * case callers must not free the returned pointer; it remains valid until the
6727
 * next call that updates ssl->cipher, or until SSL_free.
6728
 *
6729
 * @param [in] ssl  SSL/TLS object whose cipher list is searched.
6730
 * @param [in] ptr  Pointer to a 2-byte cipher suite identifier.
6731
 * @return  Matching cipher on success.
6732
 * @return  NULL if ssl or ptr is NULL, or no cipher matches.
6733
 */
6734
const WOLFSSL_CIPHER* wolfSSL_SSL_CIPHER_find(WOLFSSL* ssl,
6735
    const unsigned char* ptr)
6736
{
6737
    WOLF_STACK_OF(WOLFSSL_CIPHER)* sk;
6738
    WOLFSSL_STACK* node;
6739
6740
    WOLFSSL_ENTER("wolfSSL_SSL_CIPHER_find");
6741
6742
    if (ssl == NULL || ptr == NULL)
6743
        return NULL;
6744
6745
    sk = wolfSSL_get_ciphers_compat(ssl);
6746
    for (node = sk; node != NULL; node = node->next) {
6747
        if (node->data.cipher.cipherSuite0 == ptr[0] &&
6748
            node->data.cipher.cipherSuite  == ptr[1]) {
6749
            return &node->data.cipher;
6750
        }
6751
    }
6752
6753
    /* Not enabled on this SSL - fall back to a library-wide lookup so suite
6754
     * ids seen on the wire can still be decoded, matching OpenSSL. */
6755
    if (GetCipherNamesIdx(ptr[0], ptr[1]) < 0)
6756
        return NULL;
6757
6758
    /* Describe the suite looked up, not the session. */
6759
    wolfssl_cipher_init_suite(&ssl->cipher, ptr[0], ptr[1]);
6760
    return &ssl->cipher;
6761
}
6762
#endif
6763
6764
6765
#if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448) || \
6766
    !defined(NO_DH) || (defined(WOLFSSL_TLS13) && defined(WOLFSSL_HAVE_MLKEM))
6767
#ifdef HAVE_FFDHE
6768
static const char* wolfssl_ffdhe_name(word16 group)
6769
0
{
6770
0
    const char* str = NULL;
6771
0
    switch (group) {
6772
0
        case WOLFSSL_FFDHE_2048:
6773
0
            str = "FFDHE_2048";
6774
0
            break;
6775
0
        case WOLFSSL_FFDHE_3072:
6776
0
            str = "FFDHE_3072";
6777
0
            break;
6778
0
        case WOLFSSL_FFDHE_4096:
6779
0
            str = "FFDHE_4096";
6780
0
            break;
6781
0
        case WOLFSSL_FFDHE_6144:
6782
0
            str = "FFDHE_6144";
6783
0
            break;
6784
0
        case WOLFSSL_FFDHE_8192:
6785
0
            str = "FFDHE_8192";
6786
0
            break;
6787
0
        default:
6788
0
            break;
6789
0
    }
6790
0
    return str;
6791
0
}
6792
#endif
6793
/* Return the name of the curve used for key exchange as a printable string.
6794
 *
6795
 * ssl  The SSL/TLS object.
6796
 * returns NULL if ECDH was not used, otherwise the name as a string.
6797
 */
6798
const char* wolfSSL_get_curve_name(WOLFSSL* ssl)
6799
0
{
6800
0
    const char* cName = NULL;
6801
6802
0
    WOLFSSL_ENTER("wolfSSL_get_curve_name");
6803
6804
0
    if (ssl == NULL)
6805
0
        return NULL;
6806
6807
0
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_HAVE_MLKEM)
6808
    /* Check for post-quantum groups. Return now because we do not want the ECC
6809
     * check to override this result in the case of a hybrid. */
6810
0
    if (IsAtLeastTLSv1_3(ssl->version)) {
6811
0
        switch (ssl->namedGroup) {
6812
0
#ifndef WOLFSSL_NO_ML_KEM
6813
0
    #ifndef WOLFSSL_NO_ML_KEM_512
6814
0
        case WOLFSSL_ML_KEM_512:
6815
0
            return "ML_KEM_512";
6816
        #ifdef WOLFSSL_EXTRA_PQC_HYBRIDS
6817
        #ifdef WOLFSSL_ML_KEM_USE_OLD_IDS
6818
        case WOLFSSL_P256_ML_KEM_512_OLD:
6819
            return "P256_ML_KEM_512_OLD";
6820
        #endif /* WOLFSSL_ML_KEM_USE_OLD_IDS */
6821
        case WOLFSSL_SECP256R1MLKEM512:
6822
            return "SecP256r1MLKEM512";
6823
        #ifdef HAVE_CURVE25519
6824
        case WOLFSSL_X25519MLKEM512:
6825
            return "X25519MLKEM512";
6826
        #endif /* HAVE_CURVE25519 */
6827
        #endif /* WOLFSSL_EXTRA_PQC_HYBRIDS */
6828
0
    #endif /* WOLFSSL_NO_ML_KEM_512 */
6829
0
    #ifndef WOLFSSL_NO_ML_KEM_768
6830
0
        case WOLFSSL_ML_KEM_768:
6831
0
            return "ML_KEM_768";
6832
0
        #ifdef WOLFSSL_PQC_HYBRIDS
6833
0
        case WOLFSSL_SECP256R1MLKEM768:
6834
0
            return "SecP256r1MLKEM768";
6835
        #ifdef HAVE_CURVE25519
6836
        case WOLFSSL_X25519MLKEM768:
6837
            return "X25519MLKEM768";
6838
        #endif
6839
0
        #endif /* WOLFSSL_PQC_HYBRIDS */
6840
        #ifdef WOLFSSL_EXTRA_PQC_HYBRIDS
6841
        #ifdef WOLFSSL_ML_KEM_USE_OLD_IDS
6842
        case WOLFSSL_P384_ML_KEM_768_OLD:
6843
            return "P384_ML_KEM_768_OLD";
6844
        #endif /* WOLFSSL_ML_KEM_USE_OLD_IDS */
6845
        case WOLFSSL_SECP384R1MLKEM768:
6846
            return "SecP384r1MLKEM768";
6847
        #ifdef HAVE_CURVE448
6848
        case WOLFSSL_X448MLKEM768:
6849
            return "X448MLKEM768";
6850
        #endif /* HAVE_CURVE448 */
6851
        #endif /* WOLFSSL_EXTRA_PQC_HYBRIDS */
6852
0
    #endif /* WOLFSSL_NO_ML_KEM_768 */
6853
0
    #ifndef WOLFSSL_NO_ML_KEM_1024
6854
0
        case WOLFSSL_ML_KEM_1024:
6855
0
            return "ML_KEM_1024";
6856
0
        #ifdef WOLFSSL_PQC_HYBRIDS
6857
0
        case WOLFSSL_SECP384R1MLKEM1024:
6858
0
            return "SecP384r1MLKEM1024";
6859
0
        #endif /* WOLFSSL_PQC_HYBRIDS */
6860
        #ifdef WOLFSSL_EXTRA_PQC_HYBRIDS
6861
        #ifdef WOLFSSL_ML_KEM_USE_OLD_IDS
6862
        case WOLFSSL_P521_ML_KEM_1024_OLD:
6863
            return "P521_ML_KEM_1024_OLD";
6864
        #endif /* WOLFSSL_ML_KEM_USE_OLD_IDS */
6865
        case WOLFSSL_SECP521R1MLKEM1024:
6866
            return "SecP521r1MLKEM1024";
6867
        #endif /* WOLFSSL_EXTRA_PQC_HYBRIDS */
6868
0
    #endif /* WOLFSSL_NO_ML_KEM_1024 */
6869
0
#endif /* WOLFSSL_NO_ML_KEM */
6870
#ifdef WOLFSSL_MLKEM_KYBER
6871
    #ifndef WOLFSSL_NO_KYBER512
6872
        case WOLFSSL_KYBER_LEVEL1:
6873
            return "KYBER_LEVEL1";
6874
        case WOLFSSL_P256_KYBER_LEVEL1:
6875
            return "P256_KYBER_LEVEL1";
6876
        #ifdef HAVE_CURVE25519
6877
        case WOLFSSL_X25519_KYBER_LEVEL1:
6878
            return "X25519_KYBER_LEVEL1";
6879
        #endif
6880
    #endif
6881
    #ifndef WOLFSSL_NO_KYBER768
6882
        case WOLFSSL_KYBER_LEVEL3:
6883
            return "KYBER_LEVEL3";
6884
        case WOLFSSL_P384_KYBER_LEVEL3:
6885
            return "P384_KYBER_LEVEL3";
6886
        case WOLFSSL_P256_KYBER_LEVEL3:
6887
            return "P256_KYBER_LEVEL3";
6888
        #ifdef HAVE_CURVE25519
6889
        case WOLFSSL_X25519_KYBER_LEVEL3:
6890
            return "X25519_KYBER_LEVEL3";
6891
        #endif
6892
        #ifdef HAVE_CURVE448
6893
        case WOLFSSL_X448_KYBER_LEVEL3:
6894
            return "X448_KYBER_LEVEL3";
6895
        #endif
6896
    #endif
6897
    #ifndef WOLFSSL_NO_KYBER1024
6898
        case WOLFSSL_KYBER_LEVEL5:
6899
            return "KYBER_LEVEL5";
6900
        case WOLFSSL_P521_KYBER_LEVEL5:
6901
            return "P521_KYBER_LEVEL5";
6902
    #endif
6903
#endif /* WOLFSSL_MLKEM_KYBER */
6904
0
        }
6905
0
    }
6906
0
#endif /* WOLFSSL_TLS13 && WOLFSSL_HAVE_MLKEM */
6907
6908
0
#ifdef HAVE_FFDHE
6909
0
    if (ssl->namedGroup != 0) {
6910
0
        cName = wolfssl_ffdhe_name(ssl->namedGroup);
6911
0
    }
6912
0
#endif
6913
6914
#ifdef HAVE_CURVE25519
6915
    if (ssl->ecdhCurveOID == ECC_X25519_OID && cName == NULL) {
6916
        cName = "X25519";
6917
    }
6918
#endif
6919
6920
#ifdef HAVE_CURVE448
6921
    if (ssl->ecdhCurveOID == ECC_X448_OID && cName == NULL) {
6922
        cName = "X448";
6923
    }
6924
#endif
6925
6926
0
#ifdef HAVE_ECC
6927
0
    if (ssl->ecdhCurveOID != 0 && cName == NULL) {
6928
0
        cName = wc_ecc_get_name(wc_ecc_get_oid(ssl->ecdhCurveOID, NULL,
6929
0
                                NULL));
6930
0
    }
6931
0
#endif
6932
6933
0
    return cName;
6934
0
}
6935
#endif
6936
6937
#ifdef OPENSSL_EXTRA
6938
/* Append str to the string at *in, cut to fit the *len bytes left. */
6939
static void wolfssl_cipher_desc_append(char** in, int* len, const char* str)
6940
{
6941
    size_t strLen;
6942
6943
    if (str == NULL)
6944
        return;
6945
    XSTRNCPY(*in, str, (size_t)*len);
6946
    (*in)[*len - 1] = '\0';
6947
    strLen = XSTRLEN(*in);
6948
    *len -= (int)strLen;
6949
    *in += strLen;
6950
}
6951
6952
/* Write a cipher description into in, cut to fit len bytes:
6953
 *   <name> <version> Kx=<kx> Au=<au> Enc=<enc> Mac=<mac> */
6954
static void wolfssl_cipher_desc_write(char* in, int len, const char* name,
6955
    const char* ver, const char* kx, const char* au, const char* enc,
6956
    const char* mac)
6957
{
6958
    in[0] = '\0';
6959
    wolfssl_cipher_desc_append(&in, &len, name);
6960
    wolfssl_cipher_desc_append(&in, &len, " ");
6961
    wolfssl_cipher_desc_append(&in, &len, ver);
6962
    wolfssl_cipher_desc_append(&in, &len, " Kx=");
6963
    wolfssl_cipher_desc_append(&in, &len, kx);
6964
    wolfssl_cipher_desc_append(&in, &len, " Au=");
6965
    wolfssl_cipher_desc_append(&in, &len, au);
6966
    wolfssl_cipher_desc_append(&in, &len, " Enc=");
6967
    wolfssl_cipher_desc_append(&in, &len, enc);
6968
    wolfssl_cipher_desc_append(&in, &len, " Mac=");
6969
    wolfssl_cipher_desc_append(&in, &len, mac);
6970
}
6971
6972
#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
6973
/* return authentication NID corresponding to cipher suite
6974
 * @param cipher a pointer to WOLFSSL_CIPHER
6975
 * return NID if found, WC_NID_undef if not found
6976
 */
6977
int wolfSSL_CIPHER_get_auth_nid(const WOLFSSL_CIPHER* cipher)
6978
{
6979
    static const struct authnid {
6980
        const char* alg_name;
6981
        const int  nid;
6982
    } authnid_tbl[] = {
6983
        {"RSA",     WC_NID_auth_rsa},
6984
        {"PSK",     WC_NID_auth_psk},
6985
        {"SRP",     WC_NID_auth_srp},
6986
        {"ECDSA",   WC_NID_auth_ecdsa},
6987
        {"None",    WC_NID_auth_null},
6988
        {NULL,      WC_NID_undef}
6989
    };
6990
6991
    const char* authStr;
6992
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
6993
6994
    if (GetCipherSegment(cipher, n) == NULL) {
6995
        WOLFSSL_MSG("no suitable cipher name found");
6996
        return WC_NID_undef;
6997
    }
6998
6999
    /* in TLS 1.3 case, NID will be WC_NID_auth_any */
7000
    if (XSTRCMP(n[0], "TLS13") == 0) {
7001
        return WC_NID_auth_any;
7002
    }
7003
7004
    authStr = GetCipherAuthStr(n);
7005
7006
    if (authStr != NULL) {
7007
        const struct authnid* sa;
7008
        for(sa = authnid_tbl; sa->alg_name != NULL; sa++) {
7009
            if (XSTRCMP(sa->alg_name, authStr) == 0) {
7010
                return sa->nid;
7011
            }
7012
        }
7013
    }
7014
7015
    return WC_NID_undef;
7016
}
7017
/* return cipher NID corresponding to cipher suite
7018
 * @param cipher a pointer to WOLFSSL_CIPHER
7019
 * return NID if found, WC_NID_undef if not found
7020
 */
7021
int wolfSSL_CIPHER_get_cipher_nid(const WOLFSSL_CIPHER* cipher)
7022
{
7023
    static const struct ciphernid {
7024
        const char* alg_name;
7025
        const int  nid;
7026
    } ciphernid_tbl[] = {
7027
        {"AESGCM(256)",             WC_NID_aes_256_gcm},
7028
        {"AESGCM(128)",             WC_NID_aes_128_gcm},
7029
        {"AESCCM(128)",             WC_NID_aes_128_ccm},
7030
        {"AES(128)",                WC_NID_aes_128_cbc},
7031
        {"AES(256)",                WC_NID_aes_256_cbc},
7032
        {"CAMELLIA(256)",           WC_NID_camellia_256_cbc},
7033
        {"CAMELLIA(128)",           WC_NID_camellia_128_cbc},
7034
        {"RC4",                     WC_NID_rc4},
7035
        {"3DES",                    WC_NID_des_ede3_cbc},
7036
        {"CHACHA20/POLY1305(256)",  WC_NID_chacha20_poly1305},
7037
        {"None",                    WC_NID_undef},
7038
        {NULL,                      WC_NID_undef}
7039
    };
7040
7041
    const char* encStr;
7042
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
7043
7044
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_cipher_nid");
7045
7046
    if (GetCipherSegment(cipher, n) == NULL) {
7047
        WOLFSSL_MSG("no suitable cipher name found");
7048
        return WC_NID_undef;
7049
    }
7050
7051
    encStr = GetCipherEncStr(n);
7052
7053
    if (encStr != NULL) {
7054
        const struct ciphernid* c;
7055
        for(c = ciphernid_tbl; c->alg_name != NULL; c++) {
7056
            if (XSTRCMP(c->alg_name, encStr) == 0) {
7057
                return c->nid;
7058
            }
7059
        }
7060
    }
7061
7062
    return WC_NID_undef;
7063
}
7064
/* return digest NID corresponding to cipher suite
7065
 * @param cipher a pointer to WOLFSSL_CIPHER
7066
 * return NID if found, WC_NID_undef if not found
7067
 */
7068
int wolfSSL_CIPHER_get_digest_nid(const WOLFSSL_CIPHER* cipher)
7069
{
7070
    static const struct macnid {
7071
        const char* alg_name;
7072
        const int  nid;
7073
    } macnid_tbl[] = {
7074
        {"SHA1",    WC_NID_sha1},
7075
        {"SHA256",  WC_NID_sha256},
7076
        {"SHA384",  WC_NID_sha384},
7077
        {NULL,      WC_NID_undef}
7078
    };
7079
7080
    const char* name;
7081
    const char* macStr;
7082
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
7083
    (void)name;
7084
7085
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_digest_nid");
7086
7087
    if ((name = GetCipherSegment(cipher, n)) == NULL) {
7088
        WOLFSSL_MSG("no suitable cipher name found");
7089
        return WC_NID_undef;
7090
    }
7091
7092
    /* in MD5 case, NID will be WC_NID_md5 */
7093
    if (XSTRSTR(name, "MD5") != NULL) {
7094
        return WC_NID_md5;
7095
    }
7096
7097
    macStr = GetCipherMacStr(n);
7098
7099
    if (macStr != NULL) {
7100
        const struct macnid* mc;
7101
        for(mc = macnid_tbl; mc->alg_name != NULL; mc++) {
7102
            if (XSTRCMP(mc->alg_name, macStr) == 0) {
7103
                return mc->nid;
7104
            }
7105
        }
7106
    }
7107
7108
    return WC_NID_undef;
7109
}
7110
/* return key exchange NID corresponding to cipher suite
7111
 * @param cipher a pointer to WOLFSSL_CIPHER
7112
 * return NID if found, WC_NID_undef if not found
7113
 */
7114
int wolfSSL_CIPHER_get_kx_nid(const WOLFSSL_CIPHER* cipher)
7115
{
7116
    static const struct kxnid {
7117
        const char* name;
7118
        const int  nid;
7119
    } kxnid_table[] = {
7120
        {"ECDHEPSK",  WC_NID_kx_ecdhe_psk},
7121
        {"ECDH",      WC_NID_kx_ecdhe},
7122
        {"DHEPSK",    WC_NID_kx_dhe_psk},
7123
        {"DH",        WC_NID_kx_dhe},
7124
        {"RSAPSK",    WC_NID_kx_rsa_psk},
7125
        {"SRP",       WC_NID_kx_srp},
7126
        {"EDH",       WC_NID_kx_dhe},
7127
        {"PSK",       WC_NID_kx_psk},
7128
        {"RSA",       WC_NID_kx_rsa},
7129
        {NULL,        WC_NID_undef}
7130
    };
7131
7132
    const char* keaStr;
7133
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
7134
7135
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_kx_nid");
7136
7137
    if (GetCipherSegment(cipher, n) == NULL) {
7138
        WOLFSSL_MSG("no suitable cipher name found");
7139
        return WC_NID_undef;
7140
    }
7141
7142
    /* in TLS 1.3 case, NID will be WC_NID_kx_any */
7143
    if (XSTRCMP(n[0], "TLS13") == 0) {
7144
        return WC_NID_kx_any;
7145
    }
7146
7147
    keaStr = GetCipherKeaStr(n);
7148
7149
    if (keaStr != NULL) {
7150
        const struct kxnid* k;
7151
        for(k = kxnid_table; k->name != NULL; k++) {
7152
            if (XSTRCMP(k->name, keaStr) == 0) {
7153
                return k->nid;
7154
            }
7155
        }
7156
    }
7157
7158
    return WC_NID_undef;
7159
}
7160
/* check if cipher suite is AEAD
7161
 * @param cipher a pointer to WOLFSSL_CIPHER
7162
 * return 1 if cipher is AEAD, 0 otherwise
7163
 */
7164
int wolfSSL_CIPHER_is_aead(const WOLFSSL_CIPHER* cipher)
7165
{
7166
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
7167
7168
    WOLFSSL_ENTER("wolfSSL_CIPHER_is_aead");
7169
7170
    if (GetCipherSegment(cipher, n) == NULL) {
7171
        WOLFSSL_MSG("no suitable cipher name found");
7172
        return WC_NID_undef;
7173
    }
7174
7175
    return IsCipherAEAD(n);
7176
}
7177
#endif /* OPENSSL_ALL || WOLFSSL_QT */
7178
7179
/* The parts of a suite are named as OpenSSL's SSL_CIPHER_description() names
7180
 * them. */
7181
7182
static WC_INLINE const char* wolfssl_kea_to_string(const CipherSpecs* specs)
7183
{
7184
    const char* keaStr;
7185
7186
    switch (specs->kea) {
7187
        case no_kea:
7188
            keaStr = "None";
7189
            break;
7190
        case rsa_kea:
7191
            keaStr = "RSA";
7192
            break;
7193
        case diffie_hellman_kea:
7194
            keaStr = "DH";
7195
            break;
7196
        case psk_kea:
7197
            keaStr = "PSK";
7198
            break;
7199
        case dhe_psk_kea:
7200
            keaStr = "DHEPSK";
7201
            break;
7202
        case ecdhe_psk_kea:
7203
            keaStr = "ECDHEPSK";
7204
            break;
7205
        case ecc_diffie_hellman_kea:
7206
            /* Static ECDH is named after the signature of the CA, as in
7207
             * OpenSSL 1.0.2. */
7208
            if (!specs->static_ecdh)
7209
                keaStr = "ECDH";
7210
            else if (specs->sig_algo == rsa_sa_algo)
7211
                keaStr = "ECDH/RSA";
7212
            else
7213
                keaStr = "ECDH/ECDSA";
7214
            break;
7215
        case any_kea:
7216
            keaStr = "any";
7217
            break;
7218
        default:
7219
            keaStr = "unknown";
7220
            break;
7221
    }
7222
7223
    return keaStr;
7224
}
7225
7226
static WC_INLINE const char* wolfssl_sigalg_to_string(
7227
    const CipherSpecs* specs)
7228
{
7229
    const char* authStr;
7230
7231
    switch (specs->sig_algo) {
7232
        case anonymous_sa_algo:
7233
            /* The PSK authenticates the peer. */
7234
            if ((specs->kea == psk_kea) || (specs->kea == dhe_psk_kea) ||
7235
                    (specs->kea == ecdhe_psk_kea))
7236
                authStr = "PSK";
7237
            else
7238
                authStr = "None";
7239
            break;
7240
        case rsa_sa_algo:
7241
            authStr = "RSA";
7242
            break;
7243
        case dsa_sa_algo:
7244
            authStr = "DSS";
7245
            break;
7246
        case ecc_dsa_sa_algo:
7247
            authStr = "ECDSA";
7248
            break;
7249
        case sm2_sa_algo:
7250
            authStr = "SM2";
7251
            break;
7252
        case any_sa_algo:
7253
            authStr = "any";
7254
            break;
7255
        default:
7256
            authStr = "unknown";
7257
            break;
7258
    }
7259
    /* Static ECDH: the ECDH key of the certificate authenticates. */
7260
    if (specs->static_ecdh)
7261
        authStr = "ECDH";
7262
7263
    return authStr;
7264
}
7265
7266
/* str128 or str256 by the key size of the cipher. */
7267
static WC_INLINE const char* wolfssl_cipher_by_size(const CipherSpecs* specs,
7268
    const char* str128, const char* str256)
7269
{
7270
    const char* encStr = "unknown";
7271
7272
    if (8 * specs->key_size == 128)
7273
        encStr = str128;
7274
    else if (8 * specs->key_size == 256)
7275
        encStr = str256;
7276
7277
    return encStr;
7278
}
7279
7280
static WC_INLINE const char* wolfssl_cipher_to_string(
7281
    const CipherSpecs* specs)
7282
{
7283
    const char* encStr;
7284
7285
    switch (specs->bulk_cipher_algorithm) {
7286
        case wolfssl_cipher_null:
7287
            encStr = "None";
7288
            break;
7289
        case wolfssl_rc4:
7290
            encStr = "RC4(128)";
7291
            break;
7292
        case wolfssl_triple_des:
7293
            encStr = "3DES(168)";
7294
            break;
7295
        case wolfssl_aes:
7296
            encStr = wolfssl_cipher_by_size(specs, "AES(128)", "AES(256)");
7297
            break;
7298
        case wolfssl_aes_gcm:
7299
            encStr = wolfssl_cipher_by_size(specs, "AESGCM(128)",
7300
                "AESGCM(256)");
7301
            break;
7302
        case wolfssl_aes_ccm:
7303
            if (specs->aead_mac_size == AES_CCM_8_AUTH_SZ) {
7304
                encStr = wolfssl_cipher_by_size(specs, "AESCCM8(128)",
7305
                    "AESCCM8(256)");
7306
            }
7307
            else {
7308
                encStr = wolfssl_cipher_by_size(specs, "AESCCM(128)",
7309
                    "AESCCM(256)");
7310
            }
7311
            break;
7312
        case wolfssl_chacha:
7313
            encStr = "CHACHA20/POLY1305(256)";
7314
            break;
7315
        case wolfssl_camellia:
7316
            encStr = wolfssl_cipher_by_size(specs, "Camellia(128)",
7317
                "Camellia(256)");
7318
            break;
7319
        case wolfssl_aria_gcm:
7320
            encStr = wolfssl_cipher_by_size(specs, "ARIAGCM(128)",
7321
                "ARIAGCM(256)");
7322
            break;
7323
        case wolfssl_sm4_cbc:
7324
            encStr = "SM4";
7325
            break;
7326
        case wolfssl_sm4_gcm:
7327
            encStr = "SM4GCM";
7328
            break;
7329
        case wolfssl_sm4_ccm:
7330
            encStr = "SM4CCM";
7331
            break;
7332
        default:
7333
            encStr = "unknown";
7334
            break;
7335
    }
7336
7337
    return encStr;
7338
}
7339
7340
static WC_INLINE const char* wolfssl_mac_to_string(const CipherSpecs* specs)
7341
{
7342
    const char* macStr;
7343
7344
    /* Integrity-only suites are set up as AEAD but use an HMAC. */
7345
    if ((specs->cipher_type == aead) &&
7346
            (specs->bulk_cipher_algorithm != wolfssl_cipher_null))
7347
        return "AEAD";
7348
7349
    switch (specs->mac_algorithm) {
7350
        case md5_mac:
7351
            macStr = "MD5";
7352
            break;
7353
        case sha_mac:
7354
            macStr = "SHA1";
7355
            break;
7356
        case sha256_mac:
7357
            macStr = "SHA256";
7358
            break;
7359
        case sha384_mac:
7360
            macStr = "SHA384";
7361
            break;
7362
        case sm3_mac:
7363
            macStr = "SM3";
7364
            break;
7365
        default:
7366
            macStr = "unknown";
7367
            break;
7368
    }
7369
7370
    return macStr;
7371
}
7372
7373
/* Get the specs of the suite of cipher. They depend only on the suite.
7374
 * Only suites in cipher_names are looked up: GetCipherSpec() matches some
7375
 * others on their second byte alone. The SCSV has no specs: looking it up
7376
 * would queue an error. */
7377
static void wolfssl_cipher_get_specs(const WOLFSSL_CIPHER* cipher,
7378
    CipherSpecs* specs)
7379
{
7380
    InitCipherSpecs(specs);
7381
#ifndef NO_TLS
7382
    /* Server side: the client side check needs the SSL's PSK option. */
7383
    if ((GetCipherNamesIdx(cipher->cipherSuite0, cipher->cipherSuite) >= 0) &&
7384
            !SCSV_Check(cipher->cipherSuite0, cipher->cipherSuite) &&
7385
            (GetCipherSpec(WOLFSSL_SERVER_END, cipher->cipherSuite0,
7386
                cipher->cipherSuite, specs, NULL) != 0)) {
7387
        InitCipherSpecs(specs);
7388
    }
7389
#else
7390
    (void)cipher;
7391
#endif
7392
}
7393
7394
char* wolfSSL_CIPHER_description(const WOLFSSL_CIPHER* cipher, char* in,
7395
                                 int len)
7396
{
7397
    const char* name = NULL;
7398
    CipherSpecs specs;
7399
    WOLFSSL_ENTER("wolfSSL_CIPHER_description");
7400
7401
    if (cipher == NULL || in == NULL || len <= 0)
7402
        return NULL;
7403
7404
    wolfssl_cipher_get_specs(cipher, &specs);
7405
    /* OpenSSL names TLS 1.3 suites by their IANA name. */
7406
    if (specs.kea == any_kea)
7407
        name = GetCipherNameIana(cipher->cipherSuite0, cipher->cipherSuite);
7408
    if (name == NULL)
7409
        name = GetCipherNameInternal(cipher->cipherSuite0, cipher->cipherSuite);
7410
7411
    wolfssl_cipher_desc_write(in, len, name,
7412
        wolfSSL_internal_get_version(&cipher->pv),
7413
        wolfssl_kea_to_string(&specs), wolfssl_sigalg_to_string(&specs),
7414
        wolfssl_cipher_to_string(&specs), wolfssl_mac_to_string(&specs));
7415
7416
    return in;
7417
}
7418
7419
#ifndef NO_WOLFSSL_STUB
7420
WOLFSSL_COMP_METHOD* wolfSSL_COMP_zlib(void)
7421
{
7422
    WOLFSSL_STUB("COMP_zlib");
7423
    return 0;
7424
}
7425
7426
WOLFSSL_COMP_METHOD* wolfSSL_COMP_rle(void)
7427
{
7428
    WOLFSSL_STUB("COMP_rle");
7429
    return 0;
7430
}
7431
7432
int wolfSSL_COMP_add_compression_method(int method, void* data)
7433
{
7434
    (void)method;
7435
    (void)data;
7436
    WOLFSSL_STUB("COMP_add_compression_method");
7437
    return 0;
7438
}
7439
7440
const WOLFSSL_COMP_METHOD* wolfSSL_get_current_compression(const WOLFSSL *ssl) {
7441
    (void)ssl;
7442
    return NULL;
7443
}
7444
7445
const WOLFSSL_COMP_METHOD* wolfSSL_get_current_expansion(const WOLFSSL *ssl) {
7446
    (void)ssl;
7447
    return NULL;
7448
}
7449
7450
const char* wolfSSL_COMP_get_name(const WOLFSSL_COMP_METHOD *comp)
7451
{
7452
    static const char ret[] = "not supported";
7453
7454
    (void)comp;
7455
    WOLFSSL_STUB("wolfSSL_COMP_get_name");
7456
    return ret;
7457
}
7458
#endif
7459
7460
/*  wolfSSL_set_dynlock_create_callback
7461
 *  CRYPTO_set_dynlock_create_callback has been deprecated since openSSL 1.0.1.
7462
 *  This function exists for compatibility purposes because wolfSSL satisfies
7463
 *  thread safety without relying on the callback.
7464
 */
7465
void wolfSSL_set_dynlock_create_callback(WOLFSSL_dynlock_value* (*f)(
7466
                                                          const char*, int))
7467
{
7468
    WOLFSSL_STUB("CRYPTO_set_dynlock_create_callback");
7469
    (void)f;
7470
}
7471
/*  wolfSSL_set_dynlock_lock_callback
7472
 *  CRYPTO_set_dynlock_lock_callback has been deprecated since openSSL 1.0.1.
7473
 *  This function exists for compatibility purposes because wolfSSL satisfies
7474
 *  thread safety without relying on the callback.
7475
 */
7476
void wolfSSL_set_dynlock_lock_callback(
7477
             void (*f)(int, WOLFSSL_dynlock_value*, const char*, int))
7478
{
7479
    WOLFSSL_STUB("CRYPTO_set_set_dynlock_lock_callback");
7480
    (void)f;
7481
}
7482
/*  wolfSSL_set_dynlock_destroy_callback
7483
 *  CRYPTO_set_dynlock_destroy_callback has been deprecated since openSSL 1.0.1.
7484
 *  This function exists for compatibility purposes because wolfSSL satisfies
7485
 *  thread safety without relying on the callback.
7486
 */
7487
void wolfSSL_set_dynlock_destroy_callback(
7488
                  void (*f)(WOLFSSL_dynlock_value*, const char*, int))
7489
{
7490
    WOLFSSL_STUB("CRYPTO_set_set_dynlock_destroy_callback");
7491
    (void)f;
7492
}
7493
7494
/* Sets the DNS hostname to name.
7495
 * Hostname is cleared if name is NULL or empty. */
7496
int wolfSSL_set1_host(WOLFSSL * ssl, const char* name)
7497
{
7498
    if (ssl == NULL) {
7499
        return WOLFSSL_FAILURE;
7500
    }
7501
7502
    return wolfSSL_X509_VERIFY_PARAM_set1_host(ssl->param, name, 0);
7503
}
7504
7505
/******************************************************************************
7506
* wolfSSL_CTX_set1_param - set a pointer to the SSL verification parameters
7507
*
7508
* RETURNS:
7509
*   WOLFSSL_SUCCESS on success, otherwise returns WOLFSSL_FAILURE
7510
*   Note: Returns WOLFSSL_SUCCESS, in case either parameter is NULL,
7511
*   same as openssl.
7512
*/
7513
int wolfSSL_CTX_set1_param(WOLFSSL_CTX* ctx, WOLFSSL_X509_VERIFY_PARAM *vpm)
7514
{
7515
    if (ctx == NULL || vpm == NULL)
7516
        return WOLFSSL_SUCCESS;
7517
7518
    return wolfSSL_X509_VERIFY_PARAM_set1(ctx->param, vpm);
7519
}
7520
7521
/******************************************************************************
7522
* wolfSSL_CTX/_get0_param - return a pointer to the SSL verification parameters
7523
*
7524
* RETURNS:
7525
* returns pointer to the SSL verification parameters on success,
7526
* otherwise returns NULL
7527
*/
7528
WOLFSSL_X509_VERIFY_PARAM* wolfSSL_CTX_get0_param(WOLFSSL_CTX* ctx)
7529
{
7530
    if (ctx == NULL) {
7531
        return NULL;
7532
    }
7533
7534
    return ctx->param;
7535
}
7536
7537
WOLFSSL_X509_VERIFY_PARAM* wolfSSL_get0_param(WOLFSSL* ssl)
7538
{
7539
    if (ssl == NULL) {
7540
        return NULL;
7541
    }
7542
    return ssl->param;
7543
}
7544
7545
#endif /* OPENSSL_EXTRA */
7546
7547
7548
#ifdef OPENSSL_EXTRA
7549
/* Sets a function callback that will send information about the state of all
7550
 * WOLFSSL objects that have been created by the WOLFSSL_CTX structure passed
7551
 * in.
7552
 *
7553
 * ctx WOLFSSL_CTX structure to set callback function in
7554
 * f   callback function to use
7555
 */
7556
void wolfSSL_CTX_set_info_callback(WOLFSSL_CTX* ctx,
7557
       void (*f)(const WOLFSSL* ssl, int type, int val))
7558
{
7559
    WOLFSSL_ENTER("wolfSSL_CTX_set_info_callback");
7560
    if (ctx == NULL) {
7561
        WOLFSSL_MSG("Bad function argument");
7562
    }
7563
    else {
7564
        ctx->CBIS = f;
7565
    }
7566
}
7567
7568
void wolfSSL_set_info_callback(WOLFSSL* ssl,
7569
       void (*f)(const WOLFSSL* ssl, int type, int val))
7570
{
7571
    WOLFSSL_ENTER("wolfSSL_set_info_callback");
7572
    if (ssl == NULL) {
7573
        WOLFSSL_MSG("Bad function argument");
7574
    }
7575
    else {
7576
        ssl->CBIS = f;
7577
    }
7578
}
7579
7580
7581
7582
#ifndef NO_TLS
7583
/* The info callback (DoAlert/SendAlert) passes alerts packed as
7584
 * (level << 8) | code. Unpack for the string lookups; a raw level or code
7585
 * (high byte zero) passes through unchanged. */
7586
static int unpackAlertCode(int alertID)
7587
{
7588
    if ((alertID >> 8) != 0)
7589
        alertID = alertID & 0xff;
7590
7591
    return alertID;
7592
}
7593
7594
static int unpackAlertLevel(int alertID)
7595
{
7596
    if ((alertID >> 8) != 0)
7597
        alertID = (alertID >> 8) & 0xff;
7598
7599
    return alertID;
7600
}
7601
7602
/* returns a string that describes the alert
7603
 *
7604
 * alertID the alert value to look up
7605
 */
7606
const char* wolfSSL_alert_type_string_long(int alertID)
7607
{
7608
    WOLFSSL_ENTER("wolfSSL_alert_type_string_long");
7609
7610
    return AlertTypeToString(unpackAlertCode(alertID));
7611
}
7612
7613
const char* wolfSSL_alert_type_string(int alertID)
7614
{
7615
    WOLFSSL_ENTER("wolfSSL_alert_type_string");
7616
7617
    switch (unpackAlertLevel(alertID)) {
7618
        case alert_warning:
7619
            return "W";
7620
        case alert_fatal:
7621
            return "F";
7622
        default:
7623
            return "U";
7624
    }
7625
}
7626
7627
const char* wolfSSL_alert_desc_string_long(int alertID)
7628
{
7629
    WOLFSSL_ENTER("wolfSSL_alert_desc_string_long");
7630
7631
    return AlertTypeToString(unpackAlertCode(alertID));
7632
}
7633
7634
const char* wolfSSL_alert_desc_string(int alertID)
7635
{
7636
    WOLFSSL_ENTER("wolfSSL_alert_desc_string");
7637
7638
    switch (unpackAlertCode(alertID)) {
7639
        case close_notify:
7640
            return "CN";
7641
        case unexpected_message:
7642
            return "UM";
7643
        case bad_record_mac:
7644
            return "BM";
7645
        case record_overflow:
7646
            return "RO";
7647
        case decompression_failure:
7648
            return "DF";
7649
        case handshake_failure:
7650
            return "HF";
7651
        case no_certificate:
7652
            return "NC";
7653
        case bad_certificate:
7654
            return "BC";
7655
        case unsupported_certificate:
7656
            return "UC";
7657
        case certificate_revoked:
7658
            return "CR";
7659
        case certificate_expired:
7660
            return "CE";
7661
        case certificate_unknown:
7662
            return "CU";
7663
        case illegal_parameter:
7664
            return "IP";
7665
        case unknown_ca:
7666
            return "CA";
7667
        case access_denied:
7668
            return "AD";
7669
        case decode_error:
7670
            return "DE";
7671
        case decrypt_error:
7672
            return "DC";
7673
        case wolfssl_alert_protocol_version:
7674
            return "PV";
7675
        case insufficient_security:
7676
            return "IS";
7677
        case internal_error:
7678
            return "IE";
7679
        case inappropriate_fallback:
7680
            return "IF";
7681
        case user_canceled:
7682
            return "US";
7683
        case no_renegotiation:
7684
            return "NR";
7685
        case missing_extension:
7686
            return "ME";
7687
        case unsupported_extension:
7688
            return "UE";
7689
        case unrecognized_name:
7690
            return "UN";
7691
        case bad_certificate_status_response:
7692
            return "BR";
7693
        case unknown_psk_identity:
7694
            return "UP";
7695
        case certificate_required:
7696
            return "CQ";
7697
        case no_application_protocol:
7698
            return "AP";
7699
        default:
7700
            return "UK";
7701
    }
7702
}
7703
#endif /* !NO_TLS */
7704
7705
7706
#endif /* OPENSSL_EXTRA */
7707
7708
static long wolf_set_options(long old_op, long op)
7709
0
{
7710
    /* if SSL_OP_ALL then turn all bug workarounds on */
7711
0
    if ((op & WOLFSSL_OP_ALL) == WOLFSSL_OP_ALL) {
7712
0
        WOLFSSL_MSG("\tSSL_OP_ALL");
7713
0
    }
7714
7715
    /* by default cookie exchange is on with DTLS */
7716
0
    if ((op & WOLFSSL_OP_COOKIE_EXCHANGE) == WOLFSSL_OP_COOKIE_EXCHANGE) {
7717
0
        WOLFSSL_MSG("\tSSL_OP_COOKIE_EXCHANGE : on by default");
7718
0
    }
7719
7720
0
    if ((op & WOLFSSL_OP_NO_SSLv2) == WOLFSSL_OP_NO_SSLv2) {
7721
0
        WOLFSSL_MSG("\tWOLFSSL_OP_NO_SSLv2 : wolfSSL does not support SSLv2");
7722
0
    }
7723
7724
#ifdef SSL_OP_NO_TLSv1_3
7725
    if ((op & WOLFSSL_OP_NO_TLSv1_3) == WOLFSSL_OP_NO_TLSv1_3) {
7726
        WOLFSSL_MSG("\tSSL_OP_NO_TLSv1_3");
7727
    }
7728
#endif
7729
7730
0
    if ((op & WOLFSSL_OP_NO_TLSv1_2) == WOLFSSL_OP_NO_TLSv1_2) {
7731
0
        WOLFSSL_MSG("\tSSL_OP_NO_TLSv1_2");
7732
0
    }
7733
7734
0
    if ((op & WOLFSSL_OP_NO_TLSv1_1) == WOLFSSL_OP_NO_TLSv1_1) {
7735
0
        WOLFSSL_MSG("\tSSL_OP_NO_TLSv1_1");
7736
0
    }
7737
7738
0
    if ((op & WOLFSSL_OP_NO_TLSv1) == WOLFSSL_OP_NO_TLSv1) {
7739
0
        WOLFSSL_MSG("\tSSL_OP_NO_TLSv1");
7740
0
    }
7741
7742
0
    if ((op & WOLFSSL_OP_NO_SSLv3) == WOLFSSL_OP_NO_SSLv3) {
7743
0
        WOLFSSL_MSG("\tSSL_OP_NO_SSLv3");
7744
0
    }
7745
7746
0
    if ((op & WOLFSSL_OP_CIPHER_SERVER_PREFERENCE) ==
7747
0
            WOLFSSL_OP_CIPHER_SERVER_PREFERENCE) {
7748
0
        WOLFSSL_MSG("\tWOLFSSL_OP_CIPHER_SERVER_PREFERENCE");
7749
0
    }
7750
7751
0
    if ((op & WOLFSSL_OP_NO_COMPRESSION) == WOLFSSL_OP_NO_COMPRESSION) {
7752
    #ifdef HAVE_LIBZ
7753
        WOLFSSL_MSG("SSL_OP_NO_COMPRESSION");
7754
    #else
7755
0
        WOLFSSL_MSG("SSL_OP_NO_COMPRESSION: compression not compiled in");
7756
0
    #endif
7757
0
    }
7758
7759
0
    return old_op | op;
7760
0
}
7761
7762
static int FindHashSig(const Suites* suites, byte first, byte second)
7763
0
{
7764
0
    word16 i;
7765
7766
0
    if (suites == NULL || suites->hashSigAlgoSz == 0) {
7767
0
        WOLFSSL_MSG("Suites pointer error or suiteSz 0");
7768
0
        return SUITES_ERROR;
7769
0
    }
7770
7771
0
    for (i = 0; i < suites->hashSigAlgoSz-1; i += 2) {
7772
0
        if (suites->hashSigAlgo[i]   == first &&
7773
0
            suites->hashSigAlgo[i+1] == second )
7774
0
            return i;
7775
0
    }
7776
7777
0
    return MATCH_SUITE_ERROR;
7778
0
}
7779
7780
long wolfSSL_set_options(WOLFSSL* ssl, long op)
7781
0
{
7782
0
    word16 haveRSA = 1;
7783
0
    word16 havePSK = 0;
7784
0
    int    keySz   = 0;
7785
7786
0
    WOLFSSL_ENTER("wolfSSL_set_options");
7787
7788
0
    if (ssl == NULL) {
7789
0
        return 0;
7790
0
    }
7791
7792
0
    ssl->options.mask = (unsigned long)wolf_set_options((long)ssl->options.mask, op);
7793
7794
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1_3) == WOLFSSL_OP_NO_TLSv1_3) {
7795
0
        WOLFSSL_MSG("Disabling TLS 1.3");
7796
0
        if (ssl->version.minor == TLSv1_3_MINOR)
7797
0
            ssl->version.minor = TLSv1_2_MINOR;
7798
0
    }
7799
7800
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1_2) == WOLFSSL_OP_NO_TLSv1_2) {
7801
0
        WOLFSSL_MSG("Disabling TLS 1.2");
7802
0
        if (ssl->version.minor == TLSv1_2_MINOR)
7803
0
            ssl->version.minor = TLSv1_1_MINOR;
7804
0
    }
7805
7806
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1_1) == WOLFSSL_OP_NO_TLSv1_1) {
7807
0
        WOLFSSL_MSG("Disabling TLS 1.1");
7808
0
        if (ssl->version.minor == TLSv1_1_MINOR)
7809
0
            ssl->version.minor = TLSv1_MINOR;
7810
0
    }
7811
7812
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1) == WOLFSSL_OP_NO_TLSv1) {
7813
0
        WOLFSSL_MSG("Disabling TLS 1.0");
7814
0
        if (ssl->version.minor == TLSv1_MINOR)
7815
0
            ssl->version.minor = SSLv3_MINOR;
7816
0
    }
7817
7818
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_COMPRESSION)
7819
0
        == WOLFSSL_OP_NO_COMPRESSION) {
7820
    #ifdef HAVE_LIBZ
7821
        ssl->options.usingCompression = 0;
7822
    #endif
7823
0
    }
7824
7825
#if defined(HAVE_SESSION_TICKET) && (defined(OPENSSL_EXTRA) \
7826
        || defined(HAVE_WEBSERVER) || defined(WOLFSSL_WPAS_SMALL))
7827
    if ((ssl->options.mask & WOLFSSL_OP_NO_TICKET) == WOLFSSL_OP_NO_TICKET) {
7828
      ssl->options.noTicketTls12 = 1;
7829
    }
7830
#endif
7831
7832
7833
    /* in the case of a version change the cipher suites should be reset */
7834
#ifndef NO_PSK
7835
    havePSK = ssl->options.havePSK;
7836
#endif
7837
#ifdef NO_RSA
7838
    haveRSA = 0;
7839
#endif
7840
0
#ifndef NO_CERTS
7841
0
    keySz = ssl->buffers.keySz;
7842
0
#endif
7843
7844
0
    if (ssl->options.side != WOLFSSL_NEITHER_END) {
7845
0
        if (AllocateSuites(ssl) != 0)
7846
0
            return 0;
7847
0
        if (!ssl->suites->setSuites) {
7848
            /* Client side won't set DH params, so it needs haveDH set to TRUE. */
7849
0
            if (ssl->options.side == WOLFSSL_CLIENT_END)
7850
0
                InitSuites(ssl->suites, ssl->version, keySz, haveRSA,
7851
0
                       havePSK, TRUE, ssl->options.haveECDSAsig,
7852
0
                       ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
7853
0
                       ssl->options.useAnon,
7854
0
                       TRUE, TRUE, TRUE, TRUE, ssl->options.side);
7855
0
            else
7856
0
                InitSuites(ssl->suites, ssl->version, keySz, haveRSA,
7857
0
                       havePSK, ssl->options.haveDH, ssl->options.haveECDSAsig,
7858
0
                       ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
7859
0
                       ssl->options.useAnon,
7860
0
                       TRUE, TRUE, TRUE, TRUE, ssl->options.side);
7861
0
        }
7862
0
        else {
7863
            /* Only preserve overlapping suites */
7864
0
            Suites tmpSuites;
7865
0
            word16 in, out;
7866
0
            word16 haveECDSAsig, haveStaticECC;
7867
#ifdef NO_RSA
7868
            haveECDSAsig = 1;
7869
            haveStaticECC = 1;
7870
#else
7871
0
            haveECDSAsig = 0;
7872
0
            haveStaticECC = ssl->options.haveStaticECC;
7873
0
#endif
7874
0
            XMEMSET(&tmpSuites, 0, sizeof(Suites));
7875
            /* Get all possible ciphers and sigalgs for the version. Following
7876
             * options limit the allowed ciphers so let's try to get as many as
7877
             * possible.
7878
             * - haveStaticECC turns off haveRSA
7879
             * - haveECDSAsig turns off haveRSAsig
7880
             * - SUITES_NULL_EXPLICIT includes the integrity-only suites, so
7881
             *   an explicitly configured one is preserved */
7882
0
            InitSuites(&tmpSuites, ssl->version, 0, 1, 1, 1, haveECDSAsig, 1, 1,
7883
0
                    haveStaticECC, 1, SUITES_NULL_EXPLICIT, 1, 1, 1,
7884
0
                    ssl->options.side);
7885
0
            for (in = 0, out = 0; in < ssl->suites->suiteSz; in += SUITE_LEN) {
7886
0
                if (FindSuite(&tmpSuites, ssl->suites->suites[in],
7887
0
                        ssl->suites->suites[in+1]) >= 0) {
7888
0
                    ssl->suites->suites[out] = ssl->suites->suites[in];
7889
0
                    ssl->suites->suites[out+1] = ssl->suites->suites[in+1];
7890
0
                    out += SUITE_LEN;
7891
0
                }
7892
0
            }
7893
0
            ssl->suites->suiteSz = out;
7894
0
            for (in = 0, out = 0; in < ssl->suites->hashSigAlgoSz; in += 2) {
7895
0
                if (FindHashSig(&tmpSuites, ssl->suites->hashSigAlgo[in],
7896
0
                    ssl->suites->hashSigAlgo[in+1]) >= 0) {
7897
0
                    ssl->suites->hashSigAlgo[out] =
7898
0
                            ssl->suites->hashSigAlgo[in];
7899
0
                    ssl->suites->hashSigAlgo[out+1] =
7900
0
                            ssl->suites->hashSigAlgo[in+1];
7901
0
                    out += 2;
7902
0
                }
7903
0
            }
7904
0
            ssl->suites->hashSigAlgoSz = out;
7905
0
        }
7906
0
    }
7907
7908
0
    return (long)ssl->options.mask;
7909
0
}
7910
7911
7912
long wolfSSL_get_options(const WOLFSSL* ssl)
7913
0
{
7914
0
    WOLFSSL_ENTER("wolfSSL_get_options");
7915
0
    if(ssl == NULL)
7916
0
        return WOLFSSL_FAILURE;
7917
0
    return (long)ssl->options.mask;
7918
0
}
7919
7920
#if defined(HAVE_SECURE_RENEGOTIATION) \
7921
        || defined(HAVE_SERVER_RENEGOTIATION_INFO)
7922
/* clears the counter for number of renegotiations done
7923
 * returns the current count before it is cleared */
7924
long wolfSSL_clear_num_renegotiations(WOLFSSL *s)
7925
0
{
7926
0
    long total;
7927
7928
0
    WOLFSSL_ENTER("wolfSSL_clear_num_renegotiations");
7929
0
    if (s == NULL)
7930
0
        return 0;
7931
7932
0
    total = s->secure_rene_count;
7933
0
    s->secure_rene_count = 0;
7934
0
    return total;
7935
0
}
7936
7937
7938
/* return the number of renegotiations since wolfSSL_new */
7939
long wolfSSL_total_renegotiations(WOLFSSL *s)
7940
0
{
7941
0
    WOLFSSL_ENTER("wolfSSL_total_renegotiations");
7942
0
    return wolfSSL_num_renegotiations(s);
7943
0
}
7944
7945
7946
/* return the number of renegotiations since wolfSSL_new */
7947
long wolfSSL_num_renegotiations(WOLFSSL* s)
7948
0
{
7949
0
    if (s == NULL) {
7950
0
        return 0;
7951
0
    }
7952
7953
0
    return s->secure_rene_count;
7954
0
}
7955
7956
7957
/* Is there a renegotiation currently in progress? */
7958
int  wolfSSL_SSL_renegotiate_pending(WOLFSSL *s)
7959
0
{
7960
0
    return s && s->options.handShakeDone &&
7961
0
            s->options.handShakeState != HANDSHAKE_DONE ? 1 : 0;
7962
0
}
7963
#endif /* HAVE_SECURE_RENEGOTIATION || HAVE_SERVER_RENEGOTIATION_INFO */
7964
7965
#ifdef OPENSSL_EXTRA
7966
7967
long wolfSSL_clear_options(WOLFSSL* ssl, long opt)
7968
{
7969
    WOLFSSL_ENTER("wolfSSL_clear_options");
7970
    if(ssl == NULL)
7971
        return WOLFSSL_FAILURE;
7972
    ssl->options.mask &= (unsigned long)~opt;
7973
    return (long)ssl->options.mask;
7974
}
7975
7976
7977
#ifndef NO_WOLFSSL_STUB
7978
/*** TBD ***/
7979
void WOLFSSL_CTX_set_tmp_dh_callback(WOLFSSL_CTX *ctx,
7980
    WOLFSSL_DH *(*dh) (WOLFSSL *ssl, int is_export, int keylength))
7981
{
7982
    (void)ctx;
7983
    (void)dh;
7984
    WOLFSSL_STUB("WOLFSSL_CTX_set_tmp_dh_callback");
7985
}
7986
#endif
7987
7988
#ifndef NO_WOLFSSL_STUB
7989
/*** TBD ***/
7990
WOLF_STACK_OF(WOLFSSL_COMP) *WOLFSSL_COMP_get_compression_methods(void)
7991
{
7992
    WOLFSSL_STUB("WOLFSSL_COMP_get_compression_methods");
7993
    return NULL;
7994
}
7995
#endif
7996
7997
7998
#if !defined(NETOS)
7999
#endif
8000
8001
8002
#endif /* OPENSSL_EXTRA */
8003
8004
#ifdef WOLFSSL_HAVE_TLS_UNIQUE
8005
size_t wolfSSL_get_finished(const WOLFSSL *ssl, void *buf, size_t count)
8006
{
8007
    byte len = 0;
8008
    byte const * src;
8009
8010
    WOLFSSL_ENTER("wolfSSL_get_finished");
8011
8012
    if (!ssl || !buf) {
8013
        WOLFSSL_MSG("Bad parameter");
8014
        return WOLFSSL_FAILURE;
8015
    }
8016
8017
    if (ssl->options.side == WOLFSSL_SERVER_END) {
8018
        src = ssl->serverFinished;
8019
        len = ssl->serverFinished_len;
8020
    }
8021
    else {
8022
        src = ssl->clientFinished;
8023
        len = ssl->clientFinished_len;
8024
    }
8025
8026
    if (count < len) {
8027
        WOLFSSL_MSG("Buffer too small");
8028
        return WOLFSSL_FAILURE;
8029
    }
8030
8031
    XMEMCPY(buf, src, len);
8032
8033
    return len;
8034
}
8035
8036
size_t wolfSSL_get_peer_finished(const WOLFSSL *ssl, void *buf, size_t count)
8037
{
8038
    byte len = 0;
8039
    byte const * src;
8040
8041
    WOLFSSL_ENTER("wolfSSL_get_peer_finished");
8042
8043
    if (!ssl || !buf) {
8044
        WOLFSSL_MSG("Bad parameter");
8045
        return WOLFSSL_FAILURE;
8046
    }
8047
8048
    if (ssl->options.side == WOLFSSL_CLIENT_END) {
8049
        src = ssl->serverFinished;
8050
        len = ssl->serverFinished_len;
8051
    }
8052
    else {
8053
        src = ssl->clientFinished;
8054
        len = ssl->clientFinished_len;
8055
    }
8056
8057
    if (count < len) {
8058
        WOLFSSL_MSG("Buffer too small");
8059
        return WOLFSSL_FAILURE;
8060
    }
8061
8062
    XMEMCPY(buf, src, len);
8063
8064
    return len;
8065
}
8066
#endif /* WOLFSSL_HAVE_TLS_UNIQUE */
8067
8068
8069
#ifdef OPENSSL_EXTRA
8070
8071
#ifndef NO_WOLFSSL_STUB
8072
/* shows the number of accepts attempted by CTX in it's lifetime */
8073
long wolfSSL_CTX_sess_accept(WOLFSSL_CTX* ctx)
8074
{
8075
    WOLFSSL_STUB("wolfSSL_CTX_sess_accept");
8076
    (void)ctx;
8077
    return 0;
8078
}
8079
#endif
8080
8081
#ifndef NO_WOLFSSL_STUB
8082
/* shows the number of connects attempted CTX in it's lifetime */
8083
long wolfSSL_CTX_sess_connect(WOLFSSL_CTX* ctx)
8084
{
8085
    WOLFSSL_STUB("wolfSSL_CTX_sess_connect");
8086
    (void)ctx;
8087
    return 0;
8088
}
8089
#endif
8090
8091
8092
#ifndef NO_WOLFSSL_STUB
8093
/* shows the number of accepts completed by CTX in it's lifetime */
8094
long wolfSSL_CTX_sess_accept_good(WOLFSSL_CTX* ctx)
8095
{
8096
    WOLFSSL_STUB("wolfSSL_CTX_sess_accept_good");
8097
    (void)ctx;
8098
    return 0;
8099
}
8100
#endif
8101
8102
8103
#ifndef NO_WOLFSSL_STUB
8104
/* shows the number of connects completed by CTX in it's lifetime */
8105
long wolfSSL_CTX_sess_connect_good(WOLFSSL_CTX* ctx)
8106
{
8107
    WOLFSSL_STUB("wolfSSL_CTX_sess_connect_good");
8108
    (void)ctx;
8109
    return 0;
8110
}
8111
#endif
8112
8113
8114
#ifndef NO_WOLFSSL_STUB
8115
/* shows the number of renegotiation accepts attempted by CTX */
8116
long wolfSSL_CTX_sess_accept_renegotiate(WOLFSSL_CTX* ctx)
8117
{
8118
    WOLFSSL_STUB("wolfSSL_CTX_sess_accept_renegotiate");
8119
    (void)ctx;
8120
    return 0;
8121
}
8122
#endif
8123
8124
8125
#ifndef NO_WOLFSSL_STUB
8126
/* shows the number of renegotiation accepts attempted by CTX */
8127
long wolfSSL_CTX_sess_connect_renegotiate(WOLFSSL_CTX* ctx)
8128
{
8129
    WOLFSSL_STUB("wolfSSL_CTX_sess_connect_renegotiate");
8130
    (void)ctx;
8131
    return 0;
8132
}
8133
#endif
8134
8135
8136
#ifndef NO_WOLFSSL_STUB
8137
long wolfSSL_CTX_sess_hits(WOLFSSL_CTX* ctx)
8138
{
8139
    WOLFSSL_STUB("wolfSSL_CTX_sess_hits");
8140
    (void)ctx;
8141
    return 0;
8142
}
8143
#endif
8144
8145
8146
#ifndef NO_WOLFSSL_STUB
8147
long wolfSSL_CTX_sess_cb_hits(WOLFSSL_CTX* ctx)
8148
{
8149
    WOLFSSL_STUB("wolfSSL_CTX_sess_cb_hits");
8150
    (void)ctx;
8151
    return 0;
8152
}
8153
#endif
8154
8155
8156
#ifndef NO_WOLFSSL_STUB
8157
long wolfSSL_CTX_sess_cache_full(WOLFSSL_CTX* ctx)
8158
{
8159
    WOLFSSL_STUB("wolfSSL_CTX_sess_cache_full");
8160
    (void)ctx;
8161
    return 0;
8162
}
8163
#endif
8164
8165
8166
#ifndef NO_WOLFSSL_STUB
8167
long wolfSSL_CTX_sess_misses(WOLFSSL_CTX* ctx)
8168
{
8169
    WOLFSSL_STUB("wolfSSL_CTX_sess_misses");
8170
    (void)ctx;
8171
    return 0;
8172
}
8173
#endif
8174
8175
8176
#ifndef NO_WOLFSSL_STUB
8177
long wolfSSL_CTX_sess_timeouts(WOLFSSL_CTX* ctx)
8178
{
8179
    WOLFSSL_STUB("wolfSSL_CTX_sess_timeouts");
8180
    (void)ctx;
8181
    return 0;
8182
}
8183
#endif
8184
8185
#endif /* OPENSSL_EXTRA */
8186
8187
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_TLS_READ_AHEAD)
8188
int wolfSSL_get_read_ahead(const WOLFSSL* ssl)
8189
{
8190
    if (ssl == NULL) {
8191
        return WOLFSSL_FAILURE;
8192
    }
8193
8194
    return ssl->readAhead;
8195
}
8196
8197
8198
int wolfSSL_set_read_ahead(WOLFSSL* ssl, int v)
8199
{
8200
    if (ssl == NULL) {
8201
        return WOLFSSL_FAILURE;
8202
    }
8203
8204
    ssl->readAhead = (byte)v;
8205
8206
    return WOLFSSL_SUCCESS;
8207
}
8208
8209
8210
int wolfSSL_CTX_get_read_ahead(WOLFSSL_CTX* ctx)
8211
{
8212
    if (ctx == NULL) {
8213
        return WOLFSSL_FAILURE;
8214
    }
8215
8216
    return ctx->readAhead;
8217
}
8218
8219
8220
int wolfSSL_CTX_set_read_ahead(WOLFSSL_CTX* ctx, int v)
8221
{
8222
    if (ctx == NULL) {
8223
        return WOLFSSL_FAILURE;
8224
    }
8225
8226
    ctx->readAhead = (byte)v;
8227
8228
    return WOLFSSL_SUCCESS;
8229
}
8230
8231
/* Set the read-ahead receive window size. When read-ahead is enabled, a single
8232
 * recv() pulls in up to this many bytes:
8233
 *  - 0 (the default) requests one full record.
8234
 *  - A value larger than one record lets a single recv() coalesce several
8235
 *    back-to-back records.
8236
 *  - A value smaller than one record is honoured as-is, capping the receive
8237
 *    buffer's footprint when the peer's records are known to be small.
8238
 * 'len' is only a speculative window: a record larger than it is still received
8239
 * correctly, with the buffer grown on demand. Effective only when the library
8240
 * is built with read-ahead support (WOLFSSL_TLS_READ_AHEAD). Returns int rather
8241
 * than OpenSSL's void to match wolfSSL's other read-ahead setters; callers that
8242
 * ignore the return remain source-compatible. */
8243
int wolfSSL_CTX_set_default_read_buffer_len(WOLFSSL_CTX* ctx, size_t len)
8244
{
8245
    if (ctx == NULL) {
8246
        return WOLFSSL_FAILURE;
8247
    }
8248
8249
    /* 0 selects the default one-record window (matches OpenSSL, where 0 means
8250
     * "use the built-in default"). Otherwise clamp to a sane maximum so the
8251
     * stored window cannot overflow the signed arithmetic in the receive path
8252
     * (see WOLFSSL_MAX_READ_AHEAD_SZ). */
8253
    if (len == 0) {
8254
        len = WOLFSSL_READ_AHEAD_SZ;
8255
    }
8256
    else if (len > (size_t)WOLFSSL_MAX_READ_AHEAD_SZ) {
8257
        len = (size_t)WOLFSSL_MAX_READ_AHEAD_SZ;
8258
    }
8259
    ctx->readAheadSz = (word32)len;
8260
8261
    return WOLFSSL_SUCCESS;
8262
}
8263
8264
int wolfSSL_set_default_read_buffer_len(WOLFSSL* ssl, size_t len)
8265
{
8266
    if (ssl == NULL) {
8267
        return WOLFSSL_FAILURE;
8268
    }
8269
8270
    /* 0 selects the default one-record window (matches OpenSSL, where 0 means
8271
     * "use the built-in default"). Otherwise clamp to a sane maximum so the
8272
     * stored window cannot overflow the signed arithmetic in the receive path
8273
     * (see WOLFSSL_MAX_READ_AHEAD_SZ). */
8274
    if (len == 0) {
8275
        len = WOLFSSL_READ_AHEAD_SZ;
8276
    }
8277
    else if (len > (size_t)WOLFSSL_MAX_READ_AHEAD_SZ) {
8278
        len = (size_t)WOLFSSL_MAX_READ_AHEAD_SZ;
8279
    }
8280
    ssl->readAheadSz = (word32)len;
8281
8282
    return WOLFSSL_SUCCESS;
8283
}
8284
8285
long wolfSSL_CTX_get_default_read_buffer_len(WOLFSSL_CTX* ctx)
8286
{
8287
    if (ctx == NULL) {
8288
        return WOLFSSL_FAILURE;
8289
    }
8290
8291
    return (long)ctx->readAheadSz;
8292
}
8293
8294
long wolfSSL_get_default_read_buffer_len(const WOLFSSL* ssl)
8295
{
8296
    if (ssl == NULL) {
8297
        return WOLFSSL_FAILURE;
8298
    }
8299
8300
    return (long)ssl->readAheadSz;
8301
}
8302
#endif /* OPENSSL_EXTRA || WOLFSSL_TLS_READ_AHEAD */
8303
8304
#ifdef OPENSSL_EXTRA
8305
long wolfSSL_CTX_set_tlsext_opaque_prf_input_callback_arg(WOLFSSL_CTX* ctx,
8306
        void* arg)
8307
{
8308
    if (ctx == NULL) {
8309
        return WOLFSSL_FAILURE;
8310
    }
8311
8312
    ctx->userPRFArg = arg;
8313
    return WOLFSSL_SUCCESS;
8314
}
8315
8316
#endif /* OPENSSL_EXTRA */
8317
8318
8319
8320
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
8321
/* Free the dynamically allocated data.
8322
 *
8323
 * p  Pointer to dynamically allocated memory.
8324
 */
8325
void wolfSSL_OPENSSL_free(void* p)
8326
{
8327
    WOLFSSL_MSG("wolfSSL_OPENSSL_free");
8328
8329
    XFREE(p, NULL, DYNAMIC_TYPE_OPENSSL);
8330
}
8331
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
8332
8333
#ifdef OPENSSL_EXTRA
8334
8335
void *wolfSSL_OPENSSL_malloc(size_t a)
8336
{
8337
    return (void *)XMALLOC(a, NULL, DYNAMIC_TYPE_OPENSSL);
8338
}
8339
8340
int wolfSSL_OPENSSL_hexchar2int(unsigned char c)
8341
{
8342
    /* 'char' is unsigned on some platforms. */
8343
    return (int)(signed char)HexCharToByte((char)c);
8344
}
8345
8346
unsigned char *wolfSSL_OPENSSL_hexstr2buf(const char *str, long *len)
8347
{
8348
    unsigned char* targetBuf;
8349
    int srcDigitHigh = 0;
8350
    int srcDigitLow = 0;
8351
    size_t srcLen;
8352
    size_t srcIdx = 0;
8353
    long targetIdx = 0;
8354
8355
    srcLen = XSTRLEN(str);
8356
    targetBuf = (unsigned char*)XMALLOC(srcLen / 2, NULL, DYNAMIC_TYPE_OPENSSL);
8357
    if (targetBuf == NULL) {
8358
        return NULL;
8359
    }
8360
8361
    while (srcIdx < srcLen) {
8362
        if (str[srcIdx] == ':') {
8363
            srcIdx++;
8364
            continue;
8365
        }
8366
8367
        srcDigitHigh = wolfSSL_OPENSSL_hexchar2int((unsigned char)str[srcIdx++]);
8368
        srcDigitLow = wolfSSL_OPENSSL_hexchar2int((unsigned char)str[srcIdx++]);
8369
        if (srcDigitHigh < 0 || srcDigitLow < 0) {
8370
            WOLFSSL_MSG("Invalid hex character.");
8371
            XFREE(targetBuf, NULL, DYNAMIC_TYPE_OPENSSL);
8372
            return NULL;
8373
        }
8374
8375
        targetBuf[targetIdx++] = (unsigned char)((srcDigitHigh << 4) |
8376
                                                  srcDigitLow       );
8377
    }
8378
8379
    if (len != NULL)
8380
        *len = targetIdx;
8381
8382
    return targetBuf;
8383
}
8384
8385
int wolfSSL_OPENSSL_init_ssl(word64 opts, const WOLFSSL_INIT_SETTINGS *settings)
8386
{
8387
    (void)opts;
8388
    (void)settings;
8389
    return wolfSSL_library_init();
8390
}
8391
8392
int wolfSSL_OPENSSL_init_crypto(word64 opts,
8393
    const WOLFSSL_INIT_SETTINGS* settings)
8394
{
8395
    (void)opts;
8396
    (void)settings;
8397
    return wolfSSL_library_init();
8398
}
8399
8400
#endif /* OPENSSL_EXTRA */
8401
8402
8403
#ifdef HAVE_FUZZER
8404
void wolfSSL_SetFuzzerCb(WOLFSSL* ssl, CallbackFuzzer cbf, void* fCtx)
8405
{
8406
    if (ssl) {
8407
        ssl->fuzzerCb  = cbf;
8408
        ssl->fuzzerCtx = fCtx;
8409
    }
8410
}
8411
#endif
8412
8413
8414
#ifdef WOLFSSL_HAVE_WOLFSCEP
8415
    /* Used by autoconf to see if wolfSCEP is available */
8416
    void wolfSSL_wolfSCEP(void) {}
8417
#endif
8418
8419
8420
#ifdef WOLFSSL_HAVE_CERT_SERVICE
8421
    /* Used by autoconf to see if cert service is available */
8422
    void wolfSSL_cert_service(void) {}
8423
#endif
8424
8425
#if defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) || \
8426
    defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(HAVE_STUNNEL) || \
8427
    defined(WOLFSSL_NGINX) || defined(HAVE_POCO_LIB) || \
8428
    defined(WOLFSSL_HAPROXY)
8429
8430
    void wolfSSL_set_verify_depth(WOLFSSL *ssl, int depth)
8431
    {
8432
    #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
8433
        WOLFSSL_ENTER("wolfSSL_set_verify_depth");
8434
        /* Reject out-of-range depths; valid range is 0 to MAX_CHAIN_DEPTH. */
8435
        if ((ssl == NULL) || (depth < 0) || (depth > MAX_CHAIN_DEPTH)) {
8436
            WOLFSSL_MSG("Bad depth argument, too large or less than 0");
8437
        }
8438
        else {
8439
            ssl->options.verifyDepth = (byte)depth;
8440
        }
8441
    #endif
8442
    }
8443
8444
#endif /* OPENSSL_ALL || HAVE_LIGHTY || WOLFSSL_MYSQL_COMPATIBLE ||
8445
    HAVE_STUNNEL || WOLFSSL_NGINX || HAVE_POCO_LIB || WOLFSSL_HAPROXY */
8446
8447
#ifdef OPENSSL_EXTRA
8448
8449
/* wolfSSL uses negative values for error states. This function returns an
8450
 * unsigned type so the value returned is the absolute value of the error.
8451
 */
8452
8453
#endif /* OPENSSL_EXTRA */
8454
8455
#ifdef HAVE_EX_DATA_CRYPTO
8456
CRYPTO_EX_cb_ctx* crypto_ex_cb_ctx_session = NULL;
8457
8458
static int crypto_ex_cb_new(CRYPTO_EX_cb_ctx** dst, long ctx_l, void* ctx_ptr,
8459
        WOLFSSL_CRYPTO_EX_new* new_func, WOLFSSL_CRYPTO_EX_dup* dup_func,
8460
        WOLFSSL_CRYPTO_EX_free* free_func)
8461
{
8462
    CRYPTO_EX_cb_ctx* new_ctx = (CRYPTO_EX_cb_ctx*)XMALLOC(
8463
            sizeof(CRYPTO_EX_cb_ctx), NULL, DYNAMIC_TYPE_OPENSSL);
8464
    if (new_ctx == NULL)
8465
        return WOLFSSL_FATAL_ERROR;
8466
    new_ctx->ctx_l = ctx_l;
8467
    new_ctx->ctx_ptr = ctx_ptr;
8468
    new_ctx->new_func = new_func;
8469
    new_ctx->free_func = free_func;
8470
    new_ctx->dup_func = dup_func;
8471
    new_ctx->next = NULL;
8472
    /* Push to end of list */
8473
    while (*dst != NULL)
8474
        dst = &(*dst)->next;
8475
    *dst = new_ctx;
8476
    return 0;
8477
}
8478
8479
void crypto_ex_cb_free(CRYPTO_EX_cb_ctx* cb_ctx)
8480
{
8481
    while (cb_ctx != NULL) {
8482
        CRYPTO_EX_cb_ctx* next = cb_ctx->next;
8483
        XFREE(cb_ctx, NULL, DYNAMIC_TYPE_OPENSSL);
8484
        cb_ctx = next;
8485
    }
8486
}
8487
8488
void crypto_ex_cb_setup_new_data(void *new_obj, CRYPTO_EX_cb_ctx* cb_ctx,
8489
        WOLFSSL_CRYPTO_EX_DATA* ex_data)
8490
{
8491
    int idx = 0;
8492
    for (; cb_ctx != NULL; idx++, cb_ctx = cb_ctx->next) {
8493
        if (cb_ctx->new_func != NULL)
8494
            cb_ctx->new_func(new_obj, NULL, ex_data, idx, cb_ctx->ctx_l,
8495
                    cb_ctx->ctx_ptr);
8496
    }
8497
}
8498
8499
int crypto_ex_cb_dup_data(const WOLFSSL_CRYPTO_EX_DATA *in,
8500
        WOLFSSL_CRYPTO_EX_DATA *out, CRYPTO_EX_cb_ctx* cb_ctx)
8501
{
8502
    int idx = 0;
8503
    for (; cb_ctx != NULL; idx++, cb_ctx = cb_ctx->next) {
8504
        if (cb_ctx->dup_func != NULL) {
8505
            void* ptr = wolfSSL_CRYPTO_get_ex_data(in, idx);
8506
            if (!cb_ctx->dup_func(out, in,
8507
                    &ptr, idx,
8508
                    cb_ctx->ctx_l, cb_ctx->ctx_ptr)) {
8509
                return WOLFSSL_FAILURE;
8510
            }
8511
            wolfSSL_CRYPTO_set_ex_data(out, idx, ptr);
8512
        }
8513
    }
8514
    return WOLFSSL_SUCCESS;
8515
}
8516
8517
void crypto_ex_cb_free_data(void *obj, CRYPTO_EX_cb_ctx* cb_ctx,
8518
        WOLFSSL_CRYPTO_EX_DATA* ex_data)
8519
{
8520
    int idx = 0;
8521
    for (; cb_ctx != NULL; idx++, cb_ctx = cb_ctx->next) {
8522
        if (cb_ctx->free_func != NULL)
8523
            cb_ctx->free_func(obj, NULL, ex_data, idx, cb_ctx->ctx_l,
8524
                    cb_ctx->ctx_ptr);
8525
    }
8526
}
8527
8528
/**
8529
 * wolfssl_local_get_ex_new_index is a helper function for the following
8530
 * xx_get_ex_new_index functions:
8531
 *  - wolfSSL_CRYPTO_get_ex_new_index
8532
 *  - wolfSSL_CTX_get_ex_new_index
8533
 *  - wolfSSL_get_ex_new_index
8534
 * Issues a unique index number for the specified class-index.
8535
 * Returns an index number greater or equal to zero on success,
8536
 * -1 on failure.
8537
 */
8538
int wolfssl_local_get_ex_new_index(int class_index, long ctx_l, void* ctx_ptr,
8539
        WOLFSSL_CRYPTO_EX_new* new_func, WOLFSSL_CRYPTO_EX_dup* dup_func,
8540
        WOLFSSL_CRYPTO_EX_free* free_func)
8541
{
8542
    /* index counter for each class index*/
8543
    static int ctx_idx = 0;
8544
    static int ssl_idx = 0;
8545
    static int ssl_session_idx = 0;
8546
    static int x509_idx = 0;
8547
8548
    int idx = -1;
8549
8550
    switch(class_index) {
8551
        case WOLF_CRYPTO_EX_INDEX_SSL:
8552
            WOLFSSL_CRYPTO_EX_DATA_IGNORE_PARAMS(ctx_l, ctx_ptr, new_func,
8553
                    dup_func, free_func);
8554
            idx = ssl_idx++;
8555
            break;
8556
        case WOLF_CRYPTO_EX_INDEX_SSL_CTX:
8557
            WOLFSSL_CRYPTO_EX_DATA_IGNORE_PARAMS(ctx_l, ctx_ptr, new_func,
8558
                    dup_func, free_func);
8559
            idx = ctx_idx++;
8560
            break;
8561
        case WOLF_CRYPTO_EX_INDEX_X509:
8562
            WOLFSSL_CRYPTO_EX_DATA_IGNORE_PARAMS(ctx_l, ctx_ptr, new_func,
8563
                    dup_func, free_func);
8564
            idx = x509_idx++;
8565
            break;
8566
        case WOLF_CRYPTO_EX_INDEX_SSL_SESSION:
8567
            if (crypto_ex_cb_new(&crypto_ex_cb_ctx_session, ctx_l, ctx_ptr,
8568
                    new_func, dup_func, free_func) != 0)
8569
                return WOLFSSL_FATAL_ERROR;
8570
            idx = ssl_session_idx++;
8571
            break;
8572
        /* following class indexes are not supoprted */
8573
        case WOLF_CRYPTO_EX_INDEX_X509_STORE:
8574
        case WOLF_CRYPTO_EX_INDEX_X509_STORE_CTX:
8575
        case WOLF_CRYPTO_EX_INDEX_DH:
8576
        case WOLF_CRYPTO_EX_INDEX_DSA:
8577
        case WOLF_CRYPTO_EX_INDEX_EC_KEY:
8578
        case WOLF_CRYPTO_EX_INDEX_RSA:
8579
        case WOLF_CRYPTO_EX_INDEX_ENGINE:
8580
        case WOLF_CRYPTO_EX_INDEX_UI:
8581
        case WOLF_CRYPTO_EX_INDEX_BIO:
8582
        case WOLF_CRYPTO_EX_INDEX_APP:
8583
        case WOLF_CRYPTO_EX_INDEX_UI_METHOD:
8584
        case WOLF_CRYPTO_EX_INDEX_DRBG:
8585
        default:
8586
            break;
8587
    }
8588
    if (idx >= MAX_EX_DATA)
8589
        return WOLFSSL_FATAL_ERROR;
8590
    return idx;
8591
}
8592
#endif /* HAVE_EX_DATA_CRYPTO */
8593
8594
#ifdef HAVE_EX_DATA_CRYPTO
8595
int wolfSSL_CTX_get_ex_new_index(long idx, void* arg,
8596
                                 WOLFSSL_CRYPTO_EX_new* new_func,
8597
                                 WOLFSSL_CRYPTO_EX_dup* dup_func,
8598
                                 WOLFSSL_CRYPTO_EX_free* free_func)
8599
{
8600
8601
    WOLFSSL_ENTER("wolfSSL_CTX_get_ex_new_index");
8602
8603
    return wolfssl_local_get_ex_new_index(WOLF_CRYPTO_EX_INDEX_SSL_CTX, idx,
8604
                                    arg, new_func, dup_func, free_func);
8605
}
8606
8607
/* Return the index that can be used for the WOLFSSL structure to store
8608
 * application data.
8609
 *
8610
 */
8611
int wolfSSL_get_ex_new_index(long argValue, void* arg,
8612
        WOLFSSL_CRYPTO_EX_new* cb1, WOLFSSL_CRYPTO_EX_dup* cb2,
8613
        WOLFSSL_CRYPTO_EX_free* cb3)
8614
{
8615
    WOLFSSL_ENTER("wolfSSL_get_ex_new_index");
8616
8617
    return wolfssl_local_get_ex_new_index(WOLF_CRYPTO_EX_INDEX_SSL, argValue,
8618
            arg, cb1, cb2, cb3);
8619
}
8620
#endif /* HAVE_EX_DATA_CRYPTO */
8621
8622
#ifdef OPENSSL_EXTRA
8623
void* wolfSSL_CTX_get_ex_data(const WOLFSSL_CTX* ctx, int idx)
8624
{
8625
    WOLFSSL_ENTER("wolfSSL_CTX_get_ex_data");
8626
#ifdef HAVE_EX_DATA
8627
    if (ctx != NULL) {
8628
        return wolfSSL_CRYPTO_get_ex_data(&ctx->ex_data, idx);
8629
    }
8630
#else
8631
    (void)ctx;
8632
    (void)idx;
8633
#endif
8634
    return NULL;
8635
}
8636
8637
int wolfSSL_CTX_set_ex_data(WOLFSSL_CTX* ctx, int idx, void* data)
8638
{
8639
    WOLFSSL_ENTER("wolfSSL_CTX_set_ex_data");
8640
#ifdef HAVE_EX_DATA
8641
    if (ctx != NULL) {
8642
        return wolfSSL_CRYPTO_set_ex_data(&ctx->ex_data, idx, data);
8643
    }
8644
#else
8645
    (void)ctx;
8646
    (void)idx;
8647
    (void)data;
8648
#endif
8649
    return WOLFSSL_FAILURE;
8650
}
8651
8652
#ifdef HAVE_EX_DATA_CLEANUP_HOOKS
8653
int wolfSSL_CTX_set_ex_data_with_cleanup(
8654
    WOLFSSL_CTX* ctx,
8655
    int idx,
8656
    void* data,
8657
    wolfSSL_ex_data_cleanup_routine_t cleanup_routine)
8658
{
8659
    WOLFSSL_ENTER("wolfSSL_CTX_set_ex_data_with_cleanup");
8660
    if (ctx != NULL) {
8661
        return wolfSSL_CRYPTO_set_ex_data_with_cleanup(&ctx->ex_data, idx, data,
8662
                                                       cleanup_routine);
8663
    }
8664
    return WOLFSSL_FAILURE;
8665
}
8666
#endif /* HAVE_EX_DATA_CLEANUP_HOOKS */
8667
#endif /* OPENSSL_EXTRA */
8668
8669
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
8670
8671
/* Returns char* to app data stored in ex[0].
8672
 *
8673
 * ssl WOLFSSL structure to get app data from
8674
 */
8675
void* wolfSSL_get_app_data(const WOLFSSL *ssl)
8676
{
8677
    /* checkout exdata stuff... */
8678
    WOLFSSL_ENTER("wolfSSL_get_app_data");
8679
8680
    return wolfSSL_get_ex_data(ssl, 0);
8681
}
8682
8683
8684
/* Set ex array 0 to have app data
8685
 *
8686
 * ssl WOLFSSL struct to set app data in
8687
 * arg data to be stored
8688
 *
8689
 * Returns WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on failure
8690
 */
8691
int wolfSSL_set_app_data(WOLFSSL *ssl, void* arg) {
8692
    WOLFSSL_ENTER("wolfSSL_set_app_data");
8693
8694
    return wolfSSL_set_ex_data(ssl, 0, arg);
8695
}
8696
8697
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
8698
8699
int wolfSSL_set_ex_data(WOLFSSL* ssl, int idx, void* data)
8700
0
{
8701
0
    WOLFSSL_ENTER("wolfSSL_set_ex_data");
8702
#ifdef HAVE_EX_DATA
8703
    if (ssl != NULL) {
8704
        return wolfSSL_CRYPTO_set_ex_data(&ssl->ex_data, idx, data);
8705
    }
8706
#else
8707
0
    WOLFSSL_MSG("HAVE_EX_DATA macro is not defined");
8708
0
    (void)ssl;
8709
0
    (void)idx;
8710
0
    (void)data;
8711
0
#endif
8712
0
    return WOLFSSL_FAILURE;
8713
0
}
8714
8715
#ifdef HAVE_EX_DATA_CLEANUP_HOOKS
8716
int wolfSSL_set_ex_data_with_cleanup(
8717
    WOLFSSL* ssl,
8718
    int idx,
8719
    void* data,
8720
    wolfSSL_ex_data_cleanup_routine_t cleanup_routine)
8721
{
8722
    WOLFSSL_ENTER("wolfSSL_set_ex_data_with_cleanup");
8723
    if (ssl != NULL)
8724
    {
8725
        return wolfSSL_CRYPTO_set_ex_data_with_cleanup(&ssl->ex_data, idx, data,
8726
                                                       cleanup_routine);
8727
    }
8728
    return WOLFSSL_FAILURE;
8729
}
8730
#endif /* HAVE_EX_DATA_CLEANUP_HOOKS */
8731
8732
void* wolfSSL_get_ex_data(const WOLFSSL* ssl, int idx)
8733
0
{
8734
0
    WOLFSSL_ENTER("wolfSSL_get_ex_data");
8735
#ifdef HAVE_EX_DATA
8736
    if (ssl != NULL) {
8737
        return wolfSSL_CRYPTO_get_ex_data(&ssl->ex_data, idx);
8738
    }
8739
#else
8740
0
    WOLFSSL_MSG("HAVE_EX_DATA macro is not defined");
8741
0
    (void)ssl;
8742
0
    (void)idx;
8743
0
#endif
8744
0
    return 0;
8745
0
}
8746
8747
#if defined(HAVE_LIGHTY) || defined(HAVE_STUNNEL) \
8748
    || defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(OPENSSL_EXTRA)
8749
8750
#ifdef WOLFSSL_TLS_ST_OK
8751
/* The OpenSSL compat TLS_ST_OK/SSL_ST_OK constants (wolfssl/openssl/ssl.h)
8752
 * duplicate HANDSHAKE_DONE from the internal 'enum states' returned below;
8753
 * fail the build if the enum ever drifts. */
8754
wc_static_assert(WOLFSSL_TLS_ST_OK == HANDSHAKE_DONE);
8755
#endif
8756
8757
/* returns the enum value associated with handshake state
8758
 *
8759
 * ssl the WOLFSSL structure to get state of
8760
 */
8761
int wolfSSL_get_state(const WOLFSSL* ssl)
8762
{
8763
    WOLFSSL_ENTER("wolfSSL_get_state");
8764
8765
    if (ssl == NULL) {
8766
        WOLFSSL_MSG("Null argument passed in");
8767
        return WOLFSSL_FAILURE;
8768
    }
8769
8770
    return ssl->options.handShakeState;
8771
}
8772
#endif /* HAVE_LIGHTY || HAVE_STUNNEL || WOLFSSL_MYSQL_COMPATIBLE */
8773
8774
#ifdef OPENSSL_EXTRA
8775
void wolfSSL_certs_clear(WOLFSSL* ssl)
8776
{
8777
    WOLFSSL_ENTER("wolfSSL_certs_clear");
8778
8779
    if (ssl == NULL)
8780
        return;
8781
8782
    /* ctx still owns certificate, certChain, key, dh, and cm */
8783
    if (ssl->buffers.weOwnCert) {
8784
        FreeDer(&ssl->buffers.certificate);
8785
    #ifdef KEEP_OUR_CERT
8786
        /* ourCert is only made when this SSL owns the certificate. */
8787
        if (ssl->ourCert != NULL) {
8788
            wolfSSL_X509_free(ssl->ourCert);
8789
            ssl->ourCert = NULL;
8790
        }
8791
    #endif
8792
        ssl->buffers.weOwnCert = 0;
8793
    }
8794
    ssl->buffers.certificate = NULL;
8795
    if (ssl->buffers.weOwnCertChain) {
8796
        FreeDer(&ssl->buffers.certChain);
8797
        ssl->buffers.weOwnCertChain = 0;
8798
    }
8799
    ssl->buffers.certChain = NULL;
8800
    ssl->buffers.certChainCnt = 0;
8801
#ifdef KEEP_OUR_CERT
8802
    if (ssl->ourCertChain != NULL) {
8803
        wolfSSL_sk_X509_pop_free(ssl->ourCertChain, NULL);
8804
        ssl->ourCertChain = NULL;
8805
    }
8806
#endif
8807
    if (ssl->buffers.weOwnKey) {
8808
        FreeKeyDer(&ssl->buffers.key);
8809
    #ifdef WOLFSSL_BLIND_PRIVATE_KEY
8810
        FreeDer(&ssl->buffers.keyMask);
8811
    #endif
8812
        ssl->buffers.weOwnKey = 0;
8813
    }
8814
    ssl->buffers.key      = NULL;
8815
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
8816
    ssl->buffers.keyMask  = NULL;
8817
#endif
8818
    ssl->buffers.keyType  = 0;
8819
    ssl->buffers.keyId    = 0;
8820
    ssl->buffers.keyLabel = 0;
8821
    ssl->buffers.keySz    = 0;
8822
    ssl->buffers.keyDevId = 0;
8823
#ifdef WOLFSSL_DUAL_ALG_CERTS
8824
    if (ssl->buffers.weOwnAltKey) {
8825
        FreeKeyDer(&ssl->buffers.altKey);
8826
    #ifdef WOLFSSL_BLIND_PRIVATE_KEY
8827
        FreeDer(&ssl->buffers.altKeyMask);
8828
    #endif
8829
        ssl->buffers.weOwnAltKey = 0;
8830
    }
8831
    ssl->buffers.altKey     = NULL;
8832
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
8833
    ssl->buffers.altKeyMask = NULL;
8834
#endif
8835
#endif /* WOLFSSL_DUAL_ALG_CERTS */
8836
}
8837
#endif
8838
8839
#if defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || defined(WOLFSSL_HAPROXY) \
8840
    || defined(WOLFSSL_NGINX) || defined(WOLFSSL_QT)
8841
8842
long wolfSSL_ctrl(WOLFSSL* ssl, int cmd, long opt, void* pt)
8843
{
8844
    WOLFSSL_ENTER("wolfSSL_ctrl");
8845
    if (ssl == NULL)
8846
        return BAD_FUNC_ARG;
8847
8848
    switch (cmd) {
8849
        #if defined(WOLFSSL_NGINX) || defined(WOLFSSL_QT) || \
8850
            defined(OPENSSL_ALL)
8851
        #ifdef HAVE_SNI
8852
        case SSL_CTRL_SET_TLSEXT_HOSTNAME:
8853
            WOLFSSL_MSG("Entering Case: SSL_CTRL_SET_TLSEXT_HOSTNAME.");
8854
            if (pt == NULL) {
8855
                WOLFSSL_MSG("Passed in NULL Host Name.");
8856
                break;
8857
            }
8858
            return wolfSSL_set_tlsext_host_name(ssl, (const char*) pt);
8859
        #endif /* HAVE_SNI */
8860
        #endif /* WOLFSSL_NGINX || WOLFSSL_QT || OPENSSL_ALL */
8861
        default:
8862
            WOLFSSL_MSG("Case not implemented.");
8863
    }
8864
    (void)opt;
8865
    (void)pt;
8866
    return WOLFSSL_FAILURE;
8867
}
8868
8869
long wolfSSL_CTX_ctrl(WOLFSSL_CTX* ctx, int cmd, long opt, void* pt)
8870
{
8871
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
8872
    long ctrl_opt;
8873
#endif
8874
    long ret = WOLFSSL_SUCCESS;
8875
8876
    WOLFSSL_ENTER("wolfSSL_CTX_ctrl");
8877
    if (ctx == NULL)
8878
        return WOLFSSL_FAILURE;
8879
8880
    switch (cmd) {
8881
    case SSL_CTRL_CHAIN:
8882
#ifdef SESSION_CERTS
8883
    {
8884
        /* Build ctx->certChain (DER copies) from sk. A reference is taken on
8885
         * each certificate because wolfSSL_CTX_add_extra_chain_cert() consumes
8886
         * one on success. The ctx takes ownership of sk only on success; on
8887
         * failure no chain is set and the caller still owns sk.
8888
         * opt: 0 = set0, 1 = set1. */
8889
        WOLF_STACK_OF(WOLFSSL_X509)* sk = (WOLF_STACK_OF(WOLFSSL_X509)*) pt;
8890
        WOLFSSL_X509* x509;
8891
        int i;
8892
        if (opt != 0 && opt != 1) {
8893
            ret = WOLFSSL_FAILURE;
8894
            break;
8895
        }
8896
        /* Clear certificate chain */
8897
        FreeDer(&ctx->certChain);
8898
        ctx->certChainCnt = 0;
8899
        if (sk) {
8900
            for (i = 0; i < wolfSSL_sk_X509_num(sk); i++) {
8901
                x509 = wolfSSL_sk_X509_value(sk, i);
8902
                if (x509 == NULL) {
8903
                    ret = WOLFSSL_FAILURE;
8904
                    break;
8905
                }
8906
                /* Prevent wolfSSL_CTX_add_extra_chain_cert from freeing cert */
8907
                if (wolfSSL_X509_up_ref(x509) != 1) {
8908
                    WOLFSSL_MSG("Error increasing reference count");
8909
                    ret = WOLFSSL_FAILURE;
8910
                    break;
8911
                }
8912
                if (wolfSSL_CTX_add_extra_chain_cert(ctx, x509) !=
8913
                        WOLFSSL_SUCCESS) {
8914
                    WOLFSSL_MSG("Error adding certificate to context");
8915
                    /* Decrease reference count on failure */
8916
                    wolfSSL_X509_free(x509);
8917
                    ret = WOLFSSL_FAILURE;
8918
                    break;
8919
                }
8920
            }
8921
            x509 = NULL;
8922
        }
8923
8924
        /* Free previous chain. On failure the ctx is left with no chain */
8925
        wolfSSL_sk_X509_pop_free(ctx->x509Chain, NULL);
8926
        ctx->x509Chain = NULL;
8927
        if (ret == WOLFSSL_SUCCESS) {
8928
            ctx->x509Chain = sk;
8929
            if (sk && opt == 1) {
8930
                /* up all refs when opt == 1 */
8931
                for (i = 0; i < wolfSSL_sk_X509_num(sk); i++) {
8932
                    x509 = wolfSSL_sk_X509_value(sk, i);
8933
                    if (wolfSSL_X509_up_ref(x509) != 1) {
8934
                        WOLFSSL_MSG("Error increasing reference count");
8935
                        continue;
8936
                    }
8937
                }
8938
            }
8939
        } else {
8940
            FreeDer(&ctx->certChain);
8941
            ctx->certChainCnt = 0;
8942
        }
8943
    }
8944
#else
8945
        WOLFSSL_MSG("Session certificates not compiled in");
8946
        ret = WOLFSSL_FAILURE;
8947
#endif
8948
        break;
8949
8950
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
8951
    case SSL_CTRL_OPTIONS:
8952
        WOLFSSL_MSG("Entering Case: SSL_CTRL_OPTIONS.");
8953
        ctrl_opt = wolfSSL_CTX_set_options(ctx, opt);
8954
8955
        #ifdef WOLFSSL_QT
8956
        /* Set whether to use client or server cipher preference */
8957
        if ((ctrl_opt & WOLFSSL_OP_CIPHER_SERVER_PREFERENCE)
8958
                     == WOLFSSL_OP_CIPHER_SERVER_PREFERENCE) {
8959
            WOLFSSL_MSG("Using Server's Cipher Preference.");
8960
            ctx->useClientOrder = 0;
8961
        } else {
8962
            WOLFSSL_MSG("Using Client's Cipher Preference.");
8963
            ctx->useClientOrder = 1;
8964
        }
8965
        #endif /* WOLFSSL_QT */
8966
8967
        return ctrl_opt;
8968
#endif /* OPENSSL_EXTRA || HAVE_WEBSERVER */
8969
    case SSL_CTRL_EXTRA_CHAIN_CERT:
8970
        WOLFSSL_MSG("Entering Case: SSL_CTRL_EXTRA_CHAIN_CERT.");
8971
        if (pt == NULL) {
8972
            WOLFSSL_MSG("Passed in x509 pointer NULL.");
8973
            ret = WOLFSSL_FAILURE;
8974
            break;
8975
        }
8976
        return wolfSSL_CTX_add_extra_chain_cert(ctx, (WOLFSSL_X509*)pt);
8977
8978
#ifndef NO_DH
8979
    case SSL_CTRL_SET_TMP_DH:
8980
        WOLFSSL_MSG("Entering Case: SSL_CTRL_SET_TMP_DH.");
8981
        if (pt == NULL) {
8982
            WOLFSSL_MSG("Passed in DH pointer NULL.");
8983
            ret = WOLFSSL_FAILURE;
8984
            break;
8985
        }
8986
        return wolfSSL_CTX_set_tmp_dh(ctx, (WOLFSSL_DH*)pt);
8987
#endif
8988
8989
#ifdef HAVE_ECC
8990
    case SSL_CTRL_SET_TMP_ECDH:
8991
        WOLFSSL_MSG("Entering Case: SSL_CTRL_SET_TMP_ECDH.");
8992
        if (pt == NULL) {
8993
            WOLFSSL_MSG("Passed in ECDH pointer NULL.");
8994
            ret = WOLFSSL_FAILURE;
8995
            break;
8996
        }
8997
        return wolfSSL_SSL_CTX_set_tmp_ecdh(ctx, (WOLFSSL_EC_KEY*)pt);
8998
#endif
8999
    case SSL_CTRL_MODE:
9000
        wolfSSL_CTX_set_mode(ctx,opt);
9001
        break;
9002
    case SSL_CTRL_SET_MIN_PROTO_VERSION:
9003
        WOLFSSL_MSG("set min proto version");
9004
        return wolfSSL_CTX_set_min_proto_version(ctx, (int)opt);
9005
    case SSL_CTRL_SET_MAX_PROTO_VERSION:
9006
        WOLFSSL_MSG("set max proto version");
9007
        return wolfSSL_CTX_set_max_proto_version(ctx, (int)opt);
9008
    case SSL_CTRL_GET_MIN_PROTO_VERSION:
9009
        WOLFSSL_MSG("get min proto version");
9010
        return wolfSSL_CTX_get_min_proto_version(ctx);
9011
    case SSL_CTRL_GET_MAX_PROTO_VERSION:
9012
        WOLFSSL_MSG("get max proto version");
9013
        return wolfSSL_CTX_get_max_proto_version(ctx);
9014
    default:
9015
        WOLFSSL_MSG("CTX_ctrl cmd not implemented");
9016
        ret = WOLFSSL_FAILURE;
9017
        break;
9018
    }
9019
9020
    (void)ctx;
9021
    (void)cmd;
9022
    (void)opt;
9023
    (void)pt;
9024
    WOLFSSL_LEAVE("wolfSSL_CTX_ctrl", (int)ret);
9025
    return ret;
9026
}
9027
9028
#ifndef NO_WOLFSSL_STUB
9029
long wolfSSL_CTX_callback_ctrl(WOLFSSL_CTX* ctx, int cmd, void (*fp)(void))
9030
{
9031
    (void) ctx;
9032
    (void) cmd;
9033
    (void) fp;
9034
    WOLFSSL_STUB("wolfSSL_CTX_callback_ctrl");
9035
    return WOLFSSL_FAILURE;
9036
9037
}
9038
#endif /* NO_WOLFSSL_STUB */
9039
9040
9041
#endif /* OPENSSL_ALL || WOLFSSL_ASIO || WOLFSSL_HAPROXY || WOLFSSL_QT */
9042
9043
9044
/* stunnel compatibility functions*/
9045
#if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && \
9046
    (defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \
9047
     defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \
9048
     defined(WOLFSSL_OPENSSH)))
9049
9050
#ifndef NO_FILESYSTEM
9051
/***TBD ***/
9052
void wolfSSL_print_all_errors_fp(XFILE fp)
9053
{
9054
    (void)fp;
9055
}
9056
#endif /* !NO_FILESYSTEM */
9057
9058
#endif /* OPENSSL_ALL || OPENSSL_EXTRA || HAVE_STUNNEL || WOLFSSL_NGINX ||
9059
    HAVE_LIGHTY || WOLFSSL_HAPROXY || WOLFSSL_OPENSSH */
9060
9061
/* Note: This is a huge section of API's - through
9062
 *       wolfSSL_X509_OBJECT_get0_X509_CRL */
9063
#if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA)
9064
9065
#if defined(USE_WOLFSSL_MEMORY) && !defined(WOLFSSL_DEBUG_MEMORY) && \
9066
    !defined(WOLFSSL_STATIC_MEMORY)
9067
static wolfSSL_OSSL_Malloc_cb  ossl_malloc  = NULL;
9068
static wolfSSL_OSSL_Free_cb    ossl_free    = NULL;
9069
static wolfSSL_OSSL_Realloc_cb ossl_realloc = NULL;
9070
9071
static void* OSSL_Malloc(size_t size)
9072
{
9073
    if (ossl_malloc != NULL)
9074
        return ossl_malloc(size, NULL, 0);
9075
    else
9076
        return NULL;
9077
}
9078
9079
static void  OSSL_Free(void *ptr)
9080
{
9081
    if (ossl_free != NULL)
9082
        ossl_free(ptr, NULL, 0);
9083
}
9084
9085
static void* OSSL_Realloc(void *ptr, size_t size)
9086
{
9087
    if (ossl_realloc != NULL)
9088
        return ossl_realloc(ptr, size, NULL, 0);
9089
    else
9090
        return NULL;
9091
}
9092
#endif /* USE_WOLFSSL_MEMORY && !WOLFSSL_DEBUG_MEMORY &&
9093
        * !WOLFSSL_STATIC_MEMORY */
9094
9095
int wolfSSL_CRYPTO_set_mem_functions(
9096
        wolfSSL_OSSL_Malloc_cb  m,
9097
        wolfSSL_OSSL_Realloc_cb r,
9098
        wolfSSL_OSSL_Free_cb    f)
9099
{
9100
#if defined(USE_WOLFSSL_MEMORY) && !defined(WOLFSSL_STATIC_MEMORY)
9101
#ifdef WOLFSSL_DEBUG_MEMORY
9102
    WOLFSSL_MSG("mem functions will receive function name instead of "
9103
                "file name");
9104
    if (wolfSSL_SetAllocators((wolfSSL_Malloc_cb)m, (wolfSSL_Free_cb)f,
9105
            (wolfSSL_Realloc_cb)r) == 0)
9106
        return WOLFSSL_SUCCESS;
9107
#else
9108
    WOLFSSL_MSG("wolfSSL was compiled without WOLFSSL_DEBUG_MEMORY mem "
9109
                "functions will receive a NULL file name and 0 for the "
9110
                "line number.");
9111
    if (wolfSSL_SetAllocators((wolfSSL_Malloc_cb)OSSL_Malloc,
9112
           (wolfSSL_Free_cb)OSSL_Free, (wolfSSL_Realloc_cb)OSSL_Realloc) == 0) {
9113
        ossl_malloc = m;
9114
        ossl_free = f;
9115
        ossl_realloc = r;
9116
        return WOLFSSL_SUCCESS;
9117
    }
9118
#endif
9119
    else
9120
        return WOLFSSL_FAILURE;
9121
#else
9122
    (void)m;
9123
    (void)r;
9124
    (void)f;
9125
    WOLFSSL_MSG("wolfSSL allocator callback functions not compiled in");
9126
    return WOLFSSL_FAILURE;
9127
#endif
9128
}
9129
9130
int wolfSSL_FIPS_mode(void)
9131
{
9132
#ifdef HAVE_FIPS
9133
    return 1;
9134
#else
9135
    return 0;
9136
#endif
9137
}
9138
9139
int wolfSSL_FIPS_mode_set(int r)
9140
{
9141
#ifdef HAVE_FIPS
9142
    if (r == 0) {
9143
        WOLFSSL_MSG("Cannot disable FIPS at runtime.");
9144
        return WOLFSSL_FAILURE;
9145
    }
9146
    return WOLFSSL_SUCCESS;
9147
#else
9148
    if (r == 0) {
9149
        return WOLFSSL_SUCCESS;
9150
    }
9151
    WOLFSSL_MSG("Cannot enable FIPS. This isn't the wolfSSL FIPS code.");
9152
    return WOLFSSL_FAILURE;
9153
#endif
9154
}
9155
9156
/* Returns the strength of the suite in bits and sets alg_bits to the key bits
9157
 * of its cipher, as OpenSSL does. */
9158
int wolfSSL_CIPHER_get_bits(const WOLFSSL_CIPHER *c, int *alg_bits)
9159
{
9160
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
9161
    int algBits;
9162
    CipherSpecs specs;
9163
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_bits");
9164
9165
    if (c == NULL)
9166
        return ret;
9167
9168
    wolfssl_cipher_get_specs(c, &specs);
9169
    algBits = 8 * specs.key_size;
9170
    ret = algBits;
9171
    if (specs.bulk_cipher_algorithm == wolfssl_triple_des) {
9172
        /* 168 key bits, without parity, give a strength of 112. */
9173
        algBits = 168;
9174
        ret = 112;
9175
    }
9176
    else if (specs.bulk_cipher_algorithm == wolfssl_cipher_null) {
9177
        /* No strength. Integrity-only suites keep their HMAC key bits. */
9178
        ret = 0;
9179
    }
9180
    if (alg_bits != NULL)
9181
        *alg_bits = algBits;
9182
9183
    return ret;
9184
}
9185
9186
9187
WOLFSSL_CTX* wolfSSL_set_SSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx)
9188
{
9189
    int ret;
9190
    /* This method requires some explanation. Its sibling is
9191
     *   int SetSSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup)
9192
     * which re-inits the WOLFSSL* with all settings in the new CTX.
9193
     * That one is the right one to use *before* a handshake is started.
9194
     *
9195
     * This method was added by OpenSSL to be used *during* the handshake, e.g.
9196
     * when a server inspects the SNI in a ClientHello callback and
9197
     * decides which set of certificates to use.
9198
     *
9199
     * Since, at the time the SNI callback is run, some decisions on
9200
     * Extensions or the ServerHello might already have been taken, this
9201
     * method is very restricted in what it does:
9202
     * - changing the server certificate(s)
9203
     * - changing the server id for session handling
9204
     * and everything else in WOLFSSL* needs to remain untouched.
9205
     *
9206
     * SECURITY: swapping ssl->ctx switches cm-resolved settings (CA store,
9207
     * CRL, OCSP) to the new CTX but leaves ssl-cached ones (verify mode and
9208
     * callback, minDowngrade, key-size minimums, suites, version bounds)
9209
     * pinned to the original. SNI callbacks must re-apply those ssl-level
9210
     * settings explicitly; CRL/OCSP isolation requires an SSL-local store.
9211
     */
9212
    WOLFSSL_ENTER("wolfSSL_set_SSL_CTX");
9213
    if (ssl == NULL || ctx == NULL)
9214
        return NULL;
9215
    if (ssl->ctx == ctx)
9216
        return ssl->ctx;
9217
#ifdef WOLFSSL_STATIC_MEMORY
9218
    /* the SSL and its heap hint are freed through ssl->ctx->heap */
9219
    if (ssl->ctx != NULL && ssl->ctx->heap != ctx->heap) {
9220
        WOLFSSL_MSG("Cannot switch to a CTX with a different heap");
9221
        return NULL;
9222
    }
9223
#endif
9224
9225
    /* suites, allocated and derived under the CTX mutex as this CTX may be
9226
     * shared with other threads. Done before taking a reference below so that
9227
     * a failure here returns without having changed anything. */
9228
    if (InitCtxSuitesWithMutex(ctx) != 0)
9229
        return NULL;
9230
9231
    wolfSSL_RefWithMutexInc(&ctx->ref, &ret);
9232
#ifdef WOLFSSL_REFCNT_ERROR_RETURN
9233
    if (ret != 0) {
9234
        /* can only fail on serious stuff, like mutex not working
9235
         * or ctx refcount out of whack. */
9236
        return NULL;
9237
    }
9238
#else
9239
    (void)ret;
9240
#endif
9241
9242
    if (ssl->ctx != NULL)
9243
        wolfSSL_CTX_free(ssl->ctx);
9244
    ssl->ctx = ctx;
9245
9246
#ifndef NO_CERTS
9247
    /* Release the certificate, chain and keys this SSL owns so that a ctx
9248
     * without them leaves none of the old ones behind. */
9249
    wolfSSL_certs_clear(ssl);
9250
    /* Same certificate, chain and keys as an SSL made from this ctx. */
9251
    if (SetSSL_CTX_CertsAndKeys(ssl, ctx) != 0) {
9252
        return NULL;
9253
    }
9254
#if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \
9255
    defined(HAVE_FALCON) || defined(WOLFSSL_HAVE_MLDSA) || \
9256
    defined(WOLFSSL_HAVE_SLHDSA)
9257
    ssl->pkCurveOID = ctx->pkCurveOID;
9258
#endif
9259
#if !defined(NO_RSA) && defined(WC_RSA_PSS)
9260
    ssl->useRsaPss     = ctx->useRsaPss;
9261
    ssl->rsaPssHash    = ctx->rsaPssHash;
9262
    ssl->rsaPssMgf     = ctx->rsaPssMgf;
9263
    ssl->rsaPssSaltLen = ctx->rsaPssSaltLen;
9264
#endif
9265
    /* flags indicating what certs/keys are available */
9266
    ssl->options.haveRSA          = ctx->haveRSA;
9267
    ssl->options.haveDH           = ctx->haveDH;
9268
    ssl->options.haveECDSAsig     = ctx->haveECDSAsig;
9269
    ssl->options.haveECC          = ctx->haveECC;
9270
    ssl->options.haveStaticECC    = ctx->haveStaticECC;
9271
    ssl->options.haveFalconSig    = ctx->haveFalconSig;
9272
    ssl->options.haveMlDsaSig     = ctx->haveMlDsaSig;
9273
    ssl->options.haveSlhDsaSig    = ctx->haveSlhDsaSig;
9274
#endif
9275
9276
#ifdef WOLFSSL_SESSION_ID_CTX
9277
    /* copy over application session context ID */
9278
    ssl->sessionCtxSz = ctx->sessionCtxSz;
9279
    XMEMCPY(ssl->sessionCtx, ctx->sessionCtx, ctx->sessionCtxSz);
9280
#endif
9281
9282
    return ssl->ctx;
9283
}
9284
9285
9286
#ifndef NO_BIO
9287
#endif
9288
9289
#ifndef NO_WOLFSSL_STUB
9290
/* Set THREADID callback, return 1 on success, 0 on error */
9291
int wolfSSL_THREADID_set_callback(
9292
        void(*threadid_func)(WOLFSSL_CRYPTO_THREADID*))
9293
{
9294
    WOLFSSL_ENTER("wolfSSL_THREADID_set_callback");
9295
    WOLFSSL_STUB("CRYPTO_THREADID_set_callback");
9296
    (void)threadid_func;
9297
    return 1;
9298
}
9299
#endif
9300
9301
#ifndef NO_WOLFSSL_STUB
9302
void wolfSSL_THREADID_set_numeric(void* id, unsigned long val)
9303
{
9304
    WOLFSSL_ENTER("wolfSSL_THREADID_set_numeric");
9305
    WOLFSSL_STUB("CRYPTO_THREADID_set_numeric");
9306
    (void)id;
9307
    (void)val;
9308
    return;
9309
}
9310
#endif
9311
9312
#endif /* OPENSSL_ALL || OPENSSL_EXTRA */
9313
9314
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
9315
/* Map a signature-algorithm NID to its digest and public-key NIDs, like
9316
 * OpenSSL's OBJ_find_sigid_algs(). */
9317
int wolfSSL_OBJ_find_sigid_algs(int sigid, int *pdig, int *ppkey)
9318
{
9319
    int dig  = 0;
9320
    int pkey = 0;
9321
    int ret  = 1;
9322
9323
    WOLFSSL_ENTER("wolfSSL_OBJ_find_sigid_algs");
9324
9325
    switch (sigid) {
9326
#ifndef NO_RSA
9327
    #ifndef NO_MD5
9328
        case WC_NID_md5WithRSAEncryption:
9329
            dig = WC_NID_md5;    pkey = WC_NID_rsaEncryption; break;
9330
    #endif
9331
        case WC_NID_sha1WithRSAEncryption:
9332
            dig = WC_NID_sha1;   pkey = WC_NID_rsaEncryption; break;
9333
        case WC_NID_sha224WithRSAEncryption:
9334
            dig = WC_NID_sha224; pkey = WC_NID_rsaEncryption; break;
9335
        case WC_NID_sha256WithRSAEncryption:
9336
            dig = WC_NID_sha256; pkey = WC_NID_rsaEncryption; break;
9337
        case WC_NID_sha384WithRSAEncryption:
9338
            dig = WC_NID_sha384; pkey = WC_NID_rsaEncryption; break;
9339
        case WC_NID_sha512WithRSAEncryption:
9340
            dig = WC_NID_sha512; pkey = WC_NID_rsaEncryption; break;
9341
    #ifdef WC_RSA_PSS
9342
        case WC_NID_rsassaPss:
9343
            dig = WC_NID_undef;  pkey = WC_NID_rsassaPss; break;
9344
    #endif
9345
#endif /* !NO_RSA */
9346
#ifdef HAVE_ECC
9347
        case WC_NID_ecdsa_with_SHA1:
9348
            dig = WC_NID_sha1;   pkey = WC_NID_X9_62_id_ecPublicKey; break;
9349
        case WC_NID_ecdsa_with_SHA224:
9350
            dig = WC_NID_sha224; pkey = WC_NID_X9_62_id_ecPublicKey; break;
9351
        case WC_NID_ecdsa_with_SHA256:
9352
            dig = WC_NID_sha256; pkey = WC_NID_X9_62_id_ecPublicKey; break;
9353
        case WC_NID_ecdsa_with_SHA384:
9354
            dig = WC_NID_sha384; pkey = WC_NID_X9_62_id_ecPublicKey; break;
9355
        case WC_NID_ecdsa_with_SHA512:
9356
            dig = WC_NID_sha512; pkey = WC_NID_X9_62_id_ecPublicKey; break;
9357
#endif /* HAVE_ECC */
9358
#ifdef HAVE_ED25519
9359
        case WC_NID_ED25519:
9360
            dig = WC_NID_undef;  pkey = WC_NID_ED25519; break;
9361
#endif
9362
#ifdef HAVE_ED448
9363
        case WC_NID_ED448:
9364
            dig = WC_NID_undef;  pkey = WC_NID_ED448; break;
9365
#endif
9366
        default:
9367
            ret = 0; break;
9368
    }
9369
9370
    if (ret == 1) {
9371
        if (pdig  != NULL) *pdig  = dig;
9372
        if (ppkey != NULL) *ppkey = pkey;
9373
    }
9374
9375
    WOLFSSL_LEAVE("wolfSSL_OBJ_find_sigid_algs", ret);
9376
    return ret;
9377
}
9378
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
9379
9380
9381
#if defined(OPENSSL_EXTRA)
9382
9383
int wolfSSL_CRYPTO_memcmp(const void *a, const void *b, size_t size)
9384
{
9385
    int ret = 0;
9386
    int chunk;
9387
    const byte* pa = (const byte*)a;
9388
    const byte* pb = (const byte*)b;
9389
9390
    if (!a || !b)
9391
        return -1;
9392
    /* ConstantCompare takes an int length. Compare in chunks of at most
9393
     * INT_MAX so a size that does not fit in an int is not narrowed into a
9394
     * negative or truncated length, which could wrongly report equality. */
9395
    while (size > 0) {
9396
        chunk = (size > (size_t)INT_MAX) ? INT_MAX : (int)size;
9397
        ret |= ConstantCompare(pa, pb, chunk);
9398
        pa += chunk;
9399
        pb += chunk;
9400
        size -= (size_t)chunk;
9401
    }
9402
    return ret;
9403
}
9404
9405
9406
#endif /* OPENSSL_EXTRA */
9407
9408
int wolfSSL_version(WOLFSSL* ssl)
9409
0
{
9410
0
    WOLFSSL_ENTER("wolfSSL_version");
9411
0
    if (ssl->version.major == SSLv3_MAJOR) {
9412
0
        switch (ssl->version.minor) {
9413
0
            case SSLv3_MINOR :
9414
0
                return SSL3_VERSION;
9415
0
            case TLSv1_MINOR :
9416
0
                return TLS1_VERSION;
9417
0
            case TLSv1_1_MINOR :
9418
0
                return TLS1_1_VERSION;
9419
0
            case TLSv1_2_MINOR :
9420
0
                return TLS1_2_VERSION;
9421
0
            case TLSv1_3_MINOR :
9422
0
                return TLS1_3_VERSION;
9423
0
            default:
9424
0
                return WOLFSSL_FAILURE;
9425
0
        }
9426
0
    }
9427
0
    else if (ssl->version.major == DTLS_MAJOR) {
9428
0
        switch (ssl->version.minor) {
9429
0
            case DTLS_MINOR :
9430
0
                return DTLS1_VERSION;
9431
0
            case DTLSv1_2_MINOR :
9432
0
                return DTLS1_2_VERSION;
9433
0
            case DTLSv1_3_MINOR:
9434
0
                return DTLS1_3_VERSION;
9435
0
            default:
9436
0
                return WOLFSSL_FAILURE;
9437
0
        }
9438
0
    }
9439
0
    return WOLFSSL_FAILURE;
9440
0
}
9441
9442
WOLFSSL_CTX* wolfSSL_get_SSL_CTX(const WOLFSSL* ssl)
9443
0
{
9444
0
    WOLFSSL_ENTER("wolfSSL_get_SSL_CTX");
9445
0
    return ssl->ctx;
9446
0
}
9447
9448
9449
#ifdef WOLFSSL_JNI
9450
9451
int wolfSSL_set_jobject(WOLFSSL* ssl, void* objPtr)
9452
{
9453
    WOLFSSL_ENTER("wolfSSL_set_jobject");
9454
    if (ssl != NULL)
9455
    {
9456
        ssl->jObjectRef = objPtr;
9457
        return WOLFSSL_SUCCESS;
9458
    }
9459
    return WOLFSSL_FAILURE;
9460
}
9461
9462
void* wolfSSL_get_jobject(WOLFSSL* ssl)
9463
{
9464
    WOLFSSL_ENTER("wolfSSL_get_jobject");
9465
    if (ssl != NULL)
9466
        return ssl->jObjectRef;
9467
    return NULL;
9468
}
9469
9470
#endif /* WOLFSSL_JNI */
9471
9472
9473
#ifdef WOLFSSL_ASYNC_CRYPT
9474
int wolfSSL_CTX_AsyncPoll(WOLFSSL_CTX* ctx, WOLF_EVENT** events, int maxEvents,
9475
    WOLF_EVENT_FLAG flags, int* eventCount)
9476
{
9477
    if (ctx == NULL) {
9478
        return BAD_FUNC_ARG;
9479
    }
9480
9481
    return wolfAsync_EventQueuePoll(&ctx->event_queue, NULL,
9482
                                        events, maxEvents, flags, eventCount);
9483
}
9484
9485
int wolfSSL_AsyncPoll(WOLFSSL* ssl, WOLF_EVENT_FLAG flags)
9486
{
9487
    int ret, eventCount = 0;
9488
    WOLF_EVENT* events[1];
9489
9490
    if (ssl == NULL) {
9491
        return BAD_FUNC_ARG;
9492
    }
9493
9494
    ret = wolfAsync_EventQueuePoll(&ssl->ctx->event_queue, ssl,
9495
        events, sizeof(events)/sizeof(events[0]), flags, &eventCount);
9496
    if (ret == 0) {
9497
        ret = eventCount;
9498
    }
9499
9500
    return ret;
9501
}
9502
#endif /* WOLFSSL_ASYNC_CRYPT */
9503
9504
#ifdef OPENSSL_EXTRA
9505
9506
#endif
9507
9508
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL) || \
9509
    defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
9510
9511
#if !defined(WOLFSSL_USER_IO)
9512
/* converts an IPv6 or IPv4 address into an octet string for use with rfc3280
9513
 * example input would be "127.0.0.1" and the returned value would be 7F000001
9514
 */
9515
WOLFSSL_ASN1_STRING* wolfSSL_a2i_IPADDRESS(const char* ipa)
9516
{
9517
    int ipaSz = WOLFSSL_IP4_ADDR_LEN;
9518
    char buf[WOLFSSL_IP6_ADDR_LEN + 1]; /* plus 1 for terminator */
9519
    int  af = WOLFSSL_IP4;
9520
    WOLFSSL_ASN1_STRING *ret = NULL;
9521
9522
    if (ipa == NULL)
9523
        return NULL;
9524
9525
    if (XSTRSTR(ipa, ":") != NULL) {
9526
        af = WOLFSSL_IP6;
9527
        ipaSz = WOLFSSL_IP6_ADDR_LEN;
9528
    }
9529
9530
    buf[WOLFSSL_IP6_ADDR_LEN] = '\0';
9531
#ifdef FREESCALE_MQX
9532
    if (XINET_PTON(af, ipa, (void*)buf, sizeof(buf)) != RTCS_OK) {
9533
#else
9534
    if (XINET_PTON(af, ipa, (void*)buf) != 1) {
9535
#endif
9536
        WOLFSSL_MSG("Error parsing IP address");
9537
        return NULL;
9538
    }
9539
9540
    ret = wolfSSL_ASN1_STRING_new();
9541
    if (ret != NULL) {
9542
        if (wolfSSL_ASN1_STRING_set(ret, buf, ipaSz) != WOLFSSL_SUCCESS) {
9543
            WOLFSSL_MSG("Error setting the string");
9544
            wolfSSL_ASN1_STRING_free(ret);
9545
            ret = NULL;
9546
        }
9547
    }
9548
9549
    return ret;
9550
}
9551
#endif /* !WOLFSSL_USER_IO */
9552
9553
/* Is the suite outside the versions allowed by minDowngrade and the
9554
 * WOLFSSL_OP_NO_* bits of mask? */
9555
static WC_INLINE int CipherMinMaxCheck(byte minDowngrade, unsigned long mask,
9556
        byte suite0, byte suite)
9557
{
9558
    const CipherSuiteInfo* cipher_names = GetCipherNames();
9559
    int i = GetCipherNamesIdx(suite0, suite);
9560
9561
    if (i < 0)
9562
        return 1;
9563
    /* Suites are tagged with TLS minors. Map DTLS to the matching TLS. */
9564
    if (minDowngrade == DTLS_MINOR)
9565
        minDowngrade = TLSv1_1_MINOR;
9566
    else if (minDowngrade == DTLSv1_2_MINOR)
9567
        minDowngrade = TLSv1_2_MINOR;
9568
    else if (minDowngrade == DTLSv1_3_MINOR)
9569
        minDowngrade = TLSv1_3_MINOR;
9570
    /* Check min version */
9571
    if (cipher_names[i].minor < minDowngrade) {
9572
        if (minDowngrade <= TLSv1_2_MINOR &&
9573
                cipher_names[i].minor >= TLSv1_MINOR)
9574
            /* 1.0 ciphersuites are in general available in 1.1 and
9575
             * 1.1 ciphersuites are in general available in 1.2 */
9576
            return 0;
9577
        return 1;
9578
    }
9579
    /* Check max version */
9580
    switch (cipher_names[i].minor) {
9581
    case SSLv3_MINOR :
9582
        return mask & WOLFSSL_OP_NO_SSLv3;
9583
    case TLSv1_MINOR :
9584
        return mask & WOLFSSL_OP_NO_TLSv1;
9585
    case TLSv1_1_MINOR :
9586
        return mask & WOLFSSL_OP_NO_TLSv1_1;
9587
    case TLSv1_2_MINOR :
9588
        return mask & WOLFSSL_OP_NO_TLSv1_2;
9589
    case TLSv1_3_MINOR :
9590
        return mask & WOLFSSL_OP_NO_TLSv1_3;
9591
    default:
9592
        WOLFSSL_MSG("Unrecognized minor version");
9593
        return 1;
9594
    }
9595
}
9596
9597
static WC_INLINE int sslCipherMinMaxCheck(const WOLFSSL *ssl, byte suite0,
9598
        byte suite)
9599
{
9600
    return CipherMinMaxCheck(ssl->options.minDowngrade, ssl->options.mask,
9601
                             suite0, suite);
9602
}
9603
9604
/* Is the suite at index i left out of a cipher stack? */
9605
static WC_INLINE int CipherStackSkip(const Suites* suites, int i,
9606
        byte minDowngrade, unsigned long mask)
9607
{
9608
    /* A couple of suites are placeholders for special options, skip those. */
9609
    return SCSV_Check(suites->suites[i], suites->suites[i+1]) ||
9610
           CipherMinMaxCheck(minDowngrade, mask, suites->suites[i],
9611
                             suites->suites[i+1]);
9612
}
9613
9614
/* Build a stack of the suites that can be offered, highest priority first.
9615
 * Returns NULL when no suite can be offered or on error. */
9616
static WOLF_STACK_OF(WOLFSSL_CIPHER)* CipherStackNew(const Suites* suites,
9617
        byte minDowngrade, unsigned long mask, void* heap)
9618
{
9619
    WOLF_STACK_OF(WOLFSSL_CIPHER)* sk;
9620
    int i;
9621
9622
    sk = wolfssl_sk_new_type_ex(STACK_TYPE_CIPHER, heap);
9623
    if (sk == NULL)
9624
        return NULL;
9625
9626
    /* Walk lowest priority first: each suite is inserted at index 0, so
9627
     * the highest priority suite ends up on top of the stack. */
9628
    for (i = suites->suiteSz - 2; i >= 0; i -= 2) {
9629
        struct WOLFSSL_CIPHER cipher;
9630
9631
        if (CipherStackSkip(suites, i, minDowngrade, mask))
9632
            continue;
9633
9634
        wolfssl_cipher_init_suite(&cipher, suites->suites[i],
9635
            suites->suites[i+1]);
9636
        if (wolfSSL_sk_insert(sk, &cipher, 0) <= 0) {
9637
            WOLFSSL_MSG("Error inserting cipher onto stack");
9638
            wolfSSL_sk_CIPHER_free(sk);
9639
            return NULL;
9640
        }
9641
    }
9642
9643
    /* If no ciphers were added, free empty stack and return NULL */
9644
    if (wolfSSL_sk_num(sk) == 0) {
9645
        wolfSSL_sk_CIPHER_free(sk);
9646
        sk = NULL;
9647
    }
9648
    return sk;
9649
}
9650
9651
/* Does sk hold the suites CipherStackNew() would build, in the same order? */
9652
static int CipherStackMatches(WOLFSSL_STACK* sk, const Suites* suites,
9653
        byte minDowngrade, unsigned long mask)
9654
{
9655
    int num = wolfSSL_sk_num(sk);
9656
    int i;
9657
9658
    for (i = 0; i < suites->suiteSz; i += 2) {
9659
        if (CipherStackSkip(suites, i, minDowngrade, mask))
9660
            continue;
9661
        if (num == 0 || sk == NULL ||
9662
                sk->data.cipher.cipherSuite0 != suites->suites[i] ||
9663
                sk->data.cipher.cipherSuite != suites->suites[i+1]) {
9664
            return 0;
9665
        }
9666
        num--;
9667
        sk = sk->next;
9668
    }
9669
    return num == 0;
9670
}
9671
9672
/* returns a pointer to internal cipher suite list. Should not be free'd by
9673
 * caller.
9674
 */
9675
WOLF_STACK_OF(WOLFSSL_CIPHER) *wolfSSL_get_ciphers_compat(const WOLFSSL *ssl)
9676
{
9677
    const Suites* suites;
9678
9679
    WOLFSSL_ENTER("wolfSSL_get_ciphers_compat");
9680
    if (ssl == NULL)
9681
        return NULL;
9682
9683
    suites = WOLFSSL_SUITES(ssl);
9684
    if (suites == NULL)
9685
        return NULL;
9686
9687
    /* check if stack needs populated */
9688
    if (ssl->suitesStack == NULL) {
9689
        ((WOLFSSL*)ssl)->suitesStack = CipherStackNew(suites,
9690
            ssl->options.minDowngrade, ssl->options.mask, ssl->heap);
9691
    }
9692
    return ssl->suitesStack;
9693
}
9694
9695
/* OpenSSL SSL_CTX_get_ciphers(): the cipher list of ctx, highest priority
9696
 * first. The stack is owned by ctx and must not be freed. Changing the list
9697
 * invalidates it, as in OpenSSL; here the next call frees the old stack.
9698
 * As in SSL_get_ciphers(), suites outside the version range are left out
9699
 * and NULL is returned when none is left.
9700
 * Before wolfSSL_new() derives ctx->suites the defaults are reported, as
9701
 * OpenSSL does after SSL_CTX_new(). ctx->suites is only read, under the CTX
9702
 * mutex that guards its derivation. Entries describe their own suite and are
9703
 * not written after the stack is built, so threads may share them. */
9704
WOLF_STACK_OF(WOLFSSL_CIPHER)* wolfSSL_CTX_get_ciphers_compat(
9705
    const WOLFSSL_CTX* ctx)
9706
{
9707
    WOLFSSL_CTX* c = (WOLFSSL_CTX*)ctx;
9708
    WOLF_STACK_OF(WOLFSSL_CIPHER)* sk = NULL;
9709
    const Suites* suites;
9710
    WC_DECLARE_VAR(defSuites, Suites, 1, 0);
9711
9712
    WOLFSSL_ENTER("wolfSSL_CTX_get_ciphers_compat");
9713
    if (ctx == NULL)
9714
        return NULL;
9715
9716
    if (wolfSSL_RefWithMutexLock(&c->ref) != 0) {
9717
        WOLFSSL_MSG("Failed to lock CTX mutex");
9718
        return NULL;
9719
    }
9720
9721
    suites = ctx->suites;
9722
    if (suites == NULL) {
9723
        /* Not derived yet: use the list wolfSSL_new() would derive. */
9724
        WC_ALLOC_VAR_EX(defSuites, Suites, 1, ctx->heap, DYNAMIC_TYPE_SUITES,
9725
            WOLFSSL_MSG("Memory alloc for Suites failed"));
9726
        if (WC_VAR_OK(defSuites)) {
9727
            XMEMSET(defSuites, 0, sizeof(Suites));
9728
            InitSSL_CTX_Suites(ctx, defSuites);
9729
            suites = defSuites;
9730
        }
9731
    }
9732
9733
    if (suites != NULL) {
9734
        if (!CipherStackMatches(c->suitesStack, suites, ctx->minDowngrade,
9735
                ctx->mask)) {
9736
            wolfSSL_sk_CIPHER_free(c->suitesStack);
9737
            c->suitesStack = CipherStackNew(suites, ctx->minDowngrade,
9738
                ctx->mask, ctx->heap);
9739
        }
9740
        sk = c->suitesStack;
9741
    }
9742
9743
    if (wolfSSL_RefWithMutexUnlock(&c->ref) != 0) {
9744
        WOLFSSL_MSG("Failed to unlock CTX mutex");
9745
    }
9746
9747
    WC_FREE_VAR_EX(defSuites, ctx->heap, DYNAMIC_TYPE_SUITES);
9748
    return sk;
9749
}
9750
9751
/* Get the name of the cipher at index priority in the cipher list configured
9752
 * on this SSL. Index 0 is the highest priority suite. Returns NULL once
9753
 * priority is past the end of the list. Matches OpenSSL SSL_get_cipher_list().
9754
 */
9755
const char* wolfSSL_get_cipher_list_compat(const WOLFSSL* ssl, int priority)
9756
{
9757
    const Suites* suites;
9758
    int i;
9759
    int idx = 0;
9760
9761
    WOLFSSL_ENTER("wolfSSL_get_cipher_list_compat");
9762
9763
    if (ssl == NULL || priority < 0)
9764
        return NULL;
9765
9766
    suites = WOLFSSL_SUITES(ssl);
9767
    if (suites == NULL)
9768
        return NULL;
9769
9770
    for (i = 0; i < suites->suiteSz; i += 2) {
9771
        /* A couple of suites are placeholders for special options, skip
9772
         * those. */
9773
        if (SCSV_Check(suites->suites[i], suites->suites[i+1])
9774
                || sslCipherMinMaxCheck(ssl, suites->suites[i],
9775
                                        suites->suites[i+1])) {
9776
            continue;
9777
        }
9778
9779
        if (idx++ == priority) {
9780
            /* Report the same name that SSL_CIPHER_get_name() would. */
9781
        #if !defined(WOLFSSL_CIPHER_INTERNALNAME) && \
9782
            !defined(NO_ERROR_STRINGS) && !defined(WOLFSSL_QT)
9783
            return GetCipherNameIana(suites->suites[i], suites->suites[i+1]);
9784
        #else
9785
            return wolfSSL_get_cipher_name_from_suite(suites->suites[i],
9786
                    suites->suites[i+1]);
9787
        #endif
9788
        }
9789
    }
9790
9791
    return NULL;
9792
}
9793
#endif /* OPENSSL_EXTRA || OPENSSL_ALL || WOLFSSL_NGINX || WOLFSSL_HAPROXY */
9794
#ifdef OPENSSL_ALL
9795
/* returned pointer is to an internal element in WOLFSSL struct and should not
9796
 * be free'd. It gets free'd when the WOLFSSL struct is free'd. */
9797
WOLF_STACK_OF(WOLFSSL_CIPHER)*  wolfSSL_get_client_ciphers(WOLFSSL* ssl)
9798
{
9799
    WOLF_STACK_OF(WOLFSSL_CIPHER)* ret = NULL;
9800
    const Suites* suites;
9801
9802
    WOLFSSL_ENTER("wolfSSL_get_client_ciphers");
9803
9804
    if (ssl == NULL) {
9805
        return NULL;
9806
    }
9807
9808
    /* return NULL if is client side */
9809
    if (wolfSSL_is_server(ssl) == 0) {
9810
        return NULL;
9811
    }
9812
9813
    suites = ssl->clSuites;
9814
    if (suites == NULL) {
9815
        WOLFSSL_MSG("No client suites stored");
9816
    }
9817
    else if (ssl->clSuitesStack != NULL) {
9818
        ret = ssl->clSuitesStack;
9819
    }
9820
    else { /* generate cipher suites stack if not already done */
9821
        int i;
9822
9823
        ret = wolfSSL_sk_new_node(ssl->heap);
9824
        if (ret != NULL) {
9825
            ret->type = STACK_TYPE_CIPHER;
9826
9827
            /* higher priority of cipher suite will be on top of stack */
9828
            for (i = suites->suiteSz - 2; i >= 0; i -= 2) {
9829
                WOLFSSL_CIPHER cipher;
9830
9831
                /* A couple of suites are placeholders for special options,
9832
                 * skip those. */
9833
                if (SCSV_Check(suites->suites[i], suites->suites[i+1])
9834
                        || sslCipherMinMaxCheck(ssl, suites->suites[i],
9835
                                                suites->suites[i+1])) {
9836
                    continue;
9837
                }
9838
9839
                wolfssl_cipher_init_suite(&cipher, suites->suites[i],
9840
                    suites->suites[i+1]);
9841
                if (wolfSSL_sk_CIPHER_push(ret, &cipher) <= 0) {
9842
                    WOLFSSL_MSG("Error pushing client cipher onto stack");
9843
                    wolfSSL_sk_CIPHER_free(ret);
9844
                    ret = NULL;
9845
                    break;
9846
                }
9847
            }
9848
        }
9849
        ssl->clSuitesStack = ret;
9850
    }
9851
    return ret;
9852
}
9853
#endif /* OPENSSL_ALL */
9854
9855
#if defined(OPENSSL_EXTRA) || defined(HAVE_SECRET_CALLBACK)
9856
long wolfSSL_SSL_CTX_get_timeout(const WOLFSSL_CTX *ctx)
9857
{
9858
    WOLFSSL_ENTER("wolfSSL_SSL_CTX_get_timeout");
9859
9860
    if (ctx == NULL)
9861
        return 0;
9862
9863
    return ctx->timeout;
9864
}
9865
9866
9867
/* returns the time in seconds of the current timeout */
9868
long wolfSSL_get_timeout(WOLFSSL* ssl)
9869
{
9870
    WOLFSSL_ENTER("wolfSSL_get_timeout");
9871
9872
    if (ssl == NULL)
9873
        return 0;
9874
    return ssl->timeout;
9875
}
9876
#endif
9877
9878
#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) \
9879
    || defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY)
9880
9881
#ifndef NO_BIO
9882
WOLFSSL_BIO *wolfSSL_SSL_get_rbio(const WOLFSSL *s)
9883
{
9884
    WOLFSSL_ENTER("wolfSSL_SSL_get_rbio");
9885
    /* Nginx sets the buffer size if the read BIO is different to write BIO.
9886
     * The setting buffer size doesn't do anything so return NULL for both.
9887
     */
9888
    if (s == NULL)
9889
        return NULL;
9890
9891
    return s->biord;
9892
}
9893
WOLFSSL_BIO *wolfSSL_SSL_get_wbio(const WOLFSSL *s)
9894
{
9895
    WOLFSSL_ENTER("wolfSSL_SSL_get_wbio");
9896
    (void)s;
9897
    /* Nginx sets the buffer size if the read BIO is different to write BIO.
9898
     * The setting buffer size doesn't do anything so return NULL for both.
9899
     */
9900
    if (s == NULL)
9901
        return NULL;
9902
9903
    return s->biowr;
9904
}
9905
#endif /* !NO_BIO */
9906
9907
9908
9909
#endif /* OPENSSL_ALL || WOLFSSL_NGINX || WOLFSSL_HAPROXY ||
9910
    OPENSSL_EXTRA || HAVE_LIGHTY */
9911
9912
9913
#if defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) || \
9914
    defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)
9915
9916
9917
void wolfSSL_WOLFSSL_STRING_free(WOLFSSL_STRING s)
9918
{
9919
    WOLFSSL_ENTER("wolfSSL_WOLFSSL_STRING_free");
9920
9921
    XFREE(s, NULL, DYNAMIC_TYPE_OPENSSL);
9922
}
9923
9924
#endif /* WOLFSSL_NGINX || WOLFSSL_HAPROXY || OPENSSL_EXTRA || OPENSSL_ALL */
9925
9926
9927
#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL)
9928
9929
/* The FFDHE groups have no curve behind them, but they are named and reported
9930
 * through these same APIs, so an FFDHE-only build needs this block too. */
9931
#if (defined(HAVE_ECC) || defined(HAVE_CURVE25519) || \
9932
    defined(HAVE_CURVE448) || !defined(NO_DH))
9933
#define CURVE_NAME(c) XSTR_SIZEOF((c)), (c)
9934
9935
const WOLF_EC_NIST_NAME kNistCurves[] = {
9936
#ifdef HAVE_ECC
9937
    {CURVE_NAME("P-160"),   WC_NID_secp160r1, WOLFSSL_ECC_SECP160R1},
9938
    {CURVE_NAME("P-160-2"), WC_NID_secp160r2, WOLFSSL_ECC_SECP160R2},
9939
    {CURVE_NAME("P-192"),   WC_NID_X9_62_prime192v1, WOLFSSL_ECC_SECP192R1},
9940
    {CURVE_NAME("P-224"),   WC_NID_secp224r1, WOLFSSL_ECC_SECP224R1},
9941
    {CURVE_NAME("P-256"),   WC_NID_X9_62_prime256v1, WOLFSSL_ECC_SECP256R1},
9942
    {CURVE_NAME("P-384"),   WC_NID_secp384r1, WOLFSSL_ECC_SECP384R1},
9943
    {CURVE_NAME("P-521"),   WC_NID_secp521r1, WOLFSSL_ECC_SECP521R1},
9944
    {CURVE_NAME("K-160"),   WC_NID_secp160k1, WOLFSSL_ECC_SECP160K1},
9945
    {CURVE_NAME("K-192"),   WC_NID_secp192k1, WOLFSSL_ECC_SECP192K1},
9946
    {CURVE_NAME("K-224"),   WC_NID_secp224k1, WOLFSSL_ECC_SECP224K1},
9947
    {CURVE_NAME("K-256"),   WC_NID_secp256k1, WOLFSSL_ECC_SECP256K1},
9948
    {CURVE_NAME("B-256"),   WC_NID_brainpoolP256r1,
9949
     WOLFSSL_ECC_BRAINPOOLP256R1},
9950
    {CURVE_NAME("B-384"),   WC_NID_brainpoolP384r1,
9951
     WOLFSSL_ECC_BRAINPOOLP384R1},
9952
    {CURVE_NAME("B-512"),   WC_NID_brainpoolP512r1,
9953
     WOLFSSL_ECC_BRAINPOOLP512R1},
9954
#endif
9955
#ifdef HAVE_CURVE25519
9956
    {CURVE_NAME("X25519"),  WC_NID_X25519, WOLFSSL_ECC_X25519},
9957
#endif
9958
#ifdef HAVE_CURVE448
9959
    {CURVE_NAME("X448"),    WC_NID_X448, WOLFSSL_ECC_X448},
9960
#endif
9961
#ifdef WOLFSSL_HAVE_MLKEM
9962
#ifndef WOLFSSL_NO_ML_KEM
9963
    {CURVE_NAME("ML_KEM_512"), WOLFSSL_ML_KEM_512, WOLFSSL_ML_KEM_512},
9964
    {CURVE_NAME("ML_KEM_768"), WOLFSSL_ML_KEM_768, WOLFSSL_ML_KEM_768},
9965
    {CURVE_NAME("ML_KEM_1024"), WOLFSSL_ML_KEM_1024, WOLFSSL_ML_KEM_1024},
9966
    /* Aliases accepting the OpenSSL/IANA spelling without underscores. */
9967
    {CURVE_NAME("MLKEM512"), WOLFSSL_ML_KEM_512, WOLFSSL_ML_KEM_512},
9968
    {CURVE_NAME("MLKEM768"), WOLFSSL_ML_KEM_768, WOLFSSL_ML_KEM_768},
9969
    {CURVE_NAME("MLKEM1024"), WOLFSSL_ML_KEM_1024, WOLFSSL_ML_KEM_1024},
9970
#if defined(HAVE_ECC)
9971
    #ifdef WOLFSSL_PQC_HYBRIDS
9972
    {CURVE_NAME("SecP256r1MLKEM768"), WOLFSSL_SECP256R1MLKEM768,
9973
     WOLFSSL_SECP256R1MLKEM768},
9974
    {CURVE_NAME("SecP384r1MLKEM1024"), WOLFSSL_SECP384R1MLKEM1024,
9975
     WOLFSSL_SECP384R1MLKEM1024},
9976
    {CURVE_NAME("X25519MLKEM768"), WOLFSSL_X25519MLKEM768,
9977
     WOLFSSL_X25519MLKEM768},
9978
    #endif /* WOLFSSL_PQC_HYBRIDS */
9979
    #ifdef WOLFSSL_EXTRA_PQC_HYBRIDS
9980
    {CURVE_NAME("SecP256r1MLKEM512"), WOLFSSL_SECP256R1MLKEM512,
9981
     WOLFSSL_SECP256R1MLKEM512},
9982
    {CURVE_NAME("SecP384r1MLKEM768"), WOLFSSL_SECP384R1MLKEM768,
9983
     WOLFSSL_SECP384R1MLKEM768},
9984
    {CURVE_NAME("SecP521r1MLKEM1024"), WOLFSSL_SECP521R1MLKEM1024,
9985
     WOLFSSL_SECP521R1MLKEM1024},
9986
    {CURVE_NAME("X25519MLKEM512"), WOLFSSL_X25519MLKEM512,
9987
     WOLFSSL_X25519MLKEM512},
9988
    {CURVE_NAME("X448MLKEM768"), WOLFSSL_X448MLKEM768,
9989
     WOLFSSL_X448MLKEM768},
9990
    #endif /* WOLFSSL_EXTRA_PQC_HYBRIDS */
9991
#endif
9992
#endif /* !WOLFSSL_NO_ML_KEM */
9993
#ifdef WOLFSSL_MLKEM_KYBER
9994
    {CURVE_NAME("KYBER_LEVEL1"), WOLFSSL_KYBER_LEVEL1, WOLFSSL_KYBER_LEVEL1},
9995
    {CURVE_NAME("KYBER_LEVEL3"), WOLFSSL_KYBER_LEVEL3, WOLFSSL_KYBER_LEVEL3},
9996
    {CURVE_NAME("KYBER_LEVEL5"), WOLFSSL_KYBER_LEVEL5, WOLFSSL_KYBER_LEVEL5},
9997
#if defined(HAVE_ECC)
9998
    {CURVE_NAME("P256_KYBER_LEVEL1"), WOLFSSL_P256_KYBER_LEVEL1,
9999
     WOLFSSL_P256_KYBER_LEVEL1},
10000
    {CURVE_NAME("P384_KYBER_LEVEL3"), WOLFSSL_P384_KYBER_LEVEL3,
10001
     WOLFSSL_P384_KYBER_LEVEL3},
10002
    {CURVE_NAME("P256_KYBER_LEVEL3"), WOLFSSL_P256_KYBER_LEVEL3,
10003
     WOLFSSL_P256_KYBER_LEVEL3},
10004
    {CURVE_NAME("P521_KYBER_LEVEL5"), WOLFSSL_P521_KYBER_LEVEL5,
10005
     WOLFSSL_P521_KYBER_LEVEL5},
10006
    {CURVE_NAME("X25519_KYBER_LEVEL1"), WOLFSSL_X25519_KYBER_LEVEL1,
10007
     WOLFSSL_X25519_KYBER_LEVEL1},
10008
    {CURVE_NAME("X448_KYBER_LEVEL3"), WOLFSSL_X448_KYBER_LEVEL3,
10009
     WOLFSSL_X448_KYBER_LEVEL3},
10010
    {CURVE_NAME("X25519_KYBER_LEVEL3"), WOLFSSL_X25519_KYBER_LEVEL3,
10011
     WOLFSSL_X25519_KYBER_LEVEL3},
10012
#endif
10013
#endif /* WOLFSSL_MLKEM_KYBER */
10014
#endif /* WOLFSSL_HAVE_MLKEM */
10015
#ifndef NO_DH
10016
    /* Finite field groups are not EC curves, but they do have NIDs of their
10017
     * own (RFC 7919, same values as OpenSSL). Use those rather than the TLS
10018
     * code point, which would collide with an unrelated WC_NID_* value. */
10019
    #ifdef HAVE_FFDHE_2048
10020
    {CURVE_NAME("ffdhe2048"), WC_NID_ffdhe2048, WOLFSSL_FFDHE_2048},
10021
    #endif
10022
    #ifdef HAVE_FFDHE_3072
10023
    {CURVE_NAME("ffdhe3072"), WC_NID_ffdhe3072, WOLFSSL_FFDHE_3072},
10024
    #endif
10025
    #ifdef HAVE_FFDHE_4096
10026
    {CURVE_NAME("ffdhe4096"), WC_NID_ffdhe4096, WOLFSSL_FFDHE_4096},
10027
    #endif
10028
    #ifdef HAVE_FFDHE_6144
10029
    {CURVE_NAME("ffdhe6144"), WC_NID_ffdhe6144, WOLFSSL_FFDHE_6144},
10030
    #endif
10031
    #ifdef HAVE_FFDHE_8192
10032
    {CURVE_NAME("ffdhe8192"), WC_NID_ffdhe8192, WOLFSSL_FFDHE_8192},
10033
    #endif
10034
#endif /* !NO_DH */
10035
#ifdef WOLFSSL_SM2
10036
    {CURVE_NAME("SM2"),     WC_NID_sm2, WOLFSSL_ECC_SM2P256V1},
10037
#endif
10038
#ifdef HAVE_ECC
10039
    /* Alternative curve names */
10040
    {CURVE_NAME("prime256v1"), WC_NID_X9_62_prime256v1, WOLFSSL_ECC_SECP256R1},
10041
    {CURVE_NAME("secp256r1"),  WC_NID_X9_62_prime256v1, WOLFSSL_ECC_SECP256R1},
10042
    {CURVE_NAME("secp384r1"),  WC_NID_secp384r1, WOLFSSL_ECC_SECP384R1},
10043
    {CURVE_NAME("secp521r1"),  WC_NID_secp521r1, WOLFSSL_ECC_SECP521R1},
10044
#endif
10045
#ifdef WOLFSSL_SM2
10046
    {CURVE_NAME("sm2p256v1"),  WC_NID_sm2, WOLFSSL_ECC_SM2P256V1},
10047
#endif
10048
    {0, NULL, 0, 0},
10049
};
10050
10051
int set_curves_list(WOLFSSL* ssl, WOLFSSL_CTX *ctx, const char* names,
10052
        byte curves_only)
10053
{
10054
    int idx, start = 0, len, i, ret = WOLFSSL_FAILURE;
10055
    word16 curve;
10056
    word32 disabled;
10057
    char name[MAX_CURVE_NAME_SZ];
10058
    byte groups_len = 0;
10059
#ifdef WOLFSSL_SMALL_STACK
10060
    void *heap = ssl? ssl->heap : ctx ? ctx->heap : NULL;
10061
    int *groups;
10062
#else
10063
    int groups[WOLFSSL_MAX_GROUP_COUNT];
10064
#endif
10065
    const WOLF_EC_NIST_NAME* nist_name;
10066
10067
    WC_ALLOC_VAR_EX(groups, int, WOLFSSL_MAX_GROUP_COUNT, heap,
10068
        DYNAMIC_TYPE_TMP_BUFFER,
10069
    {
10070
        ret=MEMORY_E;
10071
        goto leave;
10072
    });
10073
10074
    for (idx = 1; names[idx-1] != '\0'; idx++) {
10075
        if (names[idx] != ':' && names[idx] != '\0')
10076
            continue;
10077
10078
        len = idx - start;
10079
        if (len > MAX_CURVE_NAME_SZ - 1)
10080
            goto leave;
10081
10082
        XMEMCPY(name, names + start, (size_t)len);
10083
        name[len] = 0;
10084
        curve = WOLFSSL_NAMED_GROUP_INVALID;
10085
10086
        for (nist_name = kNistCurves; nist_name->name != NULL; nist_name++) {
10087
            if (len == nist_name->name_len &&
10088
                    XSTRNCASECMP(name, nist_name->name, (size_t)len) == 0) {
10089
                curve = nist_name->curve;
10090
                break;
10091
            }
10092
        }
10093
10094
        if (curve == WOLFSSL_NAMED_GROUP_INVALID) {
10095
        #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && defined(HAVE_ECC)
10096
            int   nret;
10097
            const ecc_set_type *eccSet;
10098
10099
            nret = wc_ecc_get_curve_idx_from_name(name);
10100
            if (nret < 0) {
10101
                WOLFSSL_MSG("Could not find name in set");
10102
                goto leave;
10103
            }
10104
10105
            eccSet = wc_ecc_get_curve_params(nret);
10106
            if (eccSet == NULL) {
10107
                WOLFSSL_MSG("NULL set returned");
10108
                goto leave;
10109
            }
10110
10111
            curve = GetCurveByOID((int)eccSet->oidSum);
10112
        #else
10113
            WOLFSSL_MSG("API not present to search farther using name");
10114
            goto leave;
10115
        #endif
10116
        }
10117
10118
        if ((curves_only && curve >= WOLFSSL_ECC_MAX_AVAIL) ||
10119
                curve == WOLFSSL_NAMED_GROUP_INVALID) {
10120
            WOLFSSL_MSG("curve value is not supported");
10121
            goto leave;
10122
        }
10123
10124
        for (i = 0; i < groups_len; ++i) {
10125
            if (groups[i] == curve) {
10126
                /* silently drop duplicates */
10127
                break;
10128
            }
10129
        }
10130
        if (i >= groups_len) {
10131
            if (groups_len >= WOLFSSL_MAX_GROUP_COUNT) {
10132
                WOLFSSL_MSG_EX("setting %d or more supported "
10133
                               "curves is not permitted", groups_len);
10134
                goto leave;
10135
            }
10136
            groups[groups_len++] = (int)curve;
10137
        }
10138
10139
        start = idx + 1;
10140
    }
10141
10142
    /* Disable all curves so that only the ones the user wants are enabled. */
10143
    disabled = 0xFFFFFFFFUL;
10144
    for (i = 0; i < groups_len; ++i) {
10145
        /* Switch the bit to off and therefore is enabled. */
10146
        curve = (word16)groups[i];
10147
        if (curve >= 64) {
10148
            WC_DO_NOTHING;
10149
        }
10150
        else if (curve >= 32) {
10151
            /* 0 is for invalid and 1-14 aren't used otherwise. */
10152
            disabled &= ~(1U << (curve - 32));
10153
        }
10154
        else {
10155
            disabled &= ~(1U << curve);
10156
        }
10157
    #if defined(HAVE_SUPPORTED_CURVES) && !defined(NO_TLS)
10158
    #if !defined(WOLFSSL_OLD_SET_CURVES_LIST)
10159
        /* using the wolfSSL API to set the groups, this will populate
10160
         * (ssl|ctx)->groups and reset any TLSX_SUPPORTED_GROUPS.
10161
         * The order in (ssl|ctx)->groups will then be respected
10162
         * when TLSX_KEY_SHARE needs to be established */
10163
        if ((ssl && wolfSSL_set_groups(ssl, groups, groups_len)
10164
                        != WOLFSSL_SUCCESS)
10165
            || (ctx && wolfSSL_CTX_set_groups(ctx, groups, groups_len)
10166
                           != WOLFSSL_SUCCESS)) {
10167
            WOLFSSL_MSG("Unable to set supported curve");
10168
            goto leave;
10169
        }
10170
    #elif !defined(NO_WOLFSSL_CLIENT)
10171
        /* set the supported curve so client TLS extension contains only the
10172
         * desired curves */
10173
        if ((ssl && wolfSSL_UseSupportedCurve(ssl, curve) != WOLFSSL_SUCCESS)
10174
            || (ctx && wolfSSL_CTX_UseSupportedCurve(ctx, curve)
10175
                           != WOLFSSL_SUCCESS)) {
10176
            WOLFSSL_MSG("Unable to set supported curve");
10177
            goto leave;
10178
        }
10179
    #endif
10180
    #endif /* HAVE_SUPPORTED_CURVES && !NO_TLS */
10181
    }
10182
10183
    if (ssl != NULL)
10184
        ssl->disabledCurves = disabled;
10185
    else if (ctx != NULL)
10186
        ctx->disabledCurves = disabled;
10187
    ret = WOLFSSL_SUCCESS;
10188
10189
leave:
10190
#ifdef WOLFSSL_SMALL_STACK
10191
    if (groups)
10192
        XFREE((void*)groups, heap, DYNAMIC_TYPE_TMP_BUFFER);
10193
#endif
10194
    return ret;
10195
}
10196
10197
/* Get the group used for key exchange.
10198
 *
10199
 * Mirrors OpenSSL's SSL_get_negotiated_group(): the NID is returned for groups
10200
 * wolfSSL gives one, the IANA code point otherwise. NID values are wolfSSL's
10201
 * WC_NID_* (not every one matches OpenSSL's), so compare against those rather
10202
 * than against literals. The result can be passed to wolfSSL_group_to_name().
10203
 * Only a completed handshake reports a group.
10204
 *
10205
 * @param [in] ssl  SSL/TLS object.
10206
 * @return  Group identifier on success.
10207
 * @return  0 when ssl is NULL or no group has been negotiated.
10208
 */
10209
int wolfSSL_get_negotiated_group(const WOLFSSL* ssl)
10210
{
10211
    word16 group = 0;
10212
    const WOLF_EC_NIST_NAME* nist_name;
10213
#if defined(HAVE_CURVE25519) || defined(HAVE_CURVE448) || defined(HAVE_ECC)
10214
    int ecdhDone;
10215
#endif
10216
10217
    WOLFSSL_ENTER("wolfSSL_get_negotiated_group");
10218
10219
    if (ssl == NULL)
10220
        return 0;
10221
10222
#if defined(WOLFSSL_TLS13) || defined(HAVE_FFDHE)
10223
    /* Only a completed handshake has a negotiated group. Mid-handshake this
10224
     * can hold a group no key exchange used: the server seeds it from the
10225
     * resumed session in CheckPreSharedKeys(), and the client stores the group
10226
     * a HelloRetryRequest asked for. */
10227
    if (ssl->options.handShakeDone)
10228
        group = ssl->namedGroup;
10229
#endif
10230
10231
#if defined(HAVE_CURVE25519) || defined(HAVE_CURVE448) || defined(HAVE_ECC)
10232
    /* Below TLS 1.3 the negotiated curve is only in ecdhCurveOID, which
10233
     * InitSSL() also seeds from ctx->ecdhCurveOID - what
10234
     * SSL_CTX_set_tmp_ecdh() writes. Report it only once an EC(DH) exchange
10235
     * has actually run, or a configured preference reads back as a
10236
     * negotiated group on a connection that never used one. */
10237
    ecdhDone = ssl->options.handShakeDone &&
10238
               ((ssl->specs.kea == ecc_diffie_hellman_kea) ||
10239
                (ssl->specs.kea == ecdhe_psk_kea));
10240
#endif
10241
10242
#ifdef HAVE_CURVE25519
10243
    if ((group == 0) && ecdhDone && (ssl->ecdhCurveOID == ECC_X25519_OID))
10244
        group = WOLFSSL_ECC_X25519;
10245
#endif
10246
#ifdef HAVE_CURVE448
10247
    if ((group == 0) && ecdhDone && (ssl->ecdhCurveOID == ECC_X448_OID))
10248
        group = WOLFSSL_ECC_X448;
10249
#endif
10250
#ifdef HAVE_ECC
10251
    if ((group == 0) && ecdhDone && (ssl->ecdhCurveOID != 0))
10252
        group = GetCurveByOID((int)ssl->ecdhCurveOID);
10253
#endif
10254
10255
    if (group == 0)
10256
        return 0;
10257
10258
    for (nist_name = kNistCurves; nist_name->name != NULL; nist_name++) {
10259
        if (nist_name->curve == group)
10260
            return nist_name->nid;
10261
    }
10262
10263
    return (int)group;
10264
}
10265
10266
/* Names OpenSSL gives the TLS supported groups. These are the TLS group
10267
 * registry spellings, which differ from both the NIST curve names in
10268
 * kNistCurves ("P-256" is "secp256r1" here) and from wolfSSL_get_curve_name().
10269
 */
10270
static const struct {
10271
    word16      group;
10272
    const char* name;
10273
} kTlsGroupNames[] = {
10274
#ifdef HAVE_ECC
10275
    {WOLFSSL_ECC_SECP256R1,        "secp256r1"},
10276
    {WOLFSSL_ECC_SECP384R1,        "secp384r1"},
10277
    {WOLFSSL_ECC_SECP521R1,        "secp521r1"},
10278
    {WOLFSSL_ECC_SECP224R1,        "secp224r1"},
10279
    {WOLFSSL_ECC_SECP192R1,        "secp192r1"},
10280
    {WOLFSSL_ECC_SECP256K1,        "secp256k1"},
10281
#ifdef HAVE_ECC_BRAINPOOL
10282
    {WOLFSSL_ECC_BRAINPOOLP256R1,  "brainpoolP256r1"},
10283
    {WOLFSSL_ECC_BRAINPOOLP384R1,  "brainpoolP384r1"},
10284
    {WOLFSSL_ECC_BRAINPOOLP512R1,  "brainpoolP512r1"},
10285
    {WOLFSSL_ECC_BRAINPOOLP256R1TLS13, "brainpoolP256r1tls13"},
10286
    {WOLFSSL_ECC_BRAINPOOLP384R1TLS13, "brainpoolP384r1tls13"},
10287
    {WOLFSSL_ECC_BRAINPOOLP512R1TLS13, "brainpoolP512r1tls13"},
10288
#endif
10289
#endif /* HAVE_ECC */
10290
#ifdef HAVE_CURVE25519
10291
    {WOLFSSL_ECC_X25519,           "x25519"},
10292
#endif
10293
#ifdef HAVE_CURVE448
10294
    {WOLFSSL_ECC_X448,             "x448"},
10295
#endif
10296
#ifndef NO_DH
10297
    {WOLFSSL_FFDHE_2048,           "ffdhe2048"},
10298
    {WOLFSSL_FFDHE_3072,           "ffdhe3072"},
10299
    {WOLFSSL_FFDHE_4096,           "ffdhe4096"},
10300
    {WOLFSSL_FFDHE_6144,           "ffdhe6144"},
10301
    {WOLFSSL_FFDHE_8192,           "ffdhe8192"},
10302
#endif
10303
#if defined(WOLFSSL_HAVE_MLKEM) && !defined(WOLFSSL_NO_ML_KEM)
10304
    {WOLFSSL_ML_KEM_512,           "MLKEM512"},
10305
    {WOLFSSL_ML_KEM_768,           "MLKEM768"},
10306
    {WOLFSSL_ML_KEM_1024,          "MLKEM1024"},
10307
#if defined(HAVE_ECC) && defined(WOLFSSL_PQC_HYBRIDS)
10308
    {WOLFSSL_SECP256R1MLKEM768,    "SecP256r1MLKEM768"},
10309
    {WOLFSSL_SECP384R1MLKEM1024,   "SecP384r1MLKEM1024"},
10310
#ifdef HAVE_CURVE25519
10311
    {WOLFSSL_X25519MLKEM768,       "X25519MLKEM768"},
10312
#endif
10313
#endif
10314
#endif /* WOLFSSL_HAVE_MLKEM && !WOLFSSL_NO_ML_KEM */
10315
    {0, NULL}
10316
};
10317
10318
/* Get the name of a group.
10319
 *
10320
 * @param [in] ssl  SSL/TLS object. Unused, present for OpenSSL compatibility.
10321
 * @param [in] id   NID or IANA code point of the group.
10322
 * @return  Name of the group on success.
10323
 * @return  NULL when the group is unknown.
10324
 */
10325
const char* wolfSSL_group_to_name(const WOLFSSL* ssl, int id)
10326
{
10327
    const WOLF_EC_NIST_NAME* nist_name;
10328
    int group = id;
10329
    int i;
10330
10331
    WOLFSSL_ENTER("wolfSSL_group_to_name");
10332
10333
    (void)ssl;
10334
10335
    /* wolfSSL_get_negotiated_group() reports a NID where one exists, so map
10336
     * NIDs back to their code point before looking the name up. */
10337
    for (nist_name = kNistCurves; nist_name->name != NULL; nist_name++) {
10338
        if (nist_name->nid == id) {
10339
            group = (int)nist_name->curve;
10340
            break;
10341
        }
10342
    }
10343
10344
    for (i = 0; kTlsGroupNames[i].name != NULL; i++) {
10345
        if ((int)kTlsGroupNames[i].group == group)
10346
            return kTlsGroupNames[i].name;
10347
    }
10348
10349
    /* Not a group OpenSSL names - fall back to the wolfSSL name. */
10350
    for (nist_name = kNistCurves; nist_name->name != NULL; nist_name++) {
10351
        if ((int)nist_name->curve == group)
10352
            return nist_name->name;
10353
    }
10354
10355
    return NULL;
10356
}
10357
10358
#endif /* (HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 || !NO_DH) */
10359
#endif /* OPENSSL_EXTRA || HAVE_CURL */
10360
10361
10362
#ifdef OPENSSL_EXTRA
10363
/* Sets a callback for when sending and receiving protocol messages.
10364
 * This callback is copied to all WOLFSSL objects created from the ctx.
10365
 *
10366
 * ctx WOLFSSL_CTX structure to set callback in
10367
 * cb  callback to use
10368
 *
10369
 * return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE with error case
10370
 */
10371
int wolfSSL_CTX_set_msg_callback(WOLFSSL_CTX *ctx, SSL_Msg_Cb cb)
10372
{
10373
    WOLFSSL_ENTER("wolfSSL_CTX_set_msg_callback");
10374
    if (ctx == NULL) {
10375
        WOLFSSL_MSG("Null ctx passed in");
10376
        return WOLFSSL_FAILURE;
10377
    }
10378
10379
    ctx->protoMsgCb = cb;
10380
    return WOLFSSL_SUCCESS;
10381
}
10382
10383
10384
/* Sets a callback for when sending and receiving protocol messages.
10385
 *
10386
 * ssl WOLFSSL structure to set callback in
10387
 * cb  callback to use
10388
 *
10389
 * return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE with error case
10390
 */
10391
int wolfSSL_set_msg_callback(WOLFSSL *ssl, SSL_Msg_Cb cb)
10392
{
10393
    WOLFSSL_ENTER("wolfSSL_set_msg_callback");
10394
10395
    if (ssl == NULL) {
10396
        return WOLFSSL_FAILURE;
10397
    }
10398
10399
    if (cb != NULL) {
10400
        ssl->toInfoOn = 1;
10401
    }
10402
10403
    ssl->protoMsgCb = cb;
10404
    return WOLFSSL_SUCCESS;
10405
}
10406
10407
10408
/* set the user argument to pass to the msg callback when called
10409
 * return WOLFSSL_SUCCESS on success */
10410
int wolfSSL_CTX_set_msg_callback_arg(WOLFSSL_CTX *ctx, void* arg)
10411
{
10412
    WOLFSSL_ENTER("wolfSSL_CTX_set_msg_callback_arg");
10413
    if (ctx == NULL) {
10414
        WOLFSSL_MSG("Null WOLFSSL_CTX passed in");
10415
        return WOLFSSL_FAILURE;
10416
    }
10417
10418
    ctx->protoMsgCtx = arg;
10419
    return WOLFSSL_SUCCESS;
10420
}
10421
10422
10423
int wolfSSL_set_msg_callback_arg(WOLFSSL *ssl, void* arg)
10424
{
10425
    WOLFSSL_ENTER("wolfSSL_set_msg_callback_arg");
10426
    if (ssl == NULL)
10427
        return WOLFSSL_FAILURE;
10428
10429
    ssl->protoMsgCtx = arg;
10430
    return WOLFSSL_SUCCESS;
10431
}
10432
10433
10434
/* OpenSSL SSL_CTX_set_max_send_fragment(): cap the plaintext of each record
10435
 * sent. Local only: the peer is not told and receiving is not limited.
10436
 * Accepts 512 to 16384. Unset means no cap. wolfSSL_new() copies the value,
10437
 * so later changes do not reach existing objects, as in OpenSSL.
10438
 * With a negotiated max_fragment_length the smaller limit applies, where
10439
 * OpenSSL uses the negotiated one. A DTLS write over the cap fails with
10440
 * DTLS_SIZE_ERROR, like one over the MTU.
10441
 *
10442
 * return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on bad argument
10443
 */
10444
int wolfSSL_CTX_set_max_send_fragment(WOLFSSL_CTX* ctx, long max_fragment)
10445
{
10446
    WOLFSSL_ENTER("wolfSSL_CTX_set_max_send_fragment");
10447
    if (ctx == NULL || max_fragment < 512 || max_fragment > MAX_RECORD_SIZE)
10448
        return WOLFSSL_FAILURE;
10449
10450
    ctx->maxSendFragment = (word16)max_fragment;
10451
    return WOLFSSL_SUCCESS;
10452
}
10453
10454
10455
/* OpenSSL SSL_set_max_send_fragment(): as above for one object. Replaces the
10456
 * value copied from the WOLFSSL_CTX.
10457
 *
10458
 * return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on bad argument
10459
 */
10460
int wolfSSL_set_max_send_fragment(WOLFSSL* ssl, long max_fragment)
10461
{
10462
    WOLFSSL_ENTER("wolfSSL_set_max_send_fragment");
10463
    if (ssl == NULL || max_fragment < 512 || max_fragment > MAX_RECORD_SIZE)
10464
        return WOLFSSL_FAILURE;
10465
10466
    ssl->maxSendFragment = (word16)max_fragment;
10467
    return WOLFSSL_SUCCESS;
10468
}
10469
10470
void *wolfSSL_OPENSSL_memdup(const void *data, size_t siz, const char* file,
10471
    int line)
10472
{
10473
    void *ret;
10474
    (void)file;
10475
    (void)line;
10476
10477
    if (data == NULL || siz >= INT_MAX)
10478
        return NULL;
10479
10480
    ret = wolfSSL_OPENSSL_malloc(siz);
10481
    if (ret == NULL) {
10482
        return NULL;
10483
    }
10484
    return XMEMCPY(ret, data, siz);
10485
}
10486
10487
void wolfSSL_OPENSSL_cleanse(void *ptr, size_t len)
10488
{
10489
    if (ptr)
10490
        ForceZero(ptr, (word32)len);
10491
}
10492
10493
#endif /* OPENSSL_EXTRA */
10494
10495
#define WOLFSSL_SSL_API_EXT_INCLUDED
10496
#include "src/ssl_api_ext.c"
10497
10498
#if defined(OPENSSL_EXTRA)
10499
10500
#ifndef NO_BIO
10501
#define WOLFSSL_BIO_INCLUDED
10502
#include "src/bio.c"
10503
#endif
10504
10505
#endif /* OPENSSL_EXTRA */
10506
10507
10508
#if defined(OPENSSL_EXTRA)
10509
10510
/* frees all nodes in the current threads error queue
10511
 *
10512
 * id  thread id. ERR_remove_state is depreciated and id is ignored. The
10513
 *     current threads queue will be free'd.
10514
 */
10515
10516
#endif /* OPENSSL_EXTRA */
10517
10518
10519
#if defined(OPENSSL_EXTRA)
10520
/* wolfSSL_THREADID_current is provided as a compat API with
10521
 * CRYPTO_THREADID_current to register current thread id into given id object.
10522
 * However, CRYPTO_THREADID_current API has been deprecated and no longer
10523
 * exists in the OpenSSL 1.0.0 or later.This API only works as a stub
10524
 * like as existing wolfSSL_THREADID_set_numeric.
10525
 */
10526
void wolfSSL_THREADID_current(WOLFSSL_CRYPTO_THREADID* id)
10527
{
10528
    (void)id;
10529
    return;
10530
}
10531
/* wolfSSL_THREADID_hash is provided as a compatible API with
10532
 * CRYPTO_THREADID_hash which returns a hash value calculated from the
10533
 * specified thread id. However, CRYPTO_THREADID_hash API has been
10534
 * deprecated and no longer exists in the OpenSSL 1.0.0 or later.
10535
 * This API only works as a stub to returns 0. This behavior is
10536
 * equivalent to the latest OpenSSL CRYPTO_THREADID_hash.
10537
 */
10538
unsigned long wolfSSL_THREADID_hash(const WOLFSSL_CRYPTO_THREADID* id)
10539
{
10540
    (void)id;
10541
    return 0UL;
10542
}
10543
10544
/**
10545
 * Set security level (wolfSSL doesn't support setting the security level).
10546
 *
10547
 * The security level can only be set through a system wide crypto-policy
10548
 * with wolfSSL_crypto_policy_enable().
10549
 *
10550
 * @param ctx  a pointer to WOLFSSL_CTX structure
10551
 * @param level security level
10552
 */
10553
void wolfSSL_CTX_set_security_level(WOLFSSL_CTX* ctx, int level)
10554
{
10555
    WOLFSSL_ENTER("wolfSSL_CTX_set_security_level");
10556
    (void)ctx;
10557
    (void)level;
10558
}
10559
10560
int wolfSSL_CTX_get_security_level(const WOLFSSL_CTX * ctx)
10561
{
10562
    WOLFSSL_ENTER("wolfSSL_CTX_get_security_level");
10563
    #if defined(WOLFSSL_SYS_CRYPTO_POLICY)
10564
    if (ctx == NULL) {
10565
        return BAD_FUNC_ARG;
10566
    }
10567
10568
    return ctx->secLevel;
10569
    #else
10570
    (void)ctx;
10571
    return 0;
10572
    #endif /* WOLFSSL_SYS_CRYPTO_POLICY */
10573
}
10574
10575
#if defined(OPENSSL_EXTRA) && defined(HAVE_SECRET_CALLBACK)
10576
/*
10577
 * This API accepts a user callback which puts key-log records into
10578
 * a KEY LOGFILE. The callback is stored into a CTX and propagated to
10579
 * each SSL object on its creation timing.
10580
 */
10581
void wolfSSL_CTX_set_keylog_callback(WOLFSSL_CTX* ctx,
10582
    wolfSSL_CTX_keylog_cb_func cb)
10583
{
10584
    WOLFSSL_ENTER("wolfSSL_CTX_set_keylog_callback");
10585
    /* stores the callback into WOLFSSL_CTX */
10586
    if (ctx != NULL) {
10587
        ctx->keyLogCb = cb;
10588
    }
10589
}
10590
wolfSSL_CTX_keylog_cb_func wolfSSL_CTX_get_keylog_callback(
10591
    const WOLFSSL_CTX* ctx)
10592
{
10593
    WOLFSSL_ENTER("wolfSSL_CTX_get_keylog_callback");
10594
    if (ctx != NULL)
10595
        return ctx->keyLogCb;
10596
    return NULL;
10597
}
10598
#endif /* OPENSSL_EXTRA && HAVE_SECRET_CALLBACK */
10599
10600
#endif /* OPENSSL_EXTRA */
10601
10602
#ifdef WOLFSSL_THREADED_CRYPT
10603
int wolfSSL_AsyncEncryptReady(WOLFSSL* ssl, int idx)
10604
{
10605
    ThreadCrypt* encrypt;
10606
10607
    if (ssl == NULL) {
10608
        return 0;
10609
    }
10610
10611
    encrypt = &ssl->buffers.encrypt[idx];
10612
    return (encrypt->avail == 0) && (encrypt->done == 0);
10613
}
10614
10615
int wolfSSL_AsyncEncryptStop(WOLFSSL* ssl, int idx)
10616
{
10617
    ThreadCrypt* encrypt;
10618
10619
    if (ssl == NULL) {
10620
        return 1;
10621
    }
10622
10623
    encrypt = &ssl->buffers.encrypt[idx];
10624
    return encrypt->stop;
10625
}
10626
10627
int wolfSSL_AsyncEncrypt(WOLFSSL* ssl, int idx)
10628
{
10629
    int ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN);
10630
    ThreadCrypt* encrypt = &ssl->buffers.encrypt[idx];
10631
10632
    if (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm) {
10633
        unsigned char* out = encrypt->buffer.buffer + encrypt->offset;
10634
        unsigned char* input = encrypt->buffer.buffer + encrypt->offset;
10635
        word32 encSz = encrypt->buffer.length - encrypt->offset;
10636
10637
        ret =
10638
#if !defined(NO_GCM_ENCRYPT_EXTRA) && \
10639
    ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \
10640
    (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)))
10641
              wc_AesGcmEncrypt_ex
10642
#else
10643
              wc_AesGcmEncrypt
10644
#endif
10645
              (encrypt->encrypt.aes,
10646
               out + AESGCM_EXP_IV_SZ, input + AESGCM_EXP_IV_SZ,
10647
               encSz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size,
10648
               encrypt->nonce, AESGCM_NONCE_SZ,
10649
               out + encSz - ssl->specs.aead_mac_size,
10650
               ssl->specs.aead_mac_size,
10651
               encrypt->additional, AEAD_AUTH_DATA_SZ);
10652
#if !defined(NO_PUBLIC_GCM_SET_IV) && \
10653
    ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \
10654
    (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)))
10655
        XMEMCPY(out, encrypt->nonce + AESGCM_IMP_IV_SZ, AESGCM_EXP_IV_SZ);
10656
#endif
10657
        encrypt->done = 1;
10658
    }
10659
10660
    return ret;
10661
}
10662
10663
int wolfSSL_AsyncEncryptSetSignal(WOLFSSL* ssl, int idx,
10664
    WOLFSSL_THREAD_SIGNAL signal, void* ctx)
10665
{
10666
    int ret = 0;
10667
10668
    if (ssl == NULL) {
10669
        ret = BAD_FUNC_ARG;
10670
    }
10671
    else {
10672
        ssl->buffers.encrypt[idx].signal = signal;
10673
        ssl->buffers.encrypt[idx].signalCtx = ctx;
10674
    }
10675
10676
    return ret;
10677
}
10678
#endif
10679
10680
10681
#ifndef NO_CERT
10682
#define WOLFSSL_X509_INCLUDED
10683
#include "src/x509.c"
10684
#endif
10685
10686
/*******************************************************************************
10687
 * START OF standard C library wrapping APIs
10688
 ******************************************************************************/
10689
#if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && \
10690
    (defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \
10691
     defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \
10692
     defined(WOLFSSL_OPENSSH)))
10693
#ifndef NO_WOLFSSL_STUB
10694
int wolfSSL_CRYPTO_set_mem_ex_functions(void *(*m) (size_t, const char *, int),
10695
                                void *(*r) (void *, size_t, const char *,
10696
                                            int), void (*f) (void *))
10697
{
10698
    (void) m;
10699
    (void) r;
10700
    (void) f;
10701
    WOLFSSL_ENTER("wolfSSL_CRYPTO_set_mem_ex_functions");
10702
    WOLFSSL_STUB("CRYPTO_set_mem_ex_functions");
10703
10704
    return WOLFSSL_FAILURE;
10705
}
10706
#endif
10707
#endif
10708
10709
#if defined(OPENSSL_EXTRA)
10710
10711
/**
10712
 * free allocated memory resource
10713
 * @param str  a pointer to resource to be freed
10714
 * @param file dummy argument
10715
 * @param line dummy argument
10716
 */
10717
void wolfSSL_CRYPTO_free(void *str, const char *file, int line)
10718
{
10719
    (void)file;
10720
    (void)line;
10721
    XFREE(str, 0, DYNAMIC_TYPE_TMP_BUFFER);
10722
}
10723
/**
10724
 * allocate memory with size of num
10725
 * @param num  size of memory allocation to be malloced
10726
 * @param file dummy argument
10727
 * @param line dummy argument
10728
 * @return a pointer to allocated memory on succssesful, otherwise NULL
10729
 */
10730
void *wolfSSL_CRYPTO_malloc(size_t num, const char *file, int line)
10731
{
10732
    (void)file;
10733
    (void)line;
10734
    return XMALLOC(num, 0, DYNAMIC_TYPE_TMP_BUFFER);
10735
}
10736
10737
#endif
10738
10739
/*******************************************************************************
10740
 * END OF standard C library wrapping APIs
10741
 ******************************************************************************/
10742
10743
/*******************************************************************************
10744
 * START OF EX_DATA APIs
10745
 ******************************************************************************/
10746
#ifdef HAVE_EX_DATA
10747
void wolfSSL_CRYPTO_cleanup_all_ex_data(void)
10748
{
10749
    WOLFSSL_ENTER("wolfSSL_CRYPTO_cleanup_all_ex_data");
10750
}
10751
10752
void* wolfSSL_CRYPTO_get_ex_data(const WOLFSSL_CRYPTO_EX_DATA* ex_data, int idx)
10753
{
10754
    WOLFSSL_ENTER("wolfSSL_CRYPTO_get_ex_data");
10755
#ifdef MAX_EX_DATA
10756
    if (ex_data && idx < MAX_EX_DATA && idx >= 0) {
10757
        return ex_data->ex_data[idx];
10758
    }
10759
#else
10760
    (void)ex_data;
10761
    (void)idx;
10762
#endif
10763
    return NULL;
10764
}
10765
10766
int wolfSSL_CRYPTO_set_ex_data(WOLFSSL_CRYPTO_EX_DATA* ex_data, int idx,
10767
    void *data)
10768
{
10769
    WOLFSSL_ENTER("wolfSSL_CRYPTO_set_ex_data");
10770
#ifdef MAX_EX_DATA
10771
    if (ex_data && idx < MAX_EX_DATA && idx >= 0) {
10772
#ifdef HAVE_EX_DATA_CLEANUP_HOOKS
10773
        if (ex_data->ex_data_cleanup_routines[idx]) {
10774
            /* call cleanup then remove cleanup callback,
10775
             * since different value is being set */
10776
            if (ex_data->ex_data[idx])
10777
                ex_data->ex_data_cleanup_routines[idx](ex_data->ex_data[idx]);
10778
            ex_data->ex_data_cleanup_routines[idx] = NULL;
10779
        }
10780
#endif
10781
        ex_data->ex_data[idx] = data;
10782
        return WOLFSSL_SUCCESS;
10783
    }
10784
#else
10785
    (void)ex_data;
10786
    (void)idx;
10787
    (void)data;
10788
#endif
10789
    return WOLFSSL_FAILURE;
10790
}
10791
10792
#ifdef HAVE_EX_DATA_CLEANUP_HOOKS
10793
int wolfSSL_CRYPTO_set_ex_data_with_cleanup(
10794
    WOLFSSL_CRYPTO_EX_DATA* ex_data,
10795
    int idx,
10796
    void *data,
10797
    wolfSSL_ex_data_cleanup_routine_t cleanup_routine)
10798
{
10799
    WOLFSSL_ENTER("wolfSSL_CRYPTO_set_ex_data_with_cleanup");
10800
    if (ex_data && idx < MAX_EX_DATA && idx >= 0) {
10801
        if (ex_data->ex_data_cleanup_routines[idx] && ex_data->ex_data[idx])
10802
            ex_data->ex_data_cleanup_routines[idx](ex_data->ex_data[idx]);
10803
        ex_data->ex_data[idx] = data;
10804
        ex_data->ex_data_cleanup_routines[idx] = cleanup_routine;
10805
        return WOLFSSL_SUCCESS;
10806
    }
10807
    return WOLFSSL_FAILURE;
10808
}
10809
#endif /* HAVE_EX_DATA_CLEANUP_HOOKS */
10810
#endif /* HAVE_EX_DATA */
10811
10812
#ifdef HAVE_EX_DATA_CRYPTO
10813
/**
10814
 * Issues unique index for the class specified by class_index.
10815
 * Other parameter except class_index are ignored.
10816
 * Currently, following class_index are accepted:
10817
 *  - WOLF_CRYPTO_EX_INDEX_SSL
10818
 *  - WOLF_CRYPTO_EX_INDEX_SSL_CTX
10819
 *  - WOLF_CRYPTO_EX_INDEX_X509
10820
 * @param class_index index one of CRYPTO_EX_INDEX_xxx
10821
 * @param argp  parameters to be saved
10822
 * @param argl  parameters to be saved
10823
 * @param new_func a pointer to WOLFSSL_CRYPTO_EX_new
10824
 * @param dup_func a pointer to WOLFSSL_CRYPTO_EX_dup
10825
 * @param free_func a pointer to WOLFSSL_CRYPTO_EX_free
10826
 * @return index value grater or equal to zero on success, -1 on failure.
10827
 */
10828
int wolfSSL_CRYPTO_get_ex_new_index(int class_index, long argl, void *argp,
10829
                                           WOLFSSL_CRYPTO_EX_new* new_func,
10830
                                           WOLFSSL_CRYPTO_EX_dup* dup_func,
10831
                                           WOLFSSL_CRYPTO_EX_free* free_func)
10832
{
10833
    WOLFSSL_ENTER("wolfSSL_CRYPTO_get_ex_new_index");
10834
10835
    return wolfssl_local_get_ex_new_index(class_index, argl, argp, new_func,
10836
            dup_func, free_func);
10837
}
10838
#endif /* HAVE_EX_DATA_CRYPTO */
10839
10840
/*******************************************************************************
10841
 * END OF EX_DATA APIs
10842
 ******************************************************************************/
10843
10844
/*******************************************************************************
10845
 * START OF BUF_MEM API
10846
 ******************************************************************************/
10847
10848
#if defined(OPENSSL_EXTRA)
10849
10850
/* Begin functions for openssl/buffer.h */
10851
WOLFSSL_BUF_MEM* wolfSSL_BUF_MEM_new(void)
10852
{
10853
    WOLFSSL_BUF_MEM* buf;
10854
    buf = (WOLFSSL_BUF_MEM*)XMALLOC(sizeof(WOLFSSL_BUF_MEM), NULL,
10855
                                                        DYNAMIC_TYPE_OPENSSL);
10856
    if (buf) {
10857
        XMEMSET(buf, 0, sizeof(WOLFSSL_BUF_MEM));
10858
    }
10859
    return buf;
10860
}
10861
10862
/* non-compat API returns length of buffer on success */
10863
int wolfSSL_BUF_MEM_grow_ex(WOLFSSL_BUF_MEM* buf, size_t len,
10864
        char zeroFill)
10865
{
10866
    size_t mx;
10867
    char* tmp;
10868
10869
    /* verify provided arguments. The return value is an int holding the
10870
     * resulting length, so reject any len that cannot be represented as a
10871
     * non-negative int. This also prevents truncating size_t to int. */
10872
    if (buf == NULL || len > (size_t)WC_MAX_SINT_OF(int)) {
10873
        return 0; /* BAD_FUNC_ARG; */
10874
    }
10875
10876
    /* check to see if fits in existing length */
10877
    if (buf->length > len) {
10878
        buf->length = len;
10879
        return (int)len;
10880
    }
10881
10882
    /* check to see if fits in max buffer */
10883
    if (buf->max >= len) {
10884
        if (buf->data != NULL && zeroFill) {
10885
            XMEMSET(&buf->data[buf->length], 0, len - buf->length);
10886
        }
10887
        buf->length = len;
10888
        return (int)len;
10889
    }
10890
10891
    /* expand size, to handle growth */
10892
    mx = (len + 3) / 3 * 4;
10893
10894
#ifdef WOLFSSL_NO_REALLOC
10895
    tmp = (char*)XMALLOC(mx, NULL, DYNAMIC_TYPE_OPENSSL);
10896
    if (tmp != NULL && buf->data != NULL) {
10897
       /* only the existing content is valid in the old buffer; copying
10898
        * len_int (the new, larger size) would read past buf->max */
10899
       XMEMCPY(tmp, buf->data, buf->length);
10900
       XFREE(buf->data, NULL, DYNAMIC_TYPE_OPENSSL);
10901
       buf->data = NULL;
10902
    }
10903
#else
10904
    /* use realloc */
10905
    tmp = (char*)XREALLOC(buf->data, mx, NULL, DYNAMIC_TYPE_OPENSSL);
10906
#endif
10907
10908
    if (tmp == NULL) {
10909
        return 0; /* ERR_R_MALLOC_FAILURE; */
10910
    }
10911
    buf->data = tmp;
10912
10913
    buf->max = mx;
10914
    if (zeroFill)
10915
        XMEMSET(&buf->data[buf->length], 0, len - buf->length);
10916
    buf->length = len;
10917
10918
    return (int)len;
10919
10920
}
10921
10922
/* returns length of buffer on success */
10923
int wolfSSL_BUF_MEM_grow(WOLFSSL_BUF_MEM* buf, size_t len)
10924
{
10925
    return wolfSSL_BUF_MEM_grow_ex(buf, len, 1);
10926
}
10927
10928
/* non-compat API returns length of buffer on success */
10929
int wolfSSL_BUF_MEM_resize(WOLFSSL_BUF_MEM* buf, size_t len)
10930
{
10931
    char* tmp;
10932
    size_t mx;
10933
10934
    /* verify provided arguments. The return value is an int, so reject any
10935
     * len that cannot be represented as a positive int. */
10936
    if (buf == NULL || len == 0 || len > (size_t)WC_MAX_SINT_OF(int)) {
10937
        return 0; /* BAD_FUNC_ARG; */
10938
    }
10939
10940
    if (len == buf->length)
10941
        return (int)len;
10942
10943
    if (len > buf->length)
10944
        return wolfSSL_BUF_MEM_grow_ex(buf, len, 0);
10945
10946
    /* expand size, to handle growth */
10947
    mx = (len + 3) / 3 * 4;
10948
10949
    /* We want to shrink the internal buffer */
10950
#ifdef WOLFSSL_NO_REALLOC
10951
    tmp = (char*)XMALLOC(mx, NULL, DYNAMIC_TYPE_OPENSSL);
10952
    if (tmp != NULL && buf->data != NULL)
10953
    {
10954
        XMEMCPY(tmp, buf->data, len);
10955
        XFREE(buf->data,NULL,DYNAMIC_TYPE_OPENSSL);
10956
        buf->data = NULL;
10957
    }
10958
#else
10959
    tmp = (char*)XREALLOC(buf->data, mx, NULL, DYNAMIC_TYPE_OPENSSL);
10960
#endif
10961
10962
    if (tmp == NULL)
10963
        return 0;
10964
10965
    buf->data = tmp;
10966
    buf->length = len;
10967
    buf->max = mx;
10968
10969
    return (int)len;
10970
}
10971
10972
void wolfSSL_BUF_MEM_free(WOLFSSL_BUF_MEM* buf)
10973
{
10974
    if (buf) {
10975
        XFREE(buf->data, NULL, DYNAMIC_TYPE_OPENSSL);
10976
        buf->data = NULL;
10977
        buf->max = 0;
10978
        buf->length = 0;
10979
        XFREE(buf, NULL, DYNAMIC_TYPE_OPENSSL);
10980
    }
10981
}
10982
/* End Functions for openssl/buffer.h */
10983
10984
#endif /* OPENSSL_EXTRA */
10985
10986
/*******************************************************************************
10987
 * END OF BUF_MEM API
10988
 ******************************************************************************/
10989
10990
#define WOLFSSL_CONF_INCLUDED
10991
#include <src/conf.c>
10992
10993
/*******************************************************************************
10994
 * START OF EVP_CIPHER API
10995
 ******************************************************************************/
10996
10997
#ifdef OPENSSL_EXTRA
10998
10999
    /* store for external read of iv, WOLFSSL_SUCCESS on success */
11000
    int  wolfSSL_StoreExternalIV(WOLFSSL_EVP_CIPHER_CTX* ctx)
11001
    {
11002
        WOLFSSL_ENTER("wolfSSL_StoreExternalIV");
11003
11004
        if (ctx == NULL) {
11005
            WOLFSSL_MSG("Bad function argument");
11006
            return WOLFSSL_FATAL_ERROR;
11007
        }
11008
11009
        switch (ctx->cipherType) {
11010
#ifndef NO_AES
11011
#if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT)
11012
            case WC_AES_128_CBC_TYPE :
11013
            case WC_AES_192_CBC_TYPE :
11014
            case WC_AES_256_CBC_TYPE :
11015
                WOLFSSL_MSG("AES CBC");
11016
                XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, ctx->ivSz);
11017
                break;
11018
#endif
11019
#ifdef HAVE_AESGCM
11020
            case WC_AES_128_GCM_TYPE :
11021
            case WC_AES_192_GCM_TYPE :
11022
            case WC_AES_256_GCM_TYPE :
11023
                WOLFSSL_MSG("AES GCM");
11024
                XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, ctx->ivSz);
11025
                break;
11026
#endif /* HAVE_AESGCM */
11027
#ifdef HAVE_AESCCM
11028
            case WC_AES_128_CCM_TYPE :
11029
            case WC_AES_192_CCM_TYPE :
11030
            case WC_AES_256_CCM_TYPE :
11031
                WOLFSSL_MSG("AES CCM");
11032
                XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, ctx->ivSz);
11033
                break;
11034
#endif /* HAVE_AESCCM */
11035
#ifdef HAVE_AES_ECB
11036
            case WC_AES_128_ECB_TYPE :
11037
            case WC_AES_192_ECB_TYPE :
11038
            case WC_AES_256_ECB_TYPE :
11039
                WOLFSSL_MSG("AES ECB");
11040
                break;
11041
#endif
11042
#ifdef WOLFSSL_AES_COUNTER
11043
            case WC_AES_128_CTR_TYPE :
11044
            case WC_AES_192_CTR_TYPE :
11045
            case WC_AES_256_CTR_TYPE :
11046
                WOLFSSL_MSG("AES CTR");
11047
                XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, WC_AES_BLOCK_SIZE);
11048
                break;
11049
#endif /* WOLFSSL_AES_COUNTER */
11050
#ifdef WOLFSSL_AES_CFB
11051
#if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS)
11052
            case WC_AES_128_CFB1_TYPE:
11053
            case WC_AES_192_CFB1_TYPE:
11054
            case WC_AES_256_CFB1_TYPE:
11055
                WOLFSSL_MSG("AES CFB1");
11056
                break;
11057
            case WC_AES_128_CFB8_TYPE:
11058
            case WC_AES_192_CFB8_TYPE:
11059
            case WC_AES_256_CFB8_TYPE:
11060
                WOLFSSL_MSG("AES CFB8");
11061
                break;
11062
#endif /* !HAVE_SELFTEST && !HAVE_FIPS */
11063
            case WC_AES_128_CFB128_TYPE:
11064
            case WC_AES_192_CFB128_TYPE:
11065
            case WC_AES_256_CFB128_TYPE:
11066
                WOLFSSL_MSG("AES CFB128");
11067
                break;
11068
#endif /* WOLFSSL_AES_CFB */
11069
#if defined(WOLFSSL_AES_OFB)
11070
            case WC_AES_128_OFB_TYPE:
11071
            case WC_AES_192_OFB_TYPE:
11072
            case WC_AES_256_OFB_TYPE:
11073
                WOLFSSL_MSG("AES OFB");
11074
                break;
11075
#endif /* WOLFSSL_AES_OFB */
11076
#ifdef WOLFSSL_AES_XTS
11077
            case WC_AES_128_XTS_TYPE:
11078
            case WC_AES_256_XTS_TYPE:
11079
                WOLFSSL_MSG("AES XTS");
11080
                break;
11081
#endif /* WOLFSSL_AES_XTS */
11082
#endif /* NO_AES */
11083
11084
#ifdef HAVE_ARIA
11085
            case WC_ARIA_128_GCM_TYPE :
11086
            case WC_ARIA_192_GCM_TYPE :
11087
            case WC_ARIA_256_GCM_TYPE :
11088
                WOLFSSL_MSG("ARIA GCM");
11089
                XMEMCPY(ctx->iv, &ctx->cipher.aria.nonce, ARIA_BLOCK_SIZE);
11090
                break;
11091
#endif /* HAVE_ARIA */
11092
11093
#ifndef NO_DES3
11094
            case WC_DES_CBC_TYPE :
11095
                WOLFSSL_MSG("DES CBC");
11096
                XMEMCPY(ctx->iv, &ctx->cipher.des.reg, DES_BLOCK_SIZE);
11097
                break;
11098
11099
            case WC_DES_EDE3_CBC_TYPE :
11100
                WOLFSSL_MSG("DES EDE3 CBC");
11101
                XMEMCPY(ctx->iv, &ctx->cipher.des3.reg, DES_BLOCK_SIZE);
11102
                break;
11103
#endif
11104
#ifdef WOLFSSL_DES_ECB
11105
            case WC_DES_ECB_TYPE :
11106
                WOLFSSL_MSG("DES ECB");
11107
                break;
11108
            case WC_DES_EDE3_ECB_TYPE :
11109
                WOLFSSL_MSG("DES3 ECB");
11110
                break;
11111
#endif
11112
            case WC_ARC4_TYPE :
11113
                WOLFSSL_MSG("ARC4");
11114
                break;
11115
11116
#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
11117
            case WC_CHACHA20_POLY1305_TYPE:
11118
                break;
11119
#endif
11120
11121
#ifdef HAVE_CHACHA
11122
            case WC_CHACHA20_TYPE:
11123
                break;
11124
#endif
11125
11126
#ifdef WOLFSSL_SM4_ECB
11127
            case WC_SM4_ECB_TYPE:
11128
                break;
11129
#endif
11130
#ifdef WOLFSSL_SM4_CBC
11131
            case WC_SM4_CBC_TYPE:
11132
                WOLFSSL_MSG("SM4 CBC");
11133
                XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE);
11134
                break;
11135
#endif
11136
#ifdef WOLFSSL_SM4_CTR
11137
            case WC_SM4_CTR_TYPE:
11138
                WOLFSSL_MSG("SM4 CTR");
11139
                XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE);
11140
                break;
11141
#endif
11142
#ifdef WOLFSSL_SM4_GCM
11143
            case WC_SM4_GCM_TYPE:
11144
                WOLFSSL_MSG("SM4 GCM");
11145
                XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE);
11146
                break;
11147
#endif
11148
#ifdef WOLFSSL_SM4_CCM
11149
            case WC_SM4_CCM_TYPE:
11150
                WOLFSSL_MSG("SM4 CCM");
11151
                XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE);
11152
                break;
11153
#endif
11154
11155
            case WC_NULL_CIPHER_TYPE :
11156
                WOLFSSL_MSG("NULL");
11157
                break;
11158
11159
            default: {
11160
                WOLFSSL_MSG("bad type");
11161
                return WOLFSSL_FATAL_ERROR;
11162
            }
11163
        }
11164
        return WOLFSSL_SUCCESS;
11165
    }
11166
11167
    /* set internal IV from external, WOLFSSL_SUCCESS on success */
11168
    int  wolfSSL_SetInternalIV(WOLFSSL_EVP_CIPHER_CTX* ctx)
11169
    {
11170
11171
        WOLFSSL_ENTER("wolfSSL_SetInternalIV");
11172
11173
        if (ctx == NULL) {
11174
            WOLFSSL_MSG("Bad function argument");
11175
            return WOLFSSL_FATAL_ERROR;
11176
        }
11177
11178
        switch (ctx->cipherType) {
11179
11180
#ifndef NO_AES
11181
#if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT)
11182
            case WC_AES_128_CBC_TYPE :
11183
            case WC_AES_192_CBC_TYPE :
11184
            case WC_AES_256_CBC_TYPE :
11185
                WOLFSSL_MSG("AES CBC");
11186
                XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, WC_AES_BLOCK_SIZE);
11187
                break;
11188
#endif
11189
#ifdef HAVE_AESGCM
11190
            case WC_AES_128_GCM_TYPE :
11191
            case WC_AES_192_GCM_TYPE :
11192
            case WC_AES_256_GCM_TYPE :
11193
                WOLFSSL_MSG("AES GCM");
11194
                XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, WC_AES_BLOCK_SIZE);
11195
                break;
11196
#endif
11197
#ifdef HAVE_AES_ECB
11198
            case WC_AES_128_ECB_TYPE :
11199
            case WC_AES_192_ECB_TYPE :
11200
            case WC_AES_256_ECB_TYPE :
11201
                WOLFSSL_MSG("AES ECB");
11202
                break;
11203
#endif
11204
#ifdef WOLFSSL_AES_COUNTER
11205
            case WC_AES_128_CTR_TYPE :
11206
            case WC_AES_192_CTR_TYPE :
11207
            case WC_AES_256_CTR_TYPE :
11208
                WOLFSSL_MSG("AES CTR");
11209
                XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, WC_AES_BLOCK_SIZE);
11210
                break;
11211
#endif
11212
11213
#endif /* NO_AES */
11214
11215
#ifdef HAVE_ARIA
11216
            case WC_ARIA_128_GCM_TYPE :
11217
            case WC_ARIA_192_GCM_TYPE :
11218
            case WC_ARIA_256_GCM_TYPE :
11219
                WOLFSSL_MSG("ARIA GCM");
11220
                XMEMCPY(&ctx->cipher.aria.nonce, ctx->iv, ARIA_BLOCK_SIZE);
11221
                break;
11222
#endif /* HAVE_ARIA */
11223
11224
#ifndef NO_DES3
11225
            case WC_DES_CBC_TYPE :
11226
                WOLFSSL_MSG("DES CBC");
11227
                XMEMCPY(&ctx->cipher.des.reg, ctx->iv, DES_BLOCK_SIZE);
11228
                break;
11229
11230
            case WC_DES_EDE3_CBC_TYPE :
11231
                WOLFSSL_MSG("DES EDE3 CBC");
11232
                XMEMCPY(&ctx->cipher.des3.reg, ctx->iv, DES_BLOCK_SIZE);
11233
                break;
11234
#endif
11235
#ifdef WOLFSSL_DES_ECB
11236
            case WC_DES_ECB_TYPE :
11237
                WOLFSSL_MSG("DES ECB");
11238
                break;
11239
            case WC_DES_EDE3_ECB_TYPE :
11240
                WOLFSSL_MSG("DES3 ECB");
11241
                break;
11242
#endif
11243
11244
            case WC_ARC4_TYPE :
11245
                WOLFSSL_MSG("ARC4");
11246
                break;
11247
11248
#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
11249
            case WC_CHACHA20_POLY1305_TYPE:
11250
                break;
11251
#endif
11252
11253
#ifdef HAVE_CHACHA
11254
            case WC_CHACHA20_TYPE:
11255
                break;
11256
#endif
11257
11258
#ifdef WOLFSSL_SM4_ECB
11259
            case WC_SM4_ECB_TYPE:
11260
                break;
11261
#endif
11262
#ifdef WOLFSSL_SM4_CBC
11263
            case WC_SM4_CBC_TYPE:
11264
                WOLFSSL_MSG("SM4 CBC");
11265
                XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz);
11266
                break;
11267
#endif
11268
#ifdef WOLFSSL_SM4_CTR
11269
            case WC_SM4_CTR_TYPE:
11270
                WOLFSSL_MSG("SM4 CTR");
11271
                XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz);
11272
                break;
11273
#endif
11274
#ifdef WOLFSSL_SM4_GCM
11275
            case WC_SM4_GCM_TYPE:
11276
                WOLFSSL_MSG("SM4 GCM");
11277
                XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz);
11278
                break;
11279
#endif
11280
#ifdef WOLFSSL_SM4_CCM
11281
            case WC_SM4_CCM_TYPE:
11282
                WOLFSSL_MSG("SM4 CCM");
11283
                XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz);
11284
                break;
11285
#endif
11286
11287
            case WC_NULL_CIPHER_TYPE :
11288
                WOLFSSL_MSG("NULL");
11289
                break;
11290
11291
            default: {
11292
                WOLFSSL_MSG("bad type");
11293
                return WOLFSSL_FATAL_ERROR;
11294
            }
11295
        }
11296
        return WOLFSSL_SUCCESS;
11297
    }
11298
11299
#ifndef NO_DES3
11300
11301
void wolfSSL_3des_iv(WOLFSSL_EVP_CIPHER_CTX* ctx, int doset,
11302
                            unsigned char* iv, int len)
11303
{
11304
    (void)len;
11305
11306
    WOLFSSL_MSG("wolfSSL_3des_iv");
11307
11308
    if (ctx == NULL || iv == NULL) {
11309
        WOLFSSL_MSG("Bad function argument");
11310
        return;
11311
    }
11312
11313
    if (doset)
11314
        wc_Des3_SetIV(&ctx->cipher.des3, iv);  /* OpenSSL compat, no ret */
11315
    else
11316
        XMEMCPY(iv, &ctx->cipher.des3.reg, DES_BLOCK_SIZE);
11317
}
11318
11319
#endif /* NO_DES3 */
11320
11321
11322
#ifndef NO_AES
11323
11324
void wolfSSL_aes_ctr_iv(WOLFSSL_EVP_CIPHER_CTX* ctx, int doset,
11325
                      unsigned char* iv, int len)
11326
{
11327
    (void)len;
11328
11329
    WOLFSSL_MSG("wolfSSL_aes_ctr_iv");
11330
11331
    if (ctx == NULL || iv == NULL) {
11332
        WOLFSSL_MSG("Bad function argument");
11333
        return;
11334
    }
11335
11336
    if (doset)
11337
       (void)wc_AesSetIV(&ctx->cipher.aes, iv);  /* OpenSSL compat, no ret */
11338
    else
11339
        XMEMCPY(iv, &ctx->cipher.aes.reg, WC_AES_BLOCK_SIZE);
11340
}
11341
11342
#endif /* NO_AES */
11343
11344
#endif /* OPENSSL_EXTRA */
11345
11346
/*******************************************************************************
11347
 * END OF EVP_CIPHER API
11348
 ******************************************************************************/
11349
11350
#ifndef NO_CERTS
11351
11352
#define WOLFSSL_X509_STORE_INCLUDED
11353
#include <src/x509_str.c>
11354
11355
#define WOLFSSL_SSL_P7P12_INCLUDED
11356
#include <src/ssl_p7p12.c>
11357
11358
#endif /* !NO_CERTS */
11359
11360
11361
/*******************************************************************************
11362
 * BEGIN OPENSSL FIPS DRBG APIs
11363
 ******************************************************************************/
11364
#if defined(OPENSSL_EXTRA) && !defined(WC_NO_RNG) && defined(HAVE_HASHDRBG)
11365
int wolfSSL_FIPS_drbg_init(WOLFSSL_DRBG_CTX *ctx, int type, unsigned int flags)
11366
{
11367
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
11368
    if (ctx != NULL) {
11369
        XMEMSET(ctx, 0, sizeof(WOLFSSL_DRBG_CTX));
11370
        ctx->type = type;
11371
        ctx->xflags = (int)flags;
11372
        ctx->status = DRBG_STATUS_UNINITIALISED;
11373
        ret = WOLFSSL_SUCCESS;
11374
    }
11375
    return ret;
11376
}
11377
WOLFSSL_DRBG_CTX* wolfSSL_FIPS_drbg_new(int type, unsigned int flags)
11378
{
11379
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
11380
    WOLFSSL_DRBG_CTX* ctx = (WOLFSSL_DRBG_CTX*)XMALLOC(sizeof(WOLFSSL_DRBG_CTX),
11381
        NULL, DYNAMIC_TYPE_OPENSSL);
11382
    ret = wolfSSL_FIPS_drbg_init(ctx, type, flags);
11383
    if (ret == WOLFSSL_SUCCESS && type != 0) {
11384
        ret = wolfSSL_FIPS_drbg_instantiate(ctx, NULL, 0);
11385
    }
11386
    if (ret != WOLFSSL_SUCCESS) {
11387
        WOLFSSL_ERROR(ret);
11388
        wolfSSL_FIPS_drbg_free(ctx);
11389
        ctx = NULL;
11390
    }
11391
    return ctx;
11392
}
11393
int wolfSSL_FIPS_drbg_instantiate(WOLFSSL_DRBG_CTX* ctx,
11394
    const unsigned char* pers, size_t perslen)
11395
{
11396
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
11397
    if (ctx != NULL && ctx->rng == NULL) {
11398
    #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
11399
        (defined(HAVE_FIPS) && FIPS_VERSION_GE(5,0)))
11400
        ctx->rng = wc_rng_new((byte*)pers, (word32)perslen, NULL);
11401
    #else
11402
        ctx->rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
11403
        if (ctx->rng != NULL) {
11404
        #if defined(HAVE_FIPS) && FIPS_VERSION_GE(2,0)
11405
            ret = wc_InitRngNonce(ctx->rng, (byte*)pers, (word32)perslen);
11406
        #else
11407
            ret = wc_InitRng(ctx->rng);
11408
            (void)pers;
11409
            (void)perslen;
11410
        #endif
11411
            if (ret != 0) {
11412
                WOLFSSL_ERROR(ret);
11413
                XFREE(ctx->rng, NULL, DYNAMIC_TYPE_RNG);
11414
                ctx->rng = NULL;
11415
            }
11416
        }
11417
    #endif
11418
    }
11419
    if (ctx != NULL && ctx->rng != NULL) {
11420
        ctx->status = DRBG_STATUS_READY;
11421
        ret = WOLFSSL_SUCCESS;
11422
    }
11423
    return ret;
11424
}
11425
int wolfSSL_FIPS_drbg_set_callbacks(WOLFSSL_DRBG_CTX* ctx,
11426
    drbg_entropy_get entropy_get, drbg_entropy_clean entropy_clean,
11427
    size_t entropy_blocklen,
11428
    drbg_nonce_get none_get, drbg_nonce_clean nonce_clean)
11429
{
11430
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
11431
    if (ctx != NULL) {
11432
        ctx->entropy_get = entropy_get;
11433
        ctx->entropy_clean = entropy_clean;
11434
        ctx->entropy_blocklen = entropy_blocklen;
11435
        ctx->none_get = none_get;
11436
        ctx->nonce_clean = nonce_clean;
11437
        ret = WOLFSSL_SUCCESS;
11438
    }
11439
    return ret;
11440
}
11441
void wolfSSL_FIPS_rand_add(const void* buf, int num, double entropy)
11442
{
11443
    /* not implemented */
11444
    (void)buf;
11445
    (void)num;
11446
    (void)entropy;
11447
}
11448
int wolfSSL_FIPS_drbg_reseed(WOLFSSL_DRBG_CTX* ctx, const unsigned char* adin,
11449
    size_t adinlen)
11450
{
11451
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
11452
    if (ctx != NULL && ctx->rng != NULL) {
11453
    #ifdef WC_RNG_HAVE_RESEED_NOW
11454
        /* OpenSSL FIPS_drbg_reseed semantics: reseed from the module's
11455
         * source with adin as additional input.  (A credited user-class
11456
         * reseed of a conformant instance is refused with
11457
         * WC_RNG_RBGC_STRATUM_IMMUTABLE.) */
11458
        if (wc_RNG_DRBG_Reseed_Now(ctx->rng, adin, (word32)adinlen) == 0) {
11459
            ret = WOLFSSL_SUCCESS;
11460
        }
11461
    #elif !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
11462
          (defined(HAVE_FIPS) && FIPS_VERSION_GE(2,0)))
11463
        if (wc_RNG_DRBG_Reseed(ctx->rng, adin, (word32)adinlen) == 0) {
11464
            ret = WOLFSSL_SUCCESS;
11465
        }
11466
    #else
11467
        ret = WOLFSSL_SUCCESS;
11468
        (void)adin;
11469
        (void)adinlen;
11470
    #endif
11471
    }
11472
    return ret;
11473
}
11474
int wolfSSL_FIPS_drbg_generate(WOLFSSL_DRBG_CTX* ctx, unsigned char* out,
11475
    size_t outlen, int prediction_resistance, const unsigned char* adin,
11476
    size_t adinlen)
11477
{
11478
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
11479
    if (ctx != NULL && ctx->rng != NULL &&
11480
            outlen <= (size_t)WC_MAX_UINT_OF(word32)) {
11481
        ret = wc_RNG_GenerateBlock(ctx->rng, out, (word32)outlen);
11482
        if (ret == 0) {
11483
            ret = WOLFSSL_SUCCESS;
11484
        }
11485
    }
11486
    (void)prediction_resistance;
11487
    (void)adin;
11488
    (void)adinlen;
11489
    return ret;
11490
}
11491
int wolfSSL_FIPS_drbg_uninstantiate(WOLFSSL_DRBG_CTX *ctx)
11492
{
11493
    if (ctx != NULL && ctx->rng != NULL) {
11494
    #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
11495
        (defined(HAVE_FIPS) && FIPS_VERSION_GE(5,0)))
11496
        wc_rng_free(ctx->rng);
11497
    #else
11498
        wc_FreeRng(ctx->rng);
11499
        XFREE(ctx->rng, NULL, DYNAMIC_TYPE_RNG);
11500
    #endif
11501
        ctx->rng = NULL;
11502
        ctx->status = DRBG_STATUS_UNINITIALISED;
11503
    }
11504
    return WOLFSSL_SUCCESS;
11505
}
11506
void wolfSSL_FIPS_drbg_free(WOLFSSL_DRBG_CTX *ctx)
11507
{
11508
    if (ctx != NULL) {
11509
        int locked = 0;
11510
        int haveMutex = 1;
11511
        /* As safety check if free'ing the default drbg, then mark global NULL.
11512
         * Technically the user should not call free on the default drbg. */
11513
    #ifndef WOLFSSL_MUTEX_INITIALIZER
11514
        /* wolfSSL_Cleanup may free the mutex before this runs. */
11515
        haveMutex = (globalRNGMutex_valid == 1);
11516
    #endif
11517
        if (haveMutex && (wc_LockMutex(&globalRNGMutex) == 0))
11518
            locked = 1;
11519
        /* Touch the global under the lock, or unlocked only when no mutex. */
11520
        if (locked || !haveMutex) {
11521
            if (ctx == gDrbgDefCtx) {
11522
                gDrbgDefCtx = NULL;
11523
            }
11524
        }
11525
        if (locked)
11526
            wc_UnLockMutex(&globalRNGMutex);
11527
        wolfSSL_FIPS_drbg_uninstantiate(ctx);
11528
        XFREE(ctx, NULL, DYNAMIC_TYPE_OPENSSL);
11529
    }
11530
}
11531
WOLFSSL_DRBG_CTX* wolfSSL_FIPS_get_default_drbg(void)
11532
{
11533
    int locked = 0;
11534
    int haveMutex = 1;
11535
#ifndef WOLFSSL_MUTEX_INITIALIZER
11536
    haveMutex = (globalRNGMutex_valid == 1);
11537
#endif
11538
    if (haveMutex && (wc_LockMutex(&globalRNGMutex) == 0))
11539
        locked = 1;
11540
    if (locked || !haveMutex) {
11541
        if (gDrbgDefCtx == NULL) {
11542
            gDrbgDefCtx = wolfSSL_FIPS_drbg_new(0, 0);
11543
        }
11544
    }
11545
    if (locked)
11546
        wc_UnLockMutex(&globalRNGMutex);
11547
    return gDrbgDefCtx;
11548
}
11549
void wolfSSL_FIPS_get_timevec(unsigned char* buf, unsigned long* pctr)
11550
{
11551
    /* not implemented */
11552
    (void)buf;
11553
    (void)pctr;
11554
}
11555
void* wolfSSL_FIPS_drbg_get_app_data(WOLFSSL_DRBG_CTX *ctx)
11556
{
11557
    if (ctx != NULL) {
11558
        return ctx->app_data;
11559
    }
11560
    return NULL;
11561
}
11562
void wolfSSL_FIPS_drbg_set_app_data(WOLFSSL_DRBG_CTX *ctx, void *app_data)
11563
{
11564
    if (ctx != NULL) {
11565
        ctx->app_data = app_data;
11566
    }
11567
}
11568
#endif
11569
/*******************************************************************************
11570
 * END OF OPENSSL FIPS DRBG APIs
11571
 ******************************************************************************/
11572
11573
11574
#endif /* !WOLFCRYPT_ONLY */