Coverage Report

Created: 2026-09-04 06:30

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/wolfssl/src/ssl.c
Line
Count
Source
1
/* ssl.c
2
 *
3
 * Copyright (C) 2006-2026 wolfSSL Inc.
4
 *
5
 * This file is part of wolfSSL.
6
 *
7
 * wolfSSL is free software; you can redistribute it and/or modify
8
 * it under the terms of the GNU General Public License as published by
9
 * the Free Software Foundation; either version 3 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * wolfSSL is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License
18
 * along with this program; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
20
 */
21
22
#include <wolfssl/wolfcrypt/libwolfssl_sources.h>
23
24
#if defined(OPENSSL_EXTRA) && !defined(_WIN32) && !defined(_GNU_SOURCE)
25
    /* turn on GNU extensions for XISASCII */
26
    #define _GNU_SOURCE 1
27
#endif
28
29
#if !defined(WOLFCRYPT_ONLY) || defined(OPENSSL_EXTRA) || \
30
    defined(OPENSSL_EXTRA_X509_SMALL)
31
32
#include <wolfssl/internal.h>
33
#include <wolfssl/error-ssl.h>
34
#include <wolfssl/wolfcrypt/error-crypt.h>
35
#include <wolfssl/wolfcrypt/coding.h>
36
#include <wolfssl/wolfcrypt/kdf.h>
37
#ifdef NO_INLINE
38
    #include <wolfssl/wolfcrypt/misc.h>
39
#else
40
    #define WOLFSSL_MISC_INCLUDED
41
    #include <wolfcrypt/src/misc.c>
42
#endif
43
44
#ifdef HAVE_ERRNO_H
45
    #include <errno.h>
46
#endif
47
48
49
#if !defined(WOLFSSL_ALLOW_NO_SUITES) && !defined(WOLFCRYPT_ONLY)
50
    #if defined(NO_DH) && !defined(HAVE_ECC) && !defined(WOLFSSL_STATIC_RSA) \
51
                && !defined(WOLFSSL_STATIC_DH) && !defined(WOLFSSL_STATIC_PSK) \
52
                && !defined(HAVE_CURVE25519) && !defined(HAVE_CURVE448) \
53
                && (!defined(WOLFSSL_TLS13) \
54
                    || !defined(WOLFSSL_HAVE_MLKEM_CLIENT_SUPPORT) \
55
                    || defined(WOLFSSL_TLS_NO_MLKEM_STANDALONE))
56
        #error "No cipher suites defined because DH disabled, ECC disabled, " \
57
               "and no static suites defined. Please see top of README"
58
    #endif
59
    #ifdef WOLFSSL_CERT_GEN
60
        /* need access to Cert struct for creating certificate */
61
        #include <wolfssl/wolfcrypt/asn_public.h>
62
    #endif
63
#endif
64
65
#if !defined(WOLFCRYPT_ONLY) && (defined(OPENSSL_EXTRA)     \
66
    || defined(OPENSSL_EXTRA_X509_SMALL)                    \
67
    || defined(HAVE_WEBSERVER) || defined(WOLFSSL_KEY_GEN))
68
    #include <wolfssl/openssl/evp.h>
69
    /* 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
0
{
302
0
    WC_RNG* ret = NULL;
303
304
0
    if (initGlobalRNG == 0)
305
0
        WOLFSSL_MSG("Global RNG no Init");
306
0
    else
307
0
        ret = &globalRNG;
308
309
0
    return ret;
310
0
}
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
0
{
354
0
    WC_RNG* ret = NULL;
355
#ifdef WOLFSSL_SMALL_STACK
356
    int freeRng = 0;
357
358
    /* Allocate RNG object . */
359
    if (rng == NULL) {
360
        rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
361
        freeRng = 1;
362
    }
363
#endif
364
365
0
    if (rng != NULL) {
366
0
        if (wc_InitRng(rng) == 0) {
367
0
            ret = rng;
368
0
            *local = 1;
369
0
        }
370
0
        else {
371
0
            WOLFSSL_MSG("Bad RNG Init");
372
#ifdef WOLFSSL_SMALL_STACK
373
            if (freeRng) {
374
                XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
375
                rng = NULL;
376
            }
377
#endif
378
0
        }
379
0
    }
380
0
    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
0
    return ret;
388
0
}
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
0
{
544
0
    WOLFSSL_CTX* ctx = NULL;
545
546
0
    WOLFSSL_ENTER("wolfSSL_CTX_new_ex");
547
548
0
    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
0
#ifndef NO_TLS
560
0
    if (method == NULL)
561
0
        return ctx;
562
#else
563
    /* a blank TLS method */
564
    method = (WOLFSSL_METHOD*)&gNoTlsMethod;
565
#endif
566
567
0
    ctx = (WOLFSSL_CTX*)XMALLOC(sizeof(WOLFSSL_CTX), heap, DYNAMIC_TYPE_CTX);
568
0
    if (ctx) {
569
0
        int ret;
570
571
0
        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
0
        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
0
    }
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
0
    WOLFSSL_LEAVE("wolfSSL_CTX_new_ex", 0);
643
0
    return ctx;
644
0
}
645
646
647
WOLFSSL_ABI
648
WOLFSSL_CTX* wolfSSL_CTX_new(WOLFSSL_METHOD* method)
649
0
{
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
0
    return wolfSSL_CTX_new_ex(method, NULL);
655
0
#endif
656
0
}
657
658
/* increases CTX reference count to track proper time to "free" */
659
int wolfSSL_CTX_up_ref(WOLFSSL_CTX* ctx)
660
0
{
661
0
    int ret;
662
0
    wolfSSL_RefWithMutexInc(&ctx->ref, &ret);
663
#ifdef WOLFSSL_REFCNT_ERROR_RETURN
664
    return ((ret == 0) ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE);
665
#else
666
0
    (void)ret;
667
0
    return WOLFSSL_SUCCESS;
668
0
#endif
669
0
}
670
671
WOLFSSL_ABI
672
void wolfSSL_CTX_free(WOLFSSL_CTX* ctx)
673
0
{
674
0
    WOLFSSL_ENTER("wolfSSL_CTX_free");
675
0
    if (ctx) {
676
0
        FreeSSL_Ctx(ctx);
677
0
    }
678
679
0
    WOLFSSL_LEAVE("wolfSSL_CTX_free", 0);
680
0
}
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
0
{
749
0
    WOLFSSL* ssl = NULL;
750
0
    int ret = 0;
751
752
0
    WOLFSSL_ENTER("wolfSSL_new");
753
754
0
    if (ctx == NULL) {
755
0
        WOLFSSL_MSG("wolfSSL_new ctx is null");
756
0
        return NULL;
757
0
    }
758
759
0
    ssl = (WOLFSSL*) XMALLOC(sizeof(WOLFSSL), ctx->heap, DYNAMIC_TYPE_SSL);
760
761
0
    if (ssl == NULL) {
762
0
        WOLFSSL_MSG_EX("ssl xmalloc failed to allocate %d bytes",
763
0
                        (int)sizeof(WOLFSSL));
764
0
    }
765
0
    else {
766
0
        ret = InitSSL(ssl, ctx, 0);
767
0
        if (ret < 0) {
768
0
            WOLFSSL_MSG_EX("wolfSSL_new failed during InitSSL. err = %d", ret);
769
0
            FreeSSL(ssl, ctx->heap);
770
0
            ssl = NULL;
771
0
        }
772
0
        else if (ret == 0) {
773
0
            WOLFSSL_MSG("wolfSSL_new InitSSL success");
774
0
        }
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
0
    } /* ssl XMALLOC success */
781
782
0
    WOLFSSL_LEAVE("wolfSSL_new InitSSL =", ret);
783
0
    (void)ret;
784
785
0
    return ssl;
786
0
}
787
788
789
WOLFSSL_ABI
790
void wolfSSL_free(WOLFSSL* ssl)
791
0
{
792
0
    WOLFSSL_ENTER("wolfSSL_free");
793
794
0
    if (ssl) {
795
0
        WOLFSSL_MSG_EX("Free SSL: %p", (wc_ptr_t)ssl);
796
0
        FreeSSL(ssl, ssl->ctx->heap);
797
0
    }
798
0
    else {
799
0
        WOLFSSL_MSG("Free SSL: wolfSSL_free already null");
800
0
    }
801
0
    WOLFSSL_LEAVE("wolfSSL_free", 0);
802
0
}
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
0
{
1626
0
    int devId = INVALID_DEVID;
1627
0
    if (ssl != NULL)
1628
0
        devId = ssl->devId;
1629
0
    if (ctx != NULL && devId == INVALID_DEVID)
1630
0
        devId = ctx->devId;
1631
0
    return devId;
1632
0
}
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
0
{
1785
0
#ifndef WOLFSSL_AEAD_ONLY
1786
0
    if (ssl == NULL)
1787
0
        return NULL;
1788
1789
0
    if ( (ssl->options.side == WOLFSSL_CLIENT_END && !verify) ||
1790
0
         (ssl->options.side == WOLFSSL_SERVER_END &&  verify) )
1791
0
        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
0
}
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
0
{
2397
0
    int ret = WOLFSSL_SUCCESS;
2398
#if !defined(NO_SESSION_CACHE) && defined(ENABLE_SESSION_CACHE_ROW_LOCK)
2399
    int i;
2400
#endif
2401
2402
0
    WOLFSSL_ENTER("wolfSSL_Init");
2403
2404
0
#if defined(LIBWOLFSSL_CMAKE_OUTPUT)
2405
0
    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
0
    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
0
    if ((ret == WOLFSSL_SUCCESS) && (initRefCount == 0)) {
2459
        /* Initialize crypto for use with TLS connection */
2460
2461
0
        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
0
#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
0
        if (ret == WOLFSSL_SUCCESS) {
2517
0
            if (wc_InitRwLock(&session_lock) != 0) {
2518
0
                WOLFSSL_MSG("Bad Init Mutex session");
2519
0
                ret = BAD_MUTEX_E;
2520
0
            }
2521
0
            else {
2522
0
                session_lock_valid = 1;
2523
0
            }
2524
0
        }
2525
0
    #endif
2526
0
    #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
0
    #endif
2539
0
#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
0
    }
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
0
    if (ret == WOLFSSL_SUCCESS) {
2555
0
        initRefCount = initRefCount + 1;
2556
0
    }
2557
0
    else {
2558
0
        initRefCount = 1; /* Force cleanup */
2559
0
    }
2560
2561
0
    wc_UnLockMutex(&inits_count_mutex);
2562
2563
0
    if (ret != WOLFSSL_SUCCESS) {
2564
0
        (void)wolfSSL_Cleanup(); /* Ignore any error from cleanup */
2565
0
    }
2566
2567
0
    return ret;
2568
0
}
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
0
{
3630
0
    int ret = WOLFSSL_SUCCESS; /* Only the first error will be returned */
3631
0
    int release = 0;
3632
0
#if !defined(NO_SESSION_CACHE)
3633
0
    int i;
3634
0
    int j;
3635
0
#endif
3636
3637
0
    WOLFSSL_ENTER("wolfSSL_Cleanup");
3638
3639
#ifndef WOLFSSL_MUTEX_INITIALIZER
3640
    if (inits_count_mutex_valid == 1) {
3641
#endif
3642
0
        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
0
    if (initRefCount > 0) {
3651
0
        initRefCount = initRefCount - 1;
3652
0
        if (initRefCount == 0)
3653
0
            release = 1;
3654
0
    }
3655
3656
#ifndef WOLFSSL_MUTEX_INITIALIZER
3657
    if (inits_count_mutex_valid == 1) {
3658
#endif
3659
0
        wc_UnLockMutex(&inits_count_mutex);
3660
#ifndef WOLFSSL_MUTEX_INITIALIZER
3661
    }
3662
#endif
3663
3664
0
    if (!release)
3665
0
        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
0
#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
0
    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
0
    session_lock_valid = 0;
3691
0
    #endif
3692
0
    for (i = 0; i < SESSION_ROWS; i++) {
3693
0
        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
0
            EvictSessionFromCache(&SessionCache[i].Sessions[j]);
3703
0
    #endif
3704
0
        }
3705
0
    }
3706
0
    #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
0
    #endif
3716
0
#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
0
    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
0
#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
0
#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
0
    return ret;
3770
0
}
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
0
    #ifdef WOLFSSL_TLS13_COOKIE
5699
0
        ssl->options.hrrSentCookie = 0;
5700
0
    #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
#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
6226
    defined(WOLFSSL_HAPROXY) || defined(OPENSSL_EXTRA)
6227
/* Locate a cipher in the SSL's cipher list by 2-byte wire-format suite id.
6228
 *
6229
 * Mirrors OpenSSL's SSL_CIPHER_find(): the SSL's configured cipher list is
6230
 * searched first, then all cipher suites known to the library are searched as
6231
 * a fallback. This lets callers decode a suite id seen on the wire even when
6232
 * it is not enabled on the SSL object.
6233
 *
6234
 * A match found in the SSL's cipher list returns storage owned by that list.
6235
 * A match found only in the library fallback is stored in the SSL object's
6236
 * scratch cipher (ssl->cipher), as wolfSSL_get_current_cipher does. In either
6237
 * case callers must not free the returned pointer; it remains valid until the
6238
 * next call that updates ssl->cipher, or until SSL_free.
6239
 *
6240
 * @param [in] ssl  SSL/TLS object whose cipher list is searched.
6241
 * @param [in] ptr  Pointer to a 2-byte cipher suite identifier.
6242
 * @return  Matching cipher on success.
6243
 * @return  NULL if ssl or ptr is NULL, or no cipher matches.
6244
 */
6245
const WOLFSSL_CIPHER* wolfSSL_SSL_CIPHER_find(WOLFSSL* ssl,
6246
    const unsigned char* ptr)
6247
{
6248
    WOLF_STACK_OF(WOLFSSL_CIPHER)* sk;
6249
    WOLFSSL_STACK* node;
6250
    const CipherSuiteInfo* cipher_names;
6251
    int cipherSz;
6252
    int i;
6253
6254
    WOLFSSL_ENTER("wolfSSL_SSL_CIPHER_find");
6255
6256
    if (ssl == NULL || ptr == NULL)
6257
        return NULL;
6258
6259
    sk = wolfSSL_get_ciphers_compat(ssl);
6260
    for (node = sk; node != NULL; node = node->next) {
6261
        if (node->data.cipher.cipherSuite0 == ptr[0] &&
6262
            node->data.cipher.cipherSuite  == ptr[1]) {
6263
            return &node->data.cipher;
6264
        }
6265
    }
6266
6267
    /* Not enabled on this SSL - fall back to a library-wide lookup so suite
6268
     * ids seen on the wire can still be decoded, matching OpenSSL. */
6269
    cipher_names = GetCipherNames();
6270
    cipherSz = GetCipherNamesSize();
6271
    for (i = 0; i < cipherSz; i++) {
6272
        if (cipher_names[i].cipherSuite0 == ptr[0] &&
6273
            cipher_names[i].cipherSuite  == ptr[1]) {
6274
            XMEMSET(&ssl->cipher, 0, sizeof(ssl->cipher));
6275
            ssl->cipher.cipherSuite0 = ptr[0];
6276
            ssl->cipher.cipherSuite  = ptr[1];
6277
            ssl->cipher.ssl          = ssl;
6278
#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
6279
            ssl->cipher.offset       = (unsigned long)i;
6280
            /* Describe from cipher_names[offset]: ssl->specs holds the
6281
             * negotiated suite, not this one. */
6282
            ssl->cipher.in_stack     = TRUE;
6283
#endif
6284
            return &ssl->cipher;
6285
        }
6286
    }
6287
6288
    return NULL;
6289
}
6290
#endif
6291
6292
6293
#if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448) || \
6294
    !defined(NO_DH) || (defined(WOLFSSL_TLS13) && defined(WOLFSSL_HAVE_MLKEM))
6295
#ifdef HAVE_FFDHE
6296
static const char* wolfssl_ffdhe_name(word16 group)
6297
0
{
6298
0
    const char* str = NULL;
6299
0
    switch (group) {
6300
0
        case WOLFSSL_FFDHE_2048:
6301
0
            str = "FFDHE_2048";
6302
0
            break;
6303
0
        case WOLFSSL_FFDHE_3072:
6304
0
            str = "FFDHE_3072";
6305
0
            break;
6306
0
        case WOLFSSL_FFDHE_4096:
6307
0
            str = "FFDHE_4096";
6308
0
            break;
6309
0
        case WOLFSSL_FFDHE_6144:
6310
0
            str = "FFDHE_6144";
6311
0
            break;
6312
0
        case WOLFSSL_FFDHE_8192:
6313
0
            str = "FFDHE_8192";
6314
0
            break;
6315
0
        default:
6316
0
            break;
6317
0
    }
6318
0
    return str;
6319
0
}
6320
#endif
6321
/* Return the name of the curve used for key exchange as a printable string.
6322
 *
6323
 * ssl  The SSL/TLS object.
6324
 * returns NULL if ECDH was not used, otherwise the name as a string.
6325
 */
6326
const char* wolfSSL_get_curve_name(WOLFSSL* ssl)
6327
0
{
6328
0
    const char* cName = NULL;
6329
6330
0
    WOLFSSL_ENTER("wolfSSL_get_curve_name");
6331
6332
0
    if (ssl == NULL)
6333
0
        return NULL;
6334
6335
0
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_HAVE_MLKEM)
6336
    /* Check for post-quantum groups. Return now because we do not want the ECC
6337
     * check to override this result in the case of a hybrid. */
6338
0
    if (IsAtLeastTLSv1_3(ssl->version)) {
6339
0
        switch (ssl->namedGroup) {
6340
0
#ifndef WOLFSSL_NO_ML_KEM
6341
0
    #ifndef WOLFSSL_NO_ML_KEM_512
6342
0
        case WOLFSSL_ML_KEM_512:
6343
0
            return "ML_KEM_512";
6344
        #ifdef WOLFSSL_EXTRA_PQC_HYBRIDS
6345
        #ifdef WOLFSSL_ML_KEM_USE_OLD_IDS
6346
        case WOLFSSL_P256_ML_KEM_512_OLD:
6347
            return "P256_ML_KEM_512_OLD";
6348
        #endif /* WOLFSSL_ML_KEM_USE_OLD_IDS */
6349
        case WOLFSSL_SECP256R1MLKEM512:
6350
            return "SecP256r1MLKEM512";
6351
        #ifdef HAVE_CURVE25519
6352
        case WOLFSSL_X25519MLKEM512:
6353
            return "X25519MLKEM512";
6354
        #endif /* HAVE_CURVE25519 */
6355
        #endif /* WOLFSSL_EXTRA_PQC_HYBRIDS */
6356
0
    #endif /* WOLFSSL_NO_ML_KEM_512 */
6357
0
    #ifndef WOLFSSL_NO_ML_KEM_768
6358
0
        case WOLFSSL_ML_KEM_768:
6359
0
            return "ML_KEM_768";
6360
0
        #ifdef WOLFSSL_PQC_HYBRIDS
6361
0
        case WOLFSSL_SECP256R1MLKEM768:
6362
0
            return "SecP256r1MLKEM768";
6363
        #ifdef HAVE_CURVE25519
6364
        case WOLFSSL_X25519MLKEM768:
6365
            return "X25519MLKEM768";
6366
        #endif
6367
0
        #endif /* WOLFSSL_PQC_HYBRIDS */
6368
        #ifdef WOLFSSL_EXTRA_PQC_HYBRIDS
6369
        #ifdef WOLFSSL_ML_KEM_USE_OLD_IDS
6370
        case WOLFSSL_P384_ML_KEM_768_OLD:
6371
            return "P384_ML_KEM_768_OLD";
6372
        #endif /* WOLFSSL_ML_KEM_USE_OLD_IDS */
6373
        case WOLFSSL_SECP384R1MLKEM768:
6374
            return "SecP384r1MLKEM768";
6375
        #ifdef HAVE_CURVE448
6376
        case WOLFSSL_X448MLKEM768:
6377
            return "X448MLKEM768";
6378
        #endif /* HAVE_CURVE448 */
6379
        #endif /* WOLFSSL_EXTRA_PQC_HYBRIDS */
6380
0
    #endif /* WOLFSSL_NO_ML_KEM_768 */
6381
0
    #ifndef WOLFSSL_NO_ML_KEM_1024
6382
0
        case WOLFSSL_ML_KEM_1024:
6383
0
            return "ML_KEM_1024";
6384
0
        #ifdef WOLFSSL_PQC_HYBRIDS
6385
0
        case WOLFSSL_SECP384R1MLKEM1024:
6386
0
            return "SecP384r1MLKEM1024";
6387
0
        #endif /* WOLFSSL_PQC_HYBRIDS */
6388
        #ifdef WOLFSSL_EXTRA_PQC_HYBRIDS
6389
        #ifdef WOLFSSL_ML_KEM_USE_OLD_IDS
6390
        case WOLFSSL_P521_ML_KEM_1024_OLD:
6391
            return "P521_ML_KEM_1024_OLD";
6392
        #endif /* WOLFSSL_ML_KEM_USE_OLD_IDS */
6393
        case WOLFSSL_SECP521R1MLKEM1024:
6394
            return "SecP521r1MLKEM1024";
6395
        #endif /* WOLFSSL_EXTRA_PQC_HYBRIDS */
6396
0
    #endif /* WOLFSSL_NO_ML_KEM_1024 */
6397
0
#endif /* WOLFSSL_NO_ML_KEM */
6398
#ifdef WOLFSSL_MLKEM_KYBER
6399
    #ifndef WOLFSSL_NO_KYBER512
6400
        case WOLFSSL_KYBER_LEVEL1:
6401
            return "KYBER_LEVEL1";
6402
        case WOLFSSL_P256_KYBER_LEVEL1:
6403
            return "P256_KYBER_LEVEL1";
6404
        #ifdef HAVE_CURVE25519
6405
        case WOLFSSL_X25519_KYBER_LEVEL1:
6406
            return "X25519_KYBER_LEVEL1";
6407
        #endif
6408
    #endif
6409
    #ifndef WOLFSSL_NO_KYBER768
6410
        case WOLFSSL_KYBER_LEVEL3:
6411
            return "KYBER_LEVEL3";
6412
        case WOLFSSL_P384_KYBER_LEVEL3:
6413
            return "P384_KYBER_LEVEL3";
6414
        case WOLFSSL_P256_KYBER_LEVEL3:
6415
            return "P256_KYBER_LEVEL3";
6416
        #ifdef HAVE_CURVE25519
6417
        case WOLFSSL_X25519_KYBER_LEVEL3:
6418
            return "X25519_KYBER_LEVEL3";
6419
        #endif
6420
        #ifdef HAVE_CURVE448
6421
        case WOLFSSL_X448_KYBER_LEVEL3:
6422
            return "X448_KYBER_LEVEL3";
6423
        #endif
6424
    #endif
6425
    #ifndef WOLFSSL_NO_KYBER1024
6426
        case WOLFSSL_KYBER_LEVEL5:
6427
            return "KYBER_LEVEL5";
6428
        case WOLFSSL_P521_KYBER_LEVEL5:
6429
            return "P521_KYBER_LEVEL5";
6430
    #endif
6431
#endif /* WOLFSSL_MLKEM_KYBER */
6432
0
        }
6433
0
    }
6434
0
#endif /* WOLFSSL_TLS13 && WOLFSSL_HAVE_MLKEM */
6435
6436
0
#ifdef HAVE_FFDHE
6437
0
    if (ssl->namedGroup != 0) {
6438
0
        cName = wolfssl_ffdhe_name(ssl->namedGroup);
6439
0
    }
6440
0
#endif
6441
6442
#ifdef HAVE_CURVE25519
6443
    if (ssl->ecdhCurveOID == ECC_X25519_OID && cName == NULL) {
6444
        cName = "X25519";
6445
    }
6446
#endif
6447
6448
#ifdef HAVE_CURVE448
6449
    if (ssl->ecdhCurveOID == ECC_X448_OID && cName == NULL) {
6450
        cName = "X448";
6451
    }
6452
#endif
6453
6454
0
#ifdef HAVE_ECC
6455
0
    if (ssl->ecdhCurveOID != 0 && cName == NULL) {
6456
0
        cName = wc_ecc_get_name(wc_ecc_get_oid(ssl->ecdhCurveOID, NULL,
6457
0
                                NULL));
6458
0
    }
6459
0
#endif
6460
6461
0
    return cName;
6462
0
}
6463
#endif
6464
6465
#ifdef OPENSSL_EXTRA
6466
#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
6467
/* return authentication NID corresponding to cipher suite
6468
 * @param cipher a pointer to WOLFSSL_CIPHER
6469
 * return NID if found, WC_NID_undef if not found
6470
 */
6471
int wolfSSL_CIPHER_get_auth_nid(const WOLFSSL_CIPHER* cipher)
6472
{
6473
    static const struct authnid {
6474
        const char* alg_name;
6475
        const int  nid;
6476
    } authnid_tbl[] = {
6477
        {"RSA",     WC_NID_auth_rsa},
6478
        {"PSK",     WC_NID_auth_psk},
6479
        {"SRP",     WC_NID_auth_srp},
6480
        {"ECDSA",   WC_NID_auth_ecdsa},
6481
        {"None",    WC_NID_auth_null},
6482
        {NULL,      WC_NID_undef}
6483
    };
6484
6485
    const char* authStr;
6486
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
6487
6488
    if (GetCipherSegment(cipher, n) == NULL) {
6489
        WOLFSSL_MSG("no suitable cipher name found");
6490
        return WC_NID_undef;
6491
    }
6492
6493
    authStr = GetCipherAuthStr(n);
6494
6495
    if (authStr != NULL) {
6496
        const struct authnid* sa;
6497
        for(sa = authnid_tbl; sa->alg_name != NULL; sa++) {
6498
            if (XSTRCMP(sa->alg_name, authStr) == 0) {
6499
                return sa->nid;
6500
            }
6501
        }
6502
    }
6503
6504
    return WC_NID_undef;
6505
}
6506
/* return cipher NID corresponding to cipher suite
6507
 * @param cipher a pointer to WOLFSSL_CIPHER
6508
 * return NID if found, WC_NID_undef if not found
6509
 */
6510
int wolfSSL_CIPHER_get_cipher_nid(const WOLFSSL_CIPHER* cipher)
6511
{
6512
    static const struct ciphernid {
6513
        const char* alg_name;
6514
        const int  nid;
6515
    } ciphernid_tbl[] = {
6516
        {"AESGCM(256)",             WC_NID_aes_256_gcm},
6517
        {"AESGCM(128)",             WC_NID_aes_128_gcm},
6518
        {"AESCCM(128)",             WC_NID_aes_128_ccm},
6519
        {"AES(128)",                WC_NID_aes_128_cbc},
6520
        {"AES(256)",                WC_NID_aes_256_cbc},
6521
        {"CAMELLIA(256)",           WC_NID_camellia_256_cbc},
6522
        {"CAMELLIA(128)",           WC_NID_camellia_128_cbc},
6523
        {"RC4",                     WC_NID_rc4},
6524
        {"3DES",                    WC_NID_des_ede3_cbc},
6525
        {"CHACHA20/POLY1305(256)",  WC_NID_chacha20_poly1305},
6526
        {"None",                    WC_NID_undef},
6527
        {NULL,                      WC_NID_undef}
6528
    };
6529
6530
    const char* encStr;
6531
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
6532
6533
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_cipher_nid");
6534
6535
    if (GetCipherSegment(cipher, n) == NULL) {
6536
        WOLFSSL_MSG("no suitable cipher name found");
6537
        return WC_NID_undef;
6538
    }
6539
6540
    encStr = GetCipherEncStr(n);
6541
6542
    if (encStr != NULL) {
6543
        const struct ciphernid* c;
6544
        for(c = ciphernid_tbl; c->alg_name != NULL; c++) {
6545
            if (XSTRCMP(c->alg_name, encStr) == 0) {
6546
                return c->nid;
6547
            }
6548
        }
6549
    }
6550
6551
    return WC_NID_undef;
6552
}
6553
/* return digest NID corresponding to cipher suite
6554
 * @param cipher a pointer to WOLFSSL_CIPHER
6555
 * return NID if found, WC_NID_undef if not found
6556
 */
6557
int wolfSSL_CIPHER_get_digest_nid(const WOLFSSL_CIPHER* cipher)
6558
{
6559
    static const struct macnid {
6560
        const char* alg_name;
6561
        const int  nid;
6562
    } macnid_tbl[] = {
6563
        {"SHA1",    WC_NID_sha1},
6564
        {"SHA256",  WC_NID_sha256},
6565
        {"SHA384",  WC_NID_sha384},
6566
        {NULL,      WC_NID_undef}
6567
    };
6568
6569
    const char* name;
6570
    const char* macStr;
6571
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
6572
    (void)name;
6573
6574
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_digest_nid");
6575
6576
    if ((name = GetCipherSegment(cipher, n)) == NULL) {
6577
        WOLFSSL_MSG("no suitable cipher name found");
6578
        return WC_NID_undef;
6579
    }
6580
6581
    /* in MD5 case, NID will be WC_NID_md5 */
6582
    if (XSTRSTR(name, "MD5") != NULL) {
6583
        return WC_NID_md5;
6584
    }
6585
6586
    macStr = GetCipherMacStr(n);
6587
6588
    if (macStr != NULL) {
6589
        const struct macnid* mc;
6590
        for(mc = macnid_tbl; mc->alg_name != NULL; mc++) {
6591
            if (XSTRCMP(mc->alg_name, macStr) == 0) {
6592
                return mc->nid;
6593
            }
6594
        }
6595
    }
6596
6597
    return WC_NID_undef;
6598
}
6599
/* return key exchange NID corresponding to cipher suite
6600
 * @param cipher a pointer to WOLFSSL_CIPHER
6601
 * return NID if found, WC_NID_undef if not found
6602
 */
6603
int wolfSSL_CIPHER_get_kx_nid(const WOLFSSL_CIPHER* cipher)
6604
{
6605
    static const struct kxnid {
6606
        const char* name;
6607
        const int  nid;
6608
    } kxnid_table[] = {
6609
        {"ECDHEPSK",  WC_NID_kx_ecdhe_psk},
6610
        {"ECDH",      WC_NID_kx_ecdhe},
6611
        {"DHEPSK",    WC_NID_kx_dhe_psk},
6612
        {"DH",        WC_NID_kx_dhe},
6613
        {"RSAPSK",    WC_NID_kx_rsa_psk},
6614
        {"SRP",       WC_NID_kx_srp},
6615
        {"EDH",       WC_NID_kx_dhe},
6616
        {"PSK",       WC_NID_kx_psk},
6617
        {"RSA",       WC_NID_kx_rsa},
6618
        {NULL,        WC_NID_undef}
6619
    };
6620
6621
    const char* keaStr;
6622
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
6623
6624
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_kx_nid");
6625
6626
    if (GetCipherSegment(cipher, n) == NULL) {
6627
        WOLFSSL_MSG("no suitable cipher name found");
6628
        return WC_NID_undef;
6629
    }
6630
6631
    /* in TLS 1.3 case, NID will be WC_NID_kx_any */
6632
    if (XSTRCMP(n[0], "TLS13") == 0) {
6633
        return WC_NID_kx_any;
6634
    }
6635
6636
    keaStr = GetCipherKeaStr(n);
6637
6638
    if (keaStr != NULL) {
6639
        const struct kxnid* k;
6640
        for(k = kxnid_table; k->name != NULL; k++) {
6641
            if (XSTRCMP(k->name, keaStr) == 0) {
6642
                return k->nid;
6643
            }
6644
        }
6645
    }
6646
6647
    return WC_NID_undef;
6648
}
6649
/* check if cipher suite is AEAD
6650
 * @param cipher a pointer to WOLFSSL_CIPHER
6651
 * return 1 if cipher is AEAD, 0 otherwise
6652
 */
6653
int wolfSSL_CIPHER_is_aead(const WOLFSSL_CIPHER* cipher)
6654
{
6655
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
6656
6657
    WOLFSSL_ENTER("wolfSSL_CIPHER_is_aead");
6658
6659
    if (GetCipherSegment(cipher, n) == NULL) {
6660
        WOLFSSL_MSG("no suitable cipher name found");
6661
        return WC_NID_undef;
6662
    }
6663
6664
    return IsCipherAEAD(n);
6665
}
6666
/* Creates cipher->description based on cipher->offset
6667
 * cipher->offset is set in wolfSSL_get_ciphers_compat when it is added
6668
 * to a stack of ciphers.
6669
 * @param [in] cipher: A cipher from a stack of ciphers.
6670
 * return WOLFSSL_SUCCESS if cipher->description is set, else WOLFSSL_FAILURE
6671
 */
6672
int wolfSSL_sk_CIPHER_description(WOLFSSL_CIPHER* cipher)
6673
{
6674
    int strLen;
6675
    unsigned long offset;
6676
    char* dp;
6677
    const char* name;
6678
    const char *keaStr, *authStr, *encStr, *macStr, *protocol;
6679
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
6680
    int len = MAX_DESCRIPTION_SZ-1;
6681
    const CipherSuiteInfo* cipher_names;
6682
    ProtocolVersion pv;
6683
    WOLFSSL_ENTER("wolfSSL_sk_CIPHER_description");
6684
6685
    if (cipher == NULL)
6686
        return WOLFSSL_FAILURE;
6687
6688
    dp = cipher->description;
6689
    if (dp == NULL)
6690
        return WOLFSSL_FAILURE;
6691
6692
    cipher_names = GetCipherNames();
6693
6694
    offset = cipher->offset;
6695
    if (offset >= (unsigned long)GetCipherNamesSize())
6696
        return WOLFSSL_FAILURE;
6697
    pv.major = cipher_names[offset].major;
6698
    pv.minor = cipher_names[offset].minor;
6699
    protocol = wolfSSL_internal_get_version(&pv);
6700
6701
    if ((name = GetCipherSegment(cipher, n)) == NULL) {
6702
        WOLFSSL_MSG("no suitable cipher name found");
6703
        return WOLFSSL_FAILURE;
6704
    }
6705
6706
    /* keaStr */
6707
    keaStr = GetCipherKeaStr(n);
6708
    /* authStr */
6709
    authStr = GetCipherAuthStr(n);
6710
    /* encStr */
6711
    encStr = GetCipherEncStr(n);
6712
    if ((cipher->bits = SetCipherBits(encStr)) ==
6713
        WC_NO_ERR_TRACE(WOLFSSL_FAILURE))
6714
    {
6715
       WOLFSSL_MSG("Cipher Bits Not Set.");
6716
    }
6717
    /* macStr */
6718
    macStr = GetCipherMacStr(n);
6719
6720
6721
    /* Build up the string by copying onto the end. */
6722
    XSTRNCPY(dp, name, (size_t)len);
6723
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
6724
    len -= strLen; dp += strLen;
6725
6726
    XSTRNCPY(dp, " ", (size_t)len);
6727
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
6728
    len -= strLen; dp += strLen;
6729
    XSTRNCPY(dp, protocol, (size_t)len);
6730
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
6731
    len -= strLen; dp += strLen;
6732
6733
    XSTRNCPY(dp, " Kx=", (size_t)len);
6734
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
6735
    len -= strLen; dp += strLen;
6736
    XSTRNCPY(dp, keaStr, (size_t)len);
6737
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
6738
    len -= strLen; dp += strLen;
6739
6740
    XSTRNCPY(dp, " Au=", (size_t)len);
6741
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
6742
    len -= strLen; dp += strLen;
6743
    XSTRNCPY(dp, authStr, (size_t)len);
6744
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
6745
    len -= strLen; dp += strLen;
6746
6747
    XSTRNCPY(dp, " Enc=", (size_t)len);
6748
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
6749
    len -= strLen; dp += strLen;
6750
    XSTRNCPY(dp, encStr, (size_t)len);
6751
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
6752
    len -= strLen; dp += strLen;
6753
6754
    XSTRNCPY(dp, " Mac=", (size_t)len);
6755
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
6756
    len -= strLen; dp += (size_t)strLen;
6757
    XSTRNCPY(dp, macStr, (size_t)len);
6758
    dp[len-1] = '\0';
6759
6760
    return WOLFSSL_SUCCESS;
6761
}
6762
#endif /* OPENSSL_ALL || WOLFSSL_QT */
6763
6764
static WC_INLINE const char* wolfssl_kea_to_string(int kea)
6765
{
6766
    const char* keaStr;
6767
6768
    switch (kea) {
6769
        case no_kea:
6770
            keaStr = "None";
6771
            break;
6772
#ifndef NO_RSA
6773
        case rsa_kea:
6774
            keaStr = "RSA";
6775
            break;
6776
#endif
6777
#ifndef NO_DH
6778
        case diffie_hellman_kea:
6779
            keaStr = "DHE";
6780
            break;
6781
#endif
6782
        case fortezza_kea:
6783
            keaStr = "FZ";
6784
            break;
6785
#ifndef NO_PSK
6786
        case psk_kea:
6787
            keaStr = "PSK";
6788
            break;
6789
    #ifndef NO_DH
6790
        case dhe_psk_kea:
6791
            keaStr = "DHEPSK";
6792
            break;
6793
    #endif
6794
    #ifdef HAVE_ECC
6795
        case ecdhe_psk_kea:
6796
            keaStr = "ECDHEPSK";
6797
            break;
6798
    #endif
6799
#endif
6800
#ifdef HAVE_ECC
6801
        case ecc_diffie_hellman_kea:
6802
            keaStr = "ECDHE";
6803
            break;
6804
        case ecc_static_diffie_hellman_kea:
6805
            keaStr = "ECDH";
6806
            break;
6807
#endif
6808
        case any_kea:
6809
            keaStr = "any";
6810
            break;
6811
        default:
6812
            keaStr = "unknown";
6813
            break;
6814
    }
6815
6816
    return keaStr;
6817
}
6818
6819
static WC_INLINE const char* wolfssl_sigalg_to_string(int sig_algo)
6820
{
6821
    const char* authStr;
6822
6823
    switch (sig_algo) {
6824
        case anonymous_sa_algo:
6825
            authStr = "None";
6826
            break;
6827
#ifndef NO_RSA
6828
        case rsa_sa_algo:
6829
            authStr = "RSA";
6830
            break;
6831
    #ifdef WC_RSA_PSS
6832
        case rsa_pss_sa_algo:
6833
            authStr = "RSA-PSS";
6834
            break;
6835
    #endif
6836
#endif
6837
#ifndef NO_DSA
6838
        case dsa_sa_algo:
6839
            authStr = "DSA";
6840
            break;
6841
#endif
6842
#ifdef HAVE_ECC
6843
        case ecc_dsa_sa_algo:
6844
            authStr = "ECDSA";
6845
            break;
6846
#endif
6847
#ifdef WOLFSSL_SM2
6848
        case sm2_sa_algo:
6849
            authStr = "SM2";
6850
            break;
6851
#endif
6852
#ifdef HAVE_ED25519
6853
        case ed25519_sa_algo:
6854
            authStr = "Ed25519";
6855
            break;
6856
#endif
6857
#ifdef HAVE_ED448
6858
        case ed448_sa_algo:
6859
            authStr = "Ed448";
6860
            break;
6861
#endif
6862
        case any_sa_algo:
6863
            authStr = "any";
6864
            break;
6865
        default:
6866
            authStr = "unknown";
6867
            break;
6868
    }
6869
6870
    return authStr;
6871
}
6872
6873
static WC_INLINE const char* wolfssl_cipher_to_string(int cipher, int key_size)
6874
{
6875
    const char* encStr;
6876
6877
    (void)key_size;
6878
6879
    switch (cipher) {
6880
        case wolfssl_cipher_null:
6881
            encStr = "None";
6882
            break;
6883
#ifndef NO_RC4
6884
        case wolfssl_rc4:
6885
            encStr = "RC4(128)";
6886
            break;
6887
#endif
6888
#ifndef NO_DES3
6889
        case wolfssl_triple_des:
6890
            encStr = "3DES(168)";
6891
            break;
6892
#endif
6893
#ifndef NO_AES
6894
        case wolfssl_aes:
6895
            if (key_size == AES_128_KEY_SIZE)
6896
                encStr = "AES(128)";
6897
            else if (key_size == AES_256_KEY_SIZE)
6898
                encStr = "AES(256)";
6899
            else
6900
                encStr = "AES(?)";
6901
            break;
6902
    #ifdef HAVE_AESGCM
6903
        case wolfssl_aes_gcm:
6904
            if (key_size == AES_128_KEY_SIZE)
6905
                encStr = "AESGCM(128)";
6906
            else if (key_size == AES_256_KEY_SIZE)
6907
                encStr = "AESGCM(256)";
6908
            else
6909
                encStr = "AESGCM(?)";
6910
            break;
6911
    #endif
6912
    #ifdef HAVE_AESCCM
6913
        case wolfssl_aes_ccm:
6914
            if (key_size == AES_128_KEY_SIZE)
6915
                encStr = "AESCCM(128)";
6916
            else if (key_size == AES_256_KEY_SIZE)
6917
                encStr = "AESCCM(256)";
6918
            else
6919
                encStr = "AESCCM(?)";
6920
            break;
6921
    #endif
6922
#endif
6923
#ifdef HAVE_CHACHA
6924
        case wolfssl_chacha:
6925
            encStr = "CHACHA20/POLY1305(256)";
6926
            break;
6927
#endif
6928
#ifdef HAVE_ARIA
6929
        case wolfssl_aria_gcm:
6930
            if (key_size == ARIA_128_KEY_SIZE)
6931
                encStr = "Aria(128)";
6932
            else if (key_size == ARIA_192_KEY_SIZE)
6933
                encStr = "Aria(192)";
6934
            else if (key_size == ARIA_256_KEY_SIZE)
6935
                encStr = "Aria(256)";
6936
            else
6937
                encStr = "Aria(?)";
6938
            break;
6939
#endif
6940
#ifdef HAVE_CAMELLIA
6941
        case wolfssl_camellia:
6942
            if (key_size == CAMELLIA_128_KEY_SIZE)
6943
                encStr = "Camellia(128)";
6944
            else if (key_size == CAMELLIA_256_KEY_SIZE)
6945
                encStr = "Camellia(256)";
6946
            else
6947
                encStr = "Camellia(?)";
6948
            break;
6949
#endif
6950
        default:
6951
            encStr = "unknown";
6952
            break;
6953
    }
6954
6955
    return encStr;
6956
}
6957
6958
static WC_INLINE const char* wolfssl_mac_to_string(int mac)
6959
{
6960
    const char* macStr;
6961
6962
    switch (mac) {
6963
        case no_mac:
6964
            macStr = "None";
6965
            break;
6966
#ifndef NO_MD5
6967
        case md5_mac:
6968
            macStr = "MD5";
6969
            break;
6970
#endif
6971
#ifndef NO_SHA
6972
        case sha_mac:
6973
            macStr = "SHA1";
6974
            break;
6975
#endif
6976
#ifdef WOLFSSL_SHA224
6977
        case sha224_mac:
6978
            macStr = "SHA224";
6979
            break;
6980
#endif
6981
#ifndef NO_SHA256
6982
        case sha256_mac:
6983
            macStr = "SHA256";
6984
            break;
6985
#endif
6986
#ifdef WOLFSSL_SHA384
6987
        case sha384_mac:
6988
            macStr = "SHA384";
6989
            break;
6990
#endif
6991
#ifdef WOLFSSL_SHA512
6992
        case sha512_mac:
6993
            macStr = "SHA512";
6994
            break;
6995
#endif
6996
        default:
6997
            macStr = "unknown";
6998
            break;
6999
    }
7000
7001
    return macStr;
7002
}
7003
7004
char* wolfSSL_CIPHER_description(const WOLFSSL_CIPHER* cipher, char* in,
7005
                                 int len)
7006
{
7007
    char *ret = in;
7008
    const char *keaStr, *authStr, *encStr, *macStr;
7009
    size_t strLen;
7010
    WOLFSSL_ENTER("wolfSSL_CIPHER_description");
7011
7012
    if (cipher == NULL || in == NULL)
7013
        return NULL;
7014
7015
#if defined(WOLFSSL_QT) || defined(OPENSSL_ALL)
7016
    /* if cipher is in the stack from wolfSSL_get_ciphers_compat then
7017
     * Return the description based on cipher_names[cipher->offset]
7018
     */
7019
    if (cipher->in_stack == TRUE) {
7020
        wolfSSL_sk_CIPHER_description((WOLFSSL_CIPHER*)cipher);
7021
        XSTRNCPY(in,cipher->description,(size_t)len);
7022
        return ret;
7023
    }
7024
#endif
7025
7026
    /* Get the cipher description based on the SSL session cipher */
7027
    keaStr = wolfssl_kea_to_string(cipher->ssl->specs.kea);
7028
    authStr = wolfssl_sigalg_to_string(cipher->ssl->specs.sig_algo);
7029
    encStr = wolfssl_cipher_to_string(cipher->ssl->specs.bulk_cipher_algorithm,
7030
                                      cipher->ssl->specs.key_size);
7031
    if (cipher->ssl->specs.cipher_type == aead)
7032
        macStr = "AEAD";
7033
    else
7034
        macStr = wolfssl_mac_to_string(cipher->ssl->specs.mac_algorithm);
7035
7036
    /* Build up the string by copying onto the end. */
7037
    XSTRNCPY(in, wolfSSL_CIPHER_get_name(cipher), (size_t)len);
7038
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
7039
7040
    XSTRNCPY(in, " ", (size_t)len);
7041
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
7042
    XSTRNCPY(in, wolfSSL_get_version(cipher->ssl), (size_t)len);
7043
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
7044
7045
    XSTRNCPY(in, " Kx=", (size_t)len);
7046
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
7047
    XSTRNCPY(in, keaStr, (size_t)len);
7048
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
7049
7050
    XSTRNCPY(in, " Au=", (size_t)len);
7051
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
7052
    XSTRNCPY(in, authStr, (size_t)len);
7053
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
7054
7055
    XSTRNCPY(in, " Enc=", (size_t)len);
7056
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
7057
    XSTRNCPY(in, encStr, (size_t)len);
7058
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
7059
7060
    XSTRNCPY(in, " Mac=", (size_t)len);
7061
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
7062
    XSTRNCPY(in, macStr, (size_t)len);
7063
    in[len-1] = '\0';
7064
7065
    return ret;
7066
}
7067
7068
#ifndef NO_WOLFSSL_STUB
7069
WOLFSSL_COMP_METHOD* wolfSSL_COMP_zlib(void)
7070
{
7071
    WOLFSSL_STUB("COMP_zlib");
7072
    return 0;
7073
}
7074
7075
WOLFSSL_COMP_METHOD* wolfSSL_COMP_rle(void)
7076
{
7077
    WOLFSSL_STUB("COMP_rle");
7078
    return 0;
7079
}
7080
7081
int wolfSSL_COMP_add_compression_method(int method, void* data)
7082
{
7083
    (void)method;
7084
    (void)data;
7085
    WOLFSSL_STUB("COMP_add_compression_method");
7086
    return 0;
7087
}
7088
7089
const WOLFSSL_COMP_METHOD* wolfSSL_get_current_compression(const WOLFSSL *ssl) {
7090
    (void)ssl;
7091
    return NULL;
7092
}
7093
7094
const WOLFSSL_COMP_METHOD* wolfSSL_get_current_expansion(const WOLFSSL *ssl) {
7095
    (void)ssl;
7096
    return NULL;
7097
}
7098
7099
const char* wolfSSL_COMP_get_name(const WOLFSSL_COMP_METHOD *comp)
7100
{
7101
    static const char ret[] = "not supported";
7102
7103
    (void)comp;
7104
    WOLFSSL_STUB("wolfSSL_COMP_get_name");
7105
    return ret;
7106
}
7107
#endif
7108
7109
/*  wolfSSL_set_dynlock_create_callback
7110
 *  CRYPTO_set_dynlock_create_callback has been deprecated since openSSL 1.0.1.
7111
 *  This function exists for compatibility purposes because wolfSSL satisfies
7112
 *  thread safety without relying on the callback.
7113
 */
7114
void wolfSSL_set_dynlock_create_callback(WOLFSSL_dynlock_value* (*f)(
7115
                                                          const char*, int))
7116
{
7117
    WOLFSSL_STUB("CRYPTO_set_dynlock_create_callback");
7118
    (void)f;
7119
}
7120
/*  wolfSSL_set_dynlock_lock_callback
7121
 *  CRYPTO_set_dynlock_lock_callback has been deprecated since openSSL 1.0.1.
7122
 *  This function exists for compatibility purposes because wolfSSL satisfies
7123
 *  thread safety without relying on the callback.
7124
 */
7125
void wolfSSL_set_dynlock_lock_callback(
7126
             void (*f)(int, WOLFSSL_dynlock_value*, const char*, int))
7127
{
7128
    WOLFSSL_STUB("CRYPTO_set_set_dynlock_lock_callback");
7129
    (void)f;
7130
}
7131
/*  wolfSSL_set_dynlock_destroy_callback
7132
 *  CRYPTO_set_dynlock_destroy_callback has been deprecated since openSSL 1.0.1.
7133
 *  This function exists for compatibility purposes because wolfSSL satisfies
7134
 *  thread safety without relying on the callback.
7135
 */
7136
void wolfSSL_set_dynlock_destroy_callback(
7137
                  void (*f)(WOLFSSL_dynlock_value*, const char*, int))
7138
{
7139
    WOLFSSL_STUB("CRYPTO_set_set_dynlock_destroy_callback");
7140
    (void)f;
7141
}
7142
7143
/* Sets the DNS hostname to name.
7144
 * Hostname is cleared if name is NULL or empty. */
7145
int wolfSSL_set1_host(WOLFSSL * ssl, const char* name)
7146
{
7147
    if (ssl == NULL) {
7148
        return WOLFSSL_FAILURE;
7149
    }
7150
7151
    return wolfSSL_X509_VERIFY_PARAM_set1_host(ssl->param, name, 0);
7152
}
7153
7154
/******************************************************************************
7155
* wolfSSL_CTX_set1_param - set a pointer to the SSL verification parameters
7156
*
7157
* RETURNS:
7158
*   WOLFSSL_SUCCESS on success, otherwise returns WOLFSSL_FAILURE
7159
*   Note: Returns WOLFSSL_SUCCESS, in case either parameter is NULL,
7160
*   same as openssl.
7161
*/
7162
int wolfSSL_CTX_set1_param(WOLFSSL_CTX* ctx, WOLFSSL_X509_VERIFY_PARAM *vpm)
7163
{
7164
    if (ctx == NULL || vpm == NULL)
7165
        return WOLFSSL_SUCCESS;
7166
7167
    return wolfSSL_X509_VERIFY_PARAM_set1(ctx->param, vpm);
7168
}
7169
7170
/******************************************************************************
7171
* wolfSSL_CTX/_get0_param - return a pointer to the SSL verification parameters
7172
*
7173
* RETURNS:
7174
* returns pointer to the SSL verification parameters on success,
7175
* otherwise returns NULL
7176
*/
7177
WOLFSSL_X509_VERIFY_PARAM* wolfSSL_CTX_get0_param(WOLFSSL_CTX* ctx)
7178
{
7179
    if (ctx == NULL) {
7180
        return NULL;
7181
    }
7182
7183
    return ctx->param;
7184
}
7185
7186
WOLFSSL_X509_VERIFY_PARAM* wolfSSL_get0_param(WOLFSSL* ssl)
7187
{
7188
    if (ssl == NULL) {
7189
        return NULL;
7190
    }
7191
    return ssl->param;
7192
}
7193
7194
#endif /* OPENSSL_EXTRA */
7195
7196
7197
#ifdef OPENSSL_EXTRA
7198
/* Sets a function callback that will send information about the state of all
7199
 * WOLFSSL objects that have been created by the WOLFSSL_CTX structure passed
7200
 * in.
7201
 *
7202
 * ctx WOLFSSL_CTX structure to set callback function in
7203
 * f   callback function to use
7204
 */
7205
void wolfSSL_CTX_set_info_callback(WOLFSSL_CTX* ctx,
7206
       void (*f)(const WOLFSSL* ssl, int type, int val))
7207
{
7208
    WOLFSSL_ENTER("wolfSSL_CTX_set_info_callback");
7209
    if (ctx == NULL) {
7210
        WOLFSSL_MSG("Bad function argument");
7211
    }
7212
    else {
7213
        ctx->CBIS = f;
7214
    }
7215
}
7216
7217
void wolfSSL_set_info_callback(WOLFSSL* ssl,
7218
       void (*f)(const WOLFSSL* ssl, int type, int val))
7219
{
7220
    WOLFSSL_ENTER("wolfSSL_set_info_callback");
7221
    if (ssl == NULL) {
7222
        WOLFSSL_MSG("Bad function argument");
7223
    }
7224
    else {
7225
        ssl->CBIS = f;
7226
    }
7227
}
7228
7229
7230
7231
#ifndef NO_TLS
7232
/* returns a string that describes the alert
7233
 *
7234
 * alertID the alert value to look up
7235
 */
7236
const char* wolfSSL_alert_type_string_long(int alertID)
7237
{
7238
    WOLFSSL_ENTER("wolfSSL_alert_type_string_long");
7239
7240
    return AlertTypeToString(alertID);
7241
}
7242
7243
const char* wolfSSL_alert_type_string(int alertID)
7244
{
7245
    WOLFSSL_ENTER("wolfSSL_alert_type_string");
7246
7247
    switch (alertID) {
7248
        case alert_warning:
7249
            return "W";
7250
        case alert_fatal:
7251
            return "F";
7252
        default:
7253
            return "U";
7254
    }
7255
}
7256
7257
const char* wolfSSL_alert_desc_string_long(int alertID)
7258
{
7259
    WOLFSSL_ENTER("wolfSSL_alert_desc_string_long");
7260
7261
    return AlertTypeToString(alertID);
7262
}
7263
7264
const char* wolfSSL_alert_desc_string(int alertID)
7265
{
7266
    WOLFSSL_ENTER("wolfSSL_alert_desc_string");
7267
7268
    switch (alertID) {
7269
        case close_notify:
7270
            return "CN";
7271
        case unexpected_message:
7272
            return "UM";
7273
        case bad_record_mac:
7274
            return "BM";
7275
        case record_overflow:
7276
            return "RO";
7277
        case decompression_failure:
7278
            return "DF";
7279
        case handshake_failure:
7280
            return "HF";
7281
        case no_certificate:
7282
            return "NC";
7283
        case bad_certificate:
7284
            return "BC";
7285
        case unsupported_certificate:
7286
            return "UC";
7287
        case certificate_revoked:
7288
            return "CR";
7289
        case certificate_expired:
7290
            return "CE";
7291
        case certificate_unknown:
7292
            return "CU";
7293
        case illegal_parameter:
7294
            return "IP";
7295
        case unknown_ca:
7296
            return "CA";
7297
        case access_denied:
7298
            return "AD";
7299
        case decode_error:
7300
            return "DE";
7301
        case decrypt_error:
7302
            return "DC";
7303
        case wolfssl_alert_protocol_version:
7304
            return "PV";
7305
        case insufficient_security:
7306
            return "IS";
7307
        case internal_error:
7308
            return "IE";
7309
        case inappropriate_fallback:
7310
            return "IF";
7311
        case user_canceled:
7312
            return "US";
7313
        case no_renegotiation:
7314
            return "NR";
7315
        case missing_extension:
7316
            return "ME";
7317
        case unsupported_extension:
7318
            return "UE";
7319
        case unrecognized_name:
7320
            return "UN";
7321
        case bad_certificate_status_response:
7322
            return "BR";
7323
        case unknown_psk_identity:
7324
            return "UP";
7325
        case certificate_required:
7326
            return "CQ";
7327
        case no_application_protocol:
7328
            return "AP";
7329
        default:
7330
            return "UK";
7331
    }
7332
}
7333
#endif /* !NO_TLS */
7334
7335
7336
#endif /* OPENSSL_EXTRA */
7337
7338
static long wolf_set_options(long old_op, long op)
7339
0
{
7340
    /* if SSL_OP_ALL then turn all bug workarounds on */
7341
0
    if ((op & WOLFSSL_OP_ALL) == WOLFSSL_OP_ALL) {
7342
0
        WOLFSSL_MSG("\tSSL_OP_ALL");
7343
0
    }
7344
7345
    /* by default cookie exchange is on with DTLS */
7346
0
    if ((op & WOLFSSL_OP_COOKIE_EXCHANGE) == WOLFSSL_OP_COOKIE_EXCHANGE) {
7347
0
        WOLFSSL_MSG("\tSSL_OP_COOKIE_EXCHANGE : on by default");
7348
0
    }
7349
7350
0
    if ((op & WOLFSSL_OP_NO_SSLv2) == WOLFSSL_OP_NO_SSLv2) {
7351
0
        WOLFSSL_MSG("\tWOLFSSL_OP_NO_SSLv2 : wolfSSL does not support SSLv2");
7352
0
    }
7353
7354
#ifdef SSL_OP_NO_TLSv1_3
7355
    if ((op & WOLFSSL_OP_NO_TLSv1_3) == WOLFSSL_OP_NO_TLSv1_3) {
7356
        WOLFSSL_MSG("\tSSL_OP_NO_TLSv1_3");
7357
    }
7358
#endif
7359
7360
0
    if ((op & WOLFSSL_OP_NO_TLSv1_2) == WOLFSSL_OP_NO_TLSv1_2) {
7361
0
        WOLFSSL_MSG("\tSSL_OP_NO_TLSv1_2");
7362
0
    }
7363
7364
0
    if ((op & WOLFSSL_OP_NO_TLSv1_1) == WOLFSSL_OP_NO_TLSv1_1) {
7365
0
        WOLFSSL_MSG("\tSSL_OP_NO_TLSv1_1");
7366
0
    }
7367
7368
0
    if ((op & WOLFSSL_OP_NO_TLSv1) == WOLFSSL_OP_NO_TLSv1) {
7369
0
        WOLFSSL_MSG("\tSSL_OP_NO_TLSv1");
7370
0
    }
7371
7372
0
    if ((op & WOLFSSL_OP_NO_SSLv3) == WOLFSSL_OP_NO_SSLv3) {
7373
0
        WOLFSSL_MSG("\tSSL_OP_NO_SSLv3");
7374
0
    }
7375
7376
0
    if ((op & WOLFSSL_OP_CIPHER_SERVER_PREFERENCE) ==
7377
0
            WOLFSSL_OP_CIPHER_SERVER_PREFERENCE) {
7378
0
        WOLFSSL_MSG("\tWOLFSSL_OP_CIPHER_SERVER_PREFERENCE");
7379
0
    }
7380
7381
0
    if ((op & WOLFSSL_OP_NO_COMPRESSION) == WOLFSSL_OP_NO_COMPRESSION) {
7382
    #ifdef HAVE_LIBZ
7383
        WOLFSSL_MSG("SSL_OP_NO_COMPRESSION");
7384
    #else
7385
0
        WOLFSSL_MSG("SSL_OP_NO_COMPRESSION: compression not compiled in");
7386
0
    #endif
7387
0
    }
7388
7389
0
    return old_op | op;
7390
0
}
7391
7392
static int FindHashSig(const Suites* suites, byte first, byte second)
7393
0
{
7394
0
    word16 i;
7395
7396
0
    if (suites == NULL || suites->hashSigAlgoSz == 0) {
7397
0
        WOLFSSL_MSG("Suites pointer error or suiteSz 0");
7398
0
        return SUITES_ERROR;
7399
0
    }
7400
7401
0
    for (i = 0; i < suites->hashSigAlgoSz-1; i += 2) {
7402
0
        if (suites->hashSigAlgo[i]   == first &&
7403
0
            suites->hashSigAlgo[i+1] == second )
7404
0
            return i;
7405
0
    }
7406
7407
0
    return MATCH_SUITE_ERROR;
7408
0
}
7409
7410
long wolfSSL_set_options(WOLFSSL* ssl, long op)
7411
0
{
7412
0
    word16 haveRSA = 1;
7413
0
    word16 havePSK = 0;
7414
0
    int    keySz   = 0;
7415
7416
0
    WOLFSSL_ENTER("wolfSSL_set_options");
7417
7418
0
    if (ssl == NULL) {
7419
0
        return 0;
7420
0
    }
7421
7422
0
    ssl->options.mask = (unsigned long)wolf_set_options((long)ssl->options.mask, op);
7423
7424
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1_3) == WOLFSSL_OP_NO_TLSv1_3) {
7425
0
        WOLFSSL_MSG("Disabling TLS 1.3");
7426
0
        if (ssl->version.minor == TLSv1_3_MINOR)
7427
0
            ssl->version.minor = TLSv1_2_MINOR;
7428
0
    }
7429
7430
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1_2) == WOLFSSL_OP_NO_TLSv1_2) {
7431
0
        WOLFSSL_MSG("Disabling TLS 1.2");
7432
0
        if (ssl->version.minor == TLSv1_2_MINOR)
7433
0
            ssl->version.minor = TLSv1_1_MINOR;
7434
0
    }
7435
7436
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1_1) == WOLFSSL_OP_NO_TLSv1_1) {
7437
0
        WOLFSSL_MSG("Disabling TLS 1.1");
7438
0
        if (ssl->version.minor == TLSv1_1_MINOR)
7439
0
            ssl->version.minor = TLSv1_MINOR;
7440
0
    }
7441
7442
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1) == WOLFSSL_OP_NO_TLSv1) {
7443
0
        WOLFSSL_MSG("Disabling TLS 1.0");
7444
0
        if (ssl->version.minor == TLSv1_MINOR)
7445
0
            ssl->version.minor = SSLv3_MINOR;
7446
0
    }
7447
7448
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_COMPRESSION)
7449
0
        == WOLFSSL_OP_NO_COMPRESSION) {
7450
    #ifdef HAVE_LIBZ
7451
        ssl->options.usingCompression = 0;
7452
    #endif
7453
0
    }
7454
7455
#if defined(HAVE_SESSION_TICKET) && (defined(OPENSSL_EXTRA) \
7456
        || defined(HAVE_WEBSERVER) || defined(WOLFSSL_WPAS_SMALL))
7457
    if ((ssl->options.mask & WOLFSSL_OP_NO_TICKET) == WOLFSSL_OP_NO_TICKET) {
7458
      ssl->options.noTicketTls12 = 1;
7459
    }
7460
#endif
7461
7462
7463
    /* in the case of a version change the cipher suites should be reset */
7464
#ifndef NO_PSK
7465
    havePSK = ssl->options.havePSK;
7466
#endif
7467
#ifdef NO_RSA
7468
    haveRSA = 0;
7469
#endif
7470
0
#ifndef NO_CERTS
7471
0
    keySz = ssl->buffers.keySz;
7472
0
#endif
7473
7474
0
    if (ssl->options.side != WOLFSSL_NEITHER_END) {
7475
0
        if (AllocateSuites(ssl) != 0)
7476
0
            return 0;
7477
0
        if (!ssl->suites->setSuites) {
7478
            /* Client side won't set DH params, so it needs haveDH set to TRUE. */
7479
0
            if (ssl->options.side == WOLFSSL_CLIENT_END)
7480
0
                InitSuites(ssl->suites, ssl->version, keySz, haveRSA,
7481
0
                       havePSK, TRUE, ssl->options.haveECDSAsig,
7482
0
                       ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
7483
0
                       ssl->options.useAnon,
7484
0
                       TRUE, TRUE, TRUE, TRUE, ssl->options.side);
7485
0
            else
7486
0
                InitSuites(ssl->suites, ssl->version, keySz, haveRSA,
7487
0
                       havePSK, ssl->options.haveDH, ssl->options.haveECDSAsig,
7488
0
                       ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
7489
0
                       ssl->options.useAnon,
7490
0
                       TRUE, TRUE, TRUE, TRUE, ssl->options.side);
7491
0
        }
7492
0
        else {
7493
            /* Only preserve overlapping suites */
7494
0
            Suites tmpSuites;
7495
0
            word16 in, out;
7496
0
            word16 haveECDSAsig, haveStaticECC;
7497
#ifdef NO_RSA
7498
            haveECDSAsig = 1;
7499
            haveStaticECC = 1;
7500
#else
7501
0
            haveECDSAsig = 0;
7502
0
            haveStaticECC = ssl->options.haveStaticECC;
7503
0
#endif
7504
0
            XMEMSET(&tmpSuites, 0, sizeof(Suites));
7505
            /* Get all possible ciphers and sigalgs for the version. Following
7506
             * options limit the allowed ciphers so let's try to get as many as
7507
             * possible.
7508
             * - haveStaticECC turns off haveRSA
7509
             * - haveECDSAsig turns off haveRSAsig */
7510
0
            InitSuites(&tmpSuites, ssl->version, 0, 1, 1, 1, haveECDSAsig, 1, 1,
7511
0
                    haveStaticECC, 1, 1, 1, 1, 1, ssl->options.side);
7512
0
            for (in = 0, out = 0; in < ssl->suites->suiteSz; in += SUITE_LEN) {
7513
0
                if (FindSuite(&tmpSuites, ssl->suites->suites[in],
7514
0
                        ssl->suites->suites[in+1]) >= 0) {
7515
0
                    ssl->suites->suites[out] = ssl->suites->suites[in];
7516
0
                    ssl->suites->suites[out+1] = ssl->suites->suites[in+1];
7517
0
                    out += SUITE_LEN;
7518
0
                }
7519
0
            }
7520
0
            ssl->suites->suiteSz = out;
7521
0
            for (in = 0, out = 0; in < ssl->suites->hashSigAlgoSz; in += 2) {
7522
0
                if (FindHashSig(&tmpSuites, ssl->suites->hashSigAlgo[in],
7523
0
                    ssl->suites->hashSigAlgo[in+1]) >= 0) {
7524
0
                    ssl->suites->hashSigAlgo[out] =
7525
0
                            ssl->suites->hashSigAlgo[in];
7526
0
                    ssl->suites->hashSigAlgo[out+1] =
7527
0
                            ssl->suites->hashSigAlgo[in+1];
7528
0
                    out += 2;
7529
0
                }
7530
0
            }
7531
0
            ssl->suites->hashSigAlgoSz = out;
7532
0
        }
7533
0
    }
7534
7535
0
    return (long)ssl->options.mask;
7536
0
}
7537
7538
7539
long wolfSSL_get_options(const WOLFSSL* ssl)
7540
0
{
7541
0
    WOLFSSL_ENTER("wolfSSL_get_options");
7542
0
    if(ssl == NULL)
7543
0
        return WOLFSSL_FAILURE;
7544
0
    return (long)ssl->options.mask;
7545
0
}
7546
7547
#if defined(HAVE_SECURE_RENEGOTIATION) \
7548
        || defined(HAVE_SERVER_RENEGOTIATION_INFO)
7549
/* clears the counter for number of renegotiations done
7550
 * returns the current count before it is cleared */
7551
long wolfSSL_clear_num_renegotiations(WOLFSSL *s)
7552
0
{
7553
0
    long total;
7554
7555
0
    WOLFSSL_ENTER("wolfSSL_clear_num_renegotiations");
7556
0
    if (s == NULL)
7557
0
        return 0;
7558
7559
0
    total = s->secure_rene_count;
7560
0
    s->secure_rene_count = 0;
7561
0
    return total;
7562
0
}
7563
7564
7565
/* return the number of renegotiations since wolfSSL_new */
7566
long wolfSSL_total_renegotiations(WOLFSSL *s)
7567
0
{
7568
0
    WOLFSSL_ENTER("wolfSSL_total_renegotiations");
7569
0
    return wolfSSL_num_renegotiations(s);
7570
0
}
7571
7572
7573
/* return the number of renegotiations since wolfSSL_new */
7574
long wolfSSL_num_renegotiations(WOLFSSL* s)
7575
0
{
7576
0
    if (s == NULL) {
7577
0
        return 0;
7578
0
    }
7579
7580
0
    return s->secure_rene_count;
7581
0
}
7582
7583
7584
/* Is there a renegotiation currently in progress? */
7585
int  wolfSSL_SSL_renegotiate_pending(WOLFSSL *s)
7586
0
{
7587
0
    return s && s->options.handShakeDone &&
7588
0
            s->options.handShakeState != HANDSHAKE_DONE ? 1 : 0;
7589
0
}
7590
#endif /* HAVE_SECURE_RENEGOTIATION || HAVE_SERVER_RENEGOTIATION_INFO */
7591
7592
#ifdef OPENSSL_EXTRA
7593
7594
long wolfSSL_clear_options(WOLFSSL* ssl, long opt)
7595
{
7596
    WOLFSSL_ENTER("wolfSSL_clear_options");
7597
    if(ssl == NULL)
7598
        return WOLFSSL_FAILURE;
7599
    ssl->options.mask &= (unsigned long)~opt;
7600
    return (long)ssl->options.mask;
7601
}
7602
7603
7604
#ifndef NO_WOLFSSL_STUB
7605
/*** TBD ***/
7606
void WOLFSSL_CTX_set_tmp_dh_callback(WOLFSSL_CTX *ctx,
7607
    WOLFSSL_DH *(*dh) (WOLFSSL *ssl, int is_export, int keylength))
7608
{
7609
    (void)ctx;
7610
    (void)dh;
7611
    WOLFSSL_STUB("WOLFSSL_CTX_set_tmp_dh_callback");
7612
}
7613
#endif
7614
7615
#ifndef NO_WOLFSSL_STUB
7616
/*** TBD ***/
7617
WOLF_STACK_OF(WOLFSSL_COMP) *WOLFSSL_COMP_get_compression_methods(void)
7618
{
7619
    WOLFSSL_STUB("WOLFSSL_COMP_get_compression_methods");
7620
    return NULL;
7621
}
7622
#endif
7623
7624
7625
#if !defined(NETOS)
7626
#endif
7627
7628
7629
#endif /* OPENSSL_EXTRA */
7630
7631
#ifdef WOLFSSL_HAVE_TLS_UNIQUE
7632
size_t wolfSSL_get_finished(const WOLFSSL *ssl, void *buf, size_t count)
7633
{
7634
    byte len = 0;
7635
    byte const * src;
7636
7637
    WOLFSSL_ENTER("wolfSSL_get_finished");
7638
7639
    if (!ssl || !buf) {
7640
        WOLFSSL_MSG("Bad parameter");
7641
        return WOLFSSL_FAILURE;
7642
    }
7643
7644
    if (ssl->options.side == WOLFSSL_SERVER_END) {
7645
        src = ssl->serverFinished;
7646
        len = ssl->serverFinished_len;
7647
    }
7648
    else {
7649
        src = ssl->clientFinished;
7650
        len = ssl->clientFinished_len;
7651
    }
7652
7653
    if (count < len) {
7654
        WOLFSSL_MSG("Buffer too small");
7655
        return WOLFSSL_FAILURE;
7656
    }
7657
7658
    XMEMCPY(buf, src, len);
7659
7660
    return len;
7661
}
7662
7663
size_t wolfSSL_get_peer_finished(const WOLFSSL *ssl, void *buf, size_t count)
7664
{
7665
    byte len = 0;
7666
    byte const * src;
7667
7668
    WOLFSSL_ENTER("wolfSSL_get_peer_finished");
7669
7670
    if (!ssl || !buf) {
7671
        WOLFSSL_MSG("Bad parameter");
7672
        return WOLFSSL_FAILURE;
7673
    }
7674
7675
    if (ssl->options.side == WOLFSSL_CLIENT_END) {
7676
        src = ssl->serverFinished;
7677
        len = ssl->serverFinished_len;
7678
    }
7679
    else {
7680
        src = ssl->clientFinished;
7681
        len = ssl->clientFinished_len;
7682
    }
7683
7684
    if (count < len) {
7685
        WOLFSSL_MSG("Buffer too small");
7686
        return WOLFSSL_FAILURE;
7687
    }
7688
7689
    XMEMCPY(buf, src, len);
7690
7691
    return len;
7692
}
7693
#endif /* WOLFSSL_HAVE_TLS_UNIQUE */
7694
7695
7696
#ifdef OPENSSL_EXTRA
7697
7698
#ifndef NO_WOLFSSL_STUB
7699
/* shows the number of accepts attempted by CTX in it's lifetime */
7700
long wolfSSL_CTX_sess_accept(WOLFSSL_CTX* ctx)
7701
{
7702
    WOLFSSL_STUB("wolfSSL_CTX_sess_accept");
7703
    (void)ctx;
7704
    return 0;
7705
}
7706
#endif
7707
7708
#ifndef NO_WOLFSSL_STUB
7709
/* shows the number of connects attempted CTX in it's lifetime */
7710
long wolfSSL_CTX_sess_connect(WOLFSSL_CTX* ctx)
7711
{
7712
    WOLFSSL_STUB("wolfSSL_CTX_sess_connect");
7713
    (void)ctx;
7714
    return 0;
7715
}
7716
#endif
7717
7718
7719
#ifndef NO_WOLFSSL_STUB
7720
/* shows the number of accepts completed by CTX in it's lifetime */
7721
long wolfSSL_CTX_sess_accept_good(WOLFSSL_CTX* ctx)
7722
{
7723
    WOLFSSL_STUB("wolfSSL_CTX_sess_accept_good");
7724
    (void)ctx;
7725
    return 0;
7726
}
7727
#endif
7728
7729
7730
#ifndef NO_WOLFSSL_STUB
7731
/* shows the number of connects completed by CTX in it's lifetime */
7732
long wolfSSL_CTX_sess_connect_good(WOLFSSL_CTX* ctx)
7733
{
7734
    WOLFSSL_STUB("wolfSSL_CTX_sess_connect_good");
7735
    (void)ctx;
7736
    return 0;
7737
}
7738
#endif
7739
7740
7741
#ifndef NO_WOLFSSL_STUB
7742
/* shows the number of renegotiation accepts attempted by CTX */
7743
long wolfSSL_CTX_sess_accept_renegotiate(WOLFSSL_CTX* ctx)
7744
{
7745
    WOLFSSL_STUB("wolfSSL_CTX_sess_accept_renegotiate");
7746
    (void)ctx;
7747
    return 0;
7748
}
7749
#endif
7750
7751
7752
#ifndef NO_WOLFSSL_STUB
7753
/* shows the number of renegotiation accepts attempted by CTX */
7754
long wolfSSL_CTX_sess_connect_renegotiate(WOLFSSL_CTX* ctx)
7755
{
7756
    WOLFSSL_STUB("wolfSSL_CTX_sess_connect_renegotiate");
7757
    (void)ctx;
7758
    return 0;
7759
}
7760
#endif
7761
7762
7763
#ifndef NO_WOLFSSL_STUB
7764
long wolfSSL_CTX_sess_hits(WOLFSSL_CTX* ctx)
7765
{
7766
    WOLFSSL_STUB("wolfSSL_CTX_sess_hits");
7767
    (void)ctx;
7768
    return 0;
7769
}
7770
#endif
7771
7772
7773
#ifndef NO_WOLFSSL_STUB
7774
long wolfSSL_CTX_sess_cb_hits(WOLFSSL_CTX* ctx)
7775
{
7776
    WOLFSSL_STUB("wolfSSL_CTX_sess_cb_hits");
7777
    (void)ctx;
7778
    return 0;
7779
}
7780
#endif
7781
7782
7783
#ifndef NO_WOLFSSL_STUB
7784
long wolfSSL_CTX_sess_cache_full(WOLFSSL_CTX* ctx)
7785
{
7786
    WOLFSSL_STUB("wolfSSL_CTX_sess_cache_full");
7787
    (void)ctx;
7788
    return 0;
7789
}
7790
#endif
7791
7792
7793
#ifndef NO_WOLFSSL_STUB
7794
long wolfSSL_CTX_sess_misses(WOLFSSL_CTX* ctx)
7795
{
7796
    WOLFSSL_STUB("wolfSSL_CTX_sess_misses");
7797
    (void)ctx;
7798
    return 0;
7799
}
7800
#endif
7801
7802
7803
#ifndef NO_WOLFSSL_STUB
7804
long wolfSSL_CTX_sess_timeouts(WOLFSSL_CTX* ctx)
7805
{
7806
    WOLFSSL_STUB("wolfSSL_CTX_sess_timeouts");
7807
    (void)ctx;
7808
    return 0;
7809
}
7810
#endif
7811
7812
#endif /* OPENSSL_EXTRA */
7813
7814
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_TLS_READ_AHEAD)
7815
int wolfSSL_get_read_ahead(const WOLFSSL* ssl)
7816
{
7817
    if (ssl == NULL) {
7818
        return WOLFSSL_FAILURE;
7819
    }
7820
7821
    return ssl->readAhead;
7822
}
7823
7824
7825
int wolfSSL_set_read_ahead(WOLFSSL* ssl, int v)
7826
{
7827
    if (ssl == NULL) {
7828
        return WOLFSSL_FAILURE;
7829
    }
7830
7831
    ssl->readAhead = (byte)v;
7832
7833
    return WOLFSSL_SUCCESS;
7834
}
7835
7836
7837
int wolfSSL_CTX_get_read_ahead(WOLFSSL_CTX* ctx)
7838
{
7839
    if (ctx == NULL) {
7840
        return WOLFSSL_FAILURE;
7841
    }
7842
7843
    return ctx->readAhead;
7844
}
7845
7846
7847
int wolfSSL_CTX_set_read_ahead(WOLFSSL_CTX* ctx, int v)
7848
{
7849
    if (ctx == NULL) {
7850
        return WOLFSSL_FAILURE;
7851
    }
7852
7853
    ctx->readAhead = (byte)v;
7854
7855
    return WOLFSSL_SUCCESS;
7856
}
7857
7858
/* Set the read-ahead receive window size. When read-ahead is enabled, a single
7859
 * recv() pulls in up to this many bytes:
7860
 *  - 0 (the default) requests one full record.
7861
 *  - A value larger than one record lets a single recv() coalesce several
7862
 *    back-to-back records.
7863
 *  - A value smaller than one record is honoured as-is, capping the receive
7864
 *    buffer's footprint when the peer's records are known to be small.
7865
 * 'len' is only a speculative window: a record larger than it is still received
7866
 * correctly, with the buffer grown on demand. Effective only when the library
7867
 * is built with read-ahead support (WOLFSSL_TLS_READ_AHEAD). Returns int rather
7868
 * than OpenSSL's void to match wolfSSL's other read-ahead setters; callers that
7869
 * ignore the return remain source-compatible. */
7870
int wolfSSL_CTX_set_default_read_buffer_len(WOLFSSL_CTX* ctx, size_t len)
7871
{
7872
    if (ctx == NULL) {
7873
        return WOLFSSL_FAILURE;
7874
    }
7875
7876
    /* 0 selects the default one-record window (matches OpenSSL, where 0 means
7877
     * "use the built-in default"). Otherwise clamp to a sane maximum so the
7878
     * stored window cannot overflow the signed arithmetic in the receive path
7879
     * (see WOLFSSL_MAX_READ_AHEAD_SZ). */
7880
    if (len == 0) {
7881
        len = WOLFSSL_READ_AHEAD_SZ;
7882
    }
7883
    else if (len > (size_t)WOLFSSL_MAX_READ_AHEAD_SZ) {
7884
        len = (size_t)WOLFSSL_MAX_READ_AHEAD_SZ;
7885
    }
7886
    ctx->readAheadSz = (word32)len;
7887
7888
    return WOLFSSL_SUCCESS;
7889
}
7890
7891
int wolfSSL_set_default_read_buffer_len(WOLFSSL* ssl, size_t len)
7892
{
7893
    if (ssl == NULL) {
7894
        return WOLFSSL_FAILURE;
7895
    }
7896
7897
    /* 0 selects the default one-record window (matches OpenSSL, where 0 means
7898
     * "use the built-in default"). Otherwise clamp to a sane maximum so the
7899
     * stored window cannot overflow the signed arithmetic in the receive path
7900
     * (see WOLFSSL_MAX_READ_AHEAD_SZ). */
7901
    if (len == 0) {
7902
        len = WOLFSSL_READ_AHEAD_SZ;
7903
    }
7904
    else if (len > (size_t)WOLFSSL_MAX_READ_AHEAD_SZ) {
7905
        len = (size_t)WOLFSSL_MAX_READ_AHEAD_SZ;
7906
    }
7907
    ssl->readAheadSz = (word32)len;
7908
7909
    return WOLFSSL_SUCCESS;
7910
}
7911
7912
long wolfSSL_CTX_get_default_read_buffer_len(WOLFSSL_CTX* ctx)
7913
{
7914
    if (ctx == NULL) {
7915
        return WOLFSSL_FAILURE;
7916
    }
7917
7918
    return (long)ctx->readAheadSz;
7919
}
7920
7921
long wolfSSL_get_default_read_buffer_len(const WOLFSSL* ssl)
7922
{
7923
    if (ssl == NULL) {
7924
        return WOLFSSL_FAILURE;
7925
    }
7926
7927
    return (long)ssl->readAheadSz;
7928
}
7929
#endif /* OPENSSL_EXTRA || WOLFSSL_TLS_READ_AHEAD */
7930
7931
#ifdef OPENSSL_EXTRA
7932
long wolfSSL_CTX_set_tlsext_opaque_prf_input_callback_arg(WOLFSSL_CTX* ctx,
7933
        void* arg)
7934
{
7935
    if (ctx == NULL) {
7936
        return WOLFSSL_FAILURE;
7937
    }
7938
7939
    ctx->userPRFArg = arg;
7940
    return WOLFSSL_SUCCESS;
7941
}
7942
7943
#endif /* OPENSSL_EXTRA */
7944
7945
7946
7947
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
7948
/* Free the dynamically allocated data.
7949
 *
7950
 * p  Pointer to dynamically allocated memory.
7951
 */
7952
void wolfSSL_OPENSSL_free(void* p)
7953
{
7954
    WOLFSSL_MSG("wolfSSL_OPENSSL_free");
7955
7956
    XFREE(p, NULL, DYNAMIC_TYPE_OPENSSL);
7957
}
7958
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
7959
7960
#ifdef OPENSSL_EXTRA
7961
7962
void *wolfSSL_OPENSSL_malloc(size_t a)
7963
{
7964
    return (void *)XMALLOC(a, NULL, DYNAMIC_TYPE_OPENSSL);
7965
}
7966
7967
int wolfSSL_OPENSSL_hexchar2int(unsigned char c)
7968
{
7969
    /* 'char' is unsigned on some platforms. */
7970
    return (int)(signed char)HexCharToByte((char)c);
7971
}
7972
7973
unsigned char *wolfSSL_OPENSSL_hexstr2buf(const char *str, long *len)
7974
{
7975
    unsigned char* targetBuf;
7976
    int srcDigitHigh = 0;
7977
    int srcDigitLow = 0;
7978
    size_t srcLen;
7979
    size_t srcIdx = 0;
7980
    long targetIdx = 0;
7981
7982
    srcLen = XSTRLEN(str);
7983
    targetBuf = (unsigned char*)XMALLOC(srcLen / 2, NULL, DYNAMIC_TYPE_OPENSSL);
7984
    if (targetBuf == NULL) {
7985
        return NULL;
7986
    }
7987
7988
    while (srcIdx < srcLen) {
7989
        if (str[srcIdx] == ':') {
7990
            srcIdx++;
7991
            continue;
7992
        }
7993
7994
        srcDigitHigh = wolfSSL_OPENSSL_hexchar2int((unsigned char)str[srcIdx++]);
7995
        srcDigitLow = wolfSSL_OPENSSL_hexchar2int((unsigned char)str[srcIdx++]);
7996
        if (srcDigitHigh < 0 || srcDigitLow < 0) {
7997
            WOLFSSL_MSG("Invalid hex character.");
7998
            XFREE(targetBuf, NULL, DYNAMIC_TYPE_OPENSSL);
7999
            return NULL;
8000
        }
8001
8002
        targetBuf[targetIdx++] = (unsigned char)((srcDigitHigh << 4) |
8003
                                                  srcDigitLow       );
8004
    }
8005
8006
    if (len != NULL)
8007
        *len = targetIdx;
8008
8009
    return targetBuf;
8010
}
8011
8012
int wolfSSL_OPENSSL_init_ssl(word64 opts, const WOLFSSL_INIT_SETTINGS *settings)
8013
{
8014
    (void)opts;
8015
    (void)settings;
8016
    return wolfSSL_library_init();
8017
}
8018
8019
int wolfSSL_OPENSSL_init_crypto(word64 opts,
8020
    const WOLFSSL_INIT_SETTINGS* settings)
8021
{
8022
    (void)opts;
8023
    (void)settings;
8024
    return wolfSSL_library_init();
8025
}
8026
8027
#endif /* OPENSSL_EXTRA */
8028
8029
8030
#ifdef HAVE_FUZZER
8031
void wolfSSL_SetFuzzerCb(WOLFSSL* ssl, CallbackFuzzer cbf, void* fCtx)
8032
{
8033
    if (ssl) {
8034
        ssl->fuzzerCb  = cbf;
8035
        ssl->fuzzerCtx = fCtx;
8036
    }
8037
}
8038
#endif
8039
8040
8041
#ifdef WOLFSSL_HAVE_WOLFSCEP
8042
    /* Used by autoconf to see if wolfSCEP is available */
8043
    void wolfSSL_wolfSCEP(void) {}
8044
#endif
8045
8046
8047
#ifdef WOLFSSL_HAVE_CERT_SERVICE
8048
    /* Used by autoconf to see if cert service is available */
8049
    void wolfSSL_cert_service(void) {}
8050
#endif
8051
8052
#if defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) || \
8053
    defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(HAVE_STUNNEL) || \
8054
    defined(WOLFSSL_NGINX) || defined(HAVE_POCO_LIB) || \
8055
    defined(WOLFSSL_HAPROXY)
8056
8057
    void wolfSSL_set_verify_depth(WOLFSSL *ssl, int depth)
8058
    {
8059
    #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
8060
        WOLFSSL_ENTER("wolfSSL_set_verify_depth");
8061
        /* Reject out-of-range depths; valid range is 0 to MAX_CHAIN_DEPTH. */
8062
        if ((ssl == NULL) || (depth < 0) || (depth > MAX_CHAIN_DEPTH)) {
8063
            WOLFSSL_MSG("Bad depth argument, too large or less than 0");
8064
        }
8065
        else {
8066
            ssl->options.verifyDepth = (byte)depth;
8067
        }
8068
    #endif
8069
    }
8070
8071
#endif /* OPENSSL_ALL || HAVE_LIGHTY || WOLFSSL_MYSQL_COMPATIBLE ||
8072
    HAVE_STUNNEL || WOLFSSL_NGINX || HAVE_POCO_LIB || WOLFSSL_HAPROXY */
8073
8074
#ifdef OPENSSL_EXTRA
8075
8076
/* wolfSSL uses negative values for error states. This function returns an
8077
 * unsigned type so the value returned is the absolute value of the error.
8078
 */
8079
8080
#endif /* OPENSSL_EXTRA */
8081
8082
#ifdef HAVE_EX_DATA_CRYPTO
8083
CRYPTO_EX_cb_ctx* crypto_ex_cb_ctx_session = NULL;
8084
8085
static int crypto_ex_cb_new(CRYPTO_EX_cb_ctx** dst, long ctx_l, void* ctx_ptr,
8086
        WOLFSSL_CRYPTO_EX_new* new_func, WOLFSSL_CRYPTO_EX_dup* dup_func,
8087
        WOLFSSL_CRYPTO_EX_free* free_func)
8088
{
8089
    CRYPTO_EX_cb_ctx* new_ctx = (CRYPTO_EX_cb_ctx*)XMALLOC(
8090
            sizeof(CRYPTO_EX_cb_ctx), NULL, DYNAMIC_TYPE_OPENSSL);
8091
    if (new_ctx == NULL)
8092
        return WOLFSSL_FATAL_ERROR;
8093
    new_ctx->ctx_l = ctx_l;
8094
    new_ctx->ctx_ptr = ctx_ptr;
8095
    new_ctx->new_func = new_func;
8096
    new_ctx->free_func = free_func;
8097
    new_ctx->dup_func = dup_func;
8098
    new_ctx->next = NULL;
8099
    /* Push to end of list */
8100
    while (*dst != NULL)
8101
        dst = &(*dst)->next;
8102
    *dst = new_ctx;
8103
    return 0;
8104
}
8105
8106
void crypto_ex_cb_free(CRYPTO_EX_cb_ctx* cb_ctx)
8107
{
8108
    while (cb_ctx != NULL) {
8109
        CRYPTO_EX_cb_ctx* next = cb_ctx->next;
8110
        XFREE(cb_ctx, NULL, DYNAMIC_TYPE_OPENSSL);
8111
        cb_ctx = next;
8112
    }
8113
}
8114
8115
void crypto_ex_cb_setup_new_data(void *new_obj, CRYPTO_EX_cb_ctx* cb_ctx,
8116
        WOLFSSL_CRYPTO_EX_DATA* ex_data)
8117
{
8118
    int idx = 0;
8119
    for (; cb_ctx != NULL; idx++, cb_ctx = cb_ctx->next) {
8120
        if (cb_ctx->new_func != NULL)
8121
            cb_ctx->new_func(new_obj, NULL, ex_data, idx, cb_ctx->ctx_l,
8122
                    cb_ctx->ctx_ptr);
8123
    }
8124
}
8125
8126
int crypto_ex_cb_dup_data(const WOLFSSL_CRYPTO_EX_DATA *in,
8127
        WOLFSSL_CRYPTO_EX_DATA *out, CRYPTO_EX_cb_ctx* cb_ctx)
8128
{
8129
    int idx = 0;
8130
    for (; cb_ctx != NULL; idx++, cb_ctx = cb_ctx->next) {
8131
        if (cb_ctx->dup_func != NULL) {
8132
            void* ptr = wolfSSL_CRYPTO_get_ex_data(in, idx);
8133
            if (!cb_ctx->dup_func(out, in,
8134
                    &ptr, idx,
8135
                    cb_ctx->ctx_l, cb_ctx->ctx_ptr)) {
8136
                return WOLFSSL_FAILURE;
8137
            }
8138
            wolfSSL_CRYPTO_set_ex_data(out, idx, ptr);
8139
        }
8140
    }
8141
    return WOLFSSL_SUCCESS;
8142
}
8143
8144
void crypto_ex_cb_free_data(void *obj, CRYPTO_EX_cb_ctx* cb_ctx,
8145
        WOLFSSL_CRYPTO_EX_DATA* ex_data)
8146
{
8147
    int idx = 0;
8148
    for (; cb_ctx != NULL; idx++, cb_ctx = cb_ctx->next) {
8149
        if (cb_ctx->free_func != NULL)
8150
            cb_ctx->free_func(obj, NULL, ex_data, idx, cb_ctx->ctx_l,
8151
                    cb_ctx->ctx_ptr);
8152
    }
8153
}
8154
8155
/**
8156
 * wolfssl_local_get_ex_new_index is a helper function for the following
8157
 * xx_get_ex_new_index functions:
8158
 *  - wolfSSL_CRYPTO_get_ex_new_index
8159
 *  - wolfSSL_CTX_get_ex_new_index
8160
 *  - wolfSSL_get_ex_new_index
8161
 * Issues a unique index number for the specified class-index.
8162
 * Returns an index number greater or equal to zero on success,
8163
 * -1 on failure.
8164
 */
8165
int wolfssl_local_get_ex_new_index(int class_index, long ctx_l, void* ctx_ptr,
8166
        WOLFSSL_CRYPTO_EX_new* new_func, WOLFSSL_CRYPTO_EX_dup* dup_func,
8167
        WOLFSSL_CRYPTO_EX_free* free_func)
8168
{
8169
    /* index counter for each class index*/
8170
    static int ctx_idx = 0;
8171
    static int ssl_idx = 0;
8172
    static int ssl_session_idx = 0;
8173
    static int x509_idx = 0;
8174
8175
    int idx = -1;
8176
8177
    switch(class_index) {
8178
        case WOLF_CRYPTO_EX_INDEX_SSL:
8179
            WOLFSSL_CRYPTO_EX_DATA_IGNORE_PARAMS(ctx_l, ctx_ptr, new_func,
8180
                    dup_func, free_func);
8181
            idx = ssl_idx++;
8182
            break;
8183
        case WOLF_CRYPTO_EX_INDEX_SSL_CTX:
8184
            WOLFSSL_CRYPTO_EX_DATA_IGNORE_PARAMS(ctx_l, ctx_ptr, new_func,
8185
                    dup_func, free_func);
8186
            idx = ctx_idx++;
8187
            break;
8188
        case WOLF_CRYPTO_EX_INDEX_X509:
8189
            WOLFSSL_CRYPTO_EX_DATA_IGNORE_PARAMS(ctx_l, ctx_ptr, new_func,
8190
                    dup_func, free_func);
8191
            idx = x509_idx++;
8192
            break;
8193
        case WOLF_CRYPTO_EX_INDEX_SSL_SESSION:
8194
            if (crypto_ex_cb_new(&crypto_ex_cb_ctx_session, ctx_l, ctx_ptr,
8195
                    new_func, dup_func, free_func) != 0)
8196
                return WOLFSSL_FATAL_ERROR;
8197
            idx = ssl_session_idx++;
8198
            break;
8199
        /* following class indexes are not supoprted */
8200
        case WOLF_CRYPTO_EX_INDEX_X509_STORE:
8201
        case WOLF_CRYPTO_EX_INDEX_X509_STORE_CTX:
8202
        case WOLF_CRYPTO_EX_INDEX_DH:
8203
        case WOLF_CRYPTO_EX_INDEX_DSA:
8204
        case WOLF_CRYPTO_EX_INDEX_EC_KEY:
8205
        case WOLF_CRYPTO_EX_INDEX_RSA:
8206
        case WOLF_CRYPTO_EX_INDEX_ENGINE:
8207
        case WOLF_CRYPTO_EX_INDEX_UI:
8208
        case WOLF_CRYPTO_EX_INDEX_BIO:
8209
        case WOLF_CRYPTO_EX_INDEX_APP:
8210
        case WOLF_CRYPTO_EX_INDEX_UI_METHOD:
8211
        case WOLF_CRYPTO_EX_INDEX_DRBG:
8212
        default:
8213
            break;
8214
    }
8215
    if (idx >= MAX_EX_DATA)
8216
        return WOLFSSL_FATAL_ERROR;
8217
    return idx;
8218
}
8219
#endif /* HAVE_EX_DATA_CRYPTO */
8220
8221
#ifdef HAVE_EX_DATA_CRYPTO
8222
int wolfSSL_CTX_get_ex_new_index(long idx, void* arg,
8223
                                 WOLFSSL_CRYPTO_EX_new* new_func,
8224
                                 WOLFSSL_CRYPTO_EX_dup* dup_func,
8225
                                 WOLFSSL_CRYPTO_EX_free* free_func)
8226
{
8227
8228
    WOLFSSL_ENTER("wolfSSL_CTX_get_ex_new_index");
8229
8230
    return wolfssl_local_get_ex_new_index(WOLF_CRYPTO_EX_INDEX_SSL_CTX, idx,
8231
                                    arg, new_func, dup_func, free_func);
8232
}
8233
8234
/* Return the index that can be used for the WOLFSSL structure to store
8235
 * application data.
8236
 *
8237
 */
8238
int wolfSSL_get_ex_new_index(long argValue, void* arg,
8239
        WOLFSSL_CRYPTO_EX_new* cb1, WOLFSSL_CRYPTO_EX_dup* cb2,
8240
        WOLFSSL_CRYPTO_EX_free* cb3)
8241
{
8242
    WOLFSSL_ENTER("wolfSSL_get_ex_new_index");
8243
8244
    return wolfssl_local_get_ex_new_index(WOLF_CRYPTO_EX_INDEX_SSL, argValue,
8245
            arg, cb1, cb2, cb3);
8246
}
8247
#endif /* HAVE_EX_DATA_CRYPTO */
8248
8249
#ifdef OPENSSL_EXTRA
8250
void* wolfSSL_CTX_get_ex_data(const WOLFSSL_CTX* ctx, int idx)
8251
{
8252
    WOLFSSL_ENTER("wolfSSL_CTX_get_ex_data");
8253
#ifdef HAVE_EX_DATA
8254
    if (ctx != NULL) {
8255
        return wolfSSL_CRYPTO_get_ex_data(&ctx->ex_data, idx);
8256
    }
8257
#else
8258
    (void)ctx;
8259
    (void)idx;
8260
#endif
8261
    return NULL;
8262
}
8263
8264
int wolfSSL_CTX_set_ex_data(WOLFSSL_CTX* ctx, int idx, void* data)
8265
{
8266
    WOLFSSL_ENTER("wolfSSL_CTX_set_ex_data");
8267
#ifdef HAVE_EX_DATA
8268
    if (ctx != NULL) {
8269
        return wolfSSL_CRYPTO_set_ex_data(&ctx->ex_data, idx, data);
8270
    }
8271
#else
8272
    (void)ctx;
8273
    (void)idx;
8274
    (void)data;
8275
#endif
8276
    return WOLFSSL_FAILURE;
8277
}
8278
8279
#ifdef HAVE_EX_DATA_CLEANUP_HOOKS
8280
int wolfSSL_CTX_set_ex_data_with_cleanup(
8281
    WOLFSSL_CTX* ctx,
8282
    int idx,
8283
    void* data,
8284
    wolfSSL_ex_data_cleanup_routine_t cleanup_routine)
8285
{
8286
    WOLFSSL_ENTER("wolfSSL_CTX_set_ex_data_with_cleanup");
8287
    if (ctx != NULL) {
8288
        return wolfSSL_CRYPTO_set_ex_data_with_cleanup(&ctx->ex_data, idx, data,
8289
                                                       cleanup_routine);
8290
    }
8291
    return WOLFSSL_FAILURE;
8292
}
8293
#endif /* HAVE_EX_DATA_CLEANUP_HOOKS */
8294
#endif /* OPENSSL_EXTRA */
8295
8296
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
8297
8298
/* Returns char* to app data stored in ex[0].
8299
 *
8300
 * ssl WOLFSSL structure to get app data from
8301
 */
8302
void* wolfSSL_get_app_data(const WOLFSSL *ssl)
8303
{
8304
    /* checkout exdata stuff... */
8305
    WOLFSSL_ENTER("wolfSSL_get_app_data");
8306
8307
    return wolfSSL_get_ex_data(ssl, 0);
8308
}
8309
8310
8311
/* Set ex array 0 to have app data
8312
 *
8313
 * ssl WOLFSSL struct to set app data in
8314
 * arg data to be stored
8315
 *
8316
 * Returns WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on failure
8317
 */
8318
int wolfSSL_set_app_data(WOLFSSL *ssl, void* arg) {
8319
    WOLFSSL_ENTER("wolfSSL_set_app_data");
8320
8321
    return wolfSSL_set_ex_data(ssl, 0, arg);
8322
}
8323
8324
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
8325
8326
int wolfSSL_set_ex_data(WOLFSSL* ssl, int idx, void* data)
8327
0
{
8328
0
    WOLFSSL_ENTER("wolfSSL_set_ex_data");
8329
#ifdef HAVE_EX_DATA
8330
    if (ssl != NULL) {
8331
        return wolfSSL_CRYPTO_set_ex_data(&ssl->ex_data, idx, data);
8332
    }
8333
#else
8334
0
    WOLFSSL_MSG("HAVE_EX_DATA macro is not defined");
8335
0
    (void)ssl;
8336
0
    (void)idx;
8337
0
    (void)data;
8338
0
#endif
8339
0
    return WOLFSSL_FAILURE;
8340
0
}
8341
8342
#ifdef HAVE_EX_DATA_CLEANUP_HOOKS
8343
int wolfSSL_set_ex_data_with_cleanup(
8344
    WOLFSSL* ssl,
8345
    int idx,
8346
    void* data,
8347
    wolfSSL_ex_data_cleanup_routine_t cleanup_routine)
8348
{
8349
    WOLFSSL_ENTER("wolfSSL_set_ex_data_with_cleanup");
8350
    if (ssl != NULL)
8351
    {
8352
        return wolfSSL_CRYPTO_set_ex_data_with_cleanup(&ssl->ex_data, idx, data,
8353
                                                       cleanup_routine);
8354
    }
8355
    return WOLFSSL_FAILURE;
8356
}
8357
#endif /* HAVE_EX_DATA_CLEANUP_HOOKS */
8358
8359
void* wolfSSL_get_ex_data(const WOLFSSL* ssl, int idx)
8360
0
{
8361
0
    WOLFSSL_ENTER("wolfSSL_get_ex_data");
8362
#ifdef HAVE_EX_DATA
8363
    if (ssl != NULL) {
8364
        return wolfSSL_CRYPTO_get_ex_data(&ssl->ex_data, idx);
8365
    }
8366
#else
8367
0
    WOLFSSL_MSG("HAVE_EX_DATA macro is not defined");
8368
0
    (void)ssl;
8369
0
    (void)idx;
8370
0
#endif
8371
0
    return 0;
8372
0
}
8373
8374
#if defined(HAVE_LIGHTY) || defined(HAVE_STUNNEL) \
8375
    || defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(OPENSSL_EXTRA)
8376
8377
#ifdef WOLFSSL_TLS_ST_OK
8378
/* The OpenSSL compat TLS_ST_OK/SSL_ST_OK constants (wolfssl/openssl/ssl.h)
8379
 * duplicate HANDSHAKE_DONE from the internal 'enum states' returned below;
8380
 * fail the build if the enum ever drifts. */
8381
wc_static_assert(WOLFSSL_TLS_ST_OK == HANDSHAKE_DONE);
8382
#endif
8383
8384
/* returns the enum value associated with handshake state
8385
 *
8386
 * ssl the WOLFSSL structure to get state of
8387
 */
8388
int wolfSSL_get_state(const WOLFSSL* ssl)
8389
{
8390
    WOLFSSL_ENTER("wolfSSL_get_state");
8391
8392
    if (ssl == NULL) {
8393
        WOLFSSL_MSG("Null argument passed in");
8394
        return WOLFSSL_FAILURE;
8395
    }
8396
8397
    return ssl->options.handShakeState;
8398
}
8399
#endif /* HAVE_LIGHTY || HAVE_STUNNEL || WOLFSSL_MYSQL_COMPATIBLE */
8400
8401
#ifdef OPENSSL_EXTRA
8402
void wolfSSL_certs_clear(WOLFSSL* ssl)
8403
{
8404
    WOLFSSL_ENTER("wolfSSL_certs_clear");
8405
8406
    if (ssl == NULL)
8407
        return;
8408
8409
    /* ctx still owns certificate, certChain, key, dh, and cm */
8410
    if (ssl->buffers.weOwnCert) {
8411
        FreeDer(&ssl->buffers.certificate);
8412
        ssl->buffers.weOwnCert = 0;
8413
    }
8414
    ssl->buffers.certificate = NULL;
8415
    if (ssl->buffers.weOwnCertChain) {
8416
        FreeDer(&ssl->buffers.certChain);
8417
        ssl->buffers.weOwnCertChain = 0;
8418
    }
8419
    ssl->buffers.certChain = NULL;
8420
#ifdef WOLFSSL_TLS13
8421
    ssl->buffers.certChainCnt = 0;
8422
#endif
8423
    if (ssl->buffers.weOwnKey) {
8424
        FreeDer(&ssl->buffers.key);
8425
    #ifdef WOLFSSL_BLIND_PRIVATE_KEY
8426
        FreeDer(&ssl->buffers.keyMask);
8427
    #endif
8428
        ssl->buffers.weOwnKey = 0;
8429
    }
8430
    ssl->buffers.key      = NULL;
8431
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
8432
    ssl->buffers.keyMask  = NULL;
8433
#endif
8434
    ssl->buffers.keyType  = 0;
8435
    ssl->buffers.keyId    = 0;
8436
    ssl->buffers.keyLabel = 0;
8437
    ssl->buffers.keySz    = 0;
8438
    ssl->buffers.keyDevId = 0;
8439
#ifdef WOLFSSL_DUAL_ALG_CERTS
8440
    if (ssl->buffers.weOwnAltKey) {
8441
        FreeDer(&ssl->buffers.altKey);
8442
    #ifdef WOLFSSL_BLIND_PRIVATE_KEY
8443
        FreeDer(&ssl->buffers.altKeyMask);
8444
    #endif
8445
        ssl->buffers.weOwnAltKey = 0;
8446
    }
8447
    ssl->buffers.altKey     = NULL;
8448
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
8449
    ssl->buffers.altKeyMask = NULL;
8450
#endif
8451
#endif /* WOLFSSL_DUAL_ALG_CERTS */
8452
}
8453
#endif
8454
8455
#if defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || defined(WOLFSSL_HAPROXY) \
8456
    || defined(WOLFSSL_NGINX) || defined(WOLFSSL_QT)
8457
8458
long wolfSSL_ctrl(WOLFSSL* ssl, int cmd, long opt, void* pt)
8459
{
8460
    WOLFSSL_ENTER("wolfSSL_ctrl");
8461
    if (ssl == NULL)
8462
        return BAD_FUNC_ARG;
8463
8464
    switch (cmd) {
8465
        #if defined(WOLFSSL_NGINX) || defined(WOLFSSL_QT) || \
8466
            defined(OPENSSL_ALL)
8467
        #ifdef HAVE_SNI
8468
        case SSL_CTRL_SET_TLSEXT_HOSTNAME:
8469
            WOLFSSL_MSG("Entering Case: SSL_CTRL_SET_TLSEXT_HOSTNAME.");
8470
            if (pt == NULL) {
8471
                WOLFSSL_MSG("Passed in NULL Host Name.");
8472
                break;
8473
            }
8474
            return wolfSSL_set_tlsext_host_name(ssl, (const char*) pt);
8475
        #endif /* HAVE_SNI */
8476
        #endif /* WOLFSSL_NGINX || WOLFSSL_QT || OPENSSL_ALL */
8477
        default:
8478
            WOLFSSL_MSG("Case not implemented.");
8479
    }
8480
    (void)opt;
8481
    (void)pt;
8482
    return WOLFSSL_FAILURE;
8483
}
8484
8485
long wolfSSL_CTX_ctrl(WOLFSSL_CTX* ctx, int cmd, long opt, void* pt)
8486
{
8487
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
8488
    long ctrl_opt;
8489
#endif
8490
    long ret = WOLFSSL_SUCCESS;
8491
8492
    WOLFSSL_ENTER("wolfSSL_CTX_ctrl");
8493
    if (ctx == NULL)
8494
        return WOLFSSL_FAILURE;
8495
8496
    switch (cmd) {
8497
    case SSL_CTRL_CHAIN:
8498
#ifdef SESSION_CERTS
8499
    {
8500
        /*
8501
         * We don't care about opt here because a copy of the certificate is
8502
         * stored anyway so increasing the reference counter is not necessary.
8503
         * Just check to make sure that it is set to one of the correct values.
8504
         */
8505
        WOLF_STACK_OF(WOLFSSL_X509)* sk = (WOLF_STACK_OF(WOLFSSL_X509)*) pt;
8506
        WOLFSSL_X509* x509;
8507
        int i;
8508
        if (opt != 0 && opt != 1) {
8509
            ret = WOLFSSL_FAILURE;
8510
            break;
8511
        }
8512
        /* Clear certificate chain */
8513
        FreeDer(&ctx->certChain);
8514
        if (sk) {
8515
            for (i = 0; i < wolfSSL_sk_X509_num(sk); i++) {
8516
                x509 = wolfSSL_sk_X509_value(sk, i);
8517
                /* Prevent wolfSSL_CTX_add_extra_chain_cert from freeing cert */
8518
                if (wolfSSL_X509_up_ref(x509) != 1) {
8519
                    WOLFSSL_MSG("Error increasing reference count");
8520
                    continue;
8521
                }
8522
                if (wolfSSL_CTX_add_extra_chain_cert(ctx, x509) !=
8523
                        WOLFSSL_SUCCESS) {
8524
                    WOLFSSL_MSG("Error adding certificate to context");
8525
                    /* Decrease reference count on failure */
8526
                    wolfSSL_X509_free(x509);
8527
                    x509 = NULL;
8528
                }
8529
            }
8530
        }
8531
        /* Free previous chain */
8532
        wolfSSL_sk_X509_pop_free(ctx->x509Chain, NULL);
8533
        ctx->x509Chain = sk;
8534
        if (sk && opt == 1) {
8535
            /* up all refs when opt == 1 */
8536
            for (i = 0; i < wolfSSL_sk_X509_num(sk); i++) {
8537
                x509 = wolfSSL_sk_X509_value(sk, i);
8538
                if (wolfSSL_X509_up_ref(x509) != 1) {
8539
                    WOLFSSL_MSG("Error increasing reference count");
8540
                    continue;
8541
                }
8542
            }
8543
        }
8544
    }
8545
#else
8546
        WOLFSSL_MSG("Session certificates not compiled in");
8547
        ret = WOLFSSL_FAILURE;
8548
#endif
8549
        break;
8550
8551
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
8552
    case SSL_CTRL_OPTIONS:
8553
        WOLFSSL_MSG("Entering Case: SSL_CTRL_OPTIONS.");
8554
        ctrl_opt = wolfSSL_CTX_set_options(ctx, opt);
8555
8556
        #ifdef WOLFSSL_QT
8557
        /* Set whether to use client or server cipher preference */
8558
        if ((ctrl_opt & WOLFSSL_OP_CIPHER_SERVER_PREFERENCE)
8559
                     == WOLFSSL_OP_CIPHER_SERVER_PREFERENCE) {
8560
            WOLFSSL_MSG("Using Server's Cipher Preference.");
8561
            ctx->useClientOrder = 0;
8562
        } else {
8563
            WOLFSSL_MSG("Using Client's Cipher Preference.");
8564
            ctx->useClientOrder = 1;
8565
        }
8566
        #endif /* WOLFSSL_QT */
8567
8568
        return ctrl_opt;
8569
#endif /* OPENSSL_EXTRA || HAVE_WEBSERVER */
8570
    case SSL_CTRL_EXTRA_CHAIN_CERT:
8571
        WOLFSSL_MSG("Entering Case: SSL_CTRL_EXTRA_CHAIN_CERT.");
8572
        if (pt == NULL) {
8573
            WOLFSSL_MSG("Passed in x509 pointer NULL.");
8574
            ret = WOLFSSL_FAILURE;
8575
            break;
8576
        }
8577
        return wolfSSL_CTX_add_extra_chain_cert(ctx, (WOLFSSL_X509*)pt);
8578
8579
#ifndef NO_DH
8580
    case SSL_CTRL_SET_TMP_DH:
8581
        WOLFSSL_MSG("Entering Case: SSL_CTRL_SET_TMP_DH.");
8582
        if (pt == NULL) {
8583
            WOLFSSL_MSG("Passed in DH pointer NULL.");
8584
            ret = WOLFSSL_FAILURE;
8585
            break;
8586
        }
8587
        return wolfSSL_CTX_set_tmp_dh(ctx, (WOLFSSL_DH*)pt);
8588
#endif
8589
8590
#ifdef HAVE_ECC
8591
    case SSL_CTRL_SET_TMP_ECDH:
8592
        WOLFSSL_MSG("Entering Case: SSL_CTRL_SET_TMP_ECDH.");
8593
        if (pt == NULL) {
8594
            WOLFSSL_MSG("Passed in ECDH pointer NULL.");
8595
            ret = WOLFSSL_FAILURE;
8596
            break;
8597
        }
8598
        return wolfSSL_SSL_CTX_set_tmp_ecdh(ctx, (WOLFSSL_EC_KEY*)pt);
8599
#endif
8600
    case SSL_CTRL_MODE:
8601
        wolfSSL_CTX_set_mode(ctx,opt);
8602
        break;
8603
    case SSL_CTRL_SET_MIN_PROTO_VERSION:
8604
        WOLFSSL_MSG("set min proto version");
8605
        return wolfSSL_CTX_set_min_proto_version(ctx, (int)opt);
8606
    case SSL_CTRL_SET_MAX_PROTO_VERSION:
8607
        WOLFSSL_MSG("set max proto version");
8608
        return wolfSSL_CTX_set_max_proto_version(ctx, (int)opt);
8609
    case SSL_CTRL_GET_MIN_PROTO_VERSION:
8610
        WOLFSSL_MSG("get min proto version");
8611
        return wolfSSL_CTX_get_min_proto_version(ctx);
8612
    case SSL_CTRL_GET_MAX_PROTO_VERSION:
8613
        WOLFSSL_MSG("get max proto version");
8614
        return wolfSSL_CTX_get_max_proto_version(ctx);
8615
    default:
8616
        WOLFSSL_MSG("CTX_ctrl cmd not implemented");
8617
        ret = WOLFSSL_FAILURE;
8618
        break;
8619
    }
8620
8621
    (void)ctx;
8622
    (void)cmd;
8623
    (void)opt;
8624
    (void)pt;
8625
    WOLFSSL_LEAVE("wolfSSL_CTX_ctrl", (int)ret);
8626
    return ret;
8627
}
8628
8629
#ifndef NO_WOLFSSL_STUB
8630
long wolfSSL_CTX_callback_ctrl(WOLFSSL_CTX* ctx, int cmd, void (*fp)(void))
8631
{
8632
    (void) ctx;
8633
    (void) cmd;
8634
    (void) fp;
8635
    WOLFSSL_STUB("wolfSSL_CTX_callback_ctrl");
8636
    return WOLFSSL_FAILURE;
8637
8638
}
8639
#endif /* NO_WOLFSSL_STUB */
8640
8641
8642
#endif /* OPENSSL_ALL || WOLFSSL_ASIO || WOLFSSL_HAPROXY || WOLFSSL_QT */
8643
8644
8645
/* stunnel compatibility functions*/
8646
#if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && \
8647
    (defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \
8648
     defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \
8649
     defined(WOLFSSL_OPENSSH)))
8650
8651
#ifndef NO_FILESYSTEM
8652
/***TBD ***/
8653
void wolfSSL_print_all_errors_fp(XFILE fp)
8654
{
8655
    (void)fp;
8656
}
8657
#endif /* !NO_FILESYSTEM */
8658
8659
#endif /* OPENSSL_ALL || OPENSSL_EXTRA || HAVE_STUNNEL || WOLFSSL_NGINX ||
8660
    HAVE_LIGHTY || WOLFSSL_HAPROXY || WOLFSSL_OPENSSH */
8661
8662
/* Note: This is a huge section of API's - through
8663
 *       wolfSSL_X509_OBJECT_get0_X509_CRL */
8664
#if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA)
8665
8666
#if defined(USE_WOLFSSL_MEMORY) && !defined(WOLFSSL_DEBUG_MEMORY) && \
8667
    !defined(WOLFSSL_STATIC_MEMORY)
8668
static wolfSSL_OSSL_Malloc_cb  ossl_malloc  = NULL;
8669
static wolfSSL_OSSL_Free_cb    ossl_free    = NULL;
8670
static wolfSSL_OSSL_Realloc_cb ossl_realloc = NULL;
8671
8672
static void* OSSL_Malloc(size_t size)
8673
{
8674
    if (ossl_malloc != NULL)
8675
        return ossl_malloc(size, NULL, 0);
8676
    else
8677
        return NULL;
8678
}
8679
8680
static void  OSSL_Free(void *ptr)
8681
{
8682
    if (ossl_free != NULL)
8683
        ossl_free(ptr, NULL, 0);
8684
}
8685
8686
static void* OSSL_Realloc(void *ptr, size_t size)
8687
{
8688
    if (ossl_realloc != NULL)
8689
        return ossl_realloc(ptr, size, NULL, 0);
8690
    else
8691
        return NULL;
8692
}
8693
#endif /* USE_WOLFSSL_MEMORY && !WOLFSSL_DEBUG_MEMORY &&
8694
        * !WOLFSSL_STATIC_MEMORY */
8695
8696
int wolfSSL_CRYPTO_set_mem_functions(
8697
        wolfSSL_OSSL_Malloc_cb  m,
8698
        wolfSSL_OSSL_Realloc_cb r,
8699
        wolfSSL_OSSL_Free_cb    f)
8700
{
8701
#if defined(USE_WOLFSSL_MEMORY) && !defined(WOLFSSL_STATIC_MEMORY)
8702
#ifdef WOLFSSL_DEBUG_MEMORY
8703
    WOLFSSL_MSG("mem functions will receive function name instead of "
8704
                "file name");
8705
    if (wolfSSL_SetAllocators((wolfSSL_Malloc_cb)m, (wolfSSL_Free_cb)f,
8706
            (wolfSSL_Realloc_cb)r) == 0)
8707
        return WOLFSSL_SUCCESS;
8708
#else
8709
    WOLFSSL_MSG("wolfSSL was compiled without WOLFSSL_DEBUG_MEMORY mem "
8710
                "functions will receive a NULL file name and 0 for the "
8711
                "line number.");
8712
    if (wolfSSL_SetAllocators((wolfSSL_Malloc_cb)OSSL_Malloc,
8713
           (wolfSSL_Free_cb)OSSL_Free, (wolfSSL_Realloc_cb)OSSL_Realloc) == 0) {
8714
        ossl_malloc = m;
8715
        ossl_free = f;
8716
        ossl_realloc = r;
8717
        return WOLFSSL_SUCCESS;
8718
    }
8719
#endif
8720
    else
8721
        return WOLFSSL_FAILURE;
8722
#else
8723
    (void)m;
8724
    (void)r;
8725
    (void)f;
8726
    WOLFSSL_MSG("wolfSSL allocator callback functions not compiled in");
8727
    return WOLFSSL_FAILURE;
8728
#endif
8729
}
8730
8731
int wolfSSL_FIPS_mode(void)
8732
{
8733
#ifdef HAVE_FIPS
8734
    return 1;
8735
#else
8736
    return 0;
8737
#endif
8738
}
8739
8740
int wolfSSL_FIPS_mode_set(int r)
8741
{
8742
#ifdef HAVE_FIPS
8743
    if (r == 0) {
8744
        WOLFSSL_MSG("Cannot disable FIPS at runtime.");
8745
        return WOLFSSL_FAILURE;
8746
    }
8747
    return WOLFSSL_SUCCESS;
8748
#else
8749
    if (r == 0) {
8750
        return WOLFSSL_SUCCESS;
8751
    }
8752
    WOLFSSL_MSG("Cannot enable FIPS. This isn't the wolfSSL FIPS code.");
8753
    return WOLFSSL_FAILURE;
8754
#endif
8755
}
8756
8757
int wolfSSL_CIPHER_get_bits(const WOLFSSL_CIPHER *c, int *alg_bits)
8758
{
8759
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
8760
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_bits");
8761
8762
    #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL)
8763
    (void)alg_bits;
8764
    if (c!= NULL)
8765
        ret = c->bits;
8766
    #else
8767
    if (c != NULL && c->ssl != NULL) {
8768
        ret = 8 * c->ssl->specs.key_size;
8769
        if (alg_bits != NULL) {
8770
            *alg_bits = ret;
8771
        }
8772
    }
8773
    #endif
8774
    return ret;
8775
}
8776
8777
8778
WOLFSSL_CTX* wolfSSL_set_SSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx)
8779
{
8780
    int ret;
8781
    /* This method requires some explanation. Its sibling is
8782
     *   int SetSSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup)
8783
     * which re-inits the WOLFSSL* with all settings in the new CTX.
8784
     * That one is the right one to use *before* a handshake is started.
8785
     *
8786
     * This method was added by OpenSSL to be used *during* the handshake, e.g.
8787
     * when a server inspects the SNI in a ClientHello callback and
8788
     * decides which set of certificates to use.
8789
     *
8790
     * Since, at the time the SNI callback is run, some decisions on
8791
     * Extensions or the ServerHello might already have been taken, this
8792
     * method is very restricted in what it does:
8793
     * - changing the server certificate(s)
8794
     * - changing the server id for session handling
8795
     * and everything else in WOLFSSL* needs to remain untouched.
8796
     *
8797
     * SECURITY: swapping ssl->ctx switches cm-resolved settings (CA store,
8798
     * CRL, OCSP) to the new CTX but leaves ssl-cached ones (verify mode and
8799
     * callback, minDowngrade, key-size minimums, suites, version bounds)
8800
     * pinned to the original. SNI callbacks must re-apply those ssl-level
8801
     * settings explicitly; CRL/OCSP isolation requires an SSL-local store.
8802
     */
8803
    WOLFSSL_ENTER("wolfSSL_set_SSL_CTX");
8804
    if (ssl == NULL || ctx == NULL)
8805
        return NULL;
8806
    if (ssl->ctx == ctx)
8807
        return ssl->ctx;
8808
8809
    /* suites, allocated and derived under the CTX mutex as this CTX may be
8810
     * shared with other threads. Done before taking a reference below so that
8811
     * a failure here returns without having changed anything. */
8812
    if (InitCtxSuitesWithMutex(ctx) != 0)
8813
        return NULL;
8814
8815
    wolfSSL_RefWithMutexInc(&ctx->ref, &ret);
8816
#ifdef WOLFSSL_REFCNT_ERROR_RETURN
8817
    if (ret != 0) {
8818
        /* can only fail on serious stuff, like mutex not working
8819
         * or ctx refcount out of whack. */
8820
        return NULL;
8821
    }
8822
#else
8823
    (void)ret;
8824
#endif
8825
8826
    if (ssl->ctx != NULL)
8827
        wolfSSL_CTX_free(ssl->ctx);
8828
    ssl->ctx = ctx;
8829
8830
#ifndef NO_CERTS
8831
#ifdef WOLFSSL_COPY_CERT
8832
    /* If WOLFSSL_COPY_CERT defined, always make new copy of cert from ctx */
8833
    if (ctx->certificate != NULL) {
8834
        if (ssl->buffers.certificate != NULL) {
8835
            FreeDer(&ssl->buffers.certificate);
8836
            ssl->buffers.certificate = NULL;
8837
        }
8838
        ret = AllocCopyDer(&ssl->buffers.certificate, ctx->certificate->buffer,
8839
            ctx->certificate->length, ctx->certificate->type,
8840
            ctx->certificate->heap);
8841
        if (ret != 0) {
8842
            ssl->buffers.weOwnCert = 0;
8843
            return NULL;
8844
        }
8845
8846
        ssl->buffers.weOwnCert = 1;
8847
    }
8848
    if (ctx->certChain != NULL) {
8849
        if (ssl->buffers.certChain != NULL) {
8850
            FreeDer(&ssl->buffers.certChain);
8851
            ssl->buffers.certChain = NULL;
8852
        }
8853
        ret = AllocCopyDer(&ssl->buffers.certChain, ctx->certChain->buffer,
8854
            ctx->certChain->length, ctx->certChain->type,
8855
            ctx->certChain->heap);
8856
        if (ret != 0) {
8857
            ssl->buffers.weOwnCertChain = 0;
8858
            return NULL;
8859
        }
8860
8861
        ssl->buffers.weOwnCertChain = 1;
8862
    }
8863
#else
8864
    /* ctx owns certificate, certChain and key */
8865
    ssl->buffers.certificate = ctx->certificate;
8866
    ssl->buffers.certChain = ctx->certChain;
8867
#endif
8868
#ifdef WOLFSSL_TLS13
8869
    ssl->buffers.certChainCnt = ctx->certChainCnt;
8870
#endif
8871
#ifndef WOLFSSL_BLIND_PRIVATE_KEY
8872
#ifdef WOLFSSL_COPY_KEY
8873
    if (ssl->buffers.key != NULL && ssl->buffers.weOwnKey) {
8874
        FreeDer(&ssl->buffers.key);
8875
    }
8876
    if (ctx->privateKey != NULL) {
8877
        ret = AllocCopyDer(&ssl->buffers.key, ctx->privateKey->buffer,
8878
            ctx->privateKey->length, ctx->privateKey->type,
8879
            ctx->privateKey->heap);
8880
        if (ret != 0) {
8881
            ssl->buffers.weOwnKey = 0;
8882
            return NULL;
8883
        }
8884
        ssl->buffers.weOwnKey = 1;
8885
    }
8886
    else {
8887
        ssl->buffers.key      = ctx->privateKey;
8888
    }
8889
#else
8890
    ssl->buffers.key      = ctx->privateKey;
8891
#endif
8892
#else
8893
    if (ctx->privateKey != NULL) {
8894
        if (ssl->buffers.key != NULL && ssl->buffers.weOwnKey) {
8895
            FreeDer(&ssl->buffers.key);
8896
        }
8897
        ret = AllocCopyDer(&ssl->buffers.key, ctx->privateKey->buffer,
8898
            ctx->privateKey->length, ctx->privateKey->type,
8899
            ctx->privateKey->heap);
8900
        if (ret != 0) {
8901
            return NULL;
8902
        }
8903
        /* Blind the private key for the SSL with new random mask. */
8904
        wolfssl_priv_der_blind_toggle(ssl->buffers.key, ctx->privateKeyMask);
8905
        ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.key,
8906
            &ssl->buffers.keyMask);
8907
        if (ret != 0) {
8908
            return NULL;
8909
        }
8910
    }
8911
#endif
8912
    ssl->buffers.keyType  = ctx->privateKeyType;
8913
    ssl->buffers.keyId    = ctx->privateKeyId;
8914
    ssl->buffers.keyLabel = ctx->privateKeyLabel;
8915
    ssl->buffers.keySz    = ctx->privateKeySz;
8916
    ssl->buffers.keyDevId = ctx->privateKeyDevId;
8917
    /* flags indicating what certs/keys are available */
8918
    ssl->options.haveRSA          = ctx->haveRSA;
8919
    ssl->options.haveDH           = ctx->haveDH;
8920
    ssl->options.haveECDSAsig     = ctx->haveECDSAsig;
8921
    ssl->options.haveECC          = ctx->haveECC;
8922
    ssl->options.haveStaticECC    = ctx->haveStaticECC;
8923
    ssl->options.haveFalconSig    = ctx->haveFalconSig;
8924
    ssl->options.haveMlDsaSig     = ctx->haveMlDsaSig;
8925
    ssl->options.haveSlhDsaSig    = ctx->haveSlhDsaSig;
8926
#ifdef WOLFSSL_DUAL_ALG_CERTS
8927
#ifndef WOLFSSL_BLIND_PRIVATE_KEY
8928
    ssl->buffers.altKey   = ctx->altPrivateKey;
8929
#else
8930
    if (ctx->altPrivateKey != NULL) {
8931
        ret = AllocCopyDer(&ssl->buffers.altKey, ctx->altPrivateKey->buffer,
8932
            ctx->altPrivateKey->length, ctx->altPrivateKey->type,
8933
            ctx->altPrivateKey->heap);
8934
        if (ret != 0) {
8935
            return NULL;
8936
        }
8937
        /* Blind the private key for the SSL with new random mask. */
8938
        wolfssl_priv_der_blind_toggle(ssl->buffers.altKey,
8939
                                      ctx->altPrivateKeyMask);
8940
        ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.altKey,
8941
            &ssl->buffers.altKeyMask);
8942
        if (ret != 0) {
8943
            return NULL;
8944
        }
8945
    }
8946
#endif
8947
    ssl->buffers.altKeySz   = ctx->altPrivateKeySz;
8948
    ssl->buffers.altKeyType = ctx->altPrivateKeyType;
8949
#endif /* WOLFSSL_DUAL_ALG_CERTS */
8950
#endif
8951
8952
#ifdef WOLFSSL_SESSION_ID_CTX
8953
    /* copy over application session context ID */
8954
    ssl->sessionCtxSz = ctx->sessionCtxSz;
8955
    XMEMCPY(ssl->sessionCtx, ctx->sessionCtx, ctx->sessionCtxSz);
8956
#endif
8957
8958
    return ssl->ctx;
8959
}
8960
8961
8962
#ifndef NO_BIO
8963
#endif
8964
8965
#ifndef NO_WOLFSSL_STUB
8966
/* Set THREADID callback, return 1 on success, 0 on error */
8967
int wolfSSL_THREADID_set_callback(
8968
        void(*threadid_func)(WOLFSSL_CRYPTO_THREADID*))
8969
{
8970
    WOLFSSL_ENTER("wolfSSL_THREADID_set_callback");
8971
    WOLFSSL_STUB("CRYPTO_THREADID_set_callback");
8972
    (void)threadid_func;
8973
    return 1;
8974
}
8975
#endif
8976
8977
#ifndef NO_WOLFSSL_STUB
8978
void wolfSSL_THREADID_set_numeric(void* id, unsigned long val)
8979
{
8980
    WOLFSSL_ENTER("wolfSSL_THREADID_set_numeric");
8981
    WOLFSSL_STUB("CRYPTO_THREADID_set_numeric");
8982
    (void)id;
8983
    (void)val;
8984
    return;
8985
}
8986
#endif
8987
8988
#endif /* OPENSSL_ALL || OPENSSL_EXTRA */
8989
8990
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
8991
/* Map a signature-algorithm NID to its digest and public-key NIDs, like
8992
 * OpenSSL's OBJ_find_sigid_algs(). */
8993
int wolfSSL_OBJ_find_sigid_algs(int sigid, int *pdig, int *ppkey)
8994
{
8995
    int dig  = 0;
8996
    int pkey = 0;
8997
    int ret  = 1;
8998
8999
    WOLFSSL_ENTER("wolfSSL_OBJ_find_sigid_algs");
9000
9001
    switch (sigid) {
9002
#ifndef NO_RSA
9003
    #ifndef NO_MD5
9004
        case WC_NID_md5WithRSAEncryption:
9005
            dig = WC_NID_md5;    pkey = WC_NID_rsaEncryption; break;
9006
    #endif
9007
        case WC_NID_sha1WithRSAEncryption:
9008
            dig = WC_NID_sha1;   pkey = WC_NID_rsaEncryption; break;
9009
        case WC_NID_sha224WithRSAEncryption:
9010
            dig = WC_NID_sha224; pkey = WC_NID_rsaEncryption; break;
9011
        case WC_NID_sha256WithRSAEncryption:
9012
            dig = WC_NID_sha256; pkey = WC_NID_rsaEncryption; break;
9013
        case WC_NID_sha384WithRSAEncryption:
9014
            dig = WC_NID_sha384; pkey = WC_NID_rsaEncryption; break;
9015
        case WC_NID_sha512WithRSAEncryption:
9016
            dig = WC_NID_sha512; pkey = WC_NID_rsaEncryption; break;
9017
    #ifdef WC_RSA_PSS
9018
        case WC_NID_rsassaPss:
9019
            dig = WC_NID_undef;  pkey = WC_NID_rsassaPss; break;
9020
    #endif
9021
#endif /* !NO_RSA */
9022
#ifdef HAVE_ECC
9023
        case WC_NID_ecdsa_with_SHA1:
9024
            dig = WC_NID_sha1;   pkey = WC_NID_X9_62_id_ecPublicKey; break;
9025
        case WC_NID_ecdsa_with_SHA224:
9026
            dig = WC_NID_sha224; pkey = WC_NID_X9_62_id_ecPublicKey; break;
9027
        case WC_NID_ecdsa_with_SHA256:
9028
            dig = WC_NID_sha256; pkey = WC_NID_X9_62_id_ecPublicKey; break;
9029
        case WC_NID_ecdsa_with_SHA384:
9030
            dig = WC_NID_sha384; pkey = WC_NID_X9_62_id_ecPublicKey; break;
9031
        case WC_NID_ecdsa_with_SHA512:
9032
            dig = WC_NID_sha512; pkey = WC_NID_X9_62_id_ecPublicKey; break;
9033
#endif /* HAVE_ECC */
9034
#ifdef HAVE_ED25519
9035
        case WC_NID_ED25519:
9036
            dig = WC_NID_undef;  pkey = WC_NID_ED25519; break;
9037
#endif
9038
#ifdef HAVE_ED448
9039
        case WC_NID_ED448:
9040
            dig = WC_NID_undef;  pkey = WC_NID_ED448; break;
9041
#endif
9042
        default:
9043
            ret = 0; break;
9044
    }
9045
9046
    if (ret == 1) {
9047
        if (pdig  != NULL) *pdig  = dig;
9048
        if (ppkey != NULL) *ppkey = pkey;
9049
    }
9050
9051
    WOLFSSL_LEAVE("wolfSSL_OBJ_find_sigid_algs", ret);
9052
    return ret;
9053
}
9054
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
9055
9056
9057
#if defined(OPENSSL_EXTRA)
9058
9059
int wolfSSL_CRYPTO_memcmp(const void *a, const void *b, size_t size)
9060
{
9061
    int ret = 0;
9062
    int chunk;
9063
    const byte* pa = (const byte*)a;
9064
    const byte* pb = (const byte*)b;
9065
9066
    if (!a || !b)
9067
        return -1;
9068
    /* ConstantCompare takes an int length. Compare in chunks of at most
9069
     * INT_MAX so a size that does not fit in an int is not narrowed into a
9070
     * negative or truncated length, which could wrongly report equality. */
9071
    while (size > 0) {
9072
        chunk = (size > (size_t)INT_MAX) ? INT_MAX : (int)size;
9073
        ret |= ConstantCompare(pa, pb, chunk);
9074
        pa += chunk;
9075
        pb += chunk;
9076
        size -= (size_t)chunk;
9077
    }
9078
    return ret;
9079
}
9080
9081
9082
#endif /* OPENSSL_EXTRA */
9083
9084
int wolfSSL_version(WOLFSSL* ssl)
9085
0
{
9086
0
    WOLFSSL_ENTER("wolfSSL_version");
9087
0
    if (ssl->version.major == SSLv3_MAJOR) {
9088
0
        switch (ssl->version.minor) {
9089
0
            case SSLv3_MINOR :
9090
0
                return SSL3_VERSION;
9091
0
            case TLSv1_MINOR :
9092
0
                return TLS1_VERSION;
9093
0
            case TLSv1_1_MINOR :
9094
0
                return TLS1_1_VERSION;
9095
0
            case TLSv1_2_MINOR :
9096
0
                return TLS1_2_VERSION;
9097
0
            case TLSv1_3_MINOR :
9098
0
                return TLS1_3_VERSION;
9099
0
            default:
9100
0
                return WOLFSSL_FAILURE;
9101
0
        }
9102
0
    }
9103
0
    else if (ssl->version.major == DTLS_MAJOR) {
9104
0
        switch (ssl->version.minor) {
9105
0
            case DTLS_MINOR :
9106
0
                return DTLS1_VERSION;
9107
0
            case DTLSv1_2_MINOR :
9108
0
                return DTLS1_2_VERSION;
9109
0
            case DTLSv1_3_MINOR:
9110
0
                return DTLS1_3_VERSION;
9111
0
            default:
9112
0
                return WOLFSSL_FAILURE;
9113
0
        }
9114
0
    }
9115
0
    return WOLFSSL_FAILURE;
9116
0
}
9117
9118
WOLFSSL_CTX* wolfSSL_get_SSL_CTX(const WOLFSSL* ssl)
9119
0
{
9120
0
    WOLFSSL_ENTER("wolfSSL_get_SSL_CTX");
9121
0
    return ssl->ctx;
9122
0
}
9123
9124
9125
#ifdef WOLFSSL_JNI
9126
9127
int wolfSSL_set_jobject(WOLFSSL* ssl, void* objPtr)
9128
{
9129
    WOLFSSL_ENTER("wolfSSL_set_jobject");
9130
    if (ssl != NULL)
9131
    {
9132
        ssl->jObjectRef = objPtr;
9133
        return WOLFSSL_SUCCESS;
9134
    }
9135
    return WOLFSSL_FAILURE;
9136
}
9137
9138
void* wolfSSL_get_jobject(WOLFSSL* ssl)
9139
{
9140
    WOLFSSL_ENTER("wolfSSL_get_jobject");
9141
    if (ssl != NULL)
9142
        return ssl->jObjectRef;
9143
    return NULL;
9144
}
9145
9146
#endif /* WOLFSSL_JNI */
9147
9148
9149
#ifdef WOLFSSL_ASYNC_CRYPT
9150
int wolfSSL_CTX_AsyncPoll(WOLFSSL_CTX* ctx, WOLF_EVENT** events, int maxEvents,
9151
    WOLF_EVENT_FLAG flags, int* eventCount)
9152
{
9153
    if (ctx == NULL) {
9154
        return BAD_FUNC_ARG;
9155
    }
9156
9157
    return wolfAsync_EventQueuePoll(&ctx->event_queue, NULL,
9158
                                        events, maxEvents, flags, eventCount);
9159
}
9160
9161
int wolfSSL_AsyncPoll(WOLFSSL* ssl, WOLF_EVENT_FLAG flags)
9162
{
9163
    int ret, eventCount = 0;
9164
    WOLF_EVENT* events[1];
9165
9166
    if (ssl == NULL) {
9167
        return BAD_FUNC_ARG;
9168
    }
9169
9170
    ret = wolfAsync_EventQueuePoll(&ssl->ctx->event_queue, ssl,
9171
        events, sizeof(events)/sizeof(events[0]), flags, &eventCount);
9172
    if (ret == 0) {
9173
        ret = eventCount;
9174
    }
9175
9176
    return ret;
9177
}
9178
#endif /* WOLFSSL_ASYNC_CRYPT */
9179
9180
#ifdef OPENSSL_EXTRA
9181
9182
#endif
9183
9184
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL) || \
9185
    defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
9186
9187
#if !defined(WOLFSSL_USER_IO)
9188
/* converts an IPv6 or IPv4 address into an octet string for use with rfc3280
9189
 * example input would be "127.0.0.1" and the returned value would be 7F000001
9190
 */
9191
WOLFSSL_ASN1_STRING* wolfSSL_a2i_IPADDRESS(const char* ipa)
9192
{
9193
    int ipaSz = WOLFSSL_IP4_ADDR_LEN;
9194
    char buf[WOLFSSL_IP6_ADDR_LEN + 1]; /* plus 1 for terminator */
9195
    int  af = WOLFSSL_IP4;
9196
    WOLFSSL_ASN1_STRING *ret = NULL;
9197
9198
    if (ipa == NULL)
9199
        return NULL;
9200
9201
    if (XSTRSTR(ipa, ":") != NULL) {
9202
        af = WOLFSSL_IP6;
9203
        ipaSz = WOLFSSL_IP6_ADDR_LEN;
9204
    }
9205
9206
    buf[WOLFSSL_IP6_ADDR_LEN] = '\0';
9207
#ifdef FREESCALE_MQX
9208
    if (XINET_PTON(af, ipa, (void*)buf, sizeof(buf)) != RTCS_OK) {
9209
#else
9210
    if (XINET_PTON(af, ipa, (void*)buf) != 1) {
9211
#endif
9212
        WOLFSSL_MSG("Error parsing IP address");
9213
        return NULL;
9214
    }
9215
9216
    ret = wolfSSL_ASN1_STRING_new();
9217
    if (ret != NULL) {
9218
        if (wolfSSL_ASN1_STRING_set(ret, buf, ipaSz) != WOLFSSL_SUCCESS) {
9219
            WOLFSSL_MSG("Error setting the string");
9220
            wolfSSL_ASN1_STRING_free(ret);
9221
            ret = NULL;
9222
        }
9223
    }
9224
9225
    return ret;
9226
}
9227
#endif /* !WOLFSSL_USER_IO */
9228
9229
/* Is the specified cipher suite a fake one used an an extension proxy? */
9230
static WC_INLINE int SCSV_Check(byte suite0, byte suite)
9231
{
9232
    (void)suite0;
9233
    (void)suite;
9234
#ifdef HAVE_RENEGOTIATION_INDICATION
9235
    if (suite0 == CIPHER_BYTE && suite == TLS_EMPTY_RENEGOTIATION_INFO_SCSV)
9236
        return 1;
9237
#endif
9238
    return 0;
9239
}
9240
9241
static WC_INLINE int sslCipherMinMaxCheck(const WOLFSSL *ssl, byte suite0,
9242
        byte suite)
9243
{
9244
    const CipherSuiteInfo* cipher_names = GetCipherNames();
9245
    int cipherSz = GetCipherNamesSize();
9246
    int i;
9247
    for (i = 0; i < cipherSz; i++)
9248
        if (cipher_names[i].cipherSuite0 == suite0 &&
9249
                cipher_names[i].cipherSuite == suite)
9250
            break;
9251
    if (i == cipherSz)
9252
        return 1;
9253
    /* Check min version */
9254
    if (cipher_names[i].minor < ssl->options.minDowngrade) {
9255
        if (ssl->options.minDowngrade <= TLSv1_2_MINOR &&
9256
                cipher_names[i].minor >= TLSv1_MINOR)
9257
            /* 1.0 ciphersuites are in general available in 1.1 and
9258
             * 1.1 ciphersuites are in general available in 1.2 */
9259
            return 0;
9260
        return 1;
9261
    }
9262
    /* Check max version */
9263
    switch (cipher_names[i].minor) {
9264
    case SSLv3_MINOR :
9265
        return ssl->options.mask & WOLFSSL_OP_NO_SSLv3;
9266
    case TLSv1_MINOR :
9267
        return ssl->options.mask & WOLFSSL_OP_NO_TLSv1;
9268
    case TLSv1_1_MINOR :
9269
        return ssl->options.mask & WOLFSSL_OP_NO_TLSv1_1;
9270
    case TLSv1_2_MINOR :
9271
        return ssl->options.mask & WOLFSSL_OP_NO_TLSv1_2;
9272
    case TLSv1_3_MINOR :
9273
        return ssl->options.mask & WOLFSSL_OP_NO_TLSv1_3;
9274
    default:
9275
        WOLFSSL_MSG("Unrecognized minor version");
9276
        return 1;
9277
    }
9278
}
9279
9280
/* returns a pointer to internal cipher suite list. Should not be free'd by
9281
 * caller.
9282
 */
9283
WOLF_STACK_OF(WOLFSSL_CIPHER) *wolfSSL_get_ciphers_compat(const WOLFSSL *ssl)
9284
{
9285
    const Suites* suites;
9286
#if defined(OPENSSL_ALL)
9287
    const CipherSuiteInfo* cipher_names = GetCipherNames();
9288
    int cipherSz = GetCipherNamesSize();
9289
#endif
9290
9291
    WOLFSSL_ENTER("wolfSSL_get_ciphers_compat");
9292
    if (ssl == NULL)
9293
        return NULL;
9294
9295
    suites = WOLFSSL_SUITES(ssl);
9296
    if (suites == NULL)
9297
        return NULL;
9298
9299
    /* check if stack needs populated */
9300
    if (ssl->suitesStack == NULL) {
9301
        int i;
9302
9303
        ((WOLFSSL*)ssl)->suitesStack =
9304
                wolfssl_sk_new_type_ex(STACK_TYPE_CIPHER, ssl->heap);
9305
        if (ssl->suitesStack == NULL)
9306
            return NULL;
9307
9308
        /* Walk lowest priority first: each suite is inserted at index 0, so
9309
         * the highest priority suite ends up on top of the stack. */
9310
        for (i = suites->suiteSz - 2; i >= 0; i -= 2)
9311
        {
9312
            struct WOLFSSL_CIPHER cipher;
9313
9314
            /* A couple of suites are placeholders for special options,
9315
             * skip those. */
9316
            if (SCSV_Check(suites->suites[i], suites->suites[i+1])
9317
                    || sslCipherMinMaxCheck(ssl, suites->suites[i],
9318
                                            suites->suites[i+1])) {
9319
                continue;
9320
            }
9321
9322
            XMEMSET(&cipher, 0, sizeof(cipher));
9323
            cipher.cipherSuite0 = suites->suites[i];
9324
            cipher.cipherSuite  = suites->suites[i+1];
9325
            cipher.ssl          = ssl;
9326
#if defined(OPENSSL_ALL)
9327
            cipher.in_stack     = 1;
9328
            {
9329
                int j;
9330
                for (j = 0; j < cipherSz; j++) {
9331
                    if (cipher_names[j].cipherSuite0 == cipher.cipherSuite0 &&
9332
                            cipher_names[j].cipherSuite == cipher.cipherSuite) {
9333
                        cipher.offset = (unsigned long)j;
9334
                        break;
9335
                    }
9336
                }
9337
            }
9338
#endif
9339
            if (wolfSSL_sk_insert(ssl->suitesStack, &cipher, 0) <= 0) {
9340
                WOLFSSL_MSG("Error inserting cipher onto stack");
9341
                wolfSSL_sk_CIPHER_free(ssl->suitesStack);
9342
                ((WOLFSSL*)ssl)->suitesStack = NULL;
9343
                break;
9344
            }
9345
        }
9346
9347
        /* If no ciphers were added, free empty stack and return NULL */
9348
        if (ssl->suitesStack != NULL && wolfSSL_sk_num(ssl->suitesStack) == 0) {
9349
            wolfSSL_sk_CIPHER_free(ssl->suitesStack);
9350
            ((WOLFSSL*)ssl)->suitesStack = NULL;
9351
        }
9352
    }
9353
    return ssl->suitesStack;
9354
}
9355
9356
/* Get the name of the cipher at index priority in the cipher list configured
9357
 * on this SSL. Index 0 is the highest priority suite. Returns NULL once
9358
 * priority is past the end of the list. Matches OpenSSL SSL_get_cipher_list().
9359
 */
9360
const char* wolfSSL_get_cipher_list_compat(const WOLFSSL* ssl, int priority)
9361
{
9362
    const Suites* suites;
9363
    int i;
9364
    int idx = 0;
9365
9366
    WOLFSSL_ENTER("wolfSSL_get_cipher_list_compat");
9367
9368
    if (ssl == NULL || priority < 0)
9369
        return NULL;
9370
9371
    suites = WOLFSSL_SUITES(ssl);
9372
    if (suites == NULL)
9373
        return NULL;
9374
9375
    for (i = 0; i < suites->suiteSz; i += 2) {
9376
        /* A couple of suites are placeholders for special options, skip
9377
         * those. */
9378
        if (SCSV_Check(suites->suites[i], suites->suites[i+1])
9379
                || sslCipherMinMaxCheck(ssl, suites->suites[i],
9380
                                        suites->suites[i+1])) {
9381
            continue;
9382
        }
9383
9384
        if (idx++ == priority) {
9385
            /* Report the same name that SSL_CIPHER_get_name() would. */
9386
        #if !defined(WOLFSSL_CIPHER_INTERNALNAME) && \
9387
            !defined(NO_ERROR_STRINGS) && !defined(WOLFSSL_QT)
9388
            return GetCipherNameIana(suites->suites[i], suites->suites[i+1]);
9389
        #else
9390
            return wolfSSL_get_cipher_name_from_suite(suites->suites[i],
9391
                    suites->suites[i+1]);
9392
        #endif
9393
        }
9394
    }
9395
9396
    return NULL;
9397
}
9398
#endif /* OPENSSL_EXTRA || OPENSSL_ALL || WOLFSSL_NGINX || WOLFSSL_HAPROXY */
9399
#ifdef OPENSSL_ALL
9400
/* returned pointer is to an internal element in WOLFSSL struct and should not
9401
 * be free'd. It gets free'd when the WOLFSSL struct is free'd. */
9402
WOLF_STACK_OF(WOLFSSL_CIPHER)*  wolfSSL_get_client_ciphers(WOLFSSL* ssl)
9403
{
9404
    WOLF_STACK_OF(WOLFSSL_CIPHER)* ret = NULL;
9405
    const CipherSuiteInfo* cipher_names = GetCipherNames();
9406
    int cipherSz = GetCipherNamesSize();
9407
    const Suites* suites;
9408
9409
    WOLFSSL_ENTER("wolfSSL_get_client_ciphers");
9410
9411
    if (ssl == NULL) {
9412
        return NULL;
9413
    }
9414
9415
    /* return NULL if is client side */
9416
    if (wolfSSL_is_server(ssl) == 0) {
9417
        return NULL;
9418
    }
9419
9420
    suites = ssl->clSuites;
9421
    if (suites == NULL) {
9422
        WOLFSSL_MSG("No client suites stored");
9423
    }
9424
    else if (ssl->clSuitesStack != NULL) {
9425
        ret = ssl->clSuitesStack;
9426
    }
9427
    else { /* generate cipher suites stack if not already done */
9428
        int i;
9429
        int j;
9430
9431
        ret = wolfSSL_sk_new_node(ssl->heap);
9432
        if (ret != NULL) {
9433
            ret->type = STACK_TYPE_CIPHER;
9434
9435
            /* higher priority of cipher suite will be on top of stack */
9436
            for (i = suites->suiteSz - 2; i >= 0; i -= 2) {
9437
                WOLFSSL_CIPHER cipher;
9438
9439
                /* A couple of suites are placeholders for special options,
9440
                 * skip those. */
9441
                if (SCSV_Check(suites->suites[i], suites->suites[i+1])
9442
                        || sslCipherMinMaxCheck(ssl, suites->suites[i],
9443
                                                suites->suites[i+1])) {
9444
                    continue;
9445
                }
9446
9447
                cipher.cipherSuite0 = suites->suites[i];
9448
                cipher.cipherSuite  = suites->suites[i+1];
9449
                cipher.ssl          = ssl;
9450
                for (j = 0; j < cipherSz; j++) {
9451
                    if (cipher_names[j].cipherSuite0 ==
9452
                            cipher.cipherSuite0 &&
9453
                            cipher_names[j].cipherSuite ==
9454
                                    cipher.cipherSuite) {
9455
                        cipher.offset = (unsigned long)j;
9456
                        break;
9457
                    }
9458
                }
9459
9460
                /* in_stack is checked in wolfSSL_CIPHER_description */
9461
                cipher.in_stack     = 1;
9462
9463
                if (wolfSSL_sk_CIPHER_push(ret, &cipher) <= 0) {
9464
                    WOLFSSL_MSG("Error pushing client cipher onto stack");
9465
                    wolfSSL_sk_CIPHER_free(ret);
9466
                    ret = NULL;
9467
                    break;
9468
                }
9469
            }
9470
        }
9471
        ssl->clSuitesStack = ret;
9472
    }
9473
    return ret;
9474
}
9475
#endif /* OPENSSL_ALL */
9476
9477
#if defined(OPENSSL_EXTRA) || defined(HAVE_SECRET_CALLBACK)
9478
long wolfSSL_SSL_CTX_get_timeout(const WOLFSSL_CTX *ctx)
9479
{
9480
    WOLFSSL_ENTER("wolfSSL_SSL_CTX_get_timeout");
9481
9482
    if (ctx == NULL)
9483
        return 0;
9484
9485
    return ctx->timeout;
9486
}
9487
9488
9489
/* returns the time in seconds of the current timeout */
9490
long wolfSSL_get_timeout(WOLFSSL* ssl)
9491
{
9492
    WOLFSSL_ENTER("wolfSSL_get_timeout");
9493
9494
    if (ssl == NULL)
9495
        return 0;
9496
    return ssl->timeout;
9497
}
9498
#endif
9499
9500
#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) \
9501
    || defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY)
9502
9503
#ifndef NO_BIO
9504
WOLFSSL_BIO *wolfSSL_SSL_get_rbio(const WOLFSSL *s)
9505
{
9506
    WOLFSSL_ENTER("wolfSSL_SSL_get_rbio");
9507
    /* Nginx sets the buffer size if the read BIO is different to write BIO.
9508
     * The setting buffer size doesn't do anything so return NULL for both.
9509
     */
9510
    if (s == NULL)
9511
        return NULL;
9512
9513
    return s->biord;
9514
}
9515
WOLFSSL_BIO *wolfSSL_SSL_get_wbio(const WOLFSSL *s)
9516
{
9517
    WOLFSSL_ENTER("wolfSSL_SSL_get_wbio");
9518
    (void)s;
9519
    /* Nginx sets the buffer size if the read BIO is different to write BIO.
9520
     * The setting buffer size doesn't do anything so return NULL for both.
9521
     */
9522
    if (s == NULL)
9523
        return NULL;
9524
9525
    return s->biowr;
9526
}
9527
#endif /* !NO_BIO */
9528
9529
9530
9531
#endif /* OPENSSL_ALL || WOLFSSL_NGINX || WOLFSSL_HAPROXY ||
9532
    OPENSSL_EXTRA || HAVE_LIGHTY */
9533
9534
9535
#if defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) || \
9536
    defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)
9537
9538
9539
void wolfSSL_WOLFSSL_STRING_free(WOLFSSL_STRING s)
9540
{
9541
    WOLFSSL_ENTER("wolfSSL_WOLFSSL_STRING_free");
9542
9543
    XFREE(s, NULL, DYNAMIC_TYPE_OPENSSL);
9544
}
9545
9546
#endif /* WOLFSSL_NGINX || WOLFSSL_HAPROXY || OPENSSL_EXTRA || OPENSSL_ALL */
9547
9548
9549
#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL)
9550
9551
#if (defined(HAVE_ECC) || \
9552
    defined(HAVE_CURVE25519) || defined(HAVE_CURVE448))
9553
#define CURVE_NAME(c) XSTR_SIZEOF((c)), (c)
9554
9555
const WOLF_EC_NIST_NAME kNistCurves[] = {
9556
#ifdef HAVE_ECC
9557
    {CURVE_NAME("P-160"),   WC_NID_secp160r1, WOLFSSL_ECC_SECP160R1},
9558
    {CURVE_NAME("P-160-2"), WC_NID_secp160r2, WOLFSSL_ECC_SECP160R2},
9559
    {CURVE_NAME("P-192"),   WC_NID_X9_62_prime192v1, WOLFSSL_ECC_SECP192R1},
9560
    {CURVE_NAME("P-224"),   WC_NID_secp224r1, WOLFSSL_ECC_SECP224R1},
9561
    {CURVE_NAME("P-256"),   WC_NID_X9_62_prime256v1, WOLFSSL_ECC_SECP256R1},
9562
    {CURVE_NAME("P-384"),   WC_NID_secp384r1, WOLFSSL_ECC_SECP384R1},
9563
    {CURVE_NAME("P-521"),   WC_NID_secp521r1, WOLFSSL_ECC_SECP521R1},
9564
    {CURVE_NAME("K-160"),   WC_NID_secp160k1, WOLFSSL_ECC_SECP160K1},
9565
    {CURVE_NAME("K-192"),   WC_NID_secp192k1, WOLFSSL_ECC_SECP192K1},
9566
    {CURVE_NAME("K-224"),   WC_NID_secp224k1, WOLFSSL_ECC_SECP224K1},
9567
    {CURVE_NAME("K-256"),   WC_NID_secp256k1, WOLFSSL_ECC_SECP256K1},
9568
    {CURVE_NAME("B-256"),   WC_NID_brainpoolP256r1,
9569
     WOLFSSL_ECC_BRAINPOOLP256R1},
9570
    {CURVE_NAME("B-384"),   WC_NID_brainpoolP384r1,
9571
     WOLFSSL_ECC_BRAINPOOLP384R1},
9572
    {CURVE_NAME("B-512"),   WC_NID_brainpoolP512r1,
9573
     WOLFSSL_ECC_BRAINPOOLP512R1},
9574
#endif
9575
#ifdef HAVE_CURVE25519
9576
    {CURVE_NAME("X25519"),  WC_NID_X25519, WOLFSSL_ECC_X25519},
9577
#endif
9578
#ifdef HAVE_CURVE448
9579
    {CURVE_NAME("X448"),    WC_NID_X448, WOLFSSL_ECC_X448},
9580
#endif
9581
#ifdef WOLFSSL_HAVE_MLKEM
9582
#ifndef WOLFSSL_NO_ML_KEM
9583
    {CURVE_NAME("ML_KEM_512"), WOLFSSL_ML_KEM_512, WOLFSSL_ML_KEM_512},
9584
    {CURVE_NAME("ML_KEM_768"), WOLFSSL_ML_KEM_768, WOLFSSL_ML_KEM_768},
9585
    {CURVE_NAME("ML_KEM_1024"), WOLFSSL_ML_KEM_1024, WOLFSSL_ML_KEM_1024},
9586
    /* Aliases accepting the OpenSSL/IANA spelling without underscores. */
9587
    {CURVE_NAME("MLKEM512"), WOLFSSL_ML_KEM_512, WOLFSSL_ML_KEM_512},
9588
    {CURVE_NAME("MLKEM768"), WOLFSSL_ML_KEM_768, WOLFSSL_ML_KEM_768},
9589
    {CURVE_NAME("MLKEM1024"), WOLFSSL_ML_KEM_1024, WOLFSSL_ML_KEM_1024},
9590
#if defined(HAVE_ECC)
9591
    #ifdef WOLFSSL_PQC_HYBRIDS
9592
    {CURVE_NAME("SecP256r1MLKEM768"), WOLFSSL_SECP256R1MLKEM768,
9593
     WOLFSSL_SECP256R1MLKEM768},
9594
    {CURVE_NAME("SecP384r1MLKEM1024"), WOLFSSL_SECP384R1MLKEM1024,
9595
     WOLFSSL_SECP384R1MLKEM1024},
9596
    {CURVE_NAME("X25519MLKEM768"), WOLFSSL_X25519MLKEM768,
9597
     WOLFSSL_X25519MLKEM768},
9598
    #endif /* WOLFSSL_PQC_HYBRIDS */
9599
    #ifdef WOLFSSL_EXTRA_PQC_HYBRIDS
9600
    {CURVE_NAME("SecP256r1MLKEM512"), WOLFSSL_SECP256R1MLKEM512,
9601
     WOLFSSL_SECP256R1MLKEM512},
9602
    {CURVE_NAME("SecP384r1MLKEM768"), WOLFSSL_SECP384R1MLKEM768,
9603
     WOLFSSL_SECP384R1MLKEM768},
9604
    {CURVE_NAME("SecP521r1MLKEM1024"), WOLFSSL_SECP521R1MLKEM1024,
9605
     WOLFSSL_SECP521R1MLKEM1024},
9606
    {CURVE_NAME("X25519MLKEM512"), WOLFSSL_X25519MLKEM512,
9607
     WOLFSSL_X25519MLKEM512},
9608
    {CURVE_NAME("X448MLKEM768"), WOLFSSL_X448MLKEM768,
9609
     WOLFSSL_X448MLKEM768},
9610
    #endif /* WOLFSSL_EXTRA_PQC_HYBRIDS */
9611
#endif
9612
#endif /* !WOLFSSL_NO_ML_KEM */
9613
#ifdef WOLFSSL_MLKEM_KYBER
9614
    {CURVE_NAME("KYBER_LEVEL1"), WOLFSSL_KYBER_LEVEL1, WOLFSSL_KYBER_LEVEL1},
9615
    {CURVE_NAME("KYBER_LEVEL3"), WOLFSSL_KYBER_LEVEL3, WOLFSSL_KYBER_LEVEL3},
9616
    {CURVE_NAME("KYBER_LEVEL5"), WOLFSSL_KYBER_LEVEL5, WOLFSSL_KYBER_LEVEL5},
9617
#if defined(HAVE_ECC)
9618
    {CURVE_NAME("P256_KYBER_LEVEL1"), WOLFSSL_P256_KYBER_LEVEL1,
9619
     WOLFSSL_P256_KYBER_LEVEL1},
9620
    {CURVE_NAME("P384_KYBER_LEVEL3"), WOLFSSL_P384_KYBER_LEVEL3,
9621
     WOLFSSL_P384_KYBER_LEVEL3},
9622
    {CURVE_NAME("P256_KYBER_LEVEL3"), WOLFSSL_P256_KYBER_LEVEL3,
9623
     WOLFSSL_P256_KYBER_LEVEL3},
9624
    {CURVE_NAME("P521_KYBER_LEVEL5"), WOLFSSL_P521_KYBER_LEVEL5,
9625
     WOLFSSL_P521_KYBER_LEVEL5},
9626
    {CURVE_NAME("X25519_KYBER_LEVEL1"), WOLFSSL_X25519_KYBER_LEVEL1,
9627
     WOLFSSL_X25519_KYBER_LEVEL1},
9628
    {CURVE_NAME("X448_KYBER_LEVEL3"), WOLFSSL_X448_KYBER_LEVEL3,
9629
     WOLFSSL_X448_KYBER_LEVEL3},
9630
    {CURVE_NAME("X25519_KYBER_LEVEL3"), WOLFSSL_X25519_KYBER_LEVEL3,
9631
     WOLFSSL_X25519_KYBER_LEVEL3},
9632
#endif
9633
#endif /* WOLFSSL_MLKEM_KYBER */
9634
#endif /* WOLFSSL_HAVE_MLKEM */
9635
#ifdef WOLFSSL_SM2
9636
    {CURVE_NAME("SM2"),     WC_NID_sm2, WOLFSSL_ECC_SM2P256V1},
9637
#endif
9638
#ifdef HAVE_ECC
9639
    /* Alternative curve names */
9640
    {CURVE_NAME("prime256v1"), WC_NID_X9_62_prime256v1, WOLFSSL_ECC_SECP256R1},
9641
    {CURVE_NAME("secp256r1"),  WC_NID_X9_62_prime256v1, WOLFSSL_ECC_SECP256R1},
9642
    {CURVE_NAME("secp384r1"),  WC_NID_secp384r1, WOLFSSL_ECC_SECP384R1},
9643
    {CURVE_NAME("secp521r1"),  WC_NID_secp521r1, WOLFSSL_ECC_SECP521R1},
9644
#endif
9645
#ifdef WOLFSSL_SM2
9646
    {CURVE_NAME("sm2p256v1"),  WC_NID_sm2, WOLFSSL_ECC_SM2P256V1},
9647
#endif
9648
    {0, NULL, 0, 0},
9649
};
9650
9651
int set_curves_list(WOLFSSL* ssl, WOLFSSL_CTX *ctx, const char* names,
9652
        byte curves_only)
9653
{
9654
    int idx, start = 0, len, i, ret = WOLFSSL_FAILURE;
9655
    word16 curve;
9656
    word32 disabled;
9657
    char name[MAX_CURVE_NAME_SZ];
9658
    byte groups_len = 0;
9659
#ifdef WOLFSSL_SMALL_STACK
9660
    void *heap = ssl? ssl->heap : ctx ? ctx->heap : NULL;
9661
    int *groups;
9662
#else
9663
    int groups[WOLFSSL_MAX_GROUP_COUNT];
9664
#endif
9665
    const WOLF_EC_NIST_NAME* nist_name;
9666
9667
    WC_ALLOC_VAR_EX(groups, int, WOLFSSL_MAX_GROUP_COUNT, heap,
9668
        DYNAMIC_TYPE_TMP_BUFFER,
9669
    {
9670
        ret=MEMORY_E;
9671
        goto leave;
9672
    });
9673
9674
    for (idx = 1; names[idx-1] != '\0'; idx++) {
9675
        if (names[idx] != ':' && names[idx] != '\0')
9676
            continue;
9677
9678
        len = idx - start;
9679
        if (len > MAX_CURVE_NAME_SZ - 1)
9680
            goto leave;
9681
9682
        XMEMCPY(name, names + start, (size_t)len);
9683
        name[len] = 0;
9684
        curve = WOLFSSL_NAMED_GROUP_INVALID;
9685
9686
        for (nist_name = kNistCurves; nist_name->name != NULL; nist_name++) {
9687
            if (len == nist_name->name_len &&
9688
                    XSTRNCASECMP(name, nist_name->name, (size_t)len) == 0) {
9689
                curve = nist_name->curve;
9690
                break;
9691
            }
9692
        }
9693
9694
        if (curve == WOLFSSL_NAMED_GROUP_INVALID) {
9695
        #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && defined(HAVE_ECC)
9696
            int   nret;
9697
            const ecc_set_type *eccSet;
9698
9699
            nret = wc_ecc_get_curve_idx_from_name(name);
9700
            if (nret < 0) {
9701
                WOLFSSL_MSG("Could not find name in set");
9702
                goto leave;
9703
            }
9704
9705
            eccSet = wc_ecc_get_curve_params(nret);
9706
            if (eccSet == NULL) {
9707
                WOLFSSL_MSG("NULL set returned");
9708
                goto leave;
9709
            }
9710
9711
            curve = GetCurveByOID((int)eccSet->oidSum);
9712
        #else
9713
            WOLFSSL_MSG("API not present to search farther using name");
9714
            goto leave;
9715
        #endif
9716
        }
9717
9718
        if ((curves_only && curve >= WOLFSSL_ECC_MAX_AVAIL) ||
9719
                curve == WOLFSSL_NAMED_GROUP_INVALID) {
9720
            WOLFSSL_MSG("curve value is not supported");
9721
            goto leave;
9722
        }
9723
9724
        for (i = 0; i < groups_len; ++i) {
9725
            if (groups[i] == curve) {
9726
                /* silently drop duplicates */
9727
                break;
9728
            }
9729
        }
9730
        if (i >= groups_len) {
9731
            if (groups_len >= WOLFSSL_MAX_GROUP_COUNT) {
9732
                WOLFSSL_MSG_EX("setting %d or more supported "
9733
                               "curves is not permitted", groups_len);
9734
                goto leave;
9735
            }
9736
            groups[groups_len++] = (int)curve;
9737
        }
9738
9739
        start = idx + 1;
9740
    }
9741
9742
    /* Disable all curves so that only the ones the user wants are enabled. */
9743
    disabled = 0xFFFFFFFFUL;
9744
    for (i = 0; i < groups_len; ++i) {
9745
        /* Switch the bit to off and therefore is enabled. */
9746
        curve = (word16)groups[i];
9747
        if (curve >= 64) {
9748
            WC_DO_NOTHING;
9749
        }
9750
        else if (curve >= 32) {
9751
            /* 0 is for invalid and 1-14 aren't used otherwise. */
9752
            disabled &= ~(1U << (curve - 32));
9753
        }
9754
        else {
9755
            disabled &= ~(1U << curve);
9756
        }
9757
    #if defined(HAVE_SUPPORTED_CURVES) && !defined(NO_TLS)
9758
    #if !defined(WOLFSSL_OLD_SET_CURVES_LIST)
9759
        /* using the wolfSSL API to set the groups, this will populate
9760
         * (ssl|ctx)->groups and reset any TLSX_SUPPORTED_GROUPS.
9761
         * The order in (ssl|ctx)->groups will then be respected
9762
         * when TLSX_KEY_SHARE needs to be established */
9763
        if ((ssl && wolfSSL_set_groups(ssl, groups, groups_len)
9764
                        != WOLFSSL_SUCCESS)
9765
            || (ctx && wolfSSL_CTX_set_groups(ctx, groups, groups_len)
9766
                           != WOLFSSL_SUCCESS)) {
9767
            WOLFSSL_MSG("Unable to set supported curve");
9768
            goto leave;
9769
        }
9770
    #elif !defined(NO_WOLFSSL_CLIENT)
9771
        /* set the supported curve so client TLS extension contains only the
9772
         * desired curves */
9773
        if ((ssl && wolfSSL_UseSupportedCurve(ssl, curve) != WOLFSSL_SUCCESS)
9774
            || (ctx && wolfSSL_CTX_UseSupportedCurve(ctx, curve)
9775
                           != WOLFSSL_SUCCESS)) {
9776
            WOLFSSL_MSG("Unable to set supported curve");
9777
            goto leave;
9778
        }
9779
    #endif
9780
    #endif /* HAVE_SUPPORTED_CURVES && !NO_TLS */
9781
    }
9782
9783
    if (ssl != NULL)
9784
        ssl->disabledCurves = disabled;
9785
    else if (ctx != NULL)
9786
        ctx->disabledCurves = disabled;
9787
    ret = WOLFSSL_SUCCESS;
9788
9789
leave:
9790
#ifdef WOLFSSL_SMALL_STACK
9791
    if (groups)
9792
        XFREE((void*)groups, heap, DYNAMIC_TYPE_TMP_BUFFER);
9793
#endif
9794
    return ret;
9795
}
9796
9797
#endif /* (HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448) */
9798
#endif /* OPENSSL_EXTRA || HAVE_CURL */
9799
9800
9801
#ifdef OPENSSL_EXTRA
9802
/* Sets a callback for when sending and receiving protocol messages.
9803
 * This callback is copied to all WOLFSSL objects created from the ctx.
9804
 *
9805
 * ctx WOLFSSL_CTX structure to set callback in
9806
 * cb  callback to use
9807
 *
9808
 * return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE with error case
9809
 */
9810
int wolfSSL_CTX_set_msg_callback(WOLFSSL_CTX *ctx, SSL_Msg_Cb cb)
9811
{
9812
    WOLFSSL_ENTER("wolfSSL_CTX_set_msg_callback");
9813
    if (ctx == NULL) {
9814
        WOLFSSL_MSG("Null ctx passed in");
9815
        return WOLFSSL_FAILURE;
9816
    }
9817
9818
    ctx->protoMsgCb = cb;
9819
    return WOLFSSL_SUCCESS;
9820
}
9821
9822
9823
/* Sets a callback for when sending and receiving protocol messages.
9824
 *
9825
 * ssl WOLFSSL structure to set callback in
9826
 * cb  callback to use
9827
 *
9828
 * return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE with error case
9829
 */
9830
int wolfSSL_set_msg_callback(WOLFSSL *ssl, SSL_Msg_Cb cb)
9831
{
9832
    WOLFSSL_ENTER("wolfSSL_set_msg_callback");
9833
9834
    if (ssl == NULL) {
9835
        return WOLFSSL_FAILURE;
9836
    }
9837
9838
    if (cb != NULL) {
9839
        ssl->toInfoOn = 1;
9840
    }
9841
9842
    ssl->protoMsgCb = cb;
9843
    return WOLFSSL_SUCCESS;
9844
}
9845
9846
9847
/* set the user argument to pass to the msg callback when called
9848
 * return WOLFSSL_SUCCESS on success */
9849
int wolfSSL_CTX_set_msg_callback_arg(WOLFSSL_CTX *ctx, void* arg)
9850
{
9851
    WOLFSSL_ENTER("wolfSSL_CTX_set_msg_callback_arg");
9852
    if (ctx == NULL) {
9853
        WOLFSSL_MSG("Null WOLFSSL_CTX passed in");
9854
        return WOLFSSL_FAILURE;
9855
    }
9856
9857
    ctx->protoMsgCtx = arg;
9858
    return WOLFSSL_SUCCESS;
9859
}
9860
9861
9862
int wolfSSL_set_msg_callback_arg(WOLFSSL *ssl, void* arg)
9863
{
9864
    WOLFSSL_ENTER("wolfSSL_set_msg_callback_arg");
9865
    if (ssl == NULL)
9866
        return WOLFSSL_FAILURE;
9867
9868
    ssl->protoMsgCtx = arg;
9869
    return WOLFSSL_SUCCESS;
9870
}
9871
9872
void *wolfSSL_OPENSSL_memdup(const void *data, size_t siz, const char* file,
9873
    int line)
9874
{
9875
    void *ret;
9876
    (void)file;
9877
    (void)line;
9878
9879
    if (data == NULL || siz >= INT_MAX)
9880
        return NULL;
9881
9882
    ret = wolfSSL_OPENSSL_malloc(siz);
9883
    if (ret == NULL) {
9884
        return NULL;
9885
    }
9886
    return XMEMCPY(ret, data, siz);
9887
}
9888
9889
void wolfSSL_OPENSSL_cleanse(void *ptr, size_t len)
9890
{
9891
    if (ptr)
9892
        ForceZero(ptr, (word32)len);
9893
}
9894
9895
#endif /* OPENSSL_EXTRA */
9896
9897
#define WOLFSSL_SSL_API_EXT_INCLUDED
9898
#include "src/ssl_api_ext.c"
9899
9900
#if defined(OPENSSL_EXTRA)
9901
9902
#ifndef NO_BIO
9903
#define WOLFSSL_BIO_INCLUDED
9904
#include "src/bio.c"
9905
#endif
9906
9907
#endif /* OPENSSL_EXTRA */
9908
9909
9910
#if defined(OPENSSL_EXTRA)
9911
9912
/* frees all nodes in the current threads error queue
9913
 *
9914
 * id  thread id. ERR_remove_state is depreciated and id is ignored. The
9915
 *     current threads queue will be free'd.
9916
 */
9917
9918
#endif /* OPENSSL_EXTRA */
9919
9920
9921
#if defined(OPENSSL_EXTRA)
9922
/* wolfSSL_THREADID_current is provided as a compat API with
9923
 * CRYPTO_THREADID_current to register current thread id into given id object.
9924
 * However, CRYPTO_THREADID_current API has been deprecated and no longer
9925
 * exists in the OpenSSL 1.0.0 or later.This API only works as a stub
9926
 * like as existing wolfSSL_THREADID_set_numeric.
9927
 */
9928
void wolfSSL_THREADID_current(WOLFSSL_CRYPTO_THREADID* id)
9929
{
9930
    (void)id;
9931
    return;
9932
}
9933
/* wolfSSL_THREADID_hash is provided as a compatible API with
9934
 * CRYPTO_THREADID_hash which returns a hash value calculated from the
9935
 * specified thread id. However, CRYPTO_THREADID_hash API has been
9936
 * deprecated and no longer exists in the OpenSSL 1.0.0 or later.
9937
 * This API only works as a stub to returns 0. This behavior is
9938
 * equivalent to the latest OpenSSL CRYPTO_THREADID_hash.
9939
 */
9940
unsigned long wolfSSL_THREADID_hash(const WOLFSSL_CRYPTO_THREADID* id)
9941
{
9942
    (void)id;
9943
    return 0UL;
9944
}
9945
9946
/**
9947
 * Set security level (wolfSSL doesn't support setting the security level).
9948
 *
9949
 * The security level can only be set through a system wide crypto-policy
9950
 * with wolfSSL_crypto_policy_enable().
9951
 *
9952
 * @param ctx  a pointer to WOLFSSL_CTX structure
9953
 * @param level security level
9954
 */
9955
void wolfSSL_CTX_set_security_level(WOLFSSL_CTX* ctx, int level)
9956
{
9957
    WOLFSSL_ENTER("wolfSSL_CTX_set_security_level");
9958
    (void)ctx;
9959
    (void)level;
9960
}
9961
9962
int wolfSSL_CTX_get_security_level(const WOLFSSL_CTX * ctx)
9963
{
9964
    WOLFSSL_ENTER("wolfSSL_CTX_get_security_level");
9965
    #if defined(WOLFSSL_SYS_CRYPTO_POLICY)
9966
    if (ctx == NULL) {
9967
        return BAD_FUNC_ARG;
9968
    }
9969
9970
    return ctx->secLevel;
9971
    #else
9972
    (void)ctx;
9973
    return 0;
9974
    #endif /* WOLFSSL_SYS_CRYPTO_POLICY */
9975
}
9976
9977
#if defined(OPENSSL_EXTRA) && defined(HAVE_SECRET_CALLBACK)
9978
/*
9979
 * This API accepts a user callback which puts key-log records into
9980
 * a KEY LOGFILE. The callback is stored into a CTX and propagated to
9981
 * each SSL object on its creation timing.
9982
 */
9983
void wolfSSL_CTX_set_keylog_callback(WOLFSSL_CTX* ctx,
9984
    wolfSSL_CTX_keylog_cb_func cb)
9985
{
9986
    WOLFSSL_ENTER("wolfSSL_CTX_set_keylog_callback");
9987
    /* stores the callback into WOLFSSL_CTX */
9988
    if (ctx != NULL) {
9989
        ctx->keyLogCb = cb;
9990
    }
9991
}
9992
wolfSSL_CTX_keylog_cb_func wolfSSL_CTX_get_keylog_callback(
9993
    const WOLFSSL_CTX* ctx)
9994
{
9995
    WOLFSSL_ENTER("wolfSSL_CTX_get_keylog_callback");
9996
    if (ctx != NULL)
9997
        return ctx->keyLogCb;
9998
    return NULL;
9999
}
10000
#endif /* OPENSSL_EXTRA && HAVE_SECRET_CALLBACK */
10001
10002
#endif /* OPENSSL_EXTRA */
10003
10004
#ifdef WOLFSSL_THREADED_CRYPT
10005
int wolfSSL_AsyncEncryptReady(WOLFSSL* ssl, int idx)
10006
{
10007
    ThreadCrypt* encrypt;
10008
10009
    if (ssl == NULL) {
10010
        return 0;
10011
    }
10012
10013
    encrypt = &ssl->buffers.encrypt[idx];
10014
    return (encrypt->avail == 0) && (encrypt->done == 0);
10015
}
10016
10017
int wolfSSL_AsyncEncryptStop(WOLFSSL* ssl, int idx)
10018
{
10019
    ThreadCrypt* encrypt;
10020
10021
    if (ssl == NULL) {
10022
        return 1;
10023
    }
10024
10025
    encrypt = &ssl->buffers.encrypt[idx];
10026
    return encrypt->stop;
10027
}
10028
10029
int wolfSSL_AsyncEncrypt(WOLFSSL* ssl, int idx)
10030
{
10031
    int ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN);
10032
    ThreadCrypt* encrypt = &ssl->buffers.encrypt[idx];
10033
10034
    if (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm) {
10035
        unsigned char* out = encrypt->buffer.buffer + encrypt->offset;
10036
        unsigned char* input = encrypt->buffer.buffer + encrypt->offset;
10037
        word32 encSz = encrypt->buffer.length - encrypt->offset;
10038
10039
        ret =
10040
#if !defined(NO_GCM_ENCRYPT_EXTRA) && \
10041
    ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \
10042
    (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)))
10043
              wc_AesGcmEncrypt_ex
10044
#else
10045
              wc_AesGcmEncrypt
10046
#endif
10047
              (encrypt->encrypt.aes,
10048
               out + AESGCM_EXP_IV_SZ, input + AESGCM_EXP_IV_SZ,
10049
               encSz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size,
10050
               encrypt->nonce, AESGCM_NONCE_SZ,
10051
               out + encSz - ssl->specs.aead_mac_size,
10052
               ssl->specs.aead_mac_size,
10053
               encrypt->additional, AEAD_AUTH_DATA_SZ);
10054
#if !defined(NO_PUBLIC_GCM_SET_IV) && \
10055
    ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \
10056
    (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)))
10057
        XMEMCPY(out, encrypt->nonce + AESGCM_IMP_IV_SZ, AESGCM_EXP_IV_SZ);
10058
#endif
10059
        encrypt->done = 1;
10060
    }
10061
10062
    return ret;
10063
}
10064
10065
int wolfSSL_AsyncEncryptSetSignal(WOLFSSL* ssl, int idx,
10066
    WOLFSSL_THREAD_SIGNAL signal, void* ctx)
10067
{
10068
    int ret = 0;
10069
10070
    if (ssl == NULL) {
10071
        ret = BAD_FUNC_ARG;
10072
    }
10073
    else {
10074
        ssl->buffers.encrypt[idx].signal = signal;
10075
        ssl->buffers.encrypt[idx].signalCtx = ctx;
10076
    }
10077
10078
    return ret;
10079
}
10080
#endif
10081
10082
10083
#ifndef NO_CERT
10084
#define WOLFSSL_X509_INCLUDED
10085
#include "src/x509.c"
10086
#endif
10087
10088
/*******************************************************************************
10089
 * START OF standard C library wrapping APIs
10090
 ******************************************************************************/
10091
#if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && \
10092
    (defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \
10093
     defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \
10094
     defined(WOLFSSL_OPENSSH)))
10095
#ifndef NO_WOLFSSL_STUB
10096
int wolfSSL_CRYPTO_set_mem_ex_functions(void *(*m) (size_t, const char *, int),
10097
                                void *(*r) (void *, size_t, const char *,
10098
                                            int), void (*f) (void *))
10099
{
10100
    (void) m;
10101
    (void) r;
10102
    (void) f;
10103
    WOLFSSL_ENTER("wolfSSL_CRYPTO_set_mem_ex_functions");
10104
    WOLFSSL_STUB("CRYPTO_set_mem_ex_functions");
10105
10106
    return WOLFSSL_FAILURE;
10107
}
10108
#endif
10109
#endif
10110
10111
#if defined(OPENSSL_EXTRA)
10112
10113
/**
10114
 * free allocated memory resource
10115
 * @param str  a pointer to resource to be freed
10116
 * @param file dummy argument
10117
 * @param line dummy argument
10118
 */
10119
void wolfSSL_CRYPTO_free(void *str, const char *file, int line)
10120
{
10121
    (void)file;
10122
    (void)line;
10123
    XFREE(str, 0, DYNAMIC_TYPE_TMP_BUFFER);
10124
}
10125
/**
10126
 * allocate memory with size of num
10127
 * @param num  size of memory allocation to be malloced
10128
 * @param file dummy argument
10129
 * @param line dummy argument
10130
 * @return a pointer to allocated memory on succssesful, otherwise NULL
10131
 */
10132
void *wolfSSL_CRYPTO_malloc(size_t num, const char *file, int line)
10133
{
10134
    (void)file;
10135
    (void)line;
10136
    return XMALLOC(num, 0, DYNAMIC_TYPE_TMP_BUFFER);
10137
}
10138
10139
#endif
10140
10141
/*******************************************************************************
10142
 * END OF standard C library wrapping APIs
10143
 ******************************************************************************/
10144
10145
/*******************************************************************************
10146
 * START OF EX_DATA APIs
10147
 ******************************************************************************/
10148
#ifdef HAVE_EX_DATA
10149
void wolfSSL_CRYPTO_cleanup_all_ex_data(void)
10150
{
10151
    WOLFSSL_ENTER("wolfSSL_CRYPTO_cleanup_all_ex_data");
10152
}
10153
10154
void* wolfSSL_CRYPTO_get_ex_data(const WOLFSSL_CRYPTO_EX_DATA* ex_data, int idx)
10155
{
10156
    WOLFSSL_ENTER("wolfSSL_CRYPTO_get_ex_data");
10157
#ifdef MAX_EX_DATA
10158
    if (ex_data && idx < MAX_EX_DATA && idx >= 0) {
10159
        return ex_data->ex_data[idx];
10160
    }
10161
#else
10162
    (void)ex_data;
10163
    (void)idx;
10164
#endif
10165
    return NULL;
10166
}
10167
10168
int wolfSSL_CRYPTO_set_ex_data(WOLFSSL_CRYPTO_EX_DATA* ex_data, int idx,
10169
    void *data)
10170
{
10171
    WOLFSSL_ENTER("wolfSSL_CRYPTO_set_ex_data");
10172
#ifdef MAX_EX_DATA
10173
    if (ex_data && idx < MAX_EX_DATA && idx >= 0) {
10174
#ifdef HAVE_EX_DATA_CLEANUP_HOOKS
10175
        if (ex_data->ex_data_cleanup_routines[idx]) {
10176
            /* call cleanup then remove cleanup callback,
10177
             * since different value is being set */
10178
            if (ex_data->ex_data[idx])
10179
                ex_data->ex_data_cleanup_routines[idx](ex_data->ex_data[idx]);
10180
            ex_data->ex_data_cleanup_routines[idx] = NULL;
10181
        }
10182
#endif
10183
        ex_data->ex_data[idx] = data;
10184
        return WOLFSSL_SUCCESS;
10185
    }
10186
#else
10187
    (void)ex_data;
10188
    (void)idx;
10189
    (void)data;
10190
#endif
10191
    return WOLFSSL_FAILURE;
10192
}
10193
10194
#ifdef HAVE_EX_DATA_CLEANUP_HOOKS
10195
int wolfSSL_CRYPTO_set_ex_data_with_cleanup(
10196
    WOLFSSL_CRYPTO_EX_DATA* ex_data,
10197
    int idx,
10198
    void *data,
10199
    wolfSSL_ex_data_cleanup_routine_t cleanup_routine)
10200
{
10201
    WOLFSSL_ENTER("wolfSSL_CRYPTO_set_ex_data_with_cleanup");
10202
    if (ex_data && idx < MAX_EX_DATA && idx >= 0) {
10203
        if (ex_data->ex_data_cleanup_routines[idx] && ex_data->ex_data[idx])
10204
            ex_data->ex_data_cleanup_routines[idx](ex_data->ex_data[idx]);
10205
        ex_data->ex_data[idx] = data;
10206
        ex_data->ex_data_cleanup_routines[idx] = cleanup_routine;
10207
        return WOLFSSL_SUCCESS;
10208
    }
10209
    return WOLFSSL_FAILURE;
10210
}
10211
#endif /* HAVE_EX_DATA_CLEANUP_HOOKS */
10212
#endif /* HAVE_EX_DATA */
10213
10214
#ifdef HAVE_EX_DATA_CRYPTO
10215
/**
10216
 * Issues unique index for the class specified by class_index.
10217
 * Other parameter except class_index are ignored.
10218
 * Currently, following class_index are accepted:
10219
 *  - WOLF_CRYPTO_EX_INDEX_SSL
10220
 *  - WOLF_CRYPTO_EX_INDEX_SSL_CTX
10221
 *  - WOLF_CRYPTO_EX_INDEX_X509
10222
 * @param class_index index one of CRYPTO_EX_INDEX_xxx
10223
 * @param argp  parameters to be saved
10224
 * @param argl  parameters to be saved
10225
 * @param new_func a pointer to WOLFSSL_CRYPTO_EX_new
10226
 * @param dup_func a pointer to WOLFSSL_CRYPTO_EX_dup
10227
 * @param free_func a pointer to WOLFSSL_CRYPTO_EX_free
10228
 * @return index value grater or equal to zero on success, -1 on failure.
10229
 */
10230
int wolfSSL_CRYPTO_get_ex_new_index(int class_index, long argl, void *argp,
10231
                                           WOLFSSL_CRYPTO_EX_new* new_func,
10232
                                           WOLFSSL_CRYPTO_EX_dup* dup_func,
10233
                                           WOLFSSL_CRYPTO_EX_free* free_func)
10234
{
10235
    WOLFSSL_ENTER("wolfSSL_CRYPTO_get_ex_new_index");
10236
10237
    return wolfssl_local_get_ex_new_index(class_index, argl, argp, new_func,
10238
            dup_func, free_func);
10239
}
10240
#endif /* HAVE_EX_DATA_CRYPTO */
10241
10242
/*******************************************************************************
10243
 * END OF EX_DATA APIs
10244
 ******************************************************************************/
10245
10246
/*******************************************************************************
10247
 * START OF BUF_MEM API
10248
 ******************************************************************************/
10249
10250
#if defined(OPENSSL_EXTRA)
10251
10252
/* Begin functions for openssl/buffer.h */
10253
WOLFSSL_BUF_MEM* wolfSSL_BUF_MEM_new(void)
10254
{
10255
    WOLFSSL_BUF_MEM* buf;
10256
    buf = (WOLFSSL_BUF_MEM*)XMALLOC(sizeof(WOLFSSL_BUF_MEM), NULL,
10257
                                                        DYNAMIC_TYPE_OPENSSL);
10258
    if (buf) {
10259
        XMEMSET(buf, 0, sizeof(WOLFSSL_BUF_MEM));
10260
    }
10261
    return buf;
10262
}
10263
10264
/* non-compat API returns length of buffer on success */
10265
int wolfSSL_BUF_MEM_grow_ex(WOLFSSL_BUF_MEM* buf, size_t len,
10266
        char zeroFill)
10267
{
10268
    size_t mx;
10269
    char* tmp;
10270
10271
    /* verify provided arguments. The return value is an int holding the
10272
     * resulting length, so reject any len that cannot be represented as a
10273
     * non-negative int. This also prevents truncating size_t to int. */
10274
    if (buf == NULL || len > (size_t)WC_MAX_SINT_OF(int)) {
10275
        return 0; /* BAD_FUNC_ARG; */
10276
    }
10277
10278
    /* check to see if fits in existing length */
10279
    if (buf->length > len) {
10280
        buf->length = len;
10281
        return (int)len;
10282
    }
10283
10284
    /* check to see if fits in max buffer */
10285
    if (buf->max >= len) {
10286
        if (buf->data != NULL && zeroFill) {
10287
            XMEMSET(&buf->data[buf->length], 0, len - buf->length);
10288
        }
10289
        buf->length = len;
10290
        return (int)len;
10291
    }
10292
10293
    /* expand size, to handle growth */
10294
    mx = (len + 3) / 3 * 4;
10295
10296
#ifdef WOLFSSL_NO_REALLOC
10297
    tmp = (char*)XMALLOC(mx, NULL, DYNAMIC_TYPE_OPENSSL);
10298
    if (tmp != NULL && buf->data != NULL) {
10299
       /* only the existing content is valid in the old buffer; copying
10300
        * len_int (the new, larger size) would read past buf->max */
10301
       XMEMCPY(tmp, buf->data, buf->length);
10302
       XFREE(buf->data, NULL, DYNAMIC_TYPE_OPENSSL);
10303
       buf->data = NULL;
10304
    }
10305
#else
10306
    /* use realloc */
10307
    tmp = (char*)XREALLOC(buf->data, mx, NULL, DYNAMIC_TYPE_OPENSSL);
10308
#endif
10309
10310
    if (tmp == NULL) {
10311
        return 0; /* ERR_R_MALLOC_FAILURE; */
10312
    }
10313
    buf->data = tmp;
10314
10315
    buf->max = mx;
10316
    if (zeroFill)
10317
        XMEMSET(&buf->data[buf->length], 0, len - buf->length);
10318
    buf->length = len;
10319
10320
    return (int)len;
10321
10322
}
10323
10324
/* returns length of buffer on success */
10325
int wolfSSL_BUF_MEM_grow(WOLFSSL_BUF_MEM* buf, size_t len)
10326
{
10327
    return wolfSSL_BUF_MEM_grow_ex(buf, len, 1);
10328
}
10329
10330
/* non-compat API returns length of buffer on success */
10331
int wolfSSL_BUF_MEM_resize(WOLFSSL_BUF_MEM* buf, size_t len)
10332
{
10333
    char* tmp;
10334
    size_t mx;
10335
10336
    /* verify provided arguments. The return value is an int, so reject any
10337
     * len that cannot be represented as a positive int. */
10338
    if (buf == NULL || len == 0 || len > (size_t)WC_MAX_SINT_OF(int)) {
10339
        return 0; /* BAD_FUNC_ARG; */
10340
    }
10341
10342
    if (len == buf->length)
10343
        return (int)len;
10344
10345
    if (len > buf->length)
10346
        return wolfSSL_BUF_MEM_grow_ex(buf, len, 0);
10347
10348
    /* expand size, to handle growth */
10349
    mx = (len + 3) / 3 * 4;
10350
10351
    /* We want to shrink the internal buffer */
10352
#ifdef WOLFSSL_NO_REALLOC
10353
    tmp = (char*)XMALLOC(mx, NULL, DYNAMIC_TYPE_OPENSSL);
10354
    if (tmp != NULL && buf->data != NULL)
10355
    {
10356
        XMEMCPY(tmp, buf->data, len);
10357
        XFREE(buf->data,NULL,DYNAMIC_TYPE_OPENSSL);
10358
        buf->data = NULL;
10359
    }
10360
#else
10361
    tmp = (char*)XREALLOC(buf->data, mx, NULL, DYNAMIC_TYPE_OPENSSL);
10362
#endif
10363
10364
    if (tmp == NULL)
10365
        return 0;
10366
10367
    buf->data = tmp;
10368
    buf->length = len;
10369
    buf->max = mx;
10370
10371
    return (int)len;
10372
}
10373
10374
void wolfSSL_BUF_MEM_free(WOLFSSL_BUF_MEM* buf)
10375
{
10376
    if (buf) {
10377
        XFREE(buf->data, NULL, DYNAMIC_TYPE_OPENSSL);
10378
        buf->data = NULL;
10379
        buf->max = 0;
10380
        buf->length = 0;
10381
        XFREE(buf, NULL, DYNAMIC_TYPE_OPENSSL);
10382
    }
10383
}
10384
/* End Functions for openssl/buffer.h */
10385
10386
#endif /* OPENSSL_EXTRA */
10387
10388
/*******************************************************************************
10389
 * END OF BUF_MEM API
10390
 ******************************************************************************/
10391
10392
#define WOLFSSL_CONF_INCLUDED
10393
#include <src/conf.c>
10394
10395
/*******************************************************************************
10396
 * START OF EVP_CIPHER API
10397
 ******************************************************************************/
10398
10399
#ifdef OPENSSL_EXTRA
10400
10401
    /* store for external read of iv, WOLFSSL_SUCCESS on success */
10402
    int  wolfSSL_StoreExternalIV(WOLFSSL_EVP_CIPHER_CTX* ctx)
10403
    {
10404
        WOLFSSL_ENTER("wolfSSL_StoreExternalIV");
10405
10406
        if (ctx == NULL) {
10407
            WOLFSSL_MSG("Bad function argument");
10408
            return WOLFSSL_FATAL_ERROR;
10409
        }
10410
10411
        switch (ctx->cipherType) {
10412
#ifndef NO_AES
10413
#if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT)
10414
            case WC_AES_128_CBC_TYPE :
10415
            case WC_AES_192_CBC_TYPE :
10416
            case WC_AES_256_CBC_TYPE :
10417
                WOLFSSL_MSG("AES CBC");
10418
                XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, ctx->ivSz);
10419
                break;
10420
#endif
10421
#ifdef HAVE_AESGCM
10422
            case WC_AES_128_GCM_TYPE :
10423
            case WC_AES_192_GCM_TYPE :
10424
            case WC_AES_256_GCM_TYPE :
10425
                WOLFSSL_MSG("AES GCM");
10426
                XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, ctx->ivSz);
10427
                break;
10428
#endif /* HAVE_AESGCM */
10429
#ifdef HAVE_AESCCM
10430
            case WC_AES_128_CCM_TYPE :
10431
            case WC_AES_192_CCM_TYPE :
10432
            case WC_AES_256_CCM_TYPE :
10433
                WOLFSSL_MSG("AES CCM");
10434
                XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, ctx->ivSz);
10435
                break;
10436
#endif /* HAVE_AESCCM */
10437
#ifdef HAVE_AES_ECB
10438
            case WC_AES_128_ECB_TYPE :
10439
            case WC_AES_192_ECB_TYPE :
10440
            case WC_AES_256_ECB_TYPE :
10441
                WOLFSSL_MSG("AES ECB");
10442
                break;
10443
#endif
10444
#ifdef WOLFSSL_AES_COUNTER
10445
            case WC_AES_128_CTR_TYPE :
10446
            case WC_AES_192_CTR_TYPE :
10447
            case WC_AES_256_CTR_TYPE :
10448
                WOLFSSL_MSG("AES CTR");
10449
                XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, WC_AES_BLOCK_SIZE);
10450
                break;
10451
#endif /* WOLFSSL_AES_COUNTER */
10452
#ifdef WOLFSSL_AES_CFB
10453
#if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS)
10454
            case WC_AES_128_CFB1_TYPE:
10455
            case WC_AES_192_CFB1_TYPE:
10456
            case WC_AES_256_CFB1_TYPE:
10457
                WOLFSSL_MSG("AES CFB1");
10458
                break;
10459
            case WC_AES_128_CFB8_TYPE:
10460
            case WC_AES_192_CFB8_TYPE:
10461
            case WC_AES_256_CFB8_TYPE:
10462
                WOLFSSL_MSG("AES CFB8");
10463
                break;
10464
#endif /* !HAVE_SELFTEST && !HAVE_FIPS */
10465
            case WC_AES_128_CFB128_TYPE:
10466
            case WC_AES_192_CFB128_TYPE:
10467
            case WC_AES_256_CFB128_TYPE:
10468
                WOLFSSL_MSG("AES CFB128");
10469
                break;
10470
#endif /* WOLFSSL_AES_CFB */
10471
#if defined(WOLFSSL_AES_OFB)
10472
            case WC_AES_128_OFB_TYPE:
10473
            case WC_AES_192_OFB_TYPE:
10474
            case WC_AES_256_OFB_TYPE:
10475
                WOLFSSL_MSG("AES OFB");
10476
                break;
10477
#endif /* WOLFSSL_AES_OFB */
10478
#ifdef WOLFSSL_AES_XTS
10479
            case WC_AES_128_XTS_TYPE:
10480
            case WC_AES_256_XTS_TYPE:
10481
                WOLFSSL_MSG("AES XTS");
10482
                break;
10483
#endif /* WOLFSSL_AES_XTS */
10484
#endif /* NO_AES */
10485
10486
#ifdef HAVE_ARIA
10487
            case WC_ARIA_128_GCM_TYPE :
10488
            case WC_ARIA_192_GCM_TYPE :
10489
            case WC_ARIA_256_GCM_TYPE :
10490
                WOLFSSL_MSG("ARIA GCM");
10491
                XMEMCPY(ctx->iv, &ctx->cipher.aria.nonce, ARIA_BLOCK_SIZE);
10492
                break;
10493
#endif /* HAVE_ARIA */
10494
10495
#ifndef NO_DES3
10496
            case WC_DES_CBC_TYPE :
10497
                WOLFSSL_MSG("DES CBC");
10498
                XMEMCPY(ctx->iv, &ctx->cipher.des.reg, DES_BLOCK_SIZE);
10499
                break;
10500
10501
            case WC_DES_EDE3_CBC_TYPE :
10502
                WOLFSSL_MSG("DES EDE3 CBC");
10503
                XMEMCPY(ctx->iv, &ctx->cipher.des3.reg, DES_BLOCK_SIZE);
10504
                break;
10505
#endif
10506
#ifdef WOLFSSL_DES_ECB
10507
            case WC_DES_ECB_TYPE :
10508
                WOLFSSL_MSG("DES ECB");
10509
                break;
10510
            case WC_DES_EDE3_ECB_TYPE :
10511
                WOLFSSL_MSG("DES3 ECB");
10512
                break;
10513
#endif
10514
            case WC_ARC4_TYPE :
10515
                WOLFSSL_MSG("ARC4");
10516
                break;
10517
10518
#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
10519
            case WC_CHACHA20_POLY1305_TYPE:
10520
                break;
10521
#endif
10522
10523
#ifdef HAVE_CHACHA
10524
            case WC_CHACHA20_TYPE:
10525
                break;
10526
#endif
10527
10528
#ifdef WOLFSSL_SM4_ECB
10529
            case WC_SM4_ECB_TYPE:
10530
                break;
10531
#endif
10532
#ifdef WOLFSSL_SM4_CBC
10533
            case WC_SM4_CBC_TYPE:
10534
                WOLFSSL_MSG("SM4 CBC");
10535
                XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE);
10536
                break;
10537
#endif
10538
#ifdef WOLFSSL_SM4_CTR
10539
            case WC_SM4_CTR_TYPE:
10540
                WOLFSSL_MSG("SM4 CTR");
10541
                XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE);
10542
                break;
10543
#endif
10544
#ifdef WOLFSSL_SM4_GCM
10545
            case WC_SM4_GCM_TYPE:
10546
                WOLFSSL_MSG("SM4 GCM");
10547
                XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE);
10548
                break;
10549
#endif
10550
#ifdef WOLFSSL_SM4_CCM
10551
            case WC_SM4_CCM_TYPE:
10552
                WOLFSSL_MSG("SM4 CCM");
10553
                XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE);
10554
                break;
10555
#endif
10556
10557
            case WC_NULL_CIPHER_TYPE :
10558
                WOLFSSL_MSG("NULL");
10559
                break;
10560
10561
            default: {
10562
                WOLFSSL_MSG("bad type");
10563
                return WOLFSSL_FATAL_ERROR;
10564
            }
10565
        }
10566
        return WOLFSSL_SUCCESS;
10567
    }
10568
10569
    /* set internal IV from external, WOLFSSL_SUCCESS on success */
10570
    int  wolfSSL_SetInternalIV(WOLFSSL_EVP_CIPHER_CTX* ctx)
10571
    {
10572
10573
        WOLFSSL_ENTER("wolfSSL_SetInternalIV");
10574
10575
        if (ctx == NULL) {
10576
            WOLFSSL_MSG("Bad function argument");
10577
            return WOLFSSL_FATAL_ERROR;
10578
        }
10579
10580
        switch (ctx->cipherType) {
10581
10582
#ifndef NO_AES
10583
#if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT)
10584
            case WC_AES_128_CBC_TYPE :
10585
            case WC_AES_192_CBC_TYPE :
10586
            case WC_AES_256_CBC_TYPE :
10587
                WOLFSSL_MSG("AES CBC");
10588
                XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, WC_AES_BLOCK_SIZE);
10589
                break;
10590
#endif
10591
#ifdef HAVE_AESGCM
10592
            case WC_AES_128_GCM_TYPE :
10593
            case WC_AES_192_GCM_TYPE :
10594
            case WC_AES_256_GCM_TYPE :
10595
                WOLFSSL_MSG("AES GCM");
10596
                XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, WC_AES_BLOCK_SIZE);
10597
                break;
10598
#endif
10599
#ifdef HAVE_AES_ECB
10600
            case WC_AES_128_ECB_TYPE :
10601
            case WC_AES_192_ECB_TYPE :
10602
            case WC_AES_256_ECB_TYPE :
10603
                WOLFSSL_MSG("AES ECB");
10604
                break;
10605
#endif
10606
#ifdef WOLFSSL_AES_COUNTER
10607
            case WC_AES_128_CTR_TYPE :
10608
            case WC_AES_192_CTR_TYPE :
10609
            case WC_AES_256_CTR_TYPE :
10610
                WOLFSSL_MSG("AES CTR");
10611
                XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, WC_AES_BLOCK_SIZE);
10612
                break;
10613
#endif
10614
10615
#endif /* NO_AES */
10616
10617
#ifdef HAVE_ARIA
10618
            case WC_ARIA_128_GCM_TYPE :
10619
            case WC_ARIA_192_GCM_TYPE :
10620
            case WC_ARIA_256_GCM_TYPE :
10621
                WOLFSSL_MSG("ARIA GCM");
10622
                XMEMCPY(&ctx->cipher.aria.nonce, ctx->iv, ARIA_BLOCK_SIZE);
10623
                break;
10624
#endif /* HAVE_ARIA */
10625
10626
#ifndef NO_DES3
10627
            case WC_DES_CBC_TYPE :
10628
                WOLFSSL_MSG("DES CBC");
10629
                XMEMCPY(&ctx->cipher.des.reg, ctx->iv, DES_BLOCK_SIZE);
10630
                break;
10631
10632
            case WC_DES_EDE3_CBC_TYPE :
10633
                WOLFSSL_MSG("DES EDE3 CBC");
10634
                XMEMCPY(&ctx->cipher.des3.reg, ctx->iv, DES_BLOCK_SIZE);
10635
                break;
10636
#endif
10637
#ifdef WOLFSSL_DES_ECB
10638
            case WC_DES_ECB_TYPE :
10639
                WOLFSSL_MSG("DES ECB");
10640
                break;
10641
            case WC_DES_EDE3_ECB_TYPE :
10642
                WOLFSSL_MSG("DES3 ECB");
10643
                break;
10644
#endif
10645
10646
            case WC_ARC4_TYPE :
10647
                WOLFSSL_MSG("ARC4");
10648
                break;
10649
10650
#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
10651
            case WC_CHACHA20_POLY1305_TYPE:
10652
                break;
10653
#endif
10654
10655
#ifdef HAVE_CHACHA
10656
            case WC_CHACHA20_TYPE:
10657
                break;
10658
#endif
10659
10660
#ifdef WOLFSSL_SM4_ECB
10661
            case WC_SM4_ECB_TYPE:
10662
                break;
10663
#endif
10664
#ifdef WOLFSSL_SM4_CBC
10665
            case WC_SM4_CBC_TYPE:
10666
                WOLFSSL_MSG("SM4 CBC");
10667
                XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz);
10668
                break;
10669
#endif
10670
#ifdef WOLFSSL_SM4_CTR
10671
            case WC_SM4_CTR_TYPE:
10672
                WOLFSSL_MSG("SM4 CTR");
10673
                XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz);
10674
                break;
10675
#endif
10676
#ifdef WOLFSSL_SM4_GCM
10677
            case WC_SM4_GCM_TYPE:
10678
                WOLFSSL_MSG("SM4 GCM");
10679
                XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz);
10680
                break;
10681
#endif
10682
#ifdef WOLFSSL_SM4_CCM
10683
            case WC_SM4_CCM_TYPE:
10684
                WOLFSSL_MSG("SM4 CCM");
10685
                XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz);
10686
                break;
10687
#endif
10688
10689
            case WC_NULL_CIPHER_TYPE :
10690
                WOLFSSL_MSG("NULL");
10691
                break;
10692
10693
            default: {
10694
                WOLFSSL_MSG("bad type");
10695
                return WOLFSSL_FATAL_ERROR;
10696
            }
10697
        }
10698
        return WOLFSSL_SUCCESS;
10699
    }
10700
10701
#ifndef NO_DES3
10702
10703
void wolfSSL_3des_iv(WOLFSSL_EVP_CIPHER_CTX* ctx, int doset,
10704
                            unsigned char* iv, int len)
10705
{
10706
    (void)len;
10707
10708
    WOLFSSL_MSG("wolfSSL_3des_iv");
10709
10710
    if (ctx == NULL || iv == NULL) {
10711
        WOLFSSL_MSG("Bad function argument");
10712
        return;
10713
    }
10714
10715
    if (doset)
10716
        wc_Des3_SetIV(&ctx->cipher.des3, iv);  /* OpenSSL compat, no ret */
10717
    else
10718
        XMEMCPY(iv, &ctx->cipher.des3.reg, DES_BLOCK_SIZE);
10719
}
10720
10721
#endif /* NO_DES3 */
10722
10723
10724
#ifndef NO_AES
10725
10726
void wolfSSL_aes_ctr_iv(WOLFSSL_EVP_CIPHER_CTX* ctx, int doset,
10727
                      unsigned char* iv, int len)
10728
{
10729
    (void)len;
10730
10731
    WOLFSSL_MSG("wolfSSL_aes_ctr_iv");
10732
10733
    if (ctx == NULL || iv == NULL) {
10734
        WOLFSSL_MSG("Bad function argument");
10735
        return;
10736
    }
10737
10738
    if (doset)
10739
       (void)wc_AesSetIV(&ctx->cipher.aes, iv);  /* OpenSSL compat, no ret */
10740
    else
10741
        XMEMCPY(iv, &ctx->cipher.aes.reg, WC_AES_BLOCK_SIZE);
10742
}
10743
10744
#endif /* NO_AES */
10745
10746
#endif /* OPENSSL_EXTRA */
10747
10748
/*******************************************************************************
10749
 * END OF EVP_CIPHER API
10750
 ******************************************************************************/
10751
10752
#ifndef NO_CERTS
10753
10754
#define WOLFSSL_X509_STORE_INCLUDED
10755
#include <src/x509_str.c>
10756
10757
#define WOLFSSL_SSL_P7P12_INCLUDED
10758
#include <src/ssl_p7p12.c>
10759
10760
#endif /* !NO_CERTS */
10761
10762
10763
/*******************************************************************************
10764
 * BEGIN OPENSSL FIPS DRBG APIs
10765
 ******************************************************************************/
10766
#if defined(OPENSSL_EXTRA) && !defined(WC_NO_RNG) && defined(HAVE_HASHDRBG)
10767
int wolfSSL_FIPS_drbg_init(WOLFSSL_DRBG_CTX *ctx, int type, unsigned int flags)
10768
{
10769
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
10770
    if (ctx != NULL) {
10771
        XMEMSET(ctx, 0, sizeof(WOLFSSL_DRBG_CTX));
10772
        ctx->type = type;
10773
        ctx->xflags = (int)flags;
10774
        ctx->status = DRBG_STATUS_UNINITIALISED;
10775
        ret = WOLFSSL_SUCCESS;
10776
    }
10777
    return ret;
10778
}
10779
WOLFSSL_DRBG_CTX* wolfSSL_FIPS_drbg_new(int type, unsigned int flags)
10780
{
10781
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
10782
    WOLFSSL_DRBG_CTX* ctx = (WOLFSSL_DRBG_CTX*)XMALLOC(sizeof(WOLFSSL_DRBG_CTX),
10783
        NULL, DYNAMIC_TYPE_OPENSSL);
10784
    ret = wolfSSL_FIPS_drbg_init(ctx, type, flags);
10785
    if (ret == WOLFSSL_SUCCESS && type != 0) {
10786
        ret = wolfSSL_FIPS_drbg_instantiate(ctx, NULL, 0);
10787
    }
10788
    if (ret != WOLFSSL_SUCCESS) {
10789
        WOLFSSL_ERROR(ret);
10790
        wolfSSL_FIPS_drbg_free(ctx);
10791
        ctx = NULL;
10792
    }
10793
    return ctx;
10794
}
10795
int wolfSSL_FIPS_drbg_instantiate(WOLFSSL_DRBG_CTX* ctx,
10796
    const unsigned char* pers, size_t perslen)
10797
{
10798
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
10799
    if (ctx != NULL && ctx->rng == NULL) {
10800
    #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
10801
        (defined(HAVE_FIPS) && FIPS_VERSION_GE(5,0)))
10802
        ctx->rng = wc_rng_new((byte*)pers, (word32)perslen, NULL);
10803
    #else
10804
        ctx->rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
10805
        if (ctx->rng != NULL) {
10806
        #if defined(HAVE_FIPS) && FIPS_VERSION_GE(2,0)
10807
            ret = wc_InitRngNonce(ctx->rng, (byte*)pers, (word32)perslen);
10808
        #else
10809
            ret = wc_InitRng(ctx->rng);
10810
            (void)pers;
10811
            (void)perslen;
10812
        #endif
10813
            if (ret != 0) {
10814
                WOLFSSL_ERROR(ret);
10815
                XFREE(ctx->rng, NULL, DYNAMIC_TYPE_RNG);
10816
                ctx->rng = NULL;
10817
            }
10818
        }
10819
    #endif
10820
    }
10821
    if (ctx != NULL && ctx->rng != NULL) {
10822
        ctx->status = DRBG_STATUS_READY;
10823
        ret = WOLFSSL_SUCCESS;
10824
    }
10825
    return ret;
10826
}
10827
int wolfSSL_FIPS_drbg_set_callbacks(WOLFSSL_DRBG_CTX* ctx,
10828
    drbg_entropy_get entropy_get, drbg_entropy_clean entropy_clean,
10829
    size_t entropy_blocklen,
10830
    drbg_nonce_get none_get, drbg_nonce_clean nonce_clean)
10831
{
10832
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
10833
    if (ctx != NULL) {
10834
        ctx->entropy_get = entropy_get;
10835
        ctx->entropy_clean = entropy_clean;
10836
        ctx->entropy_blocklen = entropy_blocklen;
10837
        ctx->none_get = none_get;
10838
        ctx->nonce_clean = nonce_clean;
10839
        ret = WOLFSSL_SUCCESS;
10840
    }
10841
    return ret;
10842
}
10843
void wolfSSL_FIPS_rand_add(const void* buf, int num, double entropy)
10844
{
10845
    /* not implemented */
10846
    (void)buf;
10847
    (void)num;
10848
    (void)entropy;
10849
}
10850
int wolfSSL_FIPS_drbg_reseed(WOLFSSL_DRBG_CTX* ctx, const unsigned char* adin,
10851
    size_t adinlen)
10852
{
10853
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
10854
    if (ctx != NULL && ctx->rng != NULL) {
10855
    #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
10856
        (defined(HAVE_FIPS) && FIPS_VERSION_GE(2,0)))
10857
        if (wc_RNG_DRBG_Reseed(ctx->rng, adin, (word32)adinlen) == 0) {
10858
            ret = WOLFSSL_SUCCESS;
10859
        }
10860
    #else
10861
        ret = WOLFSSL_SUCCESS;
10862
        (void)adin;
10863
        (void)adinlen;
10864
    #endif
10865
    }
10866
    return ret;
10867
}
10868
int wolfSSL_FIPS_drbg_generate(WOLFSSL_DRBG_CTX* ctx, unsigned char* out,
10869
    size_t outlen, int prediction_resistance, const unsigned char* adin,
10870
    size_t adinlen)
10871
{
10872
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
10873
    if (ctx != NULL && ctx->rng != NULL) {
10874
        ret = wc_RNG_GenerateBlock(ctx->rng, out, (word32)outlen);
10875
        if (ret == 0) {
10876
            ret = WOLFSSL_SUCCESS;
10877
        }
10878
    }
10879
    (void)prediction_resistance;
10880
    (void)adin;
10881
    (void)adinlen;
10882
    return ret;
10883
}
10884
int wolfSSL_FIPS_drbg_uninstantiate(WOLFSSL_DRBG_CTX *ctx)
10885
{
10886
    if (ctx != NULL && ctx->rng != NULL) {
10887
    #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
10888
        (defined(HAVE_FIPS) && FIPS_VERSION_GE(5,0)))
10889
        wc_rng_free(ctx->rng);
10890
    #else
10891
        wc_FreeRng(ctx->rng);
10892
        XFREE(ctx->rng, NULL, DYNAMIC_TYPE_RNG);
10893
    #endif
10894
        ctx->rng = NULL;
10895
        ctx->status = DRBG_STATUS_UNINITIALISED;
10896
    }
10897
    return WOLFSSL_SUCCESS;
10898
}
10899
void wolfSSL_FIPS_drbg_free(WOLFSSL_DRBG_CTX *ctx)
10900
{
10901
    if (ctx != NULL) {
10902
        int locked = 0;
10903
        int haveMutex = 1;
10904
        /* As safety check if free'ing the default drbg, then mark global NULL.
10905
         * Technically the user should not call free on the default drbg. */
10906
    #ifndef WOLFSSL_MUTEX_INITIALIZER
10907
        /* wolfSSL_Cleanup may free the mutex before this runs. */
10908
        haveMutex = (globalRNGMutex_valid == 1);
10909
    #endif
10910
        if (haveMutex && (wc_LockMutex(&globalRNGMutex) == 0))
10911
            locked = 1;
10912
        /* Touch the global under the lock, or unlocked only when no mutex. */
10913
        if (locked || !haveMutex) {
10914
            if (ctx == gDrbgDefCtx) {
10915
                gDrbgDefCtx = NULL;
10916
            }
10917
        }
10918
        if (locked)
10919
            wc_UnLockMutex(&globalRNGMutex);
10920
        wolfSSL_FIPS_drbg_uninstantiate(ctx);
10921
        XFREE(ctx, NULL, DYNAMIC_TYPE_OPENSSL);
10922
    }
10923
}
10924
WOLFSSL_DRBG_CTX* wolfSSL_FIPS_get_default_drbg(void)
10925
{
10926
    int locked = 0;
10927
    int haveMutex = 1;
10928
#ifndef WOLFSSL_MUTEX_INITIALIZER
10929
    haveMutex = (globalRNGMutex_valid == 1);
10930
#endif
10931
    if (haveMutex && (wc_LockMutex(&globalRNGMutex) == 0))
10932
        locked = 1;
10933
    if (locked || !haveMutex) {
10934
        if (gDrbgDefCtx == NULL) {
10935
            gDrbgDefCtx = wolfSSL_FIPS_drbg_new(0, 0);
10936
        }
10937
    }
10938
    if (locked)
10939
        wc_UnLockMutex(&globalRNGMutex);
10940
    return gDrbgDefCtx;
10941
}
10942
void wolfSSL_FIPS_get_timevec(unsigned char* buf, unsigned long* pctr)
10943
{
10944
    /* not implemented */
10945
    (void)buf;
10946
    (void)pctr;
10947
}
10948
void* wolfSSL_FIPS_drbg_get_app_data(WOLFSSL_DRBG_CTX *ctx)
10949
{
10950
    if (ctx != NULL) {
10951
        return ctx->app_data;
10952
    }
10953
    return NULL;
10954
}
10955
void wolfSSL_FIPS_drbg_set_app_data(WOLFSSL_DRBG_CTX *ctx, void *app_data)
10956
{
10957
    if (ctx != NULL) {
10958
        ctx->app_data = app_data;
10959
    }
10960
}
10961
#endif
10962
/*******************************************************************************
10963
 * END OF OPENSSL FIPS DRBG APIs
10964
 ******************************************************************************/
10965
10966
10967
#endif /* !WOLFCRYPT_ONLY */