Coverage Report

Created: 2026-11-12 06:59

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