Coverage Report

Created: 2026-08-15 06:21

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