Coverage Report

Created: 2026-08-12 07:05

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
                (ssl != NULL && !IsAtLeastTLSv1_3(ssl->version))) {
3137
            /* Silently ignore TLS 1.3 ciphers if we don't support it. */
3138
            return WOLFSSL_SUCCESS;
3139
        }
3140
    }
3141
3142
    /* list contains ciphers either only for TLS 1.3 or <= TLS 1.2 */
3143
#ifdef WOLFSSL_SMALL_STACK
3144
    if (suites->suiteSz > 0) {
3145
        suitesCpy = (byte*)XMALLOC(suites->suiteSz, NULL,
3146
                DYNAMIC_TYPE_TMP_BUFFER);
3147
        if (suitesCpy == NULL) {
3148
            return WOLFSSL_FAILURE;
3149
        }
3150
3151
        XMEMSET(suitesCpy, 0, suites->suiteSz);
3152
    }
3153
#else
3154
        XMEMSET(suitesCpy, 0, sizeof(suitesCpy));
3155
#endif
3156
3157
    if (suites->suiteSz > 0)
3158
        XMEMCPY(suitesCpy, suites->suites, suites->suiteSz);
3159
    suitesCpySz = suites->suiteSz;
3160
3161
    ret = SetCipherList_ex(ctx, ssl, suites, list);
3162
    if (ret != 1) {
3163
        WC_FREE_VAR_EX(suitesCpy, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3164
        return WOLFSSL_FAILURE;
3165
    }
3166
3167
    /* The idea in this section is that OpenSSL has two API to set ciphersuites.
3168
     *   - SSL_CTX_set_cipher_list for setting TLS <= 1.2 suites
3169
     *   - SSL_CTX_set_ciphersuites for setting TLS 1.3 suites
3170
     * Since we direct both API here we attempt to provide API compatibility. If
3171
     * we only get suites from <= 1.2 or == 1.3 then we will only update those
3172
     * suites and keep the suites from the other group.
3173
     * If downgrade is disabled, skip preserving the other group's suites. */
3174
    if ((ssl != NULL && !ssl->options.downgrade) ||
3175
        (ctx != NULL && !ctx->method->downgrade)) {
3176
        /* Downgrade disabled - don't preserve other group's suites */
3177
        WC_FREE_VAR_EX(suitesCpy, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3178
        return ret;
3179
    }
3180
3181
    for (i = 0; i < suitesCpySz &&
3182
                suites->suiteSz <= (WOLFSSL_MAX_SUITE_SZ - SUITE_LEN); i += 2) {
3183
        /* Check for duplicates */
3184
        int duplicate = 0;
3185
        for (j = 0; j < suites->suiteSz; j += 2) {
3186
            if (suitesCpy[i] == suites->suites[j] &&
3187
                    suitesCpy[i+1] == suites->suites[j+1]) {
3188
                duplicate = 1;
3189
                break;
3190
            }
3191
        }
3192
        if (!duplicate) {
3193
            if (tls13Only) {
3194
                /* Updating TLS 1.3 ciphers */
3195
                if (suitesCpy[i] != TLS13_BYTE) {
3196
                    /* Only copy over <= TLS 1.2 ciphers */
3197
                    /* TLS 1.3 ciphers take precedence */
3198
                    suites->suites[suites->suiteSz++] = suitesCpy[i];
3199
                    suites->suites[suites->suiteSz++] = suitesCpy[i+1];
3200
                }
3201
            }
3202
            else {
3203
                /* Updating <= TLS 1.2 ciphers */
3204
                if (suitesCpy[i] == TLS13_BYTE) {
3205
                    /* Only copy over TLS 1.3 ciphers */
3206
                    /* TLS 1.3 ciphers take precedence */
3207
                    XMEMMOVE(suites->suites + SUITE_LEN, suites->suites,
3208
                             suites->suiteSz);
3209
                    suites->suites[0] = suitesCpy[i];
3210
                    suites->suites[1] = suitesCpy[i+1];
3211
                    suites->suiteSz += 2;
3212
                }
3213
            }
3214
        }
3215
    }
3216
3217
    WC_FREE_VAR_EX(suitesCpy, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3218
    return ret;
3219
}
3220
3221
#endif
3222
3223
3224
int wolfSSL_CTX_set_cipher_list(WOLFSSL_CTX* ctx, const char* list)
3225
0
{
3226
0
    WOLFSSL_ENTER("wolfSSL_CTX_set_cipher_list");
3227
3228
0
    if (ctx == NULL)
3229
0
        return WOLFSSL_FAILURE;
3230
3231
0
    if (AllocateCtxSuites(ctx) != 0)
3232
0
        return WOLFSSL_FAILURE;
3233
3234
#ifdef OPENSSL_EXTRA
3235
    return wolfSSL_parse_cipher_list(ctx, NULL, ctx->suites, list);
3236
#else
3237
0
    return (SetCipherList(ctx, ctx->suites, list)) ?
3238
0
        WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
3239
0
#endif
3240
0
}
3241
3242
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_SET_CIPHER_BYTES)
3243
int wolfSSL_CTX_set_cipher_list_bytes(WOLFSSL_CTX* ctx, const byte* list,
3244
                                      const int listSz)
3245
{
3246
    WOLFSSL_ENTER("wolfSSL_CTX_set_cipher_list_bytes");
3247
3248
    if (ctx == NULL)
3249
        return WOLFSSL_FAILURE;
3250
3251
    if (AllocateCtxSuites(ctx) != 0)
3252
        return WOLFSSL_FAILURE;
3253
3254
    return (SetCipherListFromBytes(ctx, ctx->suites, list, listSz)) ?
3255
        WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
3256
}
3257
#endif /* OPENSSL_EXTRA || WOLFSSL_SET_CIPHER_BYTES */
3258
3259
int wolfSSL_set_cipher_list(WOLFSSL* ssl, const char* list)
3260
0
{
3261
0
    WOLFSSL_ENTER("wolfSSL_set_cipher_list");
3262
3263
0
    if (ssl == NULL || ssl->ctx == NULL) {
3264
0
        return WOLFSSL_FAILURE;
3265
0
    }
3266
3267
0
    if (AllocateSuites(ssl) != 0)
3268
0
        return WOLFSSL_FAILURE;
3269
3270
#ifdef OPENSSL_EXTRA
3271
    return wolfSSL_parse_cipher_list(NULL, ssl, ssl->suites, list);
3272
#else
3273
0
    return (SetCipherList_ex(NULL, ssl, ssl->suites, list)) ?
3274
0
        WOLFSSL_SUCCESS :
3275
0
        WOLFSSL_FAILURE;
3276
0
#endif
3277
0
}
3278
3279
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_SET_CIPHER_BYTES)
3280
int wolfSSL_set_cipher_list_bytes(WOLFSSL* ssl, const byte* list,
3281
                                  const int listSz)
3282
{
3283
    WOLFSSL_ENTER("wolfSSL_set_cipher_list_bytes");
3284
3285
    if (ssl == NULL || ssl->ctx == NULL) {
3286
        return WOLFSSL_FAILURE;
3287
    }
3288
3289
    if (AllocateSuites(ssl) != 0)
3290
        return WOLFSSL_FAILURE;
3291
3292
    return (SetCipherListFromBytes(ssl->ctx, ssl->suites, list, listSz))
3293
           ? WOLFSSL_SUCCESS
3294
           : WOLFSSL_FAILURE;
3295
}
3296
#endif /* OPENSSL_EXTRA || WOLFSSL_SET_CIPHER_BYTES */
3297
3298
3299
#ifdef HAVE_KEYING_MATERIAL
3300
3301
#define TLS_PRF_LABEL_CLIENT_FINISHED     "client finished"
3302
#define TLS_PRF_LABEL_SERVER_FINISHED     "server finished"
3303
#define TLS_PRF_LABEL_MASTER_SECRET       "master secret"
3304
#define TLS_PRF_LABEL_EXT_MASTER_SECRET   "extended master secret"
3305
#define TLS_PRF_LABEL_KEY_EXPANSION       "key expansion"
3306
3307
static const struct ForbiddenLabels {
3308
    const char* label;
3309
    size_t labelLen;
3310
} forbiddenLabels[] = {
3311
    {TLS_PRF_LABEL_CLIENT_FINISHED, XSTR_SIZEOF(TLS_PRF_LABEL_CLIENT_FINISHED)},
3312
    {TLS_PRF_LABEL_SERVER_FINISHED, XSTR_SIZEOF(TLS_PRF_LABEL_SERVER_FINISHED)},
3313
    {TLS_PRF_LABEL_MASTER_SECRET, XSTR_SIZEOF(TLS_PRF_LABEL_MASTER_SECRET)},
3314
    {TLS_PRF_LABEL_EXT_MASTER_SECRET,
3315
     XSTR_SIZEOF(TLS_PRF_LABEL_EXT_MASTER_SECRET)},
3316
    {TLS_PRF_LABEL_KEY_EXPANSION, XSTR_SIZEOF(TLS_PRF_LABEL_KEY_EXPANSION)},
3317
    {NULL, 0},
3318
};
3319
3320
/**
3321
 * Implement RFC 5705
3322
 * TLS 1.3 uses a different exporter definition (section 7.5 of RFC 8446)
3323
 * @return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on error
3324
 */
3325
int wolfSSL_export_keying_material(WOLFSSL *ssl,
3326
        unsigned char *out, size_t outLen,
3327
        const char *label, size_t labelLen,
3328
        const unsigned char *context, size_t contextLen,
3329
        int use_context)
3330
{
3331
    byte*  seed = NULL;
3332
    word32 seedLen;
3333
    const struct ForbiddenLabels* fl;
3334
3335
    WOLFSSL_ENTER("wolfSSL_export_keying_material");
3336
3337
    if (ssl == NULL || out == NULL || label == NULL ||
3338
            (use_context && contextLen && context == NULL)) {
3339
        WOLFSSL_MSG("Bad argument");
3340
        return WOLFSSL_FAILURE;
3341
    }
3342
3343
    /* Sanity check contextLen to prevent integer overflow when cast to word32
3344
     * and to ensure it fits in the 2-byte length encoding (max 65535). */
3345
    if (use_context && contextLen > WOLFSSL_MAX_16BIT) {
3346
        WOLFSSL_MSG("contextLen too large");
3347
        return WOLFSSL_FAILURE;
3348
    }
3349
3350
    /* clientRandom + serverRandom
3351
     * OR
3352
     * clientRandom + serverRandom + ctx len encoding + ctx */
3353
    seedLen = !use_context ? (word32)SEED_LEN :
3354
                             (word32)SEED_LEN + 2 + (word32)contextLen;
3355
3356
    if (ssl->options.saveArrays == 0 || ssl->arrays == NULL) {
3357
        WOLFSSL_MSG("To export keying material wolfSSL needs to keep handshake "
3358
                    "data. Call wolfSSL_KeepArrays before attempting to "
3359
                    "export keyid material.");
3360
        return WOLFSSL_FAILURE;
3361
    }
3362
3363
    /* check forbidden labels */
3364
    for (fl = &forbiddenLabels[0]; fl->label != NULL; fl++) {
3365
        if (labelLen >= fl->labelLen &&
3366
                XMEMCMP(label, fl->label, fl->labelLen) == 0) {
3367
            WOLFSSL_MSG("Forbidden label");
3368
            return WOLFSSL_FAILURE;
3369
        }
3370
    }
3371
3372
#ifdef WOLFSSL_TLS13
3373
    if (IsAtLeastTLSv1_3(ssl->version)) {
3374
        /* Path for TLS 1.3 */
3375
        if (!use_context) {
3376
            contextLen = 0;
3377
            context = (byte*)""; /* Give valid pointer for 0 length memcpy */
3378
        }
3379
3380
        if (Tls13_Exporter(ssl, out, (word32)outLen, label, labelLen,
3381
                context, contextLen) != 0) {
3382
            WOLFSSL_MSG("Tls13_Exporter error");
3383
            return WOLFSSL_FAILURE;
3384
        }
3385
        return WOLFSSL_SUCCESS;
3386
    }
3387
#endif
3388
3389
    /* Path for <=TLS 1.2 */
3390
    seed = (byte*)XMALLOC(seedLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3391
    if (seed == NULL) {
3392
        WOLFSSL_MSG("malloc error");
3393
        return WOLFSSL_FAILURE;
3394
    }
3395
3396
    XMEMCPY(seed,           ssl->arrays->clientRandom, RAN_LEN);
3397
    XMEMCPY(seed + RAN_LEN, ssl->arrays->serverRandom, RAN_LEN);
3398
3399
    if (use_context) {
3400
        /* Encode len in big endian */
3401
        seed[SEED_LEN    ] = (contextLen >> 8) & 0xFF;
3402
        seed[SEED_LEN + 1] = (contextLen) & 0xFF;
3403
        if (contextLen) {
3404
            /* 0 length context is allowed */
3405
            XMEMCPY(seed + SEED_LEN + 2, context, contextLen);
3406
        }
3407
    }
3408
3409
    PRIVATE_KEY_UNLOCK();
3410
    if (wc_PRF_TLS(out, (word32)outLen, ssl->arrays->masterSecret, SECRET_LEN,
3411
            (byte*)label, (word32)labelLen, seed, seedLen,
3412
            IsAtLeastTLSv1_2(ssl), ssl->specs.mac_algorithm, ssl->heap,
3413
            ssl->devId) != 0) {
3414
        WOLFSSL_MSG("wc_PRF_TLS error");
3415
        PRIVATE_KEY_LOCK();
3416
        XFREE(seed, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3417
        return WOLFSSL_FAILURE;
3418
    }
3419
    PRIVATE_KEY_LOCK();
3420
3421
    XFREE(seed, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3422
    return WOLFSSL_SUCCESS;
3423
}
3424
#endif /* HAVE_KEYING_MATERIAL */
3425
3426
3427
/* EITHER SIDE METHODS */
3428
#if !defined(NO_TLS) && (defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE))
3429
    WOLFSSL_METHOD* wolfSSLv23_method(void)
3430
    {
3431
        return wolfSSLv23_method_ex(NULL);
3432
    }
3433
    WOLFSSL_METHOD* wolfSSLv23_method_ex(void* heap)
3434
    {
3435
        WOLFSSL_METHOD* m = NULL;
3436
        WOLFSSL_ENTER("wolfSSLv23_method");
3437
    #if !defined(NO_WOLFSSL_CLIENT)
3438
        m = wolfSSLv23_client_method_ex(heap);
3439
    #elif !defined(NO_WOLFSSL_SERVER)
3440
        m = wolfSSLv23_server_method_ex(heap);
3441
    #else
3442
        (void)heap;
3443
    #endif
3444
        if (m != NULL) {
3445
            m->side = WOLFSSL_NEITHER_END;
3446
        }
3447
3448
        return m;
3449
    }
3450
3451
    #ifndef NO_OLD_TLS
3452
    #ifdef WOLFSSL_ALLOW_SSLV3
3453
    WOLFSSL_METHOD* wolfSSLv3_method(void)
3454
    {
3455
        return wolfSSLv3_method_ex(NULL);
3456
    }
3457
    WOLFSSL_METHOD* wolfSSLv3_method_ex(void* heap)
3458
    {
3459
        WOLFSSL_METHOD* m = NULL;
3460
        WOLFSSL_ENTER("wolfSSLv3_method_ex");
3461
    #if !defined(NO_WOLFSSL_CLIENT)
3462
        m = wolfSSLv3_client_method_ex(heap);
3463
    #elif !defined(NO_WOLFSSL_SERVER)
3464
        m = wolfSSLv3_server_method_ex(heap);
3465
    #endif
3466
        if (m != NULL) {
3467
            m->side = WOLFSSL_NEITHER_END;
3468
        }
3469
3470
        return m;
3471
    }
3472
    #endif
3473
    #endif
3474
#endif /* !NO_TLS && (OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE) */
3475
3476
/* client only parts */
3477
#if !defined(NO_WOLFSSL_CLIENT) && !defined(NO_TLS)
3478
3479
    #if defined(OPENSSL_EXTRA) && !defined(NO_OLD_TLS)
3480
    WOLFSSL_METHOD* wolfSSLv2_client_method(void)
3481
    {
3482
        WOLFSSL_STUB("wolfSSLv2_client_method");
3483
        return NULL;
3484
    }
3485
    #endif
3486
3487
    #if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
3488
    WOLFSSL_METHOD* wolfSSLv3_client_method(void)
3489
    {
3490
        return wolfSSLv3_client_method_ex(NULL);
3491
    }
3492
    WOLFSSL_METHOD* wolfSSLv3_client_method_ex(void* heap)
3493
    {
3494
        WOLFSSL_METHOD* method =
3495
                              (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
3496
                                                     heap, DYNAMIC_TYPE_METHOD);
3497
        (void)heap;
3498
        WOLFSSL_ENTER("wolfSSLv3_client_method_ex");
3499
        if (method)
3500
            InitSSL_Method(method, MakeSSLv3());
3501
        return method;
3502
    }
3503
    #endif /* WOLFSSL_ALLOW_SSLV3 && !NO_OLD_TLS */
3504
3505
3506
    WOLFSSL_METHOD* wolfSSLv23_client_method(void)
3507
0
    {
3508
0
        return wolfSSLv23_client_method_ex(NULL);
3509
0
    }
3510
    WOLFSSL_METHOD* wolfSSLv23_client_method_ex(void* heap)
3511
0
    {
3512
0
        WOLFSSL_METHOD* method =
3513
0
                              (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
3514
0
                                                     heap, DYNAMIC_TYPE_METHOD);
3515
0
        (void)heap;
3516
0
        WOLFSSL_ENTER("wolfSSLv23_client_method_ex");
3517
0
        if (method) {
3518
0
    #if !defined(NO_SHA256) || defined(WOLFSSL_SHA384) || \
3519
0
        defined(WOLFSSL_SHA512)
3520
0
        #if defined(WOLFSSL_TLS13)
3521
0
            InitSSL_Method(method, MakeTLSv1_3());
3522
        #elif !defined(WOLFSSL_NO_TLS12)
3523
            InitSSL_Method(method, MakeTLSv1_2());
3524
        #elif !defined(NO_OLD_TLS)
3525
            InitSSL_Method(method, MakeTLSv1_1());
3526
        #endif
3527
    #else
3528
        #ifndef NO_OLD_TLS
3529
            InitSSL_Method(method, MakeTLSv1_1());
3530
        #endif
3531
    #endif
3532
0
    #if !defined(NO_OLD_TLS) || defined(WOLFSSL_TLS13)
3533
0
            method->downgrade = 1;
3534
0
    #endif
3535
0
        }
3536
0
        return method;
3537
0
    }
3538
3539
3540
#endif /* !NO_WOLFSSL_CLIENT && !NO_TLS */
3541
/* end client only parts */
3542
3543
/* server only parts */
3544
#if !defined(NO_WOLFSSL_SERVER) && !defined(NO_TLS)
3545
3546
    #if defined(OPENSSL_EXTRA) && !defined(NO_OLD_TLS)
3547
    WOLFSSL_METHOD* wolfSSLv2_server_method(void)
3548
    {
3549
        WOLFSSL_STUB("wolfSSLv2_server_method");
3550
        return 0;
3551
    }
3552
    #endif
3553
3554
    #if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
3555
    WOLFSSL_METHOD* wolfSSLv3_server_method(void)
3556
    {
3557
        return wolfSSLv3_server_method_ex(NULL);
3558
    }
3559
    WOLFSSL_METHOD* wolfSSLv3_server_method_ex(void* heap)
3560
    {
3561
        WOLFSSL_METHOD* method =
3562
                              (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
3563
                                                     heap, DYNAMIC_TYPE_METHOD);
3564
        (void)heap;
3565
        WOLFSSL_ENTER("wolfSSLv3_server_method_ex");
3566
        if (method) {
3567
            InitSSL_Method(method, MakeSSLv3());
3568
            method->side = WOLFSSL_SERVER_END;
3569
        }
3570
        return method;
3571
    }
3572
    #endif /* WOLFSSL_ALLOW_SSLV3 && !NO_OLD_TLS */
3573
3574
    WOLFSSL_METHOD* wolfSSLv23_server_method(void)
3575
0
    {
3576
0
        return wolfSSLv23_server_method_ex(NULL);
3577
0
    }
3578
3579
    WOLFSSL_METHOD* wolfSSLv23_server_method_ex(void* heap)
3580
0
    {
3581
0
        WOLFSSL_METHOD* method =
3582
0
                              (WOLFSSL_METHOD*) XMALLOC(sizeof(WOLFSSL_METHOD),
3583
0
                                                     heap, DYNAMIC_TYPE_METHOD);
3584
0
        (void)heap;
3585
0
        WOLFSSL_ENTER("wolfSSLv23_server_method_ex");
3586
0
        if (method) {
3587
0
    #if !defined(NO_SHA256) || defined(WOLFSSL_SHA384) || \
3588
0
        defined(WOLFSSL_SHA512)
3589
0
        #ifdef WOLFSSL_TLS13
3590
0
            InitSSL_Method(method, MakeTLSv1_3());
3591
        #elif !defined(WOLFSSL_NO_TLS12)
3592
            InitSSL_Method(method, MakeTLSv1_2());
3593
        #elif !defined(NO_OLD_TLS)
3594
            InitSSL_Method(method, MakeTLSv1_1());
3595
        #endif
3596
    #else
3597
        #ifndef NO_OLD_TLS
3598
            InitSSL_Method(method, MakeTLSv1_1());
3599
        #else
3600
            #error Must have SHA256, SHA384 or SHA512 enabled for TLS 1.2
3601
        #endif
3602
    #endif
3603
0
    #if !defined(NO_OLD_TLS) || defined(WOLFSSL_TLS13)
3604
0
            method->downgrade = 1;
3605
0
    #endif
3606
0
            method->side      = WOLFSSL_SERVER_END;
3607
0
        }
3608
0
        return method;
3609
0
    }
3610
3611
3612
3613
#endif /* !NO_WOLFSSL_SERVER && !NO_TLS */
3614
/* end server only parts */
3615
3616
#define WOLFSSL_SSL_API_HS_INCLUDED
3617
#include "src/ssl_api_hs.c"
3618
3619
3620
3621
WOLFSSL_ABI
3622
int wolfSSL_Cleanup(void)
3623
0
{
3624
0
    int ret = WOLFSSL_SUCCESS; /* Only the first error will be returned */
3625
0
    int release = 0;
3626
0
#if !defined(NO_SESSION_CACHE)
3627
0
    int i;
3628
0
    int j;
3629
0
#endif
3630
3631
0
    WOLFSSL_ENTER("wolfSSL_Cleanup");
3632
3633
#ifndef WOLFSSL_MUTEX_INITIALIZER
3634
    if (inits_count_mutex_valid == 1) {
3635
#endif
3636
0
        if (wc_LockMutex(&inits_count_mutex) != 0) {
3637
0
            WOLFSSL_MSG("Bad Lock Mutex count");
3638
0
            return BAD_MUTEX_E;
3639
0
        }
3640
#ifndef WOLFSSL_MUTEX_INITIALIZER
3641
    }
3642
#endif
3643
3644
0
    if (initRefCount > 0) {
3645
0
        initRefCount = initRefCount - 1;
3646
0
        if (initRefCount == 0)
3647
0
            release = 1;
3648
0
    }
3649
3650
#ifndef WOLFSSL_MUTEX_INITIALIZER
3651
    if (inits_count_mutex_valid == 1) {
3652
#endif
3653
0
        wc_UnLockMutex(&inits_count_mutex);
3654
#ifndef WOLFSSL_MUTEX_INITIALIZER
3655
    }
3656
#endif
3657
3658
0
    if (!release)
3659
0
        return ret;
3660
3661
#if defined(WOLFSSL_SYS_CRYPTO_POLICY)
3662
    wolfSSL_crypto_policy_disable();
3663
#endif /* WOLFSSL_SYS_CRYPTO_POLICY */
3664
3665
#ifdef OPENSSL_EXTRA
3666
    wolfSSL_BN_free_one();
3667
#endif
3668
3669
0
#ifndef NO_SESSION_CACHE
3670
    #ifdef ENABLE_SESSION_CACHE_ROW_LOCK
3671
    for (i = 0; i < SESSION_ROWS; ++i) {
3672
        if ((SessionCache[i].lock_valid == 1) &&
3673
            (wc_FreeRwLock(&SessionCache[i].row_lock) != 0)) {
3674
            if (ret == WOLFSSL_SUCCESS)
3675
                ret = BAD_MUTEX_E;
3676
        }
3677
        SessionCache[i].lock_valid = 0;
3678
    }
3679
    #else
3680
0
    if ((session_lock_valid == 1) && (wc_FreeRwLock(&session_lock) != 0)) {
3681
0
        if (ret == WOLFSSL_SUCCESS)
3682
0
            ret = BAD_MUTEX_E;
3683
0
    }
3684
0
    session_lock_valid = 0;
3685
0
    #endif
3686
0
    for (i = 0; i < SESSION_ROWS; i++) {
3687
0
        for (j = 0; j < SESSIONS_PER_ROW; j++) {
3688
    #ifdef SESSION_CACHE_DYNAMIC_MEM
3689
            if (SessionCache[i].Sessions[j]) {
3690
                EvictSessionFromCache(SessionCache[i].Sessions[j]);
3691
                XFREE(SessionCache[i].Sessions[j], SessionCache[i].heap,
3692
                      DYNAMIC_TYPE_SESSION);
3693
                SessionCache[i].Sessions[j] = NULL;
3694
            }
3695
    #else
3696
0
            EvictSessionFromCache(&SessionCache[i].Sessions[j]);
3697
0
    #endif
3698
0
        }
3699
0
    }
3700
0
    #ifndef NO_CLIENT_CACHE
3701
    #ifndef WOLFSSL_MUTEX_INITIALIZER
3702
    if ((clisession_mutex_valid == 1) &&
3703
        (wc_FreeMutex(&clisession_mutex) != 0)) {
3704
        if (ret == WOLFSSL_SUCCESS)
3705
            ret = BAD_MUTEX_E;
3706
    }
3707
    clisession_mutex_valid = 0;
3708
    #endif
3709
0
    #endif
3710
0
#endif /* !NO_SESSION_CACHE */
3711
3712
#if !defined(WOLFSSL_MUTEX_INITIALIZER) && \
3713
      !WOLFSSL_CLEANUP_THREADSAFE_BY_ATOMIC_OPS
3714
    if ((inits_count_mutex_valid == 1) &&
3715
            (wc_FreeMutex(&inits_count_mutex) != 0)) {
3716
        if (ret == WOLFSSL_SUCCESS)
3717
            ret = BAD_MUTEX_E;
3718
    }
3719
    inits_count_mutex_valid = 0;
3720
#endif
3721
3722
#ifdef OPENSSL_EXTRA
3723
    wolfSSL_RAND_Cleanup();
3724
#endif
3725
3726
0
    if (wolfCrypt_Cleanup() != 0) {
3727
0
        WOLFSSL_MSG("Error with wolfCrypt_Cleanup call");
3728
0
        if (ret == WOLFSSL_SUCCESS)
3729
0
            ret = WC_CLEANUP_E;
3730
0
    }
3731
3732
#if FIPS_VERSION_GE(5,1)
3733
    if (wolfCrypt_SetPrivateKeyReadEnable_fips(0, WC_KEYTYPE_ALL) < 0) {
3734
        if (ret == WOLFSSL_SUCCESS)
3735
            ret = WC_CLEANUP_E;
3736
    }
3737
#endif
3738
3739
0
#ifdef HAVE_GLOBAL_RNG
3740
#ifndef WOLFSSL_MUTEX_INITIALIZER
3741
    if ((globalRNGMutex_valid == 1) && (wc_FreeMutex(&globalRNGMutex) != 0)) {
3742
        if (ret == WOLFSSL_SUCCESS)
3743
            ret = BAD_MUTEX_E;
3744
    }
3745
    globalRNGMutex_valid = 0;
3746
#endif /* !WOLFSSL_MUTEX_INITIALIZER */
3747
3748
    #if defined(OPENSSL_EXTRA) && defined(HAVE_HASHDRBG)
3749
    wolfSSL_FIPS_drbg_free(gDrbgDefCtx);
3750
    gDrbgDefCtx = NULL;
3751
    #endif
3752
0
#endif
3753
3754
#ifdef HAVE_EX_DATA_CRYPTO
3755
    crypto_ex_cb_free(crypto_ex_cb_ctx_session);
3756
    crypto_ex_cb_ctx_session = NULL;
3757
#endif
3758
3759
#ifdef WOLFSSL_MEM_FAIL_COUNT
3760
    wc_MemFailCount_Free();
3761
#endif
3762
3763
0
    return ret;
3764
0
}
3765
3766
/* Returns 1 if name is a syntactically valid DNS FQDN per RFC 952/1123.
3767
 *
3768
 * Rules enforced:
3769
 *   - Total effective length (excluding optional trailing dot) in [1, 253]
3770
 *   - Each label is 1-63 octets of [a-zA-Z0-9-], with _ allowed in all but
3771
 *     the last label.
3772
 *   - No label starts or ends with '-'
3773
 *   - At least two labels (single-label names are not "fully qualified")
3774
 *   - Final label (TLD) contains at least one letter (rejects all-numeric
3775
 *     strings that could be confused with IPv4 literals, and matches the
3776
 *     ICANN constraint that TLDs are alphabetic)
3777
 *   - Optional trailing dot is accepted (absolute FQDN form)
3778
 *   - Internationalized names are valid in their ACE/punycode (xn--) form
3779
 */
3780
int wolfssl_local_IsValidFQDN(const char* name, word32 nameSz)
3781
0
{
3782
0
    word32 i;
3783
0
    int labelLen = 0;
3784
0
    int labelCount = 0;
3785
0
    int curLabelHasAlpha = 0;
3786
0
    int curLabelHasUnderscore = 0;
3787
3788
0
    if (name == NULL || nameSz == 0)
3789
0
        return 0;
3790
3791
    /* Strip a single optional trailing dot before measuring.  "example.com."
3792
     * is the absolute form of the same FQDN.
3793
     */
3794
0
    if (name[nameSz - 1] == '.')
3795
0
        --nameSz;
3796
3797
0
    if (nameSz < 1 || nameSz > 253)
3798
0
        return 0;
3799
3800
0
    for (i = 0; i < nameSz; i++) {
3801
0
        byte c = (byte)name[i];
3802
3803
0
        if (c == '.') {
3804
0
            if (labelLen == 0 || name[i - 1] == '-')
3805
0
                return 0;
3806
0
            ++labelCount;
3807
0
            labelLen = 0;
3808
0
            curLabelHasAlpha = 0;
3809
0
            curLabelHasUnderscore = 0;
3810
0
            continue;
3811
0
        }
3812
3813
0
        if (++labelLen > 63)
3814
0
            return 0;
3815
3816
0
        if (c == '-') {
3817
0
            if (labelLen == 1)
3818
0
                return 0;
3819
0
        }
3820
0
        else if (((c | 0x20) >= 'a') && ((c | 0x20) <= 'z')) {
3821
0
            curLabelHasAlpha = 1;
3822
0
        }
3823
0
        else if (c == '_') {
3824
0
            curLabelHasUnderscore = 1;
3825
0
        }
3826
0
        else if ((c < '0') || (c > '9')) {
3827
0
            return 0;
3828
0
        }
3829
0
    }
3830
3831
    /* Final label (no trailing dot in the effective range to close it) */
3832
0
    if ((labelLen == 0) || (name[nameSz - 1] == '-') || curLabelHasUnderscore)
3833
0
        return 0;
3834
0
    ++labelCount;
3835
3836
0
    return ((labelCount > 1) && curLabelHasAlpha);
3837
0
}
3838
3839
/* call before SSL_connect, if verifying will add name check to
3840
   date check and signature check */
3841
WOLFSSL_ABI
3842
int wolfSSL_check_domain_name(WOLFSSL* ssl, const char* dn)
3843
0
{
3844
0
    size_t dn_len;
3845
3846
0
    WOLFSSL_ENTER("wolfSSL_check_domain_name");
3847
3848
0
    if (ssl == NULL || dn == NULL) {
3849
0
        WOLFSSL_MSG("Bad function argument: NULL");
3850
0
        return WOLFSSL_FAILURE;
3851
0
    }
3852
3853
0
    dn_len = XSTRLEN(dn);
3854
3855
0
    if ((! wolfssl_local_IsValidFQDN(dn, (word32)dn_len)) &&
3856
0
        (XSTRCMP(dn, "localhost") != 0))
3857
0
    {
3858
0
        WOLFSSL_MSG("Bad function argument: fails wolfssl_local_IsValidFQDN");
3859
0
        return WOLFSSL_FAILURE;
3860
0
    }
3861
3862
0
    if (ssl->buffers.domainName.buffer)
3863
0
        XFREE(ssl->buffers.domainName.buffer, ssl->heap, DYNAMIC_TYPE_DOMAIN);
3864
3865
0
    ssl->buffers.domainName.length = (word32)XSTRLEN(dn);
3866
0
    ssl->buffers.domainName.buffer = (byte*)XMALLOC(
3867
0
            ssl->buffers.domainName.length + 1, ssl->heap, DYNAMIC_TYPE_DOMAIN);
3868
3869
0
    if (ssl->buffers.domainName.buffer) {
3870
0
        unsigned char* domainName = ssl->buffers.domainName.buffer;
3871
0
        XMEMCPY(domainName, dn, ssl->buffers.domainName.length);
3872
0
        domainName[ssl->buffers.domainName.length] = '\0';
3873
0
        return WOLFSSL_SUCCESS;
3874
0
    }
3875
0
    else {
3876
0
        ssl->error = MEMORY_ERROR;
3877
0
        return WOLFSSL_FAILURE;
3878
0
    }
3879
0
}
3880
3881
/* call before SSL_connect, if verifying will add IP SAN check to
3882
   date check and signature check */
3883
WOLFSSL_ABI
3884
int wolfSSL_check_ip_address(WOLFSSL* ssl, const char* ipaddr)
3885
0
{
3886
0
    WOLFSSL_ENTER("wolfSSL_check_ip_address");
3887
3888
0
    if (ssl == NULL || ipaddr == NULL) {
3889
0
        WOLFSSL_MSG("Bad function argument: NULL");
3890
0
        return WOLFSSL_FAILURE;
3891
0
    }
3892
3893
0
    if (ssl->buffers.ipasc.buffer != NULL) {
3894
0
        XFREE(ssl->buffers.ipasc.buffer, ssl->heap, DYNAMIC_TYPE_DOMAIN);
3895
0
        ssl->buffers.ipasc.buffer = NULL;
3896
0
        ssl->buffers.ipasc.length = 0;
3897
0
    }
3898
3899
0
    ssl->buffers.ipasc.length = (word32)XSTRLEN(ipaddr);
3900
0
    ssl->buffers.ipasc.buffer = (byte*)XMALLOC(ssl->buffers.ipasc.length + 1,
3901
0
                                               ssl->heap, DYNAMIC_TYPE_DOMAIN);
3902
0
    if (ssl->buffers.ipasc.buffer == NULL) {
3903
0
        ssl->error = MEMORY_ERROR;
3904
0
        return WOLFSSL_FAILURE;
3905
0
    }
3906
3907
0
    XMEMCPY(ssl->buffers.ipasc.buffer, ipaddr, ssl->buffers.ipasc.length);
3908
0
    ssl->buffers.ipasc.buffer[ssl->buffers.ipasc.length] = '\0';
3909
3910
#ifdef OPENSSL_EXTRA
3911
    if (ssl->param == NULL) {
3912
        return WOLFSSL_FAILURE;
3913
    }
3914
    if (wolfSSL_X509_VERIFY_PARAM_set1_ip_asc(ssl->param, ipaddr) !=
3915
            WOLFSSL_SUCCESS) {
3916
        return WOLFSSL_FAILURE;
3917
    }
3918
#endif
3919
3920
0
    return WOLFSSL_SUCCESS;
3921
0
}
3922
3923
#if defined(SESSION_CERTS) && defined(OPENSSL_EXTRA)
3924
const char *wolfSSL_get0_peername(WOLFSSL *ssl) {
3925
    if (ssl == NULL) {
3926
        return NULL;
3927
    }
3928
3929
    if (ssl->buffers.domainName.buffer)
3930
        return (const char *)ssl->buffers.domainName.buffer;
3931
    else if (ssl->session && ssl->session->peer)
3932
        return ssl->session->peer->subjectCN;
3933
#ifdef KEEP_PEER_CERT
3934
    else if (ssl->peerCert.subjectCN[0])
3935
        return ssl->peerCert.subjectCN;
3936
#endif
3937
    else {
3938
        ssl->error = NO_PEER_CERT;
3939
        return NULL;
3940
    }
3941
}
3942
3943
#endif /* SESSION_CERTS && OPENSSL_EXTRA */
3944
3945
/* turn on wolfSSL zlib compression
3946
   returns WOLFSSL_SUCCESS for success, else error (not built in)
3947
*/
3948
int wolfSSL_set_compression(WOLFSSL* ssl)
3949
0
{
3950
0
    WOLFSSL_ENTER("wolfSSL_set_compression");
3951
0
    (void)ssl;
3952
#ifdef HAVE_LIBZ
3953
    ssl->options.usingCompression = 1;
3954
    return WOLFSSL_SUCCESS;
3955
#else
3956
0
    return NOT_COMPILED_IN;
3957
0
#endif
3958
0
}
3959
3960
3961
#ifndef NO_PSK
3962
3963
    void wolfSSL_CTX_set_psk_client_callback(WOLFSSL_CTX* ctx,
3964
                                         wc_psk_client_callback cb)
3965
    {
3966
        WOLFSSL_ENTER("wolfSSL_CTX_set_psk_client_callback");
3967
3968
        if (ctx == NULL)
3969
            return;
3970
3971
        ctx->havePSK = 1;
3972
        ctx->client_psk_cb = cb;
3973
    }
3974
3975
    void wolfSSL_set_psk_client_callback(WOLFSSL* ssl,wc_psk_client_callback cb)
3976
    {
3977
        byte haveRSA = 1;
3978
        int  keySz   = 0;
3979
3980
        WOLFSSL_ENTER("wolfSSL_set_psk_client_callback");
3981
3982
        if (ssl == NULL)
3983
            return;
3984
3985
        ssl->options.havePSK = 1;
3986
        ssl->options.client_psk_cb = cb;
3987
3988
        #ifdef NO_RSA
3989
            haveRSA = 0;
3990
        #endif
3991
        #ifndef NO_CERTS
3992
            keySz = ssl->buffers.keySz;
3993
        #endif
3994
        if (AllocateSuites(ssl) != 0)
3995
            return;
3996
        InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE,
3997
                   ssl->options.haveDH, ssl->options.haveECDSAsig,
3998
                   ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
3999
                   ssl->options.useAnon, TRUE, TRUE, TRUE, TRUE, ssl->options.side);
4000
    }
4001
4002
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_CERT_WITH_EXTERN_PSK)
4003
    int wolfSSL_CTX_set_cert_with_extern_psk(WOLFSSL_CTX* ctx, int state)
4004
    {
4005
        WOLFSSL_ENTER("wolfSSL_CTX_set_cert_with_extern_psk");
4006
        if (ctx == NULL)
4007
            return WOLFSSL_FAILURE;
4008
        ctx->certWithExternPsk = (byte)(state != 0);
4009
        return WOLFSSL_SUCCESS;
4010
    }
4011
4012
    int wolfSSL_set_cert_with_extern_psk(WOLFSSL* ssl, int state)
4013
    {
4014
        WOLFSSL_ENTER("wolfSSL_set_cert_with_extern_psk");
4015
        if (ssl == NULL)
4016
            return WOLFSSL_FAILURE;
4017
        ssl->options.certWithExternPsk = (word16)(state != 0);
4018
        return WOLFSSL_SUCCESS;
4019
    }
4020
#endif
4021
4022
    #ifdef OPENSSL_EXTRA
4023
    /**
4024
     * set call back function for psk session use
4025
     * @param ssl  a pointer to WOLFSSL structure
4026
     * @param cb   a function pointer to wc_psk_use_session_cb
4027
     * @return none
4028
     */
4029
    void wolfSSL_set_psk_use_session_callback(WOLFSSL* ssl,
4030
                                                wc_psk_use_session_cb_func cb)
4031
    {
4032
        WOLFSSL_ENTER("wolfSSL_set_psk_use_session_callback");
4033
4034
        if (ssl != NULL) {
4035
            ssl->options.havePSK = 1;
4036
            ssl->options.session_psk_cb = cb;
4037
        }
4038
4039
        WOLFSSL_LEAVE("wolfSSL_set_psk_use_session_callback", WOLFSSL_SUCCESS);
4040
    }
4041
    #endif
4042
4043
    void wolfSSL_CTX_set_psk_server_callback(WOLFSSL_CTX* ctx,
4044
                                         wc_psk_server_callback cb)
4045
    {
4046
        WOLFSSL_ENTER("wolfSSL_CTX_set_psk_server_callback");
4047
        if (ctx == NULL)
4048
            return;
4049
        ctx->havePSK = 1;
4050
        ctx->server_psk_cb = cb;
4051
    }
4052
4053
    void wolfSSL_set_psk_server_callback(WOLFSSL* ssl,wc_psk_server_callback cb)
4054
    {
4055
        byte haveRSA = 1;
4056
        int  keySz   = 0;
4057
4058
        WOLFSSL_ENTER("wolfSSL_set_psk_server_callback");
4059
        if (ssl == NULL)
4060
            return;
4061
4062
        ssl->options.havePSK = 1;
4063
        ssl->options.server_psk_cb = cb;
4064
4065
        #ifdef NO_RSA
4066
            haveRSA = 0;
4067
        #endif
4068
        #ifndef NO_CERTS
4069
            keySz = ssl->buffers.keySz;
4070
        #endif
4071
        if (AllocateSuites(ssl) != 0)
4072
            return;
4073
        InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE,
4074
                   ssl->options.haveDH, ssl->options.haveECDSAsig,
4075
                   ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
4076
                   ssl->options.useAnon, TRUE, TRUE, TRUE, TRUE, ssl->options.side);
4077
    }
4078
4079
    const char* wolfSSL_get_psk_identity_hint(const WOLFSSL* ssl)
4080
    {
4081
        WOLFSSL_ENTER("wolfSSL_get_psk_identity_hint");
4082
4083
        if (ssl == NULL || ssl->arrays == NULL)
4084
            return NULL;
4085
4086
        return ssl->arrays->server_hint;
4087
    }
4088
4089
4090
    const char* wolfSSL_get_psk_identity(const WOLFSSL* ssl)
4091
    {
4092
        WOLFSSL_ENTER("wolfSSL_get_psk_identity");
4093
4094
        if (ssl == NULL || ssl->arrays == NULL)
4095
            return NULL;
4096
4097
        return ssl->arrays->client_identity;
4098
    }
4099
4100
    int wolfSSL_CTX_use_psk_identity_hint(WOLFSSL_CTX* ctx, const char* hint)
4101
    {
4102
        WOLFSSL_ENTER("wolfSSL_CTX_use_psk_identity_hint");
4103
        if (hint == 0)
4104
            ctx->server_hint[0] = '\0';
4105
        else {
4106
            /* Qt does not call CTX_set_*_psk_callbacks where havePSK is set */
4107
            #ifdef WOLFSSL_QT
4108
            ctx->havePSK=1;
4109
            #endif
4110
            XSTRNCPY(ctx->server_hint, hint, MAX_PSK_ID_LEN);
4111
            ctx->server_hint[MAX_PSK_ID_LEN] = '\0'; /* null term */
4112
        }
4113
        return WOLFSSL_SUCCESS;
4114
    }
4115
4116
    int wolfSSL_use_psk_identity_hint(WOLFSSL* ssl, const char* hint)
4117
    {
4118
        WOLFSSL_ENTER("wolfSSL_use_psk_identity_hint");
4119
4120
        if (ssl == NULL || ssl->arrays == NULL)
4121
            return WOLFSSL_FAILURE;
4122
4123
        if (hint == 0)
4124
            ssl->arrays->server_hint[0] = 0;
4125
        else {
4126
            XSTRNCPY(ssl->arrays->server_hint, hint,
4127
                                            sizeof(ssl->arrays->server_hint)-1);
4128
            ssl->arrays->server_hint[sizeof(ssl->arrays->server_hint)-1] = '\0';
4129
        }
4130
        return WOLFSSL_SUCCESS;
4131
    }
4132
4133
    void* wolfSSL_get_psk_callback_ctx(WOLFSSL* ssl)
4134
    {
4135
        return ssl ? ssl->options.psk_ctx : NULL;
4136
    }
4137
    void* wolfSSL_CTX_get_psk_callback_ctx(WOLFSSL_CTX* ctx)
4138
    {
4139
        return ctx ? ctx->psk_ctx : NULL;
4140
    }
4141
    int wolfSSL_set_psk_callback_ctx(WOLFSSL* ssl, void* psk_ctx)
4142
    {
4143
        if (ssl == NULL)
4144
            return WOLFSSL_FAILURE;
4145
        ssl->options.psk_ctx = psk_ctx;
4146
        return WOLFSSL_SUCCESS;
4147
    }
4148
    int wolfSSL_CTX_set_psk_callback_ctx(WOLFSSL_CTX* ctx, void* psk_ctx)
4149
    {
4150
        if (ctx == NULL)
4151
            return WOLFSSL_FAILURE;
4152
        ctx->psk_ctx = psk_ctx;
4153
        return WOLFSSL_SUCCESS;
4154
    }
4155
#endif /* NO_PSK */
4156
4157
4158
#ifdef HAVE_ANON
4159
4160
    int wolfSSL_CTX_allow_anon_cipher(WOLFSSL_CTX* ctx)
4161
    {
4162
        WOLFSSL_ENTER("wolfSSL_CTX_allow_anon_cipher");
4163
4164
        if (ctx == NULL)
4165
            return WOLFSSL_FAILURE;
4166
4167
        ctx->useAnon = 1;
4168
4169
        return WOLFSSL_SUCCESS;
4170
    }
4171
4172
#endif /* HAVE_ANON */
4173
4174
#ifdef OPENSSL_EXTRA
4175
4176
    int wolfSSL_add_all_algorithms(void)
4177
    {
4178
        WOLFSSL_ENTER("wolfSSL_add_all_algorithms");
4179
        if (initRefCount != 0 || wolfSSL_Init() == WOLFSSL_SUCCESS)
4180
            return WOLFSSL_SUCCESS;
4181
        else
4182
            return WOLFSSL_FATAL_ERROR;
4183
    }
4184
4185
    int wolfSSL_OpenSSL_add_all_algorithms_noconf(void)
4186
    {
4187
        WOLFSSL_ENTER("wolfSSL_OpenSSL_add_all_algorithms_noconf");
4188
4189
        if  (wolfSSL_add_all_algorithms() ==
4190
             WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR))
4191
        {
4192
            return WOLFSSL_FATAL_ERROR;
4193
        }
4194
4195
        return  WOLFSSL_SUCCESS;
4196
    }
4197
4198
    int wolfSSL_OpenSSL_add_all_algorithms_conf(void)
4199
    {
4200
        WOLFSSL_ENTER("wolfSSL_OpenSSL_add_all_algorithms_conf");
4201
        /* This function is currently the same as
4202
        wolfSSL_OpenSSL_add_all_algorithms_noconf since we do not employ
4203
        the use of a wolfssl.cnf type configuration file and is only used for
4204
        OpenSSL compatibility. */
4205
4206
        if (wolfSSL_add_all_algorithms() ==
4207
            WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR))
4208
        {
4209
            return WOLFSSL_FATAL_ERROR;
4210
        }
4211
        return WOLFSSL_SUCCESS;
4212
    }
4213
4214
#endif
4215
4216
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
4217
    defined(WOLFSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
4218
    void wolfSSL_CTX_set_quiet_shutdown(WOLFSSL_CTX* ctx, int mode)
4219
    {
4220
        WOLFSSL_ENTER("wolfSSL_CTX_set_quiet_shutdown");
4221
        if (mode)
4222
            ctx->quietShutdown = 1;
4223
    }
4224
4225
4226
    void wolfSSL_set_quiet_shutdown(WOLFSSL* ssl, int mode)
4227
    {
4228
        WOLFSSL_ENTER("wolfSSL_set_quiet_shutdown");
4229
        if (mode)
4230
            ssl->options.quietShutdown = 1;
4231
    }
4232
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL ||
4233
          WOLFSSL_EXTRA || WOLFSSL_WPAS_SMALL */
4234
4235
#ifdef OPENSSL_EXTRA
4236
#ifndef NO_BIO
4237
    static void ssl_set_bio(WOLFSSL* ssl, WOLFSSL_BIO* rd, WOLFSSL_BIO* wr, int flags)
4238
    {
4239
        WOLFSSL_ENTER("wolfSSL_set_bio");
4240
4241
        if (ssl == NULL) {
4242
            WOLFSSL_MSG("Bad argument, ssl was NULL");
4243
            return;
4244
        }
4245
4246
        /* free any existing WOLFSSL_BIOs in use but don't free those in
4247
         * a chain */
4248
        if ((flags & WOLFSSL_BIO_FLAG_READ) && (ssl->biord != NULL)) {
4249
            if ((flags & WOLFSSL_BIO_FLAG_WRITE) && (ssl->biord != ssl->biowr)) {
4250
                if (ssl->biowr != NULL && ssl->biowr->prev == NULL)
4251
                    wolfSSL_BIO_free(ssl->biowr);
4252
                ssl->biowr = NULL;
4253
            }
4254
            if (ssl->biord->prev == NULL)
4255
                wolfSSL_BIO_free(ssl->biord);
4256
            ssl->biord = NULL;
4257
        }
4258
        else if ((flags & WOLFSSL_BIO_FLAG_WRITE) && (ssl->biowr != NULL)) {
4259
            if (ssl->biowr->prev == NULL)
4260
                wolfSSL_BIO_free(ssl->biowr);
4261
            ssl->biowr = NULL;
4262
        }
4263
4264
        /* set flag obviously */
4265
        if (rd && !(rd->flags & WOLFSSL_BIO_FLAG_READ))
4266
            rd->flags |= WOLFSSL_BIO_FLAG_READ;
4267
        if (wr && !(wr->flags & WOLFSSL_BIO_FLAG_WRITE))
4268
            wr->flags |= WOLFSSL_BIO_FLAG_WRITE;
4269
4270
        if (flags & WOLFSSL_BIO_FLAG_READ)
4271
            ssl->biord = rd;
4272
        if (flags & WOLFSSL_BIO_FLAG_WRITE)
4273
            ssl->biowr = wr;
4274
4275
        /* set SSL to use BIO callbacks instead */
4276
        if ((flags & WOLFSSL_BIO_FLAG_READ) &&
4277
            (((ssl->cbioFlag & WOLFSSL_CBIO_RECV) == 0)))
4278
        {
4279
            ssl->CBIORecv = SslBioReceive;
4280
        }
4281
        if ((flags & WOLFSSL_BIO_FLAG_WRITE) &&
4282
            (((ssl->cbioFlag & WOLFSSL_CBIO_SEND) == 0)))
4283
        {
4284
            ssl->CBIOSend = SslBioSend;
4285
        }
4286
4287
        /* User programs should always retry reading from these BIOs */
4288
        if (rd) {
4289
            /* User writes to rd */
4290
            wolfSSL_BIO_set_retry_write(rd);
4291
        }
4292
        if (wr) {
4293
            /* User reads from wr */
4294
            wolfSSL_BIO_set_retry_read(wr);
4295
        }
4296
    }
4297
4298
    void wolfSSL_set_bio(WOLFSSL* ssl, WOLFSSL_BIO* rd, WOLFSSL_BIO* wr)
4299
    {
4300
        ssl_set_bio(ssl, rd, wr, WOLFSSL_BIO_FLAG_READ | WOLFSSL_BIO_FLAG_WRITE);
4301
    }
4302
4303
    void wolfSSL_set_rbio(WOLFSSL* ssl, WOLFSSL_BIO* rd)
4304
    {
4305
        ssl_set_bio(ssl, rd, NULL, WOLFSSL_BIO_FLAG_READ);
4306
    }
4307
4308
    void wolfSSL_set_wbio(WOLFSSL* ssl, WOLFSSL_BIO* wr)
4309
    {
4310
        ssl_set_bio(ssl, NULL, wr, WOLFSSL_BIO_FLAG_WRITE);
4311
    }
4312
4313
#endif /* !NO_BIO */
4314
#endif /* OPENSSL_EXTRA */
4315
4316
#ifdef WOLFSSL_CERT_SETUP_CB
4317
    int wolfSSL_get_client_suites_sigalgs(const WOLFSSL* ssl,
4318
            const byte** suites, word16* suiteSz,
4319
            const byte** hashSigAlgo, word16* hashSigAlgoSz)
4320
    {
4321
        WOLFSSL_ENTER("wolfSSL_get_client_suites_sigalgs");
4322
4323
        if (suites != NULL)
4324
            *suites = NULL;
4325
        if (suiteSz != NULL)
4326
            *suiteSz = 0;
4327
        if (hashSigAlgo != NULL)
4328
            *hashSigAlgo = NULL;
4329
        if (hashSigAlgoSz != NULL)
4330
            *hashSigAlgoSz = 0;
4331
4332
        if (ssl != NULL && ssl->clSuites != NULL) {
4333
            if (suites != NULL && suiteSz != NULL) {
4334
                *suites = ssl->clSuites->suites;
4335
                *suiteSz = ssl->clSuites->suiteSz;
4336
            }
4337
            if (hashSigAlgo != NULL && hashSigAlgoSz != NULL) {
4338
                *hashSigAlgo = ssl->clSuites->hashSigAlgo;
4339
                *hashSigAlgoSz = ssl->clSuites->hashSigAlgoSz;
4340
            }
4341
            return WOLFSSL_SUCCESS;
4342
        }
4343
        return WOLFSSL_FAILURE;
4344
    }
4345
4346
#ifndef NO_TLS
4347
    WOLFSSL_CIPHERSUITE_INFO wolfSSL_get_ciphersuite_info(byte first,
4348
            byte second)
4349
    {
4350
        WOLFSSL_CIPHERSUITE_INFO info;
4351
        info.rsaAuth = (byte)(CipherRequires(first, second, REQUIRES_RSA) ||
4352
                CipherRequires(first, second, REQUIRES_RSA_SIG));
4353
        info.eccAuth = (byte)(CipherRequires(first, second, REQUIRES_ECC) ||
4354
                /* Static ECC ciphers may require RSA for authentication */
4355
                (CipherRequires(first, second, REQUIRES_ECC_STATIC) &&
4356
                        !CipherRequires(first, second, REQUIRES_RSA_SIG)));
4357
        info.eccStatic =
4358
                (byte)CipherRequires(first, second, REQUIRES_ECC_STATIC);
4359
        info.psk = (byte)CipherRequires(first, second, REQUIRES_PSK);
4360
        return info;
4361
    }
4362
#endif
4363
4364
    /**
4365
     * @param first First byte of the hash and signature algorithm
4366
     * @param second Second byte of the hash and signature algorithm
4367
     * @param hashAlgo The enum wc_HashType of the MAC algorithm
4368
     * @param sigAlgo The enum Key_Sum of the authentication algorithm
4369
     */
4370
    int wolfSSL_get_sigalg_info(byte first, byte second,
4371
            int* hashAlgo, int* sigAlgo)
4372
    {
4373
        byte input[2];
4374
        byte hashType;
4375
        byte sigType;
4376
4377
        if (hashAlgo == NULL || sigAlgo == NULL)
4378
            return BAD_FUNC_ARG;
4379
4380
        input[0] = first;
4381
        input[1] = second;
4382
        DecodeSigAlg(input, &hashType, &sigType);
4383
4384
        /* cast so that compiler reminds us of unimplemented values */
4385
        switch ((enum SignatureAlgorithm)sigType) {
4386
        case anonymous_sa_algo:
4387
            *sigAlgo = ANONk;
4388
            break;
4389
        case rsa_sa_algo:
4390
            *sigAlgo = RSAk;
4391
            break;
4392
        case dsa_sa_algo:
4393
            *sigAlgo = DSAk;
4394
            break;
4395
        case ecc_dsa_sa_algo:
4396
        case ecc_brainpool_sa_algo:
4397
            *sigAlgo = ECDSAk;
4398
            break;
4399
        case rsa_pss_sa_algo:
4400
            *sigAlgo = RSAPSSk;
4401
            break;
4402
        case ed25519_sa_algo:
4403
            *sigAlgo = ED25519k;
4404
            break;
4405
        case rsa_pss_pss_algo:
4406
            *sigAlgo = RSAPSSk;
4407
            break;
4408
        case ed448_sa_algo:
4409
            *sigAlgo = ED448k;
4410
            break;
4411
        case falcon_level1_sa_algo:
4412
            *sigAlgo = FALCON_LEVEL1k;
4413
            break;
4414
        case falcon_level5_sa_algo:
4415
            *sigAlgo = FALCON_LEVEL5k;
4416
            break;
4417
        case mldsa_44_sa_algo:
4418
            *sigAlgo = ML_DSA_44k;
4419
            break;
4420
        case mldsa_65_sa_algo:
4421
            *sigAlgo = ML_DSA_65k;
4422
            break;
4423
        case mldsa_87_sa_algo:
4424
            *sigAlgo = ML_DSA_87k;
4425
            break;
4426
        case slhdsa_sha2_128s_sa_algo:
4427
            *sigAlgo = SLH_DSA_SHA2_128Sk;
4428
            break;
4429
        case slhdsa_sha2_128f_sa_algo:
4430
            *sigAlgo = SLH_DSA_SHA2_128Fk;
4431
            break;
4432
        case slhdsa_sha2_192s_sa_algo:
4433
            *sigAlgo = SLH_DSA_SHA2_192Sk;
4434
            break;
4435
        case slhdsa_sha2_192f_sa_algo:
4436
            *sigAlgo = SLH_DSA_SHA2_192Fk;
4437
            break;
4438
        case slhdsa_sha2_256s_sa_algo:
4439
            *sigAlgo = SLH_DSA_SHA2_256Sk;
4440
            break;
4441
        case slhdsa_sha2_256f_sa_algo:
4442
            *sigAlgo = SLH_DSA_SHA2_256Fk;
4443
            break;
4444
        case slhdsa_shake_128s_sa_algo:
4445
            *sigAlgo = SLH_DSA_SHAKE_128Sk;
4446
            break;
4447
        case slhdsa_shake_128f_sa_algo:
4448
            *sigAlgo = SLH_DSA_SHAKE_128Fk;
4449
            break;
4450
        case slhdsa_shake_192s_sa_algo:
4451
            *sigAlgo = SLH_DSA_SHAKE_192Sk;
4452
            break;
4453
        case slhdsa_shake_192f_sa_algo:
4454
            *sigAlgo = SLH_DSA_SHAKE_192Fk;
4455
            break;
4456
        case slhdsa_shake_256s_sa_algo:
4457
            *sigAlgo = SLH_DSA_SHAKE_256Sk;
4458
            break;
4459
        case slhdsa_shake_256f_sa_algo:
4460
            *sigAlgo = SLH_DSA_SHAKE_256Fk;
4461
            break;
4462
        case sm2_sa_algo:
4463
            *sigAlgo = SM2k;
4464
            break;
4465
        case invalid_sa_algo:
4466
        case any_sa_algo:
4467
        default:
4468
            *hashAlgo = WC_HASH_TYPE_NONE;
4469
            *sigAlgo = 0;
4470
            return BAD_FUNC_ARG;
4471
        }
4472
4473
        /* cast so that compiler reminds us of unimplemented values */
4474
        switch((enum wc_MACAlgorithm)hashType) {
4475
        case no_mac:
4476
        case rmd_mac: /* Don't have a RIPEMD type in wc_HashType */
4477
            *hashAlgo = WC_HASH_TYPE_NONE;
4478
            break;
4479
        case md5_mac:
4480
            *hashAlgo = WC_HASH_TYPE_MD5;
4481
            break;
4482
        case sha_mac:
4483
            *hashAlgo = WC_HASH_TYPE_SHA;
4484
            break;
4485
        case sha224_mac:
4486
            *hashAlgo = WC_HASH_TYPE_SHA224;
4487
            break;
4488
        case sha256_mac:
4489
            *hashAlgo = WC_HASH_TYPE_SHA256;
4490
            break;
4491
        case sha384_mac:
4492
            *hashAlgo = WC_HASH_TYPE_SHA384;
4493
            break;
4494
        case sha512_mac:
4495
            *hashAlgo = WC_HASH_TYPE_SHA512;
4496
            break;
4497
        case blake2b_mac:
4498
            *hashAlgo = WC_HASH_TYPE_BLAKE2B;
4499
            break;
4500
        case sm3_mac:
4501
#ifdef WOLFSSL_SM3
4502
            *hashAlgo = WC_HASH_TYPE_SM3;
4503
#else
4504
            *hashAlgo = WC_HASH_TYPE_NONE;
4505
#endif
4506
            break;
4507
        default:
4508
            *hashAlgo = WC_HASH_TYPE_NONE;
4509
            *sigAlgo = 0;
4510
            return BAD_FUNC_ARG;
4511
        }
4512
        return 0;
4513
    }
4514
#endif /* WOLFSSL_CERT_SETUP_CB */
4515
4516
#ifdef OPENSSL_EXTRA
4517
4518
    /* keyblock size in bytes or -1 */
4519
    int wolfSSL_get_keyblock_size(WOLFSSL* ssl)
4520
    {
4521
        if (ssl == NULL)
4522
            return WOLFSSL_FATAL_ERROR;
4523
4524
        return 2 * (ssl->specs.key_size + ssl->specs.iv_size +
4525
                    ssl->specs.hash_size);
4526
    }
4527
4528
#endif /* OPENSSL_EXTRA */
4529
4530
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EXTRA) || \
4531
    defined(WOLFSSL_WPAS_SMALL)
4532
4533
    /* store keys returns WOLFSSL_SUCCESS or -1 on error */
4534
    int wolfSSL_get_keys(WOLFSSL* ssl, unsigned char** ms, unsigned int* msLen,
4535
                                     unsigned char** sr, unsigned int* srLen,
4536
                                     unsigned char** cr, unsigned int* crLen)
4537
    {
4538
        if (ssl == NULL || ssl->arrays == NULL)
4539
            return WOLFSSL_FATAL_ERROR;
4540
4541
        *ms = ssl->arrays->masterSecret;
4542
        *sr = ssl->arrays->serverRandom;
4543
        *cr = ssl->arrays->clientRandom;
4544
4545
        *msLen = SECRET_LEN;
4546
        *srLen = RAN_LEN;
4547
        *crLen = RAN_LEN;
4548
4549
        return WOLFSSL_SUCCESS;
4550
    }
4551
4552
4553
#endif /* OPENSSL_EXTRA || WOLFSSL_EXTRA || WOLFSSL_WPAS_SMALL */
4554
4555
4556
#ifdef OPENSSL_EXTRA
4557
    void wolfSSL_CTX_set_tmp_rsa_callback(WOLFSSL_CTX* ctx,
4558
                                      WOLFSSL_RSA*(*f)(WOLFSSL*, int, int))
4559
    {
4560
        /* wolfSSL verifies all these internally */
4561
        (void)ctx;
4562
        (void)f;
4563
    }
4564
4565
4566
    void wolfSSL_set_shutdown(WOLFSSL* ssl, int opt)
4567
    {
4568
        WOLFSSL_ENTER("wolfSSL_set_shutdown");
4569
        if(ssl==NULL) {
4570
            WOLFSSL_MSG("Shutdown not set. ssl is null");
4571
            return;
4572
        }
4573
4574
        ssl->options.sentNotify =  (opt&WOLFSSL_SENT_SHUTDOWN) > 0;
4575
        ssl->options.closeNotify = (opt&WOLFSSL_RECEIVED_SHUTDOWN) > 0;
4576
    }
4577
#endif
4578
4579
    long wolfSSL_CTX_get_options(WOLFSSL_CTX* ctx)
4580
0
    {
4581
0
        WOLFSSL_ENTER("wolfSSL_CTX_get_options");
4582
0
        WOLFSSL_MSG("wolfSSL options are set through API calls and macros");
4583
0
        if(ctx == NULL)
4584
0
            return BAD_FUNC_ARG;
4585
0
        return (long)ctx->mask;
4586
0
    }
4587
4588
    /* forward declaration */
4589
    static long wolf_set_options(long old_op, long op);
4590
4591
    long wolfSSL_CTX_set_options(WOLFSSL_CTX* ctx, long opt)
4592
0
    {
4593
0
        WOLFSSL_ENTER("wolfSSL_CTX_set_options");
4594
4595
0
        if (ctx == NULL)
4596
0
            return BAD_FUNC_ARG;
4597
4598
0
        ctx->mask = (unsigned long)wolf_set_options((long)ctx->mask, opt);
4599
#if defined(HAVE_SESSION_TICKET) && (defined(OPENSSL_EXTRA) \
4600
        || defined(HAVE_WEBSERVER) || defined(WOLFSSL_WPAS_SMALL))
4601
        if ((ctx->mask & WOLFSSL_OP_NO_TICKET) == WOLFSSL_OP_NO_TICKET) {
4602
          ctx->noTicketTls12 = 1;
4603
        }
4604
        /* This code is here for documentation purpose. You must not turn off
4605
         * session tickets with the WOLFSSL_OP_NO_TICKET option for TLSv1.3.
4606
         * Because we need to support both stateful and stateless tickets.
4607
        #ifdef WOLFSSL_TLS13
4608
            if ((ctx->mask & WOLFSSL_OP_NO_TICKET) == WOLFSSL_OP_NO_TICKET) {
4609
                ctx->noTicketTls13 = 1;
4610
            }
4611
        #endif
4612
        */
4613
#endif
4614
0
        return (long)ctx->mask;
4615
0
    }
4616
4617
    long wolfSSL_CTX_clear_options(WOLFSSL_CTX* ctx, long opt)
4618
0
    {
4619
0
        WOLFSSL_ENTER("wolfSSL_CTX_clear_options");
4620
0
        if(ctx == NULL)
4621
0
            return BAD_FUNC_ARG;
4622
0
        ctx->mask &= (unsigned long)~opt;
4623
0
        return (long)ctx->mask;
4624
0
    }
4625
4626
#ifdef OPENSSL_EXTRA
4627
4628
    int wolfSSL_set_rfd(WOLFSSL* ssl, int rfd)
4629
    {
4630
        WOLFSSL_ENTER("wolfSSL_set_rfd");
4631
        ssl->rfd = rfd;      /* not used directly to allow IO callbacks */
4632
4633
        ssl->IOCB_ReadCtx  = &ssl->rfd;
4634
4635
    #ifdef WOLFSSL_DTLS
4636
        if (ssl->options.dtls) {
4637
            ssl->IOCB_ReadCtx = &ssl->buffers.dtlsCtx;
4638
            ssl->buffers.dtlsCtx.rfd = rfd;
4639
        #ifdef USE_WOLFSSL_IO
4640
            ssl->buffers.dtlsCtx.rfdIsDGram =
4641
                (byte)(wolfIO_SockIsDGram(rfd) != 0);
4642
        #endif
4643
        }
4644
    #endif
4645
4646
        return WOLFSSL_SUCCESS;
4647
    }
4648
4649
4650
    int wolfSSL_set_wfd(WOLFSSL* ssl, int wfd)
4651
    {
4652
        WOLFSSL_ENTER("wolfSSL_set_wfd");
4653
        ssl->wfd = wfd;      /* not used directly to allow IO callbacks */
4654
4655
        ssl->IOCB_WriteCtx  = &ssl->wfd;
4656
4657
        return WOLFSSL_SUCCESS;
4658
    }
4659
#endif /* OPENSSL_EXTRA */
4660
4661
#ifdef WOLFSSL_ENCRYPTED_KEYS
4662
4663
    void wolfSSL_CTX_set_default_passwd_cb_userdata(WOLFSSL_CTX* ctx,
4664
                                                   void* userdata)
4665
    {
4666
        WOLFSSL_ENTER("wolfSSL_CTX_set_default_passwd_cb_userdata");
4667
        if (ctx)
4668
            ctx->passwd_userdata = userdata;
4669
    }
4670
4671
4672
    void wolfSSL_CTX_set_default_passwd_cb(WOLFSSL_CTX* ctx, wc_pem_password_cb*
4673
                                           cb)
4674
    {
4675
        WOLFSSL_ENTER("wolfSSL_CTX_set_default_passwd_cb");
4676
        if (ctx)
4677
            ctx->passwd_cb = cb;
4678
    }
4679
4680
    wc_pem_password_cb* wolfSSL_CTX_get_default_passwd_cb(WOLFSSL_CTX *ctx)
4681
    {
4682
        if (ctx == NULL || ctx->passwd_cb == NULL) {
4683
            return NULL;
4684
        }
4685
4686
        return ctx->passwd_cb;
4687
    }
4688
4689
4690
    void* wolfSSL_CTX_get_default_passwd_cb_userdata(WOLFSSL_CTX *ctx)
4691
    {
4692
        if (ctx == NULL) {
4693
            return NULL;
4694
        }
4695
4696
        return ctx->passwd_userdata;
4697
    }
4698
4699
#endif /* WOLFSSL_ENCRYPTED_KEYS */
4700
4701
4702
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || defined(HAVE_MEMCACHED)
4703
#endif
4704
4705
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
4706
4707
    int wolfSSL_num_locks(void)
4708
    {
4709
        return 0;
4710
    }
4711
4712
    void wolfSSL_set_locking_callback(mutex_cb* f)
4713
    {
4714
        WOLFSSL_ENTER("wolfSSL_set_locking_callback");
4715
4716
        if (wc_SetMutexCb(f) != 0) {
4717
            WOLFSSL_MSG("Error when setting mutex call back");
4718
        }
4719
    }
4720
4721
    mutex_cb* wolfSSL_get_locking_callback(void)
4722
    {
4723
        WOLFSSL_ENTER("wolfSSL_get_locking_callback");
4724
4725
        return wc_GetMutexCb();
4726
    }
4727
4728
4729
    typedef unsigned long (idCb)(void);
4730
    static idCb* inner_idCb = NULL;
4731
4732
    unsigned long wolfSSL_thread_id(void)
4733
    {
4734
        if (inner_idCb != NULL) {
4735
            return inner_idCb();
4736
        }
4737
        else {
4738
            return 0;
4739
        }
4740
    }
4741
4742
4743
    void wolfSSL_set_id_callback(unsigned long (*f)(void))
4744
    {
4745
        inner_idCb = f;
4746
    }
4747
4748
#ifdef WOLFSSL_HAVE_ERROR_QUEUE
4749
#ifndef NO_BIO
4750
    /* print out and clear all errors */
4751
#endif /* !NO_BIO */
4752
#endif /* WOLFSSL_HAVE_ERROR_QUEUE */
4753
4754
#endif /* OPENSSL_EXTRA || HAVE_WEBSERVER */
4755
4756
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || \
4757
    defined(HAVE_SECRET_CALLBACK)
4758
#if !defined(NO_WOLFSSL_SERVER)
4759
/* Return the amount of random bytes copied over or error case.
4760
 * ssl : ssl struct after handshake
4761
 * out : buffer to hold random bytes
4762
 * outSz : either 0 (return max buffer sz) or size of out buffer
4763
 */
4764
size_t wolfSSL_get_server_random(const WOLFSSL *ssl, unsigned char *out,
4765
                                                                   size_t outSz)
4766
{
4767
    size_t size;
4768
4769
    /* return max size of buffer */
4770
    if (outSz == 0) {
4771
        return RAN_LEN;
4772
    }
4773
4774
    if (ssl == NULL || out == NULL) {
4775
        return 0;
4776
    }
4777
4778
    if (ssl->arrays == NULL) {
4779
        WOLFSSL_MSG("Arrays struct not saved after handshake");
4780
        return 0;
4781
    }
4782
4783
    if (outSz > RAN_LEN) {
4784
        size = RAN_LEN;
4785
    }
4786
    else {
4787
        size = outSz;
4788
    }
4789
4790
    XMEMCPY(out, ssl->arrays->serverRandom, size);
4791
    return size;
4792
}
4793
#endif /* !NO_WOLFSSL_SERVER */
4794
#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL || HAVE_SECRET_CALLBACK */
4795
4796
#ifdef OPENSSL_EXTRA
4797
#if !defined(NO_WOLFSSL_SERVER)
4798
/* Used to get the peer ephemeral public key sent during the connection
4799
 * NOTE: currently wolfSSL_KeepHandshakeResources(WOLFSSL* ssl) must be called
4800
 *       before the ephemeral key is stored.
4801
 * return WOLFSSL_SUCCESS on success */
4802
int wolfSSL_get_peer_tmp_key(const WOLFSSL* ssl, WOLFSSL_EVP_PKEY** pkey)
4803
{
4804
    WOLFSSL_EVP_PKEY* ret = NULL;
4805
4806
    WOLFSSL_ENTER("wolfSSL_get_server_tmp_key");
4807
4808
    if (ssl == NULL || pkey == NULL) {
4809
        WOLFSSL_MSG("Bad argument passed in");
4810
        return WOLFSSL_FAILURE;
4811
    }
4812
4813
#ifdef HAVE_ECC
4814
    if (ssl->peerEccKey != NULL) {
4815
        unsigned char* der;
4816
        const unsigned char* pt;
4817
        unsigned int   derSz = 0;
4818
        int sz;
4819
4820
        PRIVATE_KEY_UNLOCK();
4821
        if (wc_ecc_export_x963(ssl->peerEccKey, NULL, &derSz)
4822
              != WC_NO_ERR_TRACE(LENGTH_ONLY_E))
4823
        {
4824
            WOLFSSL_MSG("get ecc der size failed");
4825
            PRIVATE_KEY_LOCK();
4826
            return WOLFSSL_FAILURE;
4827
        }
4828
        PRIVATE_KEY_LOCK();
4829
4830
        derSz += MAX_SEQ_SZ + (2 * MAX_ALGO_SZ) + MAX_SEQ_SZ + TRAILING_ZERO;
4831
        der = (unsigned char*)XMALLOC(derSz, ssl->heap, DYNAMIC_TYPE_KEY);
4832
        if (der == NULL) {
4833
            WOLFSSL_MSG("Memory error");
4834
            return WOLFSSL_FAILURE;
4835
        }
4836
4837
        if ((sz = wc_EccPublicKeyToDer(ssl->peerEccKey, der, derSz, 1)) <= 0) {
4838
            WOLFSSL_MSG("get ecc der failed");
4839
            XFREE(der, ssl->heap, DYNAMIC_TYPE_KEY);
4840
            return WOLFSSL_FAILURE;
4841
        }
4842
        pt = der; /* in case pointer gets advanced */
4843
        ret = wolfSSL_d2i_PUBKEY(NULL, &pt, sz);
4844
        XFREE(der, ssl->heap, DYNAMIC_TYPE_KEY);
4845
    }
4846
#endif
4847
4848
    *pkey = ret;
4849
#ifdef HAVE_ECC
4850
    if (ret != NULL)
4851
        return WOLFSSL_SUCCESS;
4852
    else
4853
#endif
4854
        return WOLFSSL_FAILURE;
4855
}
4856
4857
#endif /* !NO_WOLFSSL_SERVER */
4858
4859
/**
4860
 * This function checks if any compiled in protocol versions are
4861
 * left enabled after calls to set_min or set_max API.
4862
 * @param major The SSL/TLS major version
4863
 * @return WOLFSSL_SUCCESS on valid settings and WOLFSSL_FAILURE when no
4864
 *         protocol versions are left enabled.
4865
 */
4866
static int CheckSslMethodVersion(byte major, unsigned long options)
4867
{
4868
    int sanityConfirmed = 0;
4869
4870
    (void)options;
4871
4872
    switch (major) {
4873
    #ifndef NO_TLS
4874
        case SSLv3_MAJOR:
4875
            #ifdef WOLFSSL_ALLOW_SSLV3
4876
                if (!(options & WOLFSSL_OP_NO_SSLv3)) {
4877
                    sanityConfirmed = 1;
4878
                }
4879
            #endif
4880
            #ifndef NO_OLD_TLS
4881
                if (!(options & WOLFSSL_OP_NO_TLSv1))
4882
                    sanityConfirmed = 1;
4883
                if (!(options & WOLFSSL_OP_NO_TLSv1_1))
4884
                    sanityConfirmed = 1;
4885
            #endif
4886
            #ifndef WOLFSSL_NO_TLS12
4887
                if (!(options & WOLFSSL_OP_NO_TLSv1_2))
4888
                    sanityConfirmed = 1;
4889
            #endif
4890
            #ifdef WOLFSSL_TLS13
4891
                if (!(options & WOLFSSL_OP_NO_TLSv1_3))
4892
                    sanityConfirmed = 1;
4893
            #endif
4894
            break;
4895
    #endif
4896
    #ifdef WOLFSSL_DTLS
4897
        case DTLS_MAJOR:
4898
            sanityConfirmed = 1;
4899
            break;
4900
    #endif
4901
        default:
4902
            WOLFSSL_MSG("Invalid major version");
4903
            return WOLFSSL_FAILURE;
4904
    }
4905
    if (!sanityConfirmed) {
4906
        WOLFSSL_MSG("All compiled in TLS versions disabled");
4907
        return WOLFSSL_FAILURE;
4908
    }
4909
    return WOLFSSL_SUCCESS;
4910
}
4911
4912
/**
4913
 * protoVerTbl holds (D)TLS version numbers in ascending order.
4914
 * Except DTLS versions, the newer version is located in the latter part of
4915
 * the table. This table is referred by wolfSSL_CTX_set_min_proto_version and
4916
 * wolfSSL_CTX_set_max_proto_version.
4917
 */
4918
static const int protoVerTbl[] = {
4919
    SSL3_VERSION,
4920
    TLS1_VERSION,
4921
    TLS1_1_VERSION,
4922
    TLS1_2_VERSION,
4923
    TLS1_3_VERSION,
4924
    DTLS1_VERSION,
4925
    DTLS1_2_VERSION
4926
};
4927
/* number of protocol versions listed in protoVerTbl */
4928
#define NUMBER_OF_PROTOCOLS (sizeof(protoVerTbl)/sizeof(int))
4929
4930
/**
4931
 * wolfSSL_CTX_set_min_proto_version attempts to set the minimum protocol
4932
 * version to use by SSL objects created from this WOLFSSL_CTX.
4933
 * This API guarantees that a version of SSL/TLS lower than specified
4934
 * here will not be allowed. If the version specified is not compiled in
4935
 * then this API sets the lowest compiled in protocol version.
4936
 * This API also accept 0 as version, to set the minimum version automatically.
4937
 * CheckSslMethodVersion() is called to check if any remaining protocol versions
4938
 * are enabled.
4939
 * @param ctx The wolfSSL CONTEXT factory for spawning SSL/TLS objects
4940
 * @param version Any of the following
4941
 *          * 0
4942
 *          * SSL3_VERSION
4943
 *          * TLS1_VERSION
4944
 *          * TLS1_1_VERSION
4945
 *          * TLS1_2_VERSION
4946
 *          * TLS1_3_VERSION
4947
 *          * DTLS1_VERSION
4948
 *          * DTLS1_2_VERSION
4949
 * @return WOLFSSL_SUCCESS on valid settings and WOLFSSL_FAILURE when no
4950
 *         protocol versions are left enabled.
4951
 */
4952
static int Set_CTX_min_proto_version(WOLFSSL_CTX* ctx, int version)
4953
{
4954
    WOLFSSL_ENTER("wolfSSL_CTX_set_min_proto_version_ex");
4955
4956
    if (ctx == NULL) {
4957
        return WOLFSSL_FAILURE;
4958
    }
4959
4960
    switch (version) {
4961
#ifndef NO_TLS
4962
        case SSL3_VERSION:
4963
#if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
4964
            ctx->minDowngrade = SSLv3_MINOR;
4965
            break;
4966
#endif
4967
        case TLS1_VERSION:
4968
        #ifdef WOLFSSL_ALLOW_TLSV10
4969
            ctx->minDowngrade = TLSv1_MINOR;
4970
            break;
4971
        #endif
4972
        case TLS1_1_VERSION:
4973
        #ifndef NO_OLD_TLS
4974
            ctx->minDowngrade = TLSv1_1_MINOR;
4975
            break;
4976
        #endif
4977
        case TLS1_2_VERSION:
4978
        #ifndef WOLFSSL_NO_TLS12
4979
            ctx->minDowngrade = TLSv1_2_MINOR;
4980
            break;
4981
        #endif
4982
        case TLS1_3_VERSION:
4983
        #ifdef WOLFSSL_TLS13
4984
            ctx->minDowngrade = TLSv1_3_MINOR;
4985
            break;
4986
        #endif
4987
#endif
4988
#ifdef WOLFSSL_DTLS
4989
        case DTLS1_VERSION:
4990
    #ifndef NO_OLD_TLS
4991
            ctx->minDowngrade = DTLS_MINOR;
4992
            break;
4993
    #endif
4994
        case DTLS1_2_VERSION:
4995
            ctx->minDowngrade = DTLSv1_2_MINOR;
4996
            break;
4997
#endif
4998
        default:
4999
            WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
5000
            return WOLFSSL_FAILURE;
5001
    }
5002
5003
    switch (version) {
5004
#ifndef NO_TLS
5005
    case TLS1_3_VERSION:
5006
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_2);
5007
        FALL_THROUGH;
5008
    case TLS1_2_VERSION:
5009
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_1);
5010
        FALL_THROUGH;
5011
    case TLS1_1_VERSION:
5012
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1);
5013
        FALL_THROUGH;
5014
    case TLS1_VERSION:
5015
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_SSLv3);
5016
        break;
5017
    case SSL3_VERSION:
5018
    case SSL2_VERSION:
5019
        /* Nothing to do here */
5020
        break;
5021
#endif
5022
#ifdef WOLFSSL_DTLS
5023
    case DTLS1_VERSION:
5024
    case DTLS1_2_VERSION:
5025
        break;
5026
#endif
5027
    default:
5028
        WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
5029
        return WOLFSSL_FAILURE;
5030
    }
5031
5032
    return CheckSslMethodVersion(ctx->method->version.major, ctx->mask);
5033
}
5034
5035
/* Sets the min protocol version allowed with WOLFSSL_CTX
5036
 * returns WOLFSSL_SUCCESS on success */
5037
int wolfSSL_CTX_set_min_proto_version(WOLFSSL_CTX* ctx, int version)
5038
{
5039
    int ret;
5040
    int proto    = 0;
5041
    int maxProto = 0;
5042
    int i;
5043
    int idx = 0;
5044
5045
    WOLFSSL_ENTER("wolfSSL_CTX_set_min_proto_version");
5046
5047
    if (ctx == NULL) {
5048
        return WOLFSSL_FAILURE;
5049
    }
5050
5051
    if (version != 0) {
5052
        proto = version;
5053
        ctx->minProto = 0; /* turn min proto flag off */
5054
        for (i = 0; (unsigned)i < NUMBER_OF_PROTOCOLS; i++) {
5055
            if (protoVerTbl[i] == version) {
5056
                break;
5057
            }
5058
        }
5059
    }
5060
    else {
5061
        /* when 0 is specified as version, try to find out the min version */
5062
        for (i = 0; (unsigned)i < NUMBER_OF_PROTOCOLS; i++) {
5063
            ret = Set_CTX_min_proto_version(ctx, protoVerTbl[i]);
5064
            if (ret == WOLFSSL_SUCCESS) {
5065
                proto = protoVerTbl[i];
5066
                ctx->minProto = 1; /* turn min proto flag on */
5067
                break;
5068
            }
5069
        }
5070
    }
5071
5072
    /* check case where max > min , if so then clear the NO_* options
5073
     * i is the index into the table for proto version used, see if the max
5074
     * proto version index found is smaller */
5075
    maxProto = wolfSSL_CTX_get_max_proto_version(ctx);
5076
    for (idx = 0; (unsigned)idx < NUMBER_OF_PROTOCOLS; idx++) {
5077
        if (protoVerTbl[idx] == maxProto) {
5078
            break;
5079
        }
5080
    }
5081
    if (idx < i) {
5082
        wolfSSL_CTX_clear_options(ctx, WOLFSSL_OP_NO_TLSv1 |
5083
                WOLFSSL_OP_NO_TLSv1_1 | WOLFSSL_OP_NO_TLSv1_2 |
5084
                WOLFSSL_OP_NO_TLSv1_3);
5085
    }
5086
5087
    ret = Set_CTX_min_proto_version(ctx, proto);
5088
    return ret;
5089
}
5090
5091
/**
5092
 * wolfSSL_CTX_set_max_proto_version attempts to set the maximum protocol
5093
 * version to use by SSL objects created from this WOLFSSL_CTX.
5094
 * This API guarantees that a version of SSL/TLS higher than specified
5095
 * here will not be allowed. If the version specified is not compiled in
5096
 * then this API sets the highest compiled in protocol version.
5097
 * This API also accept 0 as version, to set the maximum version automatically.
5098
 * CheckSslMethodVersion() is called to check if any remaining protocol versions
5099
 * are enabled.
5100
 * @param ctx The wolfSSL CONTEXT factory for spawning SSL/TLS objects
5101
 * @param ver Any of the following
5102
 *          * 0
5103
 *          * SSL3_VERSION
5104
 *          * TLS1_VERSION
5105
 *          * TLS1_1_VERSION
5106
 *          * TLS1_2_VERSION
5107
 *          * TLS1_3_VERSION
5108
 *          * DTLS1_VERSION
5109
 *          * DTLS1_2_VERSION
5110
 * @return WOLFSSL_SUCCESS on valid settings and WOLFSSL_FAILURE when no
5111
 *         protocol versions are left enabled.
5112
 */
5113
static int Set_CTX_max_proto_version(WOLFSSL_CTX* ctx, int ver)
5114
{
5115
    int ret;
5116
    WOLFSSL_ENTER("Set_CTX_max_proto_version");
5117
5118
    if (!ctx || !ctx->method) {
5119
        WOLFSSL_MSG("Bad parameter");
5120
        return WOLFSSL_FAILURE;
5121
    }
5122
5123
    switch (ver) {
5124
#ifndef NO_TLS
5125
#ifndef NO_OLD_TLS
5126
    case SSL2_VERSION:
5127
        WOLFSSL_MSG("wolfSSL does not support SSLv2");
5128
        return WOLFSSL_FAILURE;
5129
#endif
5130
    case SSL3_VERSION:
5131
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1);
5132
        FALL_THROUGH;
5133
    case TLS1_VERSION:
5134
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_1);
5135
        FALL_THROUGH;
5136
    case TLS1_1_VERSION:
5137
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_2);
5138
        FALL_THROUGH;
5139
    case TLS1_2_VERSION:
5140
        wolfSSL_CTX_set_options(ctx, WOLFSSL_OP_NO_TLSv1_3);
5141
        FALL_THROUGH;
5142
    case TLS1_3_VERSION:
5143
        /* Nothing to do here */
5144
        break;
5145
#endif
5146
#ifdef WOLFSSL_DTLS
5147
    case DTLS1_VERSION:
5148
    case DTLS1_2_VERSION:
5149
        break;
5150
#endif
5151
    default:
5152
        WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
5153
        return WOLFSSL_FAILURE;
5154
    }
5155
5156
    ret = CheckSslMethodVersion(ctx->method->version.major, ctx->mask);
5157
    if (ret == WOLFSSL_SUCCESS) {
5158
        /* Check the major */
5159
        switch (ver) {
5160
    #ifndef NO_TLS
5161
        case SSL3_VERSION:
5162
        case TLS1_VERSION:
5163
        case TLS1_1_VERSION:
5164
        case TLS1_2_VERSION:
5165
        case TLS1_3_VERSION:
5166
            if (ctx->method->version.major != SSLv3_MAJOR) {
5167
                WOLFSSL_MSG("Mismatched protocol version");
5168
                return WOLFSSL_FAILURE;
5169
            }
5170
            break;
5171
    #endif
5172
    #ifdef WOLFSSL_DTLS
5173
        case DTLS1_VERSION:
5174
        case DTLS1_2_VERSION:
5175
            if (ctx->method->version.major != DTLS_MAJOR) {
5176
                WOLFSSL_MSG("Mismatched protocol version");
5177
                return WOLFSSL_FAILURE;
5178
            }
5179
            break;
5180
    #endif
5181
        }
5182
        /* Update the method */
5183
        switch (ver) {
5184
    #ifndef NO_TLS
5185
        case SSL3_VERSION:
5186
            ctx->method->version.minor = SSLv3_MINOR;
5187
            break;
5188
        case TLS1_VERSION:
5189
            ctx->method->version.minor = TLSv1_MINOR;
5190
            break;
5191
        case TLS1_1_VERSION:
5192
            ctx->method->version.minor = TLSv1_1_MINOR;
5193
            break;
5194
        case TLS1_2_VERSION:
5195
            ctx->method->version.minor = TLSv1_2_MINOR;
5196
            break;
5197
        case TLS1_3_VERSION:
5198
            ctx->method->version.minor = TLSv1_3_MINOR;
5199
            break;
5200
    #endif
5201
    #ifdef WOLFSSL_DTLS
5202
        case DTLS1_VERSION:
5203
            ctx->method->version.minor = DTLS_MINOR;
5204
            break;
5205
        case DTLS1_2_VERSION:
5206
            ctx->method->version.minor = DTLSv1_2_MINOR;
5207
            break;
5208
    #endif
5209
        default:
5210
            WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
5211
            return WOLFSSL_FAILURE;
5212
        }
5213
    }
5214
    return ret;
5215
}
5216
5217
5218
/* Sets the max protocol version allowed with WOLFSSL_CTX
5219
 * returns WOLFSSL_SUCCESS on success */
5220
int wolfSSL_CTX_set_max_proto_version(WOLFSSL_CTX* ctx, int version)
5221
{
5222
    int i;
5223
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
5224
    int minProto;
5225
5226
    WOLFSSL_ENTER("wolfSSL_CTX_set_max_proto_version");
5227
5228
    if (ctx == NULL) {
5229
        return ret;
5230
    }
5231
5232
    /* clear out flags and reset min protocol version */
5233
    minProto = wolfSSL_CTX_get_min_proto_version(ctx);
5234
    wolfSSL_CTX_clear_options(ctx,
5235
            WOLFSSL_OP_NO_TLSv1 | WOLFSSL_OP_NO_TLSv1_1 |
5236
            WOLFSSL_OP_NO_TLSv1_2 | WOLFSSL_OP_NO_TLSv1_3);
5237
    wolfSSL_CTX_set_min_proto_version(ctx, minProto);
5238
    if (version != 0) {
5239
        ctx->maxProto = 0; /* turn max proto flag off */
5240
        return Set_CTX_max_proto_version(ctx, version);
5241
    }
5242
5243
    /* when 0 is specified as version, try to find out the min version from
5244
     * the bottom to top of the protoverTbl.
5245
     */
5246
    for (i = NUMBER_OF_PROTOCOLS -1; i >= 0; i--) {
5247
        ret = Set_CTX_max_proto_version(ctx, protoVerTbl[i]);
5248
        if (ret == WOLFSSL_SUCCESS) {
5249
            ctx->maxProto = 1; /* turn max proto flag on */
5250
            break;
5251
        }
5252
    }
5253
5254
    return ret;
5255
}
5256
5257
5258
static int Set_SSL_min_proto_version(WOLFSSL* ssl, int ver)
5259
{
5260
    WOLFSSL_ENTER("Set_SSL_min_proto_version");
5261
5262
    if (ssl == NULL) {
5263
        return WOLFSSL_FAILURE;
5264
    }
5265
5266
    switch (ver) {
5267
#ifndef NO_TLS
5268
        case SSL3_VERSION:
5269
#if defined(WOLFSSL_ALLOW_SSLV3) && !defined(NO_OLD_TLS)
5270
            ssl->options.minDowngrade = SSLv3_MINOR;
5271
            break;
5272
#endif
5273
        case TLS1_VERSION:
5274
        #ifdef WOLFSSL_ALLOW_TLSV10
5275
            ssl->options.minDowngrade = TLSv1_MINOR;
5276
            break;
5277
        #endif
5278
        case TLS1_1_VERSION:
5279
        #ifndef NO_OLD_TLS
5280
            ssl->options.minDowngrade = TLSv1_1_MINOR;
5281
            break;
5282
        #endif
5283
        case TLS1_2_VERSION:
5284
        #ifndef WOLFSSL_NO_TLS12
5285
            ssl->options.minDowngrade = TLSv1_2_MINOR;
5286
            break;
5287
        #endif
5288
        case TLS1_3_VERSION:
5289
        #ifdef WOLFSSL_TLS13
5290
            ssl->options.minDowngrade = TLSv1_3_MINOR;
5291
            break;
5292
        #endif
5293
#endif
5294
#ifdef WOLFSSL_DTLS
5295
        case DTLS1_VERSION:
5296
    #ifndef NO_OLD_TLS
5297
            ssl->options.minDowngrade = DTLS_MINOR;
5298
            break;
5299
    #endif
5300
        case DTLS1_2_VERSION:
5301
            ssl->options.minDowngrade = DTLSv1_2_MINOR;
5302
            break;
5303
#endif
5304
        default:
5305
            WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
5306
            return WOLFSSL_FAILURE;
5307
    }
5308
5309
    switch (ver) {
5310
#ifndef NO_TLS
5311
    case TLS1_3_VERSION:
5312
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_2;
5313
        FALL_THROUGH;
5314
    case TLS1_2_VERSION:
5315
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_1;
5316
        FALL_THROUGH;
5317
    case TLS1_1_VERSION:
5318
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1;
5319
        FALL_THROUGH;
5320
    case TLS1_VERSION:
5321
        ssl->options.mask |= WOLFSSL_OP_NO_SSLv3;
5322
        break;
5323
    case SSL3_VERSION:
5324
    case SSL2_VERSION:
5325
        /* Nothing to do here */
5326
        break;
5327
#endif
5328
#ifdef WOLFSSL_DTLS
5329
    case DTLS1_VERSION:
5330
    case DTLS1_2_VERSION:
5331
        break;
5332
#endif
5333
    default:
5334
        WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
5335
        return WOLFSSL_FAILURE;
5336
    }
5337
5338
    return CheckSslMethodVersion(ssl->version.major, ssl->options.mask);
5339
}
5340
5341
int wolfSSL_set_min_proto_version(WOLFSSL* ssl, int version)
5342
{
5343
    int i;
5344
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);;
5345
5346
    WOLFSSL_ENTER("wolfSSL_set_min_proto_version");
5347
5348
    if (ssl == NULL) {
5349
        return WOLFSSL_FAILURE;
5350
    }
5351
    if (version != 0) {
5352
        return Set_SSL_min_proto_version(ssl, version);
5353
    }
5354
5355
    /* when 0 is specified as version, try to find out the min version */
5356
    for (i= 0; (unsigned)i < NUMBER_OF_PROTOCOLS; i++) {
5357
        ret = Set_SSL_min_proto_version(ssl, protoVerTbl[i]);
5358
        if (ret == WOLFSSL_SUCCESS)
5359
            break;
5360
    }
5361
5362
    return ret;
5363
}
5364
5365
static int Set_SSL_max_proto_version(WOLFSSL* ssl, int ver)
5366
{
5367
5368
    WOLFSSL_ENTER("Set_SSL_max_proto_version");
5369
5370
    if (!ssl) {
5371
        WOLFSSL_MSG("Bad parameter");
5372
        return WOLFSSL_FAILURE;
5373
    }
5374
5375
    switch (ver) {
5376
    case SSL2_VERSION:
5377
        WOLFSSL_MSG("wolfSSL does not support SSLv2");
5378
        return WOLFSSL_FAILURE;
5379
#ifndef NO_TLS
5380
    case SSL3_VERSION:
5381
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1;
5382
        FALL_THROUGH;
5383
    case TLS1_VERSION:
5384
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_1;
5385
        FALL_THROUGH;
5386
    case TLS1_1_VERSION:
5387
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_2;
5388
        FALL_THROUGH;
5389
    case TLS1_2_VERSION:
5390
        ssl->options.mask |= WOLFSSL_OP_NO_TLSv1_3;
5391
        FALL_THROUGH;
5392
    case TLS1_3_VERSION:
5393
        /* Nothing to do here */
5394
        break;
5395
#endif
5396
#ifdef WOLFSSL_DTLS
5397
    case DTLS1_VERSION:
5398
    case DTLS1_2_VERSION:
5399
        break;
5400
#endif
5401
    default:
5402
        WOLFSSL_MSG("Unrecognized protocol version or not compiled in");
5403
        return WOLFSSL_FAILURE;
5404
    }
5405
5406
    return CheckSslMethodVersion(ssl->version.major, ssl->options.mask);
5407
}
5408
5409
int wolfSSL_set_max_proto_version(WOLFSSL* ssl, int version)
5410
{
5411
    int i;
5412
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);;
5413
5414
    WOLFSSL_ENTER("wolfSSL_set_max_proto_version");
5415
5416
    if (ssl == NULL) {
5417
        return WOLFSSL_FAILURE;
5418
    }
5419
    if (version != 0) {
5420
        return Set_SSL_max_proto_version(ssl, version);
5421
    }
5422
5423
    /* when 0 is specified as version, try to find out the min version from
5424
     * the bottom to top of the protoverTbl.
5425
     */
5426
    for (i = NUMBER_OF_PROTOCOLS -1; i >= 0; i--) {
5427
        ret = Set_SSL_max_proto_version(ssl, protoVerTbl[i]);
5428
        if (ret == WOLFSSL_SUCCESS)
5429
            break;
5430
    }
5431
5432
    return ret;
5433
}
5434
5435
static int GetMinProtoVersion(int minDowngrade)
5436
{
5437
    int ret;
5438
5439
    switch (minDowngrade) {
5440
#ifndef NO_OLD_TLS
5441
    #ifdef WOLFSSL_ALLOW_SSLV3
5442
        case SSLv3_MINOR:
5443
            ret = SSL3_VERSION;
5444
            break;
5445
    #endif
5446
    #ifdef WOLFSSL_ALLOW_TLSV10
5447
        case TLSv1_MINOR:
5448
            ret = TLS1_VERSION;
5449
            break;
5450
    #endif
5451
        case TLSv1_1_MINOR:
5452
            ret = TLS1_1_VERSION;
5453
            break;
5454
#endif
5455
#ifndef WOLFSSL_NO_TLS12
5456
        case TLSv1_2_MINOR:
5457
            ret = TLS1_2_VERSION;
5458
            break;
5459
#endif
5460
#ifdef WOLFSSL_TLS13
5461
        case TLSv1_3_MINOR:
5462
            ret = TLS1_3_VERSION;
5463
            break;
5464
#endif
5465
        default:
5466
            ret = 0;
5467
            break;
5468
    }
5469
5470
    return ret;
5471
}
5472
5473
int wolfSSL_CTX_get_min_proto_version(WOLFSSL_CTX* ctx)
5474
{
5475
    int ret = 0;
5476
5477
    WOLFSSL_ENTER("wolfSSL_CTX_get_min_proto_version");
5478
5479
    if (ctx != NULL) {
5480
        if (ctx->minProto) {
5481
            ret = 0;
5482
        }
5483
        else {
5484
            ret = GetMinProtoVersion(ctx->minDowngrade);
5485
        }
5486
    }
5487
    else {
5488
        ret = GetMinProtoVersion(WOLFSSL_MIN_DOWNGRADE);
5489
    }
5490
5491
    WOLFSSL_LEAVE("wolfSSL_CTX_get_min_proto_version", ret);
5492
5493
    return ret;
5494
}
5495
5496
5497
/* returns the maximum allowed protocol version given the 'options' used
5498
 * returns WOLFSSL_FATAL_ERROR on no match */
5499
static int GetMaxProtoVersion(long options)
5500
{
5501
#ifndef NO_TLS
5502
#ifdef WOLFSSL_TLS13
5503
    if (!(options & WOLFSSL_OP_NO_TLSv1_3))
5504
        return TLS1_3_VERSION;
5505
#endif
5506
#ifndef WOLFSSL_NO_TLS12
5507
    if (!(options & WOLFSSL_OP_NO_TLSv1_2))
5508
        return TLS1_2_VERSION;
5509
#endif
5510
#ifndef NO_OLD_TLS
5511
    if (!(options & WOLFSSL_OP_NO_TLSv1_1))
5512
        return TLS1_1_VERSION;
5513
    #ifdef WOLFSSL_ALLOW_TLSV10
5514
    if (!(options & WOLFSSL_OP_NO_TLSv1))
5515
        return TLS1_VERSION;
5516
    #endif
5517
    #ifdef WOLFSSL_ALLOW_SSLV3
5518
    if (!(options & WOLFSSL_OP_NO_SSLv3))
5519
        return SSL3_VERSION;
5520
    #endif
5521
#endif
5522
#else
5523
    (void)options;
5524
#endif /* NO_TLS */
5525
    return WOLFSSL_FATAL_ERROR;
5526
}
5527
5528
5529
/* returns the maximum protocol version for 'ctx' */
5530
int wolfSSL_CTX_get_max_proto_version(WOLFSSL_CTX* ctx)
5531
{
5532
    int ret = 0;
5533
    long options = 0; /* default to nothing set */
5534
5535
    WOLFSSL_ENTER("wolfSSL_CTX_get_max_proto_version");
5536
5537
    if (ctx != NULL) {
5538
        options = wolfSSL_CTX_get_options(ctx);
5539
    }
5540
5541
    if ((ctx != NULL) && ctx->maxProto) {
5542
        ret = 0;
5543
    }
5544
    else {
5545
        ret = GetMaxProtoVersion(options);
5546
    }
5547
5548
    WOLFSSL_LEAVE("wolfSSL_CTX_get_max_proto_version", ret);
5549
5550
    if (ret == WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR)) {
5551
        WOLFSSL_MSG("Error getting max proto version");
5552
        ret = 0; /* setting ret to 0 to match compat return */
5553
    }
5554
    return ret;
5555
}
5556
#endif /* OPENSSL_EXTRA */
5557
5558
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL) || \
5559
    defined(HAVE_SECRET_CALLBACK)
5560
#if !defined(NO_WOLFSSL_CLIENT)
5561
/* Return the amount of random bytes copied over or error case.
5562
 * ssl : ssl struct after handshake
5563
 * out : buffer to hold random bytes
5564
 * outSz : either 0 (return max buffer sz) or size of out buffer
5565
 */
5566
size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out,
5567
                                                                   size_t outSz)
5568
{
5569
    size_t size;
5570
5571
    /* return max size of buffer */
5572
    if (outSz == 0) {
5573
        return RAN_LEN;
5574
    }
5575
5576
    if (ssl == NULL || out == NULL) {
5577
        return 0;
5578
    }
5579
5580
    if (ssl->arrays == NULL) {
5581
        WOLFSSL_MSG("Arrays struct not saved after handshake");
5582
        return 0;
5583
    }
5584
5585
    if (outSz > RAN_LEN) {
5586
        size = RAN_LEN;
5587
    }
5588
    else {
5589
        size = outSz;
5590
    }
5591
5592
    XMEMCPY(out, ssl->arrays->clientRandom, size);
5593
    return size;
5594
}
5595
#endif /* !NO_WOLFSSL_CLIENT */
5596
#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL || HAVE_SECRET_CALLBACK */
5597
5598
#ifdef OPENSSL_EXTRA
5599
5600
    unsigned long wolfSSLeay(void)
5601
    {
5602
#ifdef SSLEAY_VERSION_NUMBER
5603
        return SSLEAY_VERSION_NUMBER;
5604
#else
5605
        return OPENSSL_VERSION_NUMBER;
5606
#endif
5607
    }
5608
5609
    unsigned long wolfSSL_OpenSSL_version_num(void)
5610
    {
5611
        return OPENSSL_VERSION_NUMBER;
5612
    }
5613
5614
    const char* wolfSSLeay_version(int type)
5615
    {
5616
        (void)type;
5617
#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L
5618
        return wolfSSL_OpenSSL_version(type);
5619
#else
5620
        return wolfSSL_OpenSSL_version();
5621
#endif
5622
    }
5623
#endif /* OPENSSL_EXTRA */
5624
5625
#ifdef OPENSSL_EXTRA
5626
5627
    void wolfSSL_cleanup_all_ex_data(void)
5628
    {
5629
        /* nothing to do here */
5630
    }
5631
5632
#endif /* OPENSSL_EXTRA */
5633
5634
#if defined(OPENSSL_EXTRA) || defined(DEBUG_WOLFSSL_VERBOSE) || \
5635
    defined(HAVE_CURL)
5636
#endif
5637
5638
    int wolfSSL_clear(WOLFSSL* ssl)
5639
0
    {
5640
0
        WOLFSSL_ENTER("wolfSSL_clear");
5641
5642
0
        if (ssl == NULL) {
5643
0
            return WOLFSSL_FAILURE;
5644
0
        }
5645
5646
0
        if (!ssl->options.handShakeDone) {
5647
            /* Only reset the session if we didn't complete a handshake */
5648
0
            wolfSSL_FreeSession(ssl->ctx, ssl->session);
5649
0
            ssl->session = wolfSSL_NewSession(ssl->heap);
5650
0
            if (ssl->session == NULL) {
5651
0
                return WOLFSSL_FAILURE;
5652
0
            }
5653
0
        }
5654
5655
        /* reset error */
5656
0
        ssl->error = 0;
5657
5658
        /* reset option bits */
5659
0
        ssl->options.isClosed = 0;
5660
0
        ssl->options.connReset = 0;
5661
0
        ssl->options.sentNotify = 0;
5662
0
        ssl->options.closeNotify = 0;
5663
0
        ssl->options.sendVerify = 0;
5664
0
        ssl->options.serverState = NULL_STATE;
5665
0
        ssl->options.clientState = NULL_STATE;
5666
0
        ssl->options.connectState = CONNECT_BEGIN;
5667
0
        ssl->options.acceptState  = ACCEPT_BEGIN;
5668
0
        ssl->options.handShakeState  = NULL_STATE;
5669
0
        ssl->options.handShakeDone = 0;
5670
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WOLFSSL_ASYNC_CERT_YIELD)
5671
        /* A per-certificate yield (WOLFSSL_ASYNC_CERT_YIELD) sets this and it is
5672
         * normally cleared on the next ProcessPeerCerts re-entry. Clear it here
5673
         * so reusing this object after abandoning a yielded handshake cannot
5674
         * skip the ProcessPeerCerts state reset on the next fresh entry. */
5675
        ssl->options.certYieldPending = 0;
5676
#endif
5677
0
        ssl->recordSzOverhead = 0;
5678
#ifdef WOLFSSL_TLS13_STREAM_CERT_VERIFY
5679
        /* Drop any half-sent streamed CertificateVerify. Left in place, the
5680
         * resume guard in SendTls13CertificateVerify would fire on the next
5681
         * handshake and re-send the previous one's signature. */
5682
        XFREE(ssl->buffers.certVerifyMsg.buffer, ssl->heap,
5683
              DYNAMIC_TYPE_TMP_BUFFER);
5684
        ssl->buffers.certVerifyMsg.buffer = NULL;
5685
        ssl->buffers.certVerifyMsg.length = 0;
5686
        ssl->fragOffset = 0;
5687
#endif
5688
0
        ssl->options.processReply = 0; /* doProcessInit */
5689
0
        ssl->options.havePeerVerify = 0;
5690
0
        ssl->options.havePeerCert = 0;
5691
0
        ssl->options.peerAuthGood = 0;
5692
0
        ssl->options.tls1_3 = 0;
5693
0
        ssl->options.haveSessionId = 0;
5694
0
        ssl->options.tls = 0;
5695
0
        ssl->options.tls1_1 = 0;
5696
0
    #ifdef WOLFSSL_TLS13
5697
    #ifdef WOLFSSL_SEND_HRR_COOKIE
5698
        ssl->options.hrrSentCookie = 0;
5699
    #endif
5700
0
        ssl->options.hrrSentKeyShare = 0;
5701
0
    #endif
5702
    #ifdef WOLFSSL_DTLS
5703
        ssl->options.dtlsStateful = 0;
5704
    #endif
5705
0
    #ifdef WOLFSSL_TLS13
5706
    #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
5707
        ssl->options.noPskDheKe = ssl->ctx->noPskDheKe;
5708
        #ifdef HAVE_SUPPORTED_CURVES
5709
        ssl->options.onlyPskDheKe = ssl->ctx->onlyPskDheKe;
5710
        #endif
5711
    #endif
5712
0
    #endif
5713
    #ifdef HAVE_SESSION_TICKET
5714
        #ifdef WOLFSSL_TLS13
5715
        ssl->options.ticketsSent = 0;
5716
        #endif
5717
        ssl->options.rejectTicket = 0;
5718
    #endif
5719
    #ifdef WOLFSSL_EARLY_DATA
5720
        ssl->earlyData = no_early_data;
5721
        ssl->earlyDataSz = 0;
5722
    #endif
5723
    #ifdef HAVE_RPK
5724
        /* Drop the negotiated cert types so one peer's choice cannot carry into
5725
         * the next handshake. Clearing the counts is enough: every read of the
5726
         * type arrays is gated on its count. */
5727
        ssl->options.rpkState.sending_ClientCertTypeCnt = 0;
5728
        ssl->options.rpkState.sending_ServerCertTypeCnt = 0;
5729
        ssl->options.rpkState.received_ClientCertTypeCnt = 0;
5730
        ssl->options.rpkState.received_ServerCertTypeCnt = 0;
5731
    #endif
5732
5733
0
    #if defined(HAVE_TLS_EXTENSIONS) && !defined(NO_TLS)
5734
0
        TLSX_FreeAll(ssl->extensions, ssl->heap);
5735
0
        ssl->extensions = NULL;
5736
0
      #if defined(HAVE_SECURE_RENEGOTIATION) \
5737
0
       || defined(HAVE_SERVER_RENEGOTIATION_INFO)
5738
0
        ssl->secure_renegotiation = NULL;
5739
        /* The renegotiation_info advertising is re-established when the next
5740
         * ClientHello is built (SendClientHello), so a reused client object
5741
         * keeps the "advertise implies enforce" invariant (RFC 5746). */
5742
0
      #endif
5743
0
    #endif
5744
5745
0
        if (ssl->keys.encryptionOn) {
5746
0
            ForceZero(ssl->buffers.inputBuffer.buffer -
5747
0
                ssl->buffers.inputBuffer.offset,
5748
0
                ssl->buffers.inputBuffer.bufferSize);
5749
        #ifdef WOLFSSL_CHECK_MEM_ZERO
5750
            wc_MemZero_Check(ssl->buffers.inputBuffer.buffer -
5751
                ssl->buffers.inputBuffer.offset,
5752
                ssl->buffers.inputBuffer.bufferSize);
5753
        #endif
5754
0
        }
5755
        /* Recycling the object for a new connection must not carry the
5756
         * previous connection's key material along with it. A freshly
5757
         * created object has all of this zeroed. */
5758
0
        ForceZero(&ssl->keys, sizeof(Keys));
5759
    #ifdef WOLFSSL_MULTICAST
5760
        if (ssl->options.haveMcast) {
5761
            int i;
5762
5763
            for (i = 0; i < WOLFSSL_DTLS_PEERSEQ_SZ; i++)
5764
                ssl->keys.peerSeq[i].peerId = INVALID_PEER_ID;
5765
        }
5766
    #endif
5767
0
    #ifdef WOLFSSL_TLS13
5768
0
        ForceZero(ssl->clientSecret, sizeof(ssl->clientSecret));
5769
0
        ForceZero(ssl->serverSecret, sizeof(ssl->serverSecret));
5770
        /* A key update the previous connection asked for has nothing to say
5771
         * about the next one, and the keys it would rotate are gone. */
5772
0
        ssl->options.sendKeyUpdate = 0;
5773
0
    #endif
5774
    #ifdef WOLFSSL_HAVE_TLS_UNIQUE
5775
        /* The channel binding of the connection that just ended. Leaving it
5776
         * in place would let the next caller bind to the wrong session. */
5777
        ForceZero(ssl->clientFinished, TLS_FINISHED_SZ_MAX);
5778
        ForceZero(ssl->serverFinished, TLS_FINISHED_SZ_MAX);
5779
        ssl->clientFinished_len = 0;
5780
        ssl->serverFinished_len = 0;
5781
    #endif
5782
    #ifdef WOLFSSL_DTLS13
5783
        /* Per-epoch traffic keys, IVs and sequence number keys. */
5784
        ForceZero(ssl->dtls13Epochs, sizeof(ssl->dtls13Epochs));
5785
        /* Only InitSSL() sets up the unprotected epoch 0 and aims the epoch
5786
         * pointers at it, and this object is being reused rather than freed,
5787
         * so put it back or the next handshake has no valid epoch. */
5788
        ssl->dtls13Epochs[0].isValid = 1;
5789
        ssl->dtls13Epochs[0].side = ENCRYPT_AND_DECRYPT_SIDE;
5790
        ssl->dtls13EncryptEpoch = &ssl->dtls13Epochs[0];
5791
        ssl->dtls13DecryptEpoch = &ssl->dtls13Epochs[0];
5792
        /* The numbers that say which epoch to use sit outside the table and
5793
         * only ever move up, so wiping the table has to be matched here by
5794
         * hand. InitSSL() gets this for free from clearing the whole object.
5795
         * Left behind, they ask the next handshake to send under an epoch the
5796
         * table no longer holds, and Dtls13SetEpochKeys() fails the connection
5797
         * with BAD_STATE_E. */
5798
        w64Zero(&ssl->dtls13Epoch);
5799
        w64Zero(&ssl->dtls13PeerEpoch);
5800
        w64Zero(&ssl->dtls13InvalidateBefore);
5801
        ssl->dtls13WaitKeyUpdateAck = 0;
5802
        ssl->dtls13DoKeyUpdate = 0;
5803
        ssl->dtls13SendingAckOrRtx = 0;
5804
        /* Anything still queued for retransmission or acknowledgement is
5805
         * tagged with an epoch that no longer exists, so it can never be sent
5806
         * and would only be released when the object is freed. */
5807
        Dtls13FreeFsmResources(ssl);
5808
        ssl->dtls13Rtx.sendAcks = 0;
5809
        ssl->dtls13Rtx.retransmit = 0;
5810
    #endif
5811
        /* The handshake arrays hold the master and pre-master secrets. Wipe
5812
         * those in place rather than releasing the arrays, so that the
5813
         * allocation stays valid for wolfSSL_set_secret(), the exporter and
5814
         * the other accessors that read from it once a connection has ended.
5815
         * An application that asked to keep the arrays still gets back
5816
         * everything the API can hand it, so only the rest goes. */
5817
0
        if (ssl->arrays != NULL) {
5818
0
            if (ssl->arrays->preMasterSecret != NULL) {
5819
0
                ForceZero(ssl->arrays->preMasterSecret, ENCRYPT_LEN);
5820
                /* The key agreement routines take this as the size of the
5821
                 * buffer they may write, so put back what a freshly
5822
                 * allocated Arrays would carry. */
5823
0
                ssl->arrays->preMasterSz = ENCRYPT_LEN;
5824
0
            }
5825
        #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
5826
            ForceZero(ssl->arrays->psk_key, MAX_PSK_KEY_LEN);
5827
            ssl->arrays->psk_keySz = 0;
5828
        #endif
5829
0
        #ifdef WOLFSSL_TLS13
5830
            /* The key schedule secret. No API hands this one back. */
5831
0
            ForceZero(ssl->arrays->secret, SECRET_LEN);
5832
0
        #endif
5833
0
            if (!ssl->options.saveArrays) {
5834
0
                ForceZero(ssl->arrays->masterSecret, SECRET_LEN);
5835
            #ifdef HAVE_KEYING_MATERIAL
5836
                /* Tls13_Exporter() reads this one, and exporting keying
5837
                 * material requires the arrays to be kept, so it only goes
5838
                 * when the application did not ask for that. */
5839
                ForceZero(ssl->arrays->exporterSecret, WC_MAX_DIGEST_SIZE);
5840
            #endif
5841
0
            }
5842
0
        }
5843
0
        XMEMSET(&ssl->msgsReceived, 0, sizeof(ssl->msgsReceived));
5844
5845
        /* Discard any partial handshake-message reassembly on reuse. */
5846
0
        XFREE(ssl->pendingMsg, ssl->heap, DYNAMIC_TYPE_ARRAYS);
5847
0
        ssl->pendingMsg = NULL;
5848
0
        ssl->pendingMsgSz = 0;
5849
0
        ssl->pendingMsgOffset = 0;
5850
0
        ssl->pendingMsgType = 0;
5851
5852
0
        FreeCiphers(ssl);
5853
0
        InitCiphers(ssl);
5854
0
        InitCipherSpecs(&ssl->specs);
5855
5856
0
        if (InitSSL_Suites(ssl) != WOLFSSL_SUCCESS)
5857
0
            return WOLFSSL_FAILURE;
5858
5859
0
        if (InitHandshakeHashes(ssl) != 0)
5860
0
            return WOLFSSL_FAILURE;
5861
5862
#ifdef KEEP_PEER_CERT
5863
        FreeX509(&ssl->peerCert);
5864
        InitX509(&ssl->peerCert, 0, ssl->heap);
5865
#endif
5866
5867
#ifdef WOLFSSL_QUIC
5868
        wolfSSL_quic_clear(ssl);
5869
#endif
5870
#ifdef HAVE_OCSP
5871
#if defined(WOLFSSL_TLS13) && defined(HAVE_CERTIFICATE_STATUS_REQUEST)
5872
        ssl->response_idx = 0;
5873
#endif
5874
#endif
5875
0
        return WOLFSSL_SUCCESS;
5876
0
    }
5877
5878
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || defined(HAVE_MEMCACHED)
5879
    long wolfSSL_CTX_set_mode(WOLFSSL_CTX* ctx, long mode)
5880
    {
5881
        /* WOLFSSL_MODE_ACCEPT_MOVING_WRITE_BUFFER is wolfSSL default mode */
5882
5883
        WOLFSSL_ENTER("wolfSSL_CTX_set_mode");
5884
        switch(mode) {
5885
            case WOLFSSL_MODE_ENABLE_PARTIAL_WRITE:
5886
                ctx->partialWrite = 1;
5887
                break;
5888
            #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
5889
            case SSL_MODE_RELEASE_BUFFERS:
5890
                WOLFSSL_MSG("SSL_MODE_RELEASE_BUFFERS not implemented.");
5891
                break;
5892
            #endif
5893
            case WOLFSSL_MODE_AUTO_RETRY:
5894
                ctx->autoRetry = 1;
5895
                break;
5896
            default:
5897
                WOLFSSL_MSG("Mode Not Implemented");
5898
        }
5899
5900
        /* WOLFSSL_MODE_AUTO_RETRY
5901
         * Should not return WOLFSSL_FATAL_ERROR with renegotiation on read/write */
5902
5903
        return mode;
5904
    }
5905
5906
    long wolfSSL_CTX_clear_mode(WOLFSSL_CTX* ctx, long mode)
5907
    {
5908
        /* WOLFSSL_MODE_ACCEPT_MOVING_WRITE_BUFFER is wolfSSL default mode */
5909
5910
        WOLFSSL_ENTER("wolfSSL_CTX_clear_mode");
5911
        switch(mode) {
5912
            case WOLFSSL_MODE_ENABLE_PARTIAL_WRITE:
5913
                ctx->partialWrite = 0;
5914
                break;
5915
            #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
5916
            case SSL_MODE_RELEASE_BUFFERS:
5917
                WOLFSSL_MSG("SSL_MODE_RELEASE_BUFFERS not implemented.");
5918
                break;
5919
            #endif
5920
            case WOLFSSL_MODE_AUTO_RETRY:
5921
                ctx->autoRetry = 0;
5922
                break;
5923
            default:
5924
                WOLFSSL_MSG("Mode Not Implemented");
5925
        }
5926
5927
        /* WOLFSSL_MODE_AUTO_RETRY
5928
         * Should not return WOLFSSL_FATAL_ERROR with renegotiation on read/write */
5929
5930
        return 0;
5931
    }
5932
#endif
5933
5934
#ifdef OPENSSL_EXTRA
5935
5936
    #ifndef NO_WOLFSSL_STUB
5937
    long wolfSSL_SSL_get_mode(WOLFSSL* ssl)
5938
    {
5939
        /* TODO: */
5940
        (void)ssl;
5941
        WOLFSSL_STUB("SSL_get_mode");
5942
        return 0;
5943
    }
5944
    #endif
5945
5946
    #ifndef NO_WOLFSSL_STUB
5947
    long wolfSSL_CTX_get_mode(WOLFSSL_CTX* ctx)
5948
    {
5949
        /* TODO: */
5950
        (void)ctx;
5951
        WOLFSSL_STUB("SSL_CTX_get_mode");
5952
        return 0;
5953
    }
5954
    #endif
5955
5956
    #ifndef NO_WOLFSSL_STUB
5957
    void wolfSSL_CTX_set_default_read_ahead(WOLFSSL_CTX* ctx, int m)
5958
    {
5959
        /* TODO: maybe? */
5960
        (void)ctx;
5961
        (void)m;
5962
        WOLFSSL_STUB("SSL_CTX_set_default_read_ahead");
5963
    }
5964
    #endif
5965
5966
5967
    /* returns the unsigned error value and increments the pointer into the
5968
     * error queue.
5969
     *
5970
     * file  pointer to file name
5971
     * line  gets set to line number of error when not NULL
5972
     */
5973
5974
5975
5976
5977
5978
#endif /* OPENSSL_EXTRA */
5979
5980
5981
5982
5983
5984
5985
5986
int wolfSSL_session_reused(WOLFSSL* ssl)
5987
0
{
5988
0
    int resuming = 0;
5989
0
    WOLFSSL_ENTER("wolfSSL_session_reused");
5990
0
    if (ssl) {
5991
0
#ifndef HAVE_SECURE_RENEGOTIATION
5992
0
        resuming = ssl->options.resuming;
5993
#else
5994
        resuming = ssl->options.resuming || ssl->options.resumed;
5995
#endif
5996
0
    }
5997
0
    WOLFSSL_LEAVE("wolfSSL_session_reused", resuming);
5998
0
    return resuming;
5999
0
}
6000
6001
/* helper function that takes in a protocol version struct and returns string */
6002
static const char* wolfSSL_internal_get_version(const ProtocolVersion* version)
6003
0
{
6004
0
    WOLFSSL_ENTER("wolfSSL_get_version");
6005
6006
0
    if (version == NULL) {
6007
0
        return "Bad arg";
6008
0
    }
6009
6010
0
    if (version->major == SSLv3_MAJOR) {
6011
0
        switch (version->minor) {
6012
0
            case SSLv3_MINOR :
6013
0
                return "SSLv3";
6014
0
            case TLSv1_MINOR :
6015
0
                return "TLSv1";
6016
0
            case TLSv1_1_MINOR :
6017
0
                return "TLSv1.1";
6018
0
            case TLSv1_2_MINOR :
6019
0
                return "TLSv1.2";
6020
0
            case TLSv1_3_MINOR :
6021
0
                return "TLSv1.3";
6022
0
            default:
6023
0
                return "unknown";
6024
0
        }
6025
0
    }
6026
#ifdef WOLFSSL_DTLS
6027
    else if (version->major == DTLS_MAJOR) {
6028
        switch (version->minor) {
6029
            case DTLS_MINOR :
6030
                return "DTLS";
6031
            case DTLSv1_2_MINOR :
6032
                return "DTLSv1.2";
6033
            case DTLSv1_3_MINOR :
6034
                return "DTLSv1.3";
6035
            default:
6036
                return "unknown";
6037
        }
6038
    }
6039
#endif /* WOLFSSL_DTLS */
6040
0
    return "unknown";
6041
0
}
6042
6043
6044
const char* wolfSSL_get_version(const WOLFSSL* ssl)
6045
0
{
6046
0
    if (ssl == NULL) {
6047
0
        WOLFSSL_MSG("Bad argument");
6048
0
        return "unknown";
6049
0
    }
6050
6051
0
    return wolfSSL_internal_get_version(&ssl->version);
6052
0
}
6053
6054
6055
/* current library version */
6056
const char* wolfSSL_lib_version(void)
6057
0
{
6058
0
    return LIBWOLFSSL_VERSION_STRING;
6059
0
}
6060
6061
#ifdef OPENSSL_EXTRA
6062
#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L
6063
const char* wolfSSL_OpenSSL_version(int a)
6064
{
6065
    (void)a;
6066
    return "wolfSSL " LIBWOLFSSL_VERSION_STRING;
6067
}
6068
#else
6069
const char* wolfSSL_OpenSSL_version(void)
6070
{
6071
    return "wolfSSL " LIBWOLFSSL_VERSION_STRING;
6072
}
6073
#endif /* WOLFSSL_QT */
6074
#endif
6075
6076
6077
/* current library version in hex */
6078
word32 wolfSSL_lib_version_hex(void)
6079
0
{
6080
0
    return LIBWOLFSSL_VERSION_HEX;
6081
0
}
6082
6083
6084
int wolfSSL_get_current_cipher_suite(WOLFSSL* ssl)
6085
0
{
6086
0
    WOLFSSL_ENTER("wolfSSL_get_current_cipher_suite");
6087
0
    if (ssl)
6088
0
        return (ssl->options.cipherSuite0 << 8) | ssl->options.cipherSuite;
6089
0
    return 0;
6090
0
}
6091
6092
WOLFSSL_CIPHER* wolfSSL_get_current_cipher(WOLFSSL* ssl)
6093
0
{
6094
0
    WOLFSSL_ENTER("wolfSSL_get_current_cipher");
6095
0
    if (ssl) {
6096
0
        ssl->cipher.cipherSuite0 = ssl->options.cipherSuite0;
6097
0
        ssl->cipher.cipherSuite  = ssl->options.cipherSuite;
6098
#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
6099
        ssl->cipher.bits = ssl->specs.key_size * 8;
6100
#endif
6101
0
        return &ssl->cipher;
6102
0
    }
6103
0
    else
6104
0
        return NULL;
6105
0
}
6106
6107
6108
const char* wolfSSL_CIPHER_get_name(const WOLFSSL_CIPHER* cipher)
6109
0
{
6110
0
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_name");
6111
6112
0
    if (cipher == NULL) {
6113
0
        return NULL;
6114
0
    }
6115
6116
0
    #if !defined(WOLFSSL_CIPHER_INTERNALNAME) && !defined(NO_ERROR_STRINGS) && \
6117
0
        !defined(WOLFSSL_QT)
6118
0
        return GetCipherNameIana(cipher->cipherSuite0, cipher->cipherSuite);
6119
    #else
6120
        return wolfSSL_get_cipher_name_from_suite(cipher->cipherSuite0,
6121
                cipher->cipherSuite);
6122
    #endif
6123
0
}
6124
6125
const char*  wolfSSL_CIPHER_get_version(const WOLFSSL_CIPHER* cipher)
6126
0
{
6127
0
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_version");
6128
6129
0
    if (cipher == NULL || cipher->ssl == NULL) {
6130
0
        return NULL;
6131
0
    }
6132
6133
0
    return wolfSSL_get_version(cipher->ssl);
6134
0
}
6135
6136
const char* wolfSSL_get_cipher(WOLFSSL* ssl)
6137
0
{
6138
0
    WOLFSSL_ENTER("wolfSSL_get_cipher");
6139
0
    return wolfSSL_CIPHER_get_name(wolfSSL_get_current_cipher(ssl));
6140
0
}
6141
6142
/* gets cipher name in the format DHE-RSA-... rather then TLS_DHE... */
6143
const char* wolfSSL_get_cipher_name(WOLFSSL* ssl)
6144
0
{
6145
    /* get access to cipher_name_idx in internal.c */
6146
0
    return wolfSSL_get_cipher_name_internal(ssl);
6147
0
}
6148
6149
const char* wolfSSL_get_cipher_name_from_suite(byte cipherSuite0,
6150
    byte cipherSuite)
6151
0
{
6152
0
    return GetCipherNameInternal(cipherSuite0, cipherSuite);
6153
0
}
6154
6155
const char* wolfSSL_get_cipher_name_iana_from_suite(byte cipherSuite0,
6156
        byte cipherSuite)
6157
0
{
6158
0
    return GetCipherNameIana(cipherSuite0, cipherSuite);
6159
0
}
6160
6161
int wolfSSL_get_cipher_suite_from_name(const char* name, byte* cipherSuite0,
6162
0
                                       byte* cipherSuite, int *flags) {
6163
0
    if ((name == NULL) ||
6164
0
        (cipherSuite0 == NULL) ||
6165
0
        (cipherSuite == NULL) ||
6166
0
        (flags == NULL))
6167
0
        return BAD_FUNC_ARG;
6168
0
    return GetCipherSuiteFromName(name, cipherSuite0, cipherSuite, NULL, NULL,
6169
0
                                  flags);
6170
0
}
6171
6172
6173
word32 wolfSSL_CIPHER_get_id(const WOLFSSL_CIPHER* cipher)
6174
0
{
6175
0
    word16 cipher_id = 0;
6176
6177
0
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_id");
6178
6179
0
    if (cipher && cipher->ssl) {
6180
0
        cipher_id = (word16)(cipher->ssl->options.cipherSuite0 << 8) |
6181
0
                     cipher->ssl->options.cipherSuite;
6182
0
    }
6183
6184
0
    return cipher_id;
6185
0
}
6186
6187
const WOLFSSL_CIPHER* wolfSSL_get_cipher_by_value(word16 value)
6188
0
{
6189
0
    const WOLFSSL_CIPHER* cipher = NULL;
6190
0
    byte cipherSuite0, cipherSuite;
6191
0
    WOLFSSL_ENTER("wolfSSL_get_cipher_by_value");
6192
6193
    /* extract cipher id information */
6194
0
    cipherSuite =   (value       & 0xFF);
6195
0
    cipherSuite0 = ((value >> 8) & 0xFF);
6196
6197
    /* TODO: lookup by cipherSuite0 / cipherSuite */
6198
0
    (void)cipherSuite0;
6199
0
    (void)cipherSuite;
6200
6201
0
    return cipher;
6202
0
}
6203
6204
6205
#if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448) || \
6206
    !defined(NO_DH) || (defined(WOLFSSL_TLS13) && defined(WOLFSSL_HAVE_MLKEM))
6207
#ifdef HAVE_FFDHE
6208
static const char* wolfssl_ffdhe_name(word16 group)
6209
0
{
6210
0
    const char* str = NULL;
6211
0
    switch (group) {
6212
0
        case WOLFSSL_FFDHE_2048:
6213
0
            str = "FFDHE_2048";
6214
0
            break;
6215
0
        case WOLFSSL_FFDHE_3072:
6216
0
            str = "FFDHE_3072";
6217
0
            break;
6218
0
        case WOLFSSL_FFDHE_4096:
6219
0
            str = "FFDHE_4096";
6220
0
            break;
6221
0
        case WOLFSSL_FFDHE_6144:
6222
0
            str = "FFDHE_6144";
6223
0
            break;
6224
0
        case WOLFSSL_FFDHE_8192:
6225
0
            str = "FFDHE_8192";
6226
0
            break;
6227
0
        default:
6228
0
            break;
6229
0
    }
6230
0
    return str;
6231
0
}
6232
#endif
6233
/* Return the name of the curve used for key exchange as a printable string.
6234
 *
6235
 * ssl  The SSL/TLS object.
6236
 * returns NULL if ECDH was not used, otherwise the name as a string.
6237
 */
6238
const char* wolfSSL_get_curve_name(WOLFSSL* ssl)
6239
0
{
6240
0
    const char* cName = NULL;
6241
6242
0
    WOLFSSL_ENTER("wolfSSL_get_curve_name");
6243
6244
0
    if (ssl == NULL)
6245
0
        return NULL;
6246
6247
0
#if defined(WOLFSSL_TLS13) && defined(WOLFSSL_HAVE_MLKEM)
6248
    /* Check for post-quantum groups. Return now because we do not want the ECC
6249
     * check to override this result in the case of a hybrid. */
6250
0
    if (IsAtLeastTLSv1_3(ssl->version)) {
6251
0
        switch (ssl->namedGroup) {
6252
0
#ifndef WOLFSSL_NO_ML_KEM
6253
0
    #ifndef WOLFSSL_NO_ML_KEM_512
6254
0
        case WOLFSSL_ML_KEM_512:
6255
0
            return "ML_KEM_512";
6256
        #ifdef WOLFSSL_EXTRA_PQC_HYBRIDS
6257
        #ifdef WOLFSSL_ML_KEM_USE_OLD_IDS
6258
        case WOLFSSL_P256_ML_KEM_512_OLD:
6259
            return "P256_ML_KEM_512_OLD";
6260
        #endif /* WOLFSSL_ML_KEM_USE_OLD_IDS */
6261
        case WOLFSSL_SECP256R1MLKEM512:
6262
            return "SecP256r1MLKEM512";
6263
        #ifdef HAVE_CURVE25519
6264
        case WOLFSSL_X25519MLKEM512:
6265
            return "X25519MLKEM512";
6266
        #endif /* HAVE_CURVE25519 */
6267
        #endif /* WOLFSSL_EXTRA_PQC_HYBRIDS */
6268
0
    #endif /* WOLFSSL_NO_ML_KEM_512 */
6269
0
    #ifndef WOLFSSL_NO_ML_KEM_768
6270
0
        case WOLFSSL_ML_KEM_768:
6271
0
            return "ML_KEM_768";
6272
0
        #ifdef WOLFSSL_PQC_HYBRIDS
6273
0
        case WOLFSSL_SECP256R1MLKEM768:
6274
0
            return "SecP256r1MLKEM768";
6275
        #ifdef HAVE_CURVE25519
6276
        case WOLFSSL_X25519MLKEM768:
6277
            return "X25519MLKEM768";
6278
        #endif
6279
0
        #endif /* WOLFSSL_PQC_HYBRIDS */
6280
        #ifdef WOLFSSL_EXTRA_PQC_HYBRIDS
6281
        #ifdef WOLFSSL_ML_KEM_USE_OLD_IDS
6282
        case WOLFSSL_P384_ML_KEM_768_OLD:
6283
            return "P384_ML_KEM_768_OLD";
6284
        #endif /* WOLFSSL_ML_KEM_USE_OLD_IDS */
6285
        case WOLFSSL_SECP384R1MLKEM768:
6286
            return "SecP384r1MLKEM768";
6287
        #ifdef HAVE_CURVE448
6288
        case WOLFSSL_X448MLKEM768:
6289
            return "X448MLKEM768";
6290
        #endif /* HAVE_CURVE448 */
6291
        #endif /* WOLFSSL_EXTRA_PQC_HYBRIDS */
6292
0
    #endif /* WOLFSSL_NO_ML_KEM_768 */
6293
0
    #ifndef WOLFSSL_NO_ML_KEM_1024
6294
0
        case WOLFSSL_ML_KEM_1024:
6295
0
            return "ML_KEM_1024";
6296
0
        #ifdef WOLFSSL_PQC_HYBRIDS
6297
0
        case WOLFSSL_SECP384R1MLKEM1024:
6298
0
            return "SecP384r1MLKEM1024";
6299
0
        #endif /* WOLFSSL_PQC_HYBRIDS */
6300
        #ifdef WOLFSSL_EXTRA_PQC_HYBRIDS
6301
        #ifdef WOLFSSL_ML_KEM_USE_OLD_IDS
6302
        case WOLFSSL_P521_ML_KEM_1024_OLD:
6303
            return "P521_ML_KEM_1024_OLD";
6304
        #endif /* WOLFSSL_ML_KEM_USE_OLD_IDS */
6305
        case WOLFSSL_SECP521R1MLKEM1024:
6306
            return "SecP521r1MLKEM1024";
6307
        #endif /* WOLFSSL_EXTRA_PQC_HYBRIDS */
6308
0
    #endif /* WOLFSSL_NO_ML_KEM_1024 */
6309
0
#endif /* WOLFSSL_NO_ML_KEM */
6310
#ifdef WOLFSSL_MLKEM_KYBER
6311
    #ifndef WOLFSSL_NO_KYBER512
6312
        case WOLFSSL_KYBER_LEVEL1:
6313
            return "KYBER_LEVEL1";
6314
        case WOLFSSL_P256_KYBER_LEVEL1:
6315
            return "P256_KYBER_LEVEL1";
6316
        #ifdef HAVE_CURVE25519
6317
        case WOLFSSL_X25519_KYBER_LEVEL1:
6318
            return "X25519_KYBER_LEVEL1";
6319
        #endif
6320
    #endif
6321
    #ifndef WOLFSSL_NO_KYBER768
6322
        case WOLFSSL_KYBER_LEVEL3:
6323
            return "KYBER_LEVEL3";
6324
        case WOLFSSL_P384_KYBER_LEVEL3:
6325
            return "P384_KYBER_LEVEL3";
6326
        case WOLFSSL_P256_KYBER_LEVEL3:
6327
            return "P256_KYBER_LEVEL3";
6328
        #ifdef HAVE_CURVE25519
6329
        case WOLFSSL_X25519_KYBER_LEVEL3:
6330
            return "X25519_KYBER_LEVEL3";
6331
        #endif
6332
        #ifdef HAVE_CURVE448
6333
        case WOLFSSL_X448_KYBER_LEVEL3:
6334
            return "X448_KYBER_LEVEL3";
6335
        #endif
6336
    #endif
6337
    #ifndef WOLFSSL_NO_KYBER1024
6338
        case WOLFSSL_KYBER_LEVEL5:
6339
            return "KYBER_LEVEL5";
6340
        case WOLFSSL_P521_KYBER_LEVEL5:
6341
            return "P521_KYBER_LEVEL5";
6342
    #endif
6343
#endif /* WOLFSSL_MLKEM_KYBER */
6344
0
        }
6345
0
    }
6346
0
#endif /* WOLFSSL_TLS13 && WOLFSSL_HAVE_MLKEM */
6347
6348
0
#ifdef HAVE_FFDHE
6349
0
    if (ssl->namedGroup != 0) {
6350
0
        cName = wolfssl_ffdhe_name(ssl->namedGroup);
6351
0
    }
6352
0
#endif
6353
6354
#ifdef HAVE_CURVE25519
6355
    if (ssl->ecdhCurveOID == ECC_X25519_OID && cName == NULL) {
6356
        cName = "X25519";
6357
    }
6358
#endif
6359
6360
#ifdef HAVE_CURVE448
6361
    if (ssl->ecdhCurveOID == ECC_X448_OID && cName == NULL) {
6362
        cName = "X448";
6363
    }
6364
#endif
6365
6366
0
#ifdef HAVE_ECC
6367
0
    if (ssl->ecdhCurveOID != 0 && cName == NULL) {
6368
0
        cName = wc_ecc_get_name(wc_ecc_get_oid(ssl->ecdhCurveOID, NULL,
6369
0
                                NULL));
6370
0
    }
6371
0
#endif
6372
6373
0
    return cName;
6374
0
}
6375
#endif
6376
6377
#ifdef OPENSSL_EXTRA
6378
#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
6379
/* return authentication NID corresponding to cipher suite
6380
 * @param cipher a pointer to WOLFSSL_CIPHER
6381
 * return NID if found, WC_NID_undef if not found
6382
 */
6383
int wolfSSL_CIPHER_get_auth_nid(const WOLFSSL_CIPHER* cipher)
6384
{
6385
    static const struct authnid {
6386
        const char* alg_name;
6387
        const int  nid;
6388
    } authnid_tbl[] = {
6389
        {"RSA",     WC_NID_auth_rsa},
6390
        {"PSK",     WC_NID_auth_psk},
6391
        {"SRP",     WC_NID_auth_srp},
6392
        {"ECDSA",   WC_NID_auth_ecdsa},
6393
        {"None",    WC_NID_auth_null},
6394
        {NULL,      WC_NID_undef}
6395
    };
6396
6397
    const char* authStr;
6398
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
6399
6400
    if (GetCipherSegment(cipher, n) == NULL) {
6401
        WOLFSSL_MSG("no suitable cipher name found");
6402
        return WC_NID_undef;
6403
    }
6404
6405
    authStr = GetCipherAuthStr(n);
6406
6407
    if (authStr != NULL) {
6408
        const struct authnid* sa;
6409
        for(sa = authnid_tbl; sa->alg_name != NULL; sa++) {
6410
            if (XSTRCMP(sa->alg_name, authStr) == 0) {
6411
                return sa->nid;
6412
            }
6413
        }
6414
    }
6415
6416
    return WC_NID_undef;
6417
}
6418
/* return cipher NID corresponding to cipher suite
6419
 * @param cipher a pointer to WOLFSSL_CIPHER
6420
 * return NID if found, WC_NID_undef if not found
6421
 */
6422
int wolfSSL_CIPHER_get_cipher_nid(const WOLFSSL_CIPHER* cipher)
6423
{
6424
    static const struct ciphernid {
6425
        const char* alg_name;
6426
        const int  nid;
6427
    } ciphernid_tbl[] = {
6428
        {"AESGCM(256)",             WC_NID_aes_256_gcm},
6429
        {"AESGCM(128)",             WC_NID_aes_128_gcm},
6430
        {"AESCCM(128)",             WC_NID_aes_128_ccm},
6431
        {"AES(128)",                WC_NID_aes_128_cbc},
6432
        {"AES(256)",                WC_NID_aes_256_cbc},
6433
        {"CAMELLIA(256)",           WC_NID_camellia_256_cbc},
6434
        {"CAMELLIA(128)",           WC_NID_camellia_128_cbc},
6435
        {"RC4",                     WC_NID_rc4},
6436
        {"3DES",                    WC_NID_des_ede3_cbc},
6437
        {"CHACHA20/POLY1305(256)",  WC_NID_chacha20_poly1305},
6438
        {"None",                    WC_NID_undef},
6439
        {NULL,                      WC_NID_undef}
6440
    };
6441
6442
    const char* encStr;
6443
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
6444
6445
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_cipher_nid");
6446
6447
    if (GetCipherSegment(cipher, n) == NULL) {
6448
        WOLFSSL_MSG("no suitable cipher name found");
6449
        return WC_NID_undef;
6450
    }
6451
6452
    encStr = GetCipherEncStr(n);
6453
6454
    if (encStr != NULL) {
6455
        const struct ciphernid* c;
6456
        for(c = ciphernid_tbl; c->alg_name != NULL; c++) {
6457
            if (XSTRCMP(c->alg_name, encStr) == 0) {
6458
                return c->nid;
6459
            }
6460
        }
6461
    }
6462
6463
    return WC_NID_undef;
6464
}
6465
/* return digest NID corresponding to cipher suite
6466
 * @param cipher a pointer to WOLFSSL_CIPHER
6467
 * return NID if found, WC_NID_undef if not found
6468
 */
6469
int wolfSSL_CIPHER_get_digest_nid(const WOLFSSL_CIPHER* cipher)
6470
{
6471
    static const struct macnid {
6472
        const char* alg_name;
6473
        const int  nid;
6474
    } macnid_tbl[] = {
6475
        {"SHA1",    WC_NID_sha1},
6476
        {"SHA256",  WC_NID_sha256},
6477
        {"SHA384",  WC_NID_sha384},
6478
        {NULL,      WC_NID_undef}
6479
    };
6480
6481
    const char* name;
6482
    const char* macStr;
6483
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
6484
    (void)name;
6485
6486
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_digest_nid");
6487
6488
    if ((name = GetCipherSegment(cipher, n)) == NULL) {
6489
        WOLFSSL_MSG("no suitable cipher name found");
6490
        return WC_NID_undef;
6491
    }
6492
6493
    /* in MD5 case, NID will be WC_NID_md5 */
6494
    if (XSTRSTR(name, "MD5") != NULL) {
6495
        return WC_NID_md5;
6496
    }
6497
6498
    macStr = GetCipherMacStr(n);
6499
6500
    if (macStr != NULL) {
6501
        const struct macnid* mc;
6502
        for(mc = macnid_tbl; mc->alg_name != NULL; mc++) {
6503
            if (XSTRCMP(mc->alg_name, macStr) == 0) {
6504
                return mc->nid;
6505
            }
6506
        }
6507
    }
6508
6509
    return WC_NID_undef;
6510
}
6511
/* return key exchange NID corresponding to cipher suite
6512
 * @param cipher a pointer to WOLFSSL_CIPHER
6513
 * return NID if found, WC_NID_undef if not found
6514
 */
6515
int wolfSSL_CIPHER_get_kx_nid(const WOLFSSL_CIPHER* cipher)
6516
{
6517
    static const struct kxnid {
6518
        const char* name;
6519
        const int  nid;
6520
    } kxnid_table[] = {
6521
        {"ECDHEPSK",  WC_NID_kx_ecdhe_psk},
6522
        {"ECDH",      WC_NID_kx_ecdhe},
6523
        {"DHEPSK",    WC_NID_kx_dhe_psk},
6524
        {"DH",        WC_NID_kx_dhe},
6525
        {"RSAPSK",    WC_NID_kx_rsa_psk},
6526
        {"SRP",       WC_NID_kx_srp},
6527
        {"EDH",       WC_NID_kx_dhe},
6528
        {"PSK",       WC_NID_kx_psk},
6529
        {"RSA",       WC_NID_kx_rsa},
6530
        {NULL,        WC_NID_undef}
6531
    };
6532
6533
    const char* keaStr;
6534
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
6535
6536
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_kx_nid");
6537
6538
    if (GetCipherSegment(cipher, n) == NULL) {
6539
        WOLFSSL_MSG("no suitable cipher name found");
6540
        return WC_NID_undef;
6541
    }
6542
6543
    /* in TLS 1.3 case, NID will be WC_NID_kx_any */
6544
    if (XSTRCMP(n[0], "TLS13") == 0) {
6545
        return WC_NID_kx_any;
6546
    }
6547
6548
    keaStr = GetCipherKeaStr(n);
6549
6550
    if (keaStr != NULL) {
6551
        const struct kxnid* k;
6552
        for(k = kxnid_table; k->name != NULL; k++) {
6553
            if (XSTRCMP(k->name, keaStr) == 0) {
6554
                return k->nid;
6555
            }
6556
        }
6557
    }
6558
6559
    return WC_NID_undef;
6560
}
6561
/* check if cipher suite is AEAD
6562
 * @param cipher a pointer to WOLFSSL_CIPHER
6563
 * return 1 if cipher is AEAD, 0 otherwise
6564
 */
6565
int wolfSSL_CIPHER_is_aead(const WOLFSSL_CIPHER* cipher)
6566
{
6567
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
6568
6569
    WOLFSSL_ENTER("wolfSSL_CIPHER_is_aead");
6570
6571
    if (GetCipherSegment(cipher, n) == NULL) {
6572
        WOLFSSL_MSG("no suitable cipher name found");
6573
        return WC_NID_undef;
6574
    }
6575
6576
    return IsCipherAEAD(n);
6577
}
6578
/* Creates cipher->description based on cipher->offset
6579
 * cipher->offset is set in wolfSSL_get_ciphers_compat when it is added
6580
 * to a stack of ciphers.
6581
 * @param [in] cipher: A cipher from a stack of ciphers.
6582
 * return WOLFSSL_SUCCESS if cipher->description is set, else WOLFSSL_FAILURE
6583
 */
6584
int wolfSSL_sk_CIPHER_description(WOLFSSL_CIPHER* cipher)
6585
{
6586
    int strLen;
6587
    unsigned long offset;
6588
    char* dp;
6589
    const char* name;
6590
    const char *keaStr, *authStr, *encStr, *macStr, *protocol;
6591
    char n[MAX_SEGMENTS][MAX_SEGMENT_SZ] = {{0}};
6592
    int len = MAX_DESCRIPTION_SZ-1;
6593
    const CipherSuiteInfo* cipher_names;
6594
    ProtocolVersion pv;
6595
    WOLFSSL_ENTER("wolfSSL_sk_CIPHER_description");
6596
6597
    if (cipher == NULL)
6598
        return WOLFSSL_FAILURE;
6599
6600
    dp = cipher->description;
6601
    if (dp == NULL)
6602
        return WOLFSSL_FAILURE;
6603
6604
    cipher_names = GetCipherNames();
6605
6606
    offset = cipher->offset;
6607
    if (offset >= (unsigned long)GetCipherNamesSize())
6608
        return WOLFSSL_FAILURE;
6609
    pv.major = cipher_names[offset].major;
6610
    pv.minor = cipher_names[offset].minor;
6611
    protocol = wolfSSL_internal_get_version(&pv);
6612
6613
    if ((name = GetCipherSegment(cipher, n)) == NULL) {
6614
        WOLFSSL_MSG("no suitable cipher name found");
6615
        return WOLFSSL_FAILURE;
6616
    }
6617
6618
    /* keaStr */
6619
    keaStr = GetCipherKeaStr(n);
6620
    /* authStr */
6621
    authStr = GetCipherAuthStr(n);
6622
    /* encStr */
6623
    encStr = GetCipherEncStr(n);
6624
    if ((cipher->bits = SetCipherBits(encStr)) ==
6625
        WC_NO_ERR_TRACE(WOLFSSL_FAILURE))
6626
    {
6627
       WOLFSSL_MSG("Cipher Bits Not Set.");
6628
    }
6629
    /* macStr */
6630
    macStr = GetCipherMacStr(n);
6631
6632
6633
    /* Build up the string by copying onto the end. */
6634
    XSTRNCPY(dp, name, (size_t)len);
6635
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
6636
    len -= strLen; dp += strLen;
6637
6638
    XSTRNCPY(dp, " ", (size_t)len);
6639
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
6640
    len -= strLen; dp += strLen;
6641
    XSTRNCPY(dp, protocol, (size_t)len);
6642
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
6643
    len -= strLen; dp += strLen;
6644
6645
    XSTRNCPY(dp, " Kx=", (size_t)len);
6646
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
6647
    len -= strLen; dp += strLen;
6648
    XSTRNCPY(dp, keaStr, (size_t)len);
6649
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
6650
    len -= strLen; dp += strLen;
6651
6652
    XSTRNCPY(dp, " Au=", (size_t)len);
6653
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
6654
    len -= strLen; dp += strLen;
6655
    XSTRNCPY(dp, authStr, (size_t)len);
6656
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
6657
    len -= strLen; dp += strLen;
6658
6659
    XSTRNCPY(dp, " Enc=", (size_t)len);
6660
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
6661
    len -= strLen; dp += strLen;
6662
    XSTRNCPY(dp, encStr, (size_t)len);
6663
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
6664
    len -= strLen; dp += strLen;
6665
6666
    XSTRNCPY(dp, " Mac=", (size_t)len);
6667
    dp[len-1] = '\0'; strLen = (int)XSTRLEN(dp);
6668
    len -= strLen; dp += (size_t)strLen;
6669
    XSTRNCPY(dp, macStr, (size_t)len);
6670
    dp[len-1] = '\0';
6671
6672
    return WOLFSSL_SUCCESS;
6673
}
6674
#endif /* OPENSSL_ALL || WOLFSSL_QT */
6675
6676
static WC_INLINE const char* wolfssl_kea_to_string(int kea)
6677
{
6678
    const char* keaStr;
6679
6680
    switch (kea) {
6681
        case no_kea:
6682
            keaStr = "None";
6683
            break;
6684
#ifndef NO_RSA
6685
        case rsa_kea:
6686
            keaStr = "RSA";
6687
            break;
6688
#endif
6689
#ifndef NO_DH
6690
        case diffie_hellman_kea:
6691
            keaStr = "DHE";
6692
            break;
6693
#endif
6694
        case fortezza_kea:
6695
            keaStr = "FZ";
6696
            break;
6697
#ifndef NO_PSK
6698
        case psk_kea:
6699
            keaStr = "PSK";
6700
            break;
6701
    #ifndef NO_DH
6702
        case dhe_psk_kea:
6703
            keaStr = "DHEPSK";
6704
            break;
6705
    #endif
6706
    #ifdef HAVE_ECC
6707
        case ecdhe_psk_kea:
6708
            keaStr = "ECDHEPSK";
6709
            break;
6710
    #endif
6711
#endif
6712
#ifdef HAVE_ECC
6713
        case ecc_diffie_hellman_kea:
6714
            keaStr = "ECDHE";
6715
            break;
6716
        case ecc_static_diffie_hellman_kea:
6717
            keaStr = "ECDH";
6718
            break;
6719
#endif
6720
        case any_kea:
6721
            keaStr = "any";
6722
            break;
6723
        default:
6724
            keaStr = "unknown";
6725
            break;
6726
    }
6727
6728
    return keaStr;
6729
}
6730
6731
static WC_INLINE const char* wolfssl_sigalg_to_string(int sig_algo)
6732
{
6733
    const char* authStr;
6734
6735
    switch (sig_algo) {
6736
        case anonymous_sa_algo:
6737
            authStr = "None";
6738
            break;
6739
#ifndef NO_RSA
6740
        case rsa_sa_algo:
6741
            authStr = "RSA";
6742
            break;
6743
    #ifdef WC_RSA_PSS
6744
        case rsa_pss_sa_algo:
6745
            authStr = "RSA-PSS";
6746
            break;
6747
    #endif
6748
#endif
6749
#ifndef NO_DSA
6750
        case dsa_sa_algo:
6751
            authStr = "DSA";
6752
            break;
6753
#endif
6754
#ifdef HAVE_ECC
6755
        case ecc_dsa_sa_algo:
6756
            authStr = "ECDSA";
6757
            break;
6758
#endif
6759
#ifdef WOLFSSL_SM2
6760
        case sm2_sa_algo:
6761
            authStr = "SM2";
6762
            break;
6763
#endif
6764
#ifdef HAVE_ED25519
6765
        case ed25519_sa_algo:
6766
            authStr = "Ed25519";
6767
            break;
6768
#endif
6769
#ifdef HAVE_ED448
6770
        case ed448_sa_algo:
6771
            authStr = "Ed448";
6772
            break;
6773
#endif
6774
        case any_sa_algo:
6775
            authStr = "any";
6776
            break;
6777
        default:
6778
            authStr = "unknown";
6779
            break;
6780
    }
6781
6782
    return authStr;
6783
}
6784
6785
static WC_INLINE const char* wolfssl_cipher_to_string(int cipher, int key_size)
6786
{
6787
    const char* encStr;
6788
6789
    (void)key_size;
6790
6791
    switch (cipher) {
6792
        case wolfssl_cipher_null:
6793
            encStr = "None";
6794
            break;
6795
#ifndef NO_RC4
6796
        case wolfssl_rc4:
6797
            encStr = "RC4(128)";
6798
            break;
6799
#endif
6800
#ifndef NO_DES3
6801
        case wolfssl_triple_des:
6802
            encStr = "3DES(168)";
6803
            break;
6804
#endif
6805
#ifndef NO_AES
6806
        case wolfssl_aes:
6807
            if (key_size == AES_128_KEY_SIZE)
6808
                encStr = "AES(128)";
6809
            else if (key_size == AES_256_KEY_SIZE)
6810
                encStr = "AES(256)";
6811
            else
6812
                encStr = "AES(?)";
6813
            break;
6814
    #ifdef HAVE_AESGCM
6815
        case wolfssl_aes_gcm:
6816
            if (key_size == AES_128_KEY_SIZE)
6817
                encStr = "AESGCM(128)";
6818
            else if (key_size == AES_256_KEY_SIZE)
6819
                encStr = "AESGCM(256)";
6820
            else
6821
                encStr = "AESGCM(?)";
6822
            break;
6823
    #endif
6824
    #ifdef HAVE_AESCCM
6825
        case wolfssl_aes_ccm:
6826
            if (key_size == AES_128_KEY_SIZE)
6827
                encStr = "AESCCM(128)";
6828
            else if (key_size == AES_256_KEY_SIZE)
6829
                encStr = "AESCCM(256)";
6830
            else
6831
                encStr = "AESCCM(?)";
6832
            break;
6833
    #endif
6834
#endif
6835
#ifdef HAVE_CHACHA
6836
        case wolfssl_chacha:
6837
            encStr = "CHACHA20/POLY1305(256)";
6838
            break;
6839
#endif
6840
#ifdef HAVE_ARIA
6841
        case wolfssl_aria_gcm:
6842
            if (key_size == ARIA_128_KEY_SIZE)
6843
                encStr = "Aria(128)";
6844
            else if (key_size == ARIA_192_KEY_SIZE)
6845
                encStr = "Aria(192)";
6846
            else if (key_size == ARIA_256_KEY_SIZE)
6847
                encStr = "Aria(256)";
6848
            else
6849
                encStr = "Aria(?)";
6850
            break;
6851
#endif
6852
#ifdef HAVE_CAMELLIA
6853
        case wolfssl_camellia:
6854
            if (key_size == CAMELLIA_128_KEY_SIZE)
6855
                encStr = "Camellia(128)";
6856
            else if (key_size == CAMELLIA_256_KEY_SIZE)
6857
                encStr = "Camellia(256)";
6858
            else
6859
                encStr = "Camellia(?)";
6860
            break;
6861
#endif
6862
        default:
6863
            encStr = "unknown";
6864
            break;
6865
    }
6866
6867
    return encStr;
6868
}
6869
6870
static WC_INLINE const char* wolfssl_mac_to_string(int mac)
6871
{
6872
    const char* macStr;
6873
6874
    switch (mac) {
6875
        case no_mac:
6876
            macStr = "None";
6877
            break;
6878
#ifndef NO_MD5
6879
        case md5_mac:
6880
            macStr = "MD5";
6881
            break;
6882
#endif
6883
#ifndef NO_SHA
6884
        case sha_mac:
6885
            macStr = "SHA1";
6886
            break;
6887
#endif
6888
#ifdef WOLFSSL_SHA224
6889
        case sha224_mac:
6890
            macStr = "SHA224";
6891
            break;
6892
#endif
6893
#ifndef NO_SHA256
6894
        case sha256_mac:
6895
            macStr = "SHA256";
6896
            break;
6897
#endif
6898
#ifdef WOLFSSL_SHA384
6899
        case sha384_mac:
6900
            macStr = "SHA384";
6901
            break;
6902
#endif
6903
#ifdef WOLFSSL_SHA512
6904
        case sha512_mac:
6905
            macStr = "SHA512";
6906
            break;
6907
#endif
6908
        default:
6909
            macStr = "unknown";
6910
            break;
6911
    }
6912
6913
    return macStr;
6914
}
6915
6916
char* wolfSSL_CIPHER_description(const WOLFSSL_CIPHER* cipher, char* in,
6917
                                 int len)
6918
{
6919
    char *ret = in;
6920
    const char *keaStr, *authStr, *encStr, *macStr;
6921
    size_t strLen;
6922
    WOLFSSL_ENTER("wolfSSL_CIPHER_description");
6923
6924
    if (cipher == NULL || in == NULL)
6925
        return NULL;
6926
6927
#if defined(WOLFSSL_QT) || defined(OPENSSL_ALL)
6928
    /* if cipher is in the stack from wolfSSL_get_ciphers_compat then
6929
     * Return the description based on cipher_names[cipher->offset]
6930
     */
6931
    if (cipher->in_stack == TRUE) {
6932
        wolfSSL_sk_CIPHER_description((WOLFSSL_CIPHER*)cipher);
6933
        XSTRNCPY(in,cipher->description,(size_t)len);
6934
        return ret;
6935
    }
6936
#endif
6937
6938
    /* Get the cipher description based on the SSL session cipher */
6939
    keaStr = wolfssl_kea_to_string(cipher->ssl->specs.kea);
6940
    authStr = wolfssl_sigalg_to_string(cipher->ssl->specs.sig_algo);
6941
    encStr = wolfssl_cipher_to_string(cipher->ssl->specs.bulk_cipher_algorithm,
6942
                                      cipher->ssl->specs.key_size);
6943
    if (cipher->ssl->specs.cipher_type == aead)
6944
        macStr = "AEAD";
6945
    else
6946
        macStr = wolfssl_mac_to_string(cipher->ssl->specs.mac_algorithm);
6947
6948
    /* Build up the string by copying onto the end. */
6949
    XSTRNCPY(in, wolfSSL_CIPHER_get_name(cipher), (size_t)len);
6950
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
6951
6952
    XSTRNCPY(in, " ", (size_t)len);
6953
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
6954
    XSTRNCPY(in, wolfSSL_get_version(cipher->ssl), (size_t)len);
6955
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
6956
6957
    XSTRNCPY(in, " Kx=", (size_t)len);
6958
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
6959
    XSTRNCPY(in, keaStr, (size_t)len);
6960
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
6961
6962
    XSTRNCPY(in, " Au=", (size_t)len);
6963
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
6964
    XSTRNCPY(in, authStr, (size_t)len);
6965
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
6966
6967
    XSTRNCPY(in, " Enc=", (size_t)len);
6968
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
6969
    XSTRNCPY(in, encStr, (size_t)len);
6970
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
6971
6972
    XSTRNCPY(in, " Mac=", (size_t)len);
6973
    in[len-1] = '\0'; strLen = XSTRLEN(in); len -= (int)strLen; in += strLen;
6974
    XSTRNCPY(in, macStr, (size_t)len);
6975
    in[len-1] = '\0';
6976
6977
    return ret;
6978
}
6979
6980
#ifndef NO_WOLFSSL_STUB
6981
WOLFSSL_COMP_METHOD* wolfSSL_COMP_zlib(void)
6982
{
6983
    WOLFSSL_STUB("COMP_zlib");
6984
    return 0;
6985
}
6986
6987
WOLFSSL_COMP_METHOD* wolfSSL_COMP_rle(void)
6988
{
6989
    WOLFSSL_STUB("COMP_rle");
6990
    return 0;
6991
}
6992
6993
int wolfSSL_COMP_add_compression_method(int method, void* data)
6994
{
6995
    (void)method;
6996
    (void)data;
6997
    WOLFSSL_STUB("COMP_add_compression_method");
6998
    return 0;
6999
}
7000
7001
const WOLFSSL_COMP_METHOD* wolfSSL_get_current_compression(const WOLFSSL *ssl) {
7002
    (void)ssl;
7003
    return NULL;
7004
}
7005
7006
const WOLFSSL_COMP_METHOD* wolfSSL_get_current_expansion(const WOLFSSL *ssl) {
7007
    (void)ssl;
7008
    return NULL;
7009
}
7010
7011
const char* wolfSSL_COMP_get_name(const WOLFSSL_COMP_METHOD *comp)
7012
{
7013
    static const char ret[] = "not supported";
7014
7015
    (void)comp;
7016
    WOLFSSL_STUB("wolfSSL_COMP_get_name");
7017
    return ret;
7018
}
7019
#endif
7020
7021
/*  wolfSSL_set_dynlock_create_callback
7022
 *  CRYPTO_set_dynlock_create_callback has been deprecated since openSSL 1.0.1.
7023
 *  This function exists for compatibility purposes because wolfSSL satisfies
7024
 *  thread safety without relying on the callback.
7025
 */
7026
void wolfSSL_set_dynlock_create_callback(WOLFSSL_dynlock_value* (*f)(
7027
                                                          const char*, int))
7028
{
7029
    WOLFSSL_STUB("CRYPTO_set_dynlock_create_callback");
7030
    (void)f;
7031
}
7032
/*  wolfSSL_set_dynlock_lock_callback
7033
 *  CRYPTO_set_dynlock_lock_callback has been deprecated since openSSL 1.0.1.
7034
 *  This function exists for compatibility purposes because wolfSSL satisfies
7035
 *  thread safety without relying on the callback.
7036
 */
7037
void wolfSSL_set_dynlock_lock_callback(
7038
             void (*f)(int, WOLFSSL_dynlock_value*, const char*, int))
7039
{
7040
    WOLFSSL_STUB("CRYPTO_set_set_dynlock_lock_callback");
7041
    (void)f;
7042
}
7043
/*  wolfSSL_set_dynlock_destroy_callback
7044
 *  CRYPTO_set_dynlock_destroy_callback has been deprecated since openSSL 1.0.1.
7045
 *  This function exists for compatibility purposes because wolfSSL satisfies
7046
 *  thread safety without relying on the callback.
7047
 */
7048
void wolfSSL_set_dynlock_destroy_callback(
7049
                  void (*f)(WOLFSSL_dynlock_value*, const char*, int))
7050
{
7051
    WOLFSSL_STUB("CRYPTO_set_set_dynlock_destroy_callback");
7052
    (void)f;
7053
}
7054
7055
/* Sets the DNS hostname to name.
7056
 * Hostname is cleared if name is NULL or empty. */
7057
int wolfSSL_set1_host(WOLFSSL * ssl, const char* name)
7058
{
7059
    if (ssl == NULL) {
7060
        return WOLFSSL_FAILURE;
7061
    }
7062
7063
    return wolfSSL_X509_VERIFY_PARAM_set1_host(ssl->param, name, 0);
7064
}
7065
7066
/******************************************************************************
7067
* wolfSSL_CTX_set1_param - set a pointer to the SSL verification parameters
7068
*
7069
* RETURNS:
7070
*   WOLFSSL_SUCCESS on success, otherwise returns WOLFSSL_FAILURE
7071
*   Note: Returns WOLFSSL_SUCCESS, in case either parameter is NULL,
7072
*   same as openssl.
7073
*/
7074
int wolfSSL_CTX_set1_param(WOLFSSL_CTX* ctx, WOLFSSL_X509_VERIFY_PARAM *vpm)
7075
{
7076
    if (ctx == NULL || vpm == NULL)
7077
        return WOLFSSL_SUCCESS;
7078
7079
    return wolfSSL_X509_VERIFY_PARAM_set1(ctx->param, vpm);
7080
}
7081
7082
/******************************************************************************
7083
* wolfSSL_CTX/_get0_param - return a pointer to the SSL verification parameters
7084
*
7085
* RETURNS:
7086
* returns pointer to the SSL verification parameters on success,
7087
* otherwise returns NULL
7088
*/
7089
WOLFSSL_X509_VERIFY_PARAM* wolfSSL_CTX_get0_param(WOLFSSL_CTX* ctx)
7090
{
7091
    if (ctx == NULL) {
7092
        return NULL;
7093
    }
7094
7095
    return ctx->param;
7096
}
7097
7098
WOLFSSL_X509_VERIFY_PARAM* wolfSSL_get0_param(WOLFSSL* ssl)
7099
{
7100
    if (ssl == NULL) {
7101
        return NULL;
7102
    }
7103
    return ssl->param;
7104
}
7105
7106
#endif /* OPENSSL_EXTRA */
7107
7108
7109
#ifdef OPENSSL_EXTRA
7110
/* Sets a function callback that will send information about the state of all
7111
 * WOLFSSL objects that have been created by the WOLFSSL_CTX structure passed
7112
 * in.
7113
 *
7114
 * ctx WOLFSSL_CTX structure to set callback function in
7115
 * f   callback function to use
7116
 */
7117
void wolfSSL_CTX_set_info_callback(WOLFSSL_CTX* ctx,
7118
       void (*f)(const WOLFSSL* ssl, int type, int val))
7119
{
7120
    WOLFSSL_ENTER("wolfSSL_CTX_set_info_callback");
7121
    if (ctx == NULL) {
7122
        WOLFSSL_MSG("Bad function argument");
7123
    }
7124
    else {
7125
        ctx->CBIS = f;
7126
    }
7127
}
7128
7129
void wolfSSL_set_info_callback(WOLFSSL* ssl,
7130
       void (*f)(const WOLFSSL* ssl, int type, int val))
7131
{
7132
    WOLFSSL_ENTER("wolfSSL_set_info_callback");
7133
    if (ssl == NULL) {
7134
        WOLFSSL_MSG("Bad function argument");
7135
    }
7136
    else {
7137
        ssl->CBIS = f;
7138
    }
7139
}
7140
7141
7142
7143
#ifndef NO_TLS
7144
/* returns a string that describes the alert
7145
 *
7146
 * alertID the alert value to look up
7147
 */
7148
const char* wolfSSL_alert_type_string_long(int alertID)
7149
{
7150
    WOLFSSL_ENTER("wolfSSL_alert_type_string_long");
7151
7152
    return AlertTypeToString(alertID);
7153
}
7154
7155
const char* wolfSSL_alert_type_string(int alertID)
7156
{
7157
    WOLFSSL_ENTER("wolfSSL_alert_type_string");
7158
7159
    switch (alertID) {
7160
        case alert_warning:
7161
            return "W";
7162
        case alert_fatal:
7163
            return "F";
7164
        default:
7165
            return "U";
7166
    }
7167
}
7168
7169
const char* wolfSSL_alert_desc_string_long(int alertID)
7170
{
7171
    WOLFSSL_ENTER("wolfSSL_alert_desc_string_long");
7172
7173
    return AlertTypeToString(alertID);
7174
}
7175
7176
const char* wolfSSL_alert_desc_string(int alertID)
7177
{
7178
    WOLFSSL_ENTER("wolfSSL_alert_desc_string");
7179
7180
    switch (alertID) {
7181
        case close_notify:
7182
            return "CN";
7183
        case unexpected_message:
7184
            return "UM";
7185
        case bad_record_mac:
7186
            return "BM";
7187
        case record_overflow:
7188
            return "RO";
7189
        case decompression_failure:
7190
            return "DF";
7191
        case handshake_failure:
7192
            return "HF";
7193
        case no_certificate:
7194
            return "NC";
7195
        case bad_certificate:
7196
            return "BC";
7197
        case unsupported_certificate:
7198
            return "UC";
7199
        case certificate_revoked:
7200
            return "CR";
7201
        case certificate_expired:
7202
            return "CE";
7203
        case certificate_unknown:
7204
            return "CU";
7205
        case illegal_parameter:
7206
            return "IP";
7207
        case unknown_ca:
7208
            return "CA";
7209
        case access_denied:
7210
            return "AD";
7211
        case decode_error:
7212
            return "DE";
7213
        case decrypt_error:
7214
            return "DC";
7215
        case wolfssl_alert_protocol_version:
7216
            return "PV";
7217
        case insufficient_security:
7218
            return "IS";
7219
        case internal_error:
7220
            return "IE";
7221
        case inappropriate_fallback:
7222
            return "IF";
7223
        case user_canceled:
7224
            return "US";
7225
        case no_renegotiation:
7226
            return "NR";
7227
        case missing_extension:
7228
            return "ME";
7229
        case unsupported_extension:
7230
            return "UE";
7231
        case unrecognized_name:
7232
            return "UN";
7233
        case bad_certificate_status_response:
7234
            return "BR";
7235
        case unknown_psk_identity:
7236
            return "UP";
7237
        case certificate_required:
7238
            return "CQ";
7239
        case no_application_protocol:
7240
            return "AP";
7241
        default:
7242
            return "UK";
7243
    }
7244
}
7245
#endif /* !NO_TLS */
7246
7247
7248
#endif /* OPENSSL_EXTRA */
7249
7250
static long wolf_set_options(long old_op, long op)
7251
0
{
7252
    /* if SSL_OP_ALL then turn all bug workarounds on */
7253
0
    if ((op & WOLFSSL_OP_ALL) == WOLFSSL_OP_ALL) {
7254
0
        WOLFSSL_MSG("\tSSL_OP_ALL");
7255
0
    }
7256
7257
    /* by default cookie exchange is on with DTLS */
7258
0
    if ((op & WOLFSSL_OP_COOKIE_EXCHANGE) == WOLFSSL_OP_COOKIE_EXCHANGE) {
7259
0
        WOLFSSL_MSG("\tSSL_OP_COOKIE_EXCHANGE : on by default");
7260
0
    }
7261
7262
0
    if ((op & WOLFSSL_OP_NO_SSLv2) == WOLFSSL_OP_NO_SSLv2) {
7263
0
        WOLFSSL_MSG("\tWOLFSSL_OP_NO_SSLv2 : wolfSSL does not support SSLv2");
7264
0
    }
7265
7266
#ifdef SSL_OP_NO_TLSv1_3
7267
    if ((op & WOLFSSL_OP_NO_TLSv1_3) == WOLFSSL_OP_NO_TLSv1_3) {
7268
        WOLFSSL_MSG("\tSSL_OP_NO_TLSv1_3");
7269
    }
7270
#endif
7271
7272
0
    if ((op & WOLFSSL_OP_NO_TLSv1_2) == WOLFSSL_OP_NO_TLSv1_2) {
7273
0
        WOLFSSL_MSG("\tSSL_OP_NO_TLSv1_2");
7274
0
    }
7275
7276
0
    if ((op & WOLFSSL_OP_NO_TLSv1_1) == WOLFSSL_OP_NO_TLSv1_1) {
7277
0
        WOLFSSL_MSG("\tSSL_OP_NO_TLSv1_1");
7278
0
    }
7279
7280
0
    if ((op & WOLFSSL_OP_NO_TLSv1) == WOLFSSL_OP_NO_TLSv1) {
7281
0
        WOLFSSL_MSG("\tSSL_OP_NO_TLSv1");
7282
0
    }
7283
7284
0
    if ((op & WOLFSSL_OP_NO_SSLv3) == WOLFSSL_OP_NO_SSLv3) {
7285
0
        WOLFSSL_MSG("\tSSL_OP_NO_SSLv3");
7286
0
    }
7287
7288
0
    if ((op & WOLFSSL_OP_CIPHER_SERVER_PREFERENCE) ==
7289
0
            WOLFSSL_OP_CIPHER_SERVER_PREFERENCE) {
7290
0
        WOLFSSL_MSG("\tWOLFSSL_OP_CIPHER_SERVER_PREFERENCE");
7291
0
    }
7292
7293
0
    if ((op & WOLFSSL_OP_NO_COMPRESSION) == WOLFSSL_OP_NO_COMPRESSION) {
7294
    #ifdef HAVE_LIBZ
7295
        WOLFSSL_MSG("SSL_OP_NO_COMPRESSION");
7296
    #else
7297
0
        WOLFSSL_MSG("SSL_OP_NO_COMPRESSION: compression not compiled in");
7298
0
    #endif
7299
0
    }
7300
7301
0
    return old_op | op;
7302
0
}
7303
7304
static int FindHashSig(const Suites* suites, byte first, byte second)
7305
0
{
7306
0
    word16 i;
7307
7308
0
    if (suites == NULL || suites->hashSigAlgoSz == 0) {
7309
0
        WOLFSSL_MSG("Suites pointer error or suiteSz 0");
7310
0
        return SUITES_ERROR;
7311
0
    }
7312
7313
0
    for (i = 0; i < suites->hashSigAlgoSz-1; i += 2) {
7314
0
        if (suites->hashSigAlgo[i]   == first &&
7315
0
            suites->hashSigAlgo[i+1] == second )
7316
0
            return i;
7317
0
    }
7318
7319
0
    return MATCH_SUITE_ERROR;
7320
0
}
7321
7322
long wolfSSL_set_options(WOLFSSL* ssl, long op)
7323
0
{
7324
0
    word16 haveRSA = 1;
7325
0
    word16 havePSK = 0;
7326
0
    int    keySz   = 0;
7327
7328
0
    WOLFSSL_ENTER("wolfSSL_set_options");
7329
7330
0
    if (ssl == NULL) {
7331
0
        return 0;
7332
0
    }
7333
7334
0
    ssl->options.mask = (unsigned long)wolf_set_options((long)ssl->options.mask, op);
7335
7336
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1_3) == WOLFSSL_OP_NO_TLSv1_3) {
7337
0
        WOLFSSL_MSG("Disabling TLS 1.3");
7338
0
        if (ssl->version.minor == TLSv1_3_MINOR)
7339
0
            ssl->version.minor = TLSv1_2_MINOR;
7340
0
    }
7341
7342
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1_2) == WOLFSSL_OP_NO_TLSv1_2) {
7343
0
        WOLFSSL_MSG("Disabling TLS 1.2");
7344
0
        if (ssl->version.minor == TLSv1_2_MINOR)
7345
0
            ssl->version.minor = TLSv1_1_MINOR;
7346
0
    }
7347
7348
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1_1) == WOLFSSL_OP_NO_TLSv1_1) {
7349
0
        WOLFSSL_MSG("Disabling TLS 1.1");
7350
0
        if (ssl->version.minor == TLSv1_1_MINOR)
7351
0
            ssl->version.minor = TLSv1_MINOR;
7352
0
    }
7353
7354
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_TLSv1) == WOLFSSL_OP_NO_TLSv1) {
7355
0
        WOLFSSL_MSG("Disabling TLS 1.0");
7356
0
        if (ssl->version.minor == TLSv1_MINOR)
7357
0
            ssl->version.minor = SSLv3_MINOR;
7358
0
    }
7359
7360
0
    if ((ssl->options.mask & WOLFSSL_OP_NO_COMPRESSION)
7361
0
        == WOLFSSL_OP_NO_COMPRESSION) {
7362
    #ifdef HAVE_LIBZ
7363
        ssl->options.usingCompression = 0;
7364
    #endif
7365
0
    }
7366
7367
#if defined(HAVE_SESSION_TICKET) && (defined(OPENSSL_EXTRA) \
7368
        || defined(HAVE_WEBSERVER) || defined(WOLFSSL_WPAS_SMALL))
7369
    if ((ssl->options.mask & WOLFSSL_OP_NO_TICKET) == WOLFSSL_OP_NO_TICKET) {
7370
      ssl->options.noTicketTls12 = 1;
7371
    }
7372
#endif
7373
7374
7375
    /* in the case of a version change the cipher suites should be reset */
7376
#ifndef NO_PSK
7377
    havePSK = ssl->options.havePSK;
7378
#endif
7379
#ifdef NO_RSA
7380
    haveRSA = 0;
7381
#endif
7382
0
#ifndef NO_CERTS
7383
0
    keySz = ssl->buffers.keySz;
7384
0
#endif
7385
7386
0
    if (ssl->options.side != WOLFSSL_NEITHER_END) {
7387
0
        if (AllocateSuites(ssl) != 0)
7388
0
            return 0;
7389
0
        if (!ssl->suites->setSuites) {
7390
            /* Client side won't set DH params, so it needs haveDH set to TRUE. */
7391
0
            if (ssl->options.side == WOLFSSL_CLIENT_END)
7392
0
                InitSuites(ssl->suites, ssl->version, keySz, haveRSA,
7393
0
                       havePSK, TRUE, ssl->options.haveECDSAsig,
7394
0
                       ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
7395
0
                       ssl->options.useAnon,
7396
0
                       TRUE, TRUE, TRUE, TRUE, ssl->options.side);
7397
0
            else
7398
0
                InitSuites(ssl->suites, ssl->version, keySz, haveRSA,
7399
0
                       havePSK, ssl->options.haveDH, ssl->options.haveECDSAsig,
7400
0
                       ssl->options.haveECC, TRUE, ssl->options.haveStaticECC,
7401
0
                       ssl->options.useAnon,
7402
0
                       TRUE, TRUE, TRUE, TRUE, ssl->options.side);
7403
0
        }
7404
0
        else {
7405
            /* Only preserve overlapping suites */
7406
0
            Suites tmpSuites;
7407
0
            word16 in, out;
7408
0
            word16 haveECDSAsig, haveStaticECC;
7409
#ifdef NO_RSA
7410
            haveECDSAsig = 1;
7411
            haveStaticECC = 1;
7412
#else
7413
0
            haveECDSAsig = 0;
7414
0
            haveStaticECC = ssl->options.haveStaticECC;
7415
0
#endif
7416
0
            XMEMSET(&tmpSuites, 0, sizeof(Suites));
7417
            /* Get all possible ciphers and sigalgs for the version. Following
7418
             * options limit the allowed ciphers so let's try to get as many as
7419
             * possible.
7420
             * - haveStaticECC turns off haveRSA
7421
             * - haveECDSAsig turns off haveRSAsig */
7422
0
            InitSuites(&tmpSuites, ssl->version, 0, 1, 1, 1, haveECDSAsig, 1, 1,
7423
0
                    haveStaticECC, 1, 1, 1, 1, 1, ssl->options.side);
7424
0
            for (in = 0, out = 0; in < ssl->suites->suiteSz; in += SUITE_LEN) {
7425
0
                if (FindSuite(&tmpSuites, ssl->suites->suites[in],
7426
0
                        ssl->suites->suites[in+1]) >= 0) {
7427
0
                    ssl->suites->suites[out] = ssl->suites->suites[in];
7428
0
                    ssl->suites->suites[out+1] = ssl->suites->suites[in+1];
7429
0
                    out += SUITE_LEN;
7430
0
                }
7431
0
            }
7432
0
            ssl->suites->suiteSz = out;
7433
0
            for (in = 0, out = 0; in < ssl->suites->hashSigAlgoSz; in += 2) {
7434
0
                if (FindHashSig(&tmpSuites, ssl->suites->hashSigAlgo[in],
7435
0
                    ssl->suites->hashSigAlgo[in+1]) >= 0) {
7436
0
                    ssl->suites->hashSigAlgo[out] =
7437
0
                            ssl->suites->hashSigAlgo[in];
7438
0
                    ssl->suites->hashSigAlgo[out+1] =
7439
0
                            ssl->suites->hashSigAlgo[in+1];
7440
0
                    out += 2;
7441
0
                }
7442
0
            }
7443
0
            ssl->suites->hashSigAlgoSz = out;
7444
0
        }
7445
0
    }
7446
7447
0
    return (long)ssl->options.mask;
7448
0
}
7449
7450
7451
long wolfSSL_get_options(const WOLFSSL* ssl)
7452
0
{
7453
0
    WOLFSSL_ENTER("wolfSSL_get_options");
7454
0
    if(ssl == NULL)
7455
0
        return WOLFSSL_FAILURE;
7456
0
    return (long)ssl->options.mask;
7457
0
}
7458
7459
#if defined(HAVE_SECURE_RENEGOTIATION) \
7460
        || defined(HAVE_SERVER_RENEGOTIATION_INFO)
7461
/* clears the counter for number of renegotiations done
7462
 * returns the current count before it is cleared */
7463
long wolfSSL_clear_num_renegotiations(WOLFSSL *s)
7464
0
{
7465
0
    long total;
7466
7467
0
    WOLFSSL_ENTER("wolfSSL_clear_num_renegotiations");
7468
0
    if (s == NULL)
7469
0
        return 0;
7470
7471
0
    total = s->secure_rene_count;
7472
0
    s->secure_rene_count = 0;
7473
0
    return total;
7474
0
}
7475
7476
7477
/* return the number of renegotiations since wolfSSL_new */
7478
long wolfSSL_total_renegotiations(WOLFSSL *s)
7479
0
{
7480
0
    WOLFSSL_ENTER("wolfSSL_total_renegotiations");
7481
0
    return wolfSSL_num_renegotiations(s);
7482
0
}
7483
7484
7485
/* return the number of renegotiations since wolfSSL_new */
7486
long wolfSSL_num_renegotiations(WOLFSSL* s)
7487
0
{
7488
0
    if (s == NULL) {
7489
0
        return 0;
7490
0
    }
7491
7492
0
    return s->secure_rene_count;
7493
0
}
7494
7495
7496
/* Is there a renegotiation currently in progress? */
7497
int  wolfSSL_SSL_renegotiate_pending(WOLFSSL *s)
7498
0
{
7499
0
    return s && s->options.handShakeDone &&
7500
0
            s->options.handShakeState != HANDSHAKE_DONE ? 1 : 0;
7501
0
}
7502
#endif /* HAVE_SECURE_RENEGOTIATION || HAVE_SERVER_RENEGOTIATION_INFO */
7503
7504
#ifdef OPENSSL_EXTRA
7505
7506
long wolfSSL_clear_options(WOLFSSL* ssl, long opt)
7507
{
7508
    WOLFSSL_ENTER("wolfSSL_clear_options");
7509
    if(ssl == NULL)
7510
        return WOLFSSL_FAILURE;
7511
    ssl->options.mask &= (unsigned long)~opt;
7512
    return (long)ssl->options.mask;
7513
}
7514
7515
7516
#ifndef NO_WOLFSSL_STUB
7517
/*** TBD ***/
7518
void WOLFSSL_CTX_set_tmp_dh_callback(WOLFSSL_CTX *ctx,
7519
    WOLFSSL_DH *(*dh) (WOLFSSL *ssl, int is_export, int keylength))
7520
{
7521
    (void)ctx;
7522
    (void)dh;
7523
    WOLFSSL_STUB("WOLFSSL_CTX_set_tmp_dh_callback");
7524
}
7525
#endif
7526
7527
#ifndef NO_WOLFSSL_STUB
7528
/*** TBD ***/
7529
WOLF_STACK_OF(WOLFSSL_COMP) *WOLFSSL_COMP_get_compression_methods(void)
7530
{
7531
    WOLFSSL_STUB("WOLFSSL_COMP_get_compression_methods");
7532
    return NULL;
7533
}
7534
#endif
7535
7536
7537
#if !defined(NETOS)
7538
#endif
7539
7540
7541
#endif /* OPENSSL_EXTRA */
7542
7543
#ifdef WOLFSSL_HAVE_TLS_UNIQUE
7544
size_t wolfSSL_get_finished(const WOLFSSL *ssl, void *buf, size_t count)
7545
{
7546
    byte len = 0;
7547
    byte const * src;
7548
7549
    WOLFSSL_ENTER("wolfSSL_get_finished");
7550
7551
    if (!ssl || !buf) {
7552
        WOLFSSL_MSG("Bad parameter");
7553
        return WOLFSSL_FAILURE;
7554
    }
7555
7556
    if (ssl->options.side == WOLFSSL_SERVER_END) {
7557
        src = ssl->serverFinished;
7558
        len = ssl->serverFinished_len;
7559
    }
7560
    else {
7561
        src = ssl->clientFinished;
7562
        len = ssl->clientFinished_len;
7563
    }
7564
7565
    if (count < len) {
7566
        WOLFSSL_MSG("Buffer too small");
7567
        return WOLFSSL_FAILURE;
7568
    }
7569
7570
    XMEMCPY(buf, src, len);
7571
7572
    return len;
7573
}
7574
7575
size_t wolfSSL_get_peer_finished(const WOLFSSL *ssl, void *buf, size_t count)
7576
{
7577
    byte len = 0;
7578
    byte const * src;
7579
7580
    WOLFSSL_ENTER("wolfSSL_get_peer_finished");
7581
7582
    if (!ssl || !buf) {
7583
        WOLFSSL_MSG("Bad parameter");
7584
        return WOLFSSL_FAILURE;
7585
    }
7586
7587
    if (ssl->options.side == WOLFSSL_CLIENT_END) {
7588
        src = ssl->serverFinished;
7589
        len = ssl->serverFinished_len;
7590
    }
7591
    else {
7592
        src = ssl->clientFinished;
7593
        len = ssl->clientFinished_len;
7594
    }
7595
7596
    if (count < len) {
7597
        WOLFSSL_MSG("Buffer too small");
7598
        return WOLFSSL_FAILURE;
7599
    }
7600
7601
    XMEMCPY(buf, src, len);
7602
7603
    return len;
7604
}
7605
#endif /* WOLFSSL_HAVE_TLS_UNIQUE */
7606
7607
7608
#ifdef OPENSSL_EXTRA
7609
7610
#ifndef NO_WOLFSSL_STUB
7611
/* shows the number of accepts attempted by CTX in it's lifetime */
7612
long wolfSSL_CTX_sess_accept(WOLFSSL_CTX* ctx)
7613
{
7614
    WOLFSSL_STUB("wolfSSL_CTX_sess_accept");
7615
    (void)ctx;
7616
    return 0;
7617
}
7618
#endif
7619
7620
#ifndef NO_WOLFSSL_STUB
7621
/* shows the number of connects attempted CTX in it's lifetime */
7622
long wolfSSL_CTX_sess_connect(WOLFSSL_CTX* ctx)
7623
{
7624
    WOLFSSL_STUB("wolfSSL_CTX_sess_connect");
7625
    (void)ctx;
7626
    return 0;
7627
}
7628
#endif
7629
7630
7631
#ifndef NO_WOLFSSL_STUB
7632
/* shows the number of accepts completed by CTX in it's lifetime */
7633
long wolfSSL_CTX_sess_accept_good(WOLFSSL_CTX* ctx)
7634
{
7635
    WOLFSSL_STUB("wolfSSL_CTX_sess_accept_good");
7636
    (void)ctx;
7637
    return 0;
7638
}
7639
#endif
7640
7641
7642
#ifndef NO_WOLFSSL_STUB
7643
/* shows the number of connects completed by CTX in it's lifetime */
7644
long wolfSSL_CTX_sess_connect_good(WOLFSSL_CTX* ctx)
7645
{
7646
    WOLFSSL_STUB("wolfSSL_CTX_sess_connect_good");
7647
    (void)ctx;
7648
    return 0;
7649
}
7650
#endif
7651
7652
7653
#ifndef NO_WOLFSSL_STUB
7654
/* shows the number of renegotiation accepts attempted by CTX */
7655
long wolfSSL_CTX_sess_accept_renegotiate(WOLFSSL_CTX* ctx)
7656
{
7657
    WOLFSSL_STUB("wolfSSL_CTX_sess_accept_renegotiate");
7658
    (void)ctx;
7659
    return 0;
7660
}
7661
#endif
7662
7663
7664
#ifndef NO_WOLFSSL_STUB
7665
/* shows the number of renegotiation accepts attempted by CTX */
7666
long wolfSSL_CTX_sess_connect_renegotiate(WOLFSSL_CTX* ctx)
7667
{
7668
    WOLFSSL_STUB("wolfSSL_CTX_sess_connect_renegotiate");
7669
    (void)ctx;
7670
    return 0;
7671
}
7672
#endif
7673
7674
7675
#ifndef NO_WOLFSSL_STUB
7676
long wolfSSL_CTX_sess_hits(WOLFSSL_CTX* ctx)
7677
{
7678
    WOLFSSL_STUB("wolfSSL_CTX_sess_hits");
7679
    (void)ctx;
7680
    return 0;
7681
}
7682
#endif
7683
7684
7685
#ifndef NO_WOLFSSL_STUB
7686
long wolfSSL_CTX_sess_cb_hits(WOLFSSL_CTX* ctx)
7687
{
7688
    WOLFSSL_STUB("wolfSSL_CTX_sess_cb_hits");
7689
    (void)ctx;
7690
    return 0;
7691
}
7692
#endif
7693
7694
7695
#ifndef NO_WOLFSSL_STUB
7696
long wolfSSL_CTX_sess_cache_full(WOLFSSL_CTX* ctx)
7697
{
7698
    WOLFSSL_STUB("wolfSSL_CTX_sess_cache_full");
7699
    (void)ctx;
7700
    return 0;
7701
}
7702
#endif
7703
7704
7705
#ifndef NO_WOLFSSL_STUB
7706
long wolfSSL_CTX_sess_misses(WOLFSSL_CTX* ctx)
7707
{
7708
    WOLFSSL_STUB("wolfSSL_CTX_sess_misses");
7709
    (void)ctx;
7710
    return 0;
7711
}
7712
#endif
7713
7714
7715
#ifndef NO_WOLFSSL_STUB
7716
long wolfSSL_CTX_sess_timeouts(WOLFSSL_CTX* ctx)
7717
{
7718
    WOLFSSL_STUB("wolfSSL_CTX_sess_timeouts");
7719
    (void)ctx;
7720
    return 0;
7721
}
7722
#endif
7723
7724
#endif /* OPENSSL_EXTRA */
7725
7726
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_TLS_READ_AHEAD)
7727
int wolfSSL_get_read_ahead(const WOLFSSL* ssl)
7728
{
7729
    if (ssl == NULL) {
7730
        return WOLFSSL_FAILURE;
7731
    }
7732
7733
    return ssl->readAhead;
7734
}
7735
7736
7737
int wolfSSL_set_read_ahead(WOLFSSL* ssl, int v)
7738
{
7739
    if (ssl == NULL) {
7740
        return WOLFSSL_FAILURE;
7741
    }
7742
7743
    ssl->readAhead = (byte)v;
7744
7745
    return WOLFSSL_SUCCESS;
7746
}
7747
7748
7749
int wolfSSL_CTX_get_read_ahead(WOLFSSL_CTX* ctx)
7750
{
7751
    if (ctx == NULL) {
7752
        return WOLFSSL_FAILURE;
7753
    }
7754
7755
    return ctx->readAhead;
7756
}
7757
7758
7759
int wolfSSL_CTX_set_read_ahead(WOLFSSL_CTX* ctx, int v)
7760
{
7761
    if (ctx == NULL) {
7762
        return WOLFSSL_FAILURE;
7763
    }
7764
7765
    ctx->readAhead = (byte)v;
7766
7767
    return WOLFSSL_SUCCESS;
7768
}
7769
7770
/* Set the read-ahead receive window size. When read-ahead is enabled, a single
7771
 * recv() pulls in up to this many bytes:
7772
 *  - 0 (the default) requests one full record.
7773
 *  - A value larger than one record lets a single recv() coalesce several
7774
 *    back-to-back records.
7775
 *  - A value smaller than one record is honoured as-is, capping the receive
7776
 *    buffer's footprint when the peer's records are known to be small.
7777
 * 'len' is only a speculative window: a record larger than it is still received
7778
 * correctly, with the buffer grown on demand. Effective only when the library
7779
 * is built with read-ahead support (WOLFSSL_TLS_READ_AHEAD). Returns int rather
7780
 * than OpenSSL's void to match wolfSSL's other read-ahead setters; callers that
7781
 * ignore the return remain source-compatible. */
7782
int wolfSSL_CTX_set_default_read_buffer_len(WOLFSSL_CTX* ctx, size_t len)
7783
{
7784
    if (ctx == NULL) {
7785
        return WOLFSSL_FAILURE;
7786
    }
7787
7788
    /* 0 selects the default one-record window (matches OpenSSL, where 0 means
7789
     * "use the built-in default"). Otherwise clamp to a sane maximum so the
7790
     * stored window cannot overflow the signed arithmetic in the receive path
7791
     * (see WOLFSSL_MAX_READ_AHEAD_SZ). */
7792
    if (len == 0) {
7793
        len = WOLFSSL_READ_AHEAD_SZ;
7794
    }
7795
    else if (len > (size_t)WOLFSSL_MAX_READ_AHEAD_SZ) {
7796
        len = (size_t)WOLFSSL_MAX_READ_AHEAD_SZ;
7797
    }
7798
    ctx->readAheadSz = (word32)len;
7799
7800
    return WOLFSSL_SUCCESS;
7801
}
7802
7803
int wolfSSL_set_default_read_buffer_len(WOLFSSL* ssl, size_t len)
7804
{
7805
    if (ssl == NULL) {
7806
        return WOLFSSL_FAILURE;
7807
    }
7808
7809
    /* 0 selects the default one-record window (matches OpenSSL, where 0 means
7810
     * "use the built-in default"). Otherwise clamp to a sane maximum so the
7811
     * stored window cannot overflow the signed arithmetic in the receive path
7812
     * (see WOLFSSL_MAX_READ_AHEAD_SZ). */
7813
    if (len == 0) {
7814
        len = WOLFSSL_READ_AHEAD_SZ;
7815
    }
7816
    else if (len > (size_t)WOLFSSL_MAX_READ_AHEAD_SZ) {
7817
        len = (size_t)WOLFSSL_MAX_READ_AHEAD_SZ;
7818
    }
7819
    ssl->readAheadSz = (word32)len;
7820
7821
    return WOLFSSL_SUCCESS;
7822
}
7823
7824
long wolfSSL_CTX_get_default_read_buffer_len(WOLFSSL_CTX* ctx)
7825
{
7826
    if (ctx == NULL) {
7827
        return WOLFSSL_FAILURE;
7828
    }
7829
7830
    return (long)ctx->readAheadSz;
7831
}
7832
7833
long wolfSSL_get_default_read_buffer_len(const WOLFSSL* ssl)
7834
{
7835
    if (ssl == NULL) {
7836
        return WOLFSSL_FAILURE;
7837
    }
7838
7839
    return (long)ssl->readAheadSz;
7840
}
7841
#endif /* OPENSSL_EXTRA || WOLFSSL_TLS_READ_AHEAD */
7842
7843
#ifdef OPENSSL_EXTRA
7844
long wolfSSL_CTX_set_tlsext_opaque_prf_input_callback_arg(WOLFSSL_CTX* ctx,
7845
        void* arg)
7846
{
7847
    if (ctx == NULL) {
7848
        return WOLFSSL_FAILURE;
7849
    }
7850
7851
    ctx->userPRFArg = arg;
7852
    return WOLFSSL_SUCCESS;
7853
}
7854
7855
#endif /* OPENSSL_EXTRA */
7856
7857
7858
7859
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
7860
/* Free the dynamically allocated data.
7861
 *
7862
 * p  Pointer to dynamically allocated memory.
7863
 */
7864
void wolfSSL_OPENSSL_free(void* p)
7865
{
7866
    WOLFSSL_MSG("wolfSSL_OPENSSL_free");
7867
7868
    XFREE(p, NULL, DYNAMIC_TYPE_OPENSSL);
7869
}
7870
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
7871
7872
#ifdef OPENSSL_EXTRA
7873
7874
void *wolfSSL_OPENSSL_malloc(size_t a)
7875
{
7876
    return (void *)XMALLOC(a, NULL, DYNAMIC_TYPE_OPENSSL);
7877
}
7878
7879
int wolfSSL_OPENSSL_hexchar2int(unsigned char c)
7880
{
7881
    /* 'char' is unsigned on some platforms. */
7882
    return (int)(signed char)HexCharToByte((char)c);
7883
}
7884
7885
unsigned char *wolfSSL_OPENSSL_hexstr2buf(const char *str, long *len)
7886
{
7887
    unsigned char* targetBuf;
7888
    int srcDigitHigh = 0;
7889
    int srcDigitLow = 0;
7890
    size_t srcLen;
7891
    size_t srcIdx = 0;
7892
    long targetIdx = 0;
7893
7894
    srcLen = XSTRLEN(str);
7895
    targetBuf = (unsigned char*)XMALLOC(srcLen / 2, NULL, DYNAMIC_TYPE_OPENSSL);
7896
    if (targetBuf == NULL) {
7897
        return NULL;
7898
    }
7899
7900
    while (srcIdx < srcLen) {
7901
        if (str[srcIdx] == ':') {
7902
            srcIdx++;
7903
            continue;
7904
        }
7905
7906
        srcDigitHigh = wolfSSL_OPENSSL_hexchar2int((unsigned char)str[srcIdx++]);
7907
        srcDigitLow = wolfSSL_OPENSSL_hexchar2int((unsigned char)str[srcIdx++]);
7908
        if (srcDigitHigh < 0 || srcDigitLow < 0) {
7909
            WOLFSSL_MSG("Invalid hex character.");
7910
            XFREE(targetBuf, NULL, DYNAMIC_TYPE_OPENSSL);
7911
            return NULL;
7912
        }
7913
7914
        targetBuf[targetIdx++] = (unsigned char)((srcDigitHigh << 4) |
7915
                                                  srcDigitLow       );
7916
    }
7917
7918
    if (len != NULL)
7919
        *len = targetIdx;
7920
7921
    return targetBuf;
7922
}
7923
7924
int wolfSSL_OPENSSL_init_ssl(word64 opts, const WOLFSSL_INIT_SETTINGS *settings)
7925
{
7926
    (void)opts;
7927
    (void)settings;
7928
    return wolfSSL_library_init();
7929
}
7930
7931
int wolfSSL_OPENSSL_init_crypto(word64 opts,
7932
    const WOLFSSL_INIT_SETTINGS* settings)
7933
{
7934
    (void)opts;
7935
    (void)settings;
7936
    return wolfSSL_library_init();
7937
}
7938
7939
#endif /* OPENSSL_EXTRA */
7940
7941
7942
#ifdef HAVE_FUZZER
7943
void wolfSSL_SetFuzzerCb(WOLFSSL* ssl, CallbackFuzzer cbf, void* fCtx)
7944
{
7945
    if (ssl) {
7946
        ssl->fuzzerCb  = cbf;
7947
        ssl->fuzzerCtx = fCtx;
7948
    }
7949
}
7950
#endif
7951
7952
7953
#ifdef WOLFSSL_HAVE_WOLFSCEP
7954
    /* Used by autoconf to see if wolfSCEP is available */
7955
    void wolfSSL_wolfSCEP(void) {}
7956
#endif
7957
7958
7959
#ifdef WOLFSSL_HAVE_CERT_SERVICE
7960
    /* Used by autoconf to see if cert service is available */
7961
    void wolfSSL_cert_service(void) {}
7962
#endif
7963
7964
#if defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) || \
7965
    defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(HAVE_STUNNEL) || \
7966
    defined(WOLFSSL_NGINX) || defined(HAVE_POCO_LIB) || \
7967
    defined(WOLFSSL_HAPROXY)
7968
7969
    void wolfSSL_set_verify_depth(WOLFSSL *ssl, int depth)
7970
    {
7971
    #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
7972
        WOLFSSL_ENTER("wolfSSL_set_verify_depth");
7973
        ssl->options.verifyDepth = (byte)depth;
7974
    #endif
7975
    }
7976
7977
#endif /* OPENSSL_ALL || HAVE_LIGHTY || WOLFSSL_MYSQL_COMPATIBLE ||
7978
    HAVE_STUNNEL || WOLFSSL_NGINX || HAVE_POCO_LIB || WOLFSSL_HAPROXY */
7979
7980
#ifdef OPENSSL_EXTRA
7981
7982
/* wolfSSL uses negative values for error states. This function returns an
7983
 * unsigned type so the value returned is the absolute value of the error.
7984
 */
7985
7986
#endif /* OPENSSL_EXTRA */
7987
7988
#ifdef HAVE_EX_DATA_CRYPTO
7989
CRYPTO_EX_cb_ctx* crypto_ex_cb_ctx_session = NULL;
7990
7991
static int crypto_ex_cb_new(CRYPTO_EX_cb_ctx** dst, long ctx_l, void* ctx_ptr,
7992
        WOLFSSL_CRYPTO_EX_new* new_func, WOLFSSL_CRYPTO_EX_dup* dup_func,
7993
        WOLFSSL_CRYPTO_EX_free* free_func)
7994
{
7995
    CRYPTO_EX_cb_ctx* new_ctx = (CRYPTO_EX_cb_ctx*)XMALLOC(
7996
            sizeof(CRYPTO_EX_cb_ctx), NULL, DYNAMIC_TYPE_OPENSSL);
7997
    if (new_ctx == NULL)
7998
        return WOLFSSL_FATAL_ERROR;
7999
    new_ctx->ctx_l = ctx_l;
8000
    new_ctx->ctx_ptr = ctx_ptr;
8001
    new_ctx->new_func = new_func;
8002
    new_ctx->free_func = free_func;
8003
    new_ctx->dup_func = dup_func;
8004
    new_ctx->next = NULL;
8005
    /* Push to end of list */
8006
    while (*dst != NULL)
8007
        dst = &(*dst)->next;
8008
    *dst = new_ctx;
8009
    return 0;
8010
}
8011
8012
void crypto_ex_cb_free(CRYPTO_EX_cb_ctx* cb_ctx)
8013
{
8014
    while (cb_ctx != NULL) {
8015
        CRYPTO_EX_cb_ctx* next = cb_ctx->next;
8016
        XFREE(cb_ctx, NULL, DYNAMIC_TYPE_OPENSSL);
8017
        cb_ctx = next;
8018
    }
8019
}
8020
8021
void crypto_ex_cb_setup_new_data(void *new_obj, CRYPTO_EX_cb_ctx* cb_ctx,
8022
        WOLFSSL_CRYPTO_EX_DATA* ex_data)
8023
{
8024
    int idx = 0;
8025
    for (; cb_ctx != NULL; idx++, cb_ctx = cb_ctx->next) {
8026
        if (cb_ctx->new_func != NULL)
8027
            cb_ctx->new_func(new_obj, NULL, ex_data, idx, cb_ctx->ctx_l,
8028
                    cb_ctx->ctx_ptr);
8029
    }
8030
}
8031
8032
int crypto_ex_cb_dup_data(const WOLFSSL_CRYPTO_EX_DATA *in,
8033
        WOLFSSL_CRYPTO_EX_DATA *out, CRYPTO_EX_cb_ctx* cb_ctx)
8034
{
8035
    int idx = 0;
8036
    for (; cb_ctx != NULL; idx++, cb_ctx = cb_ctx->next) {
8037
        if (cb_ctx->dup_func != NULL) {
8038
            void* ptr = wolfSSL_CRYPTO_get_ex_data(in, idx);
8039
            if (!cb_ctx->dup_func(out, in,
8040
                    &ptr, idx,
8041
                    cb_ctx->ctx_l, cb_ctx->ctx_ptr)) {
8042
                return WOLFSSL_FAILURE;
8043
            }
8044
            wolfSSL_CRYPTO_set_ex_data(out, idx, ptr);
8045
        }
8046
    }
8047
    return WOLFSSL_SUCCESS;
8048
}
8049
8050
void crypto_ex_cb_free_data(void *obj, CRYPTO_EX_cb_ctx* cb_ctx,
8051
        WOLFSSL_CRYPTO_EX_DATA* ex_data)
8052
{
8053
    int idx = 0;
8054
    for (; cb_ctx != NULL; idx++, cb_ctx = cb_ctx->next) {
8055
        if (cb_ctx->free_func != NULL)
8056
            cb_ctx->free_func(obj, NULL, ex_data, idx, cb_ctx->ctx_l,
8057
                    cb_ctx->ctx_ptr);
8058
    }
8059
}
8060
8061
/**
8062
 * wolfssl_local_get_ex_new_index is a helper function for the following
8063
 * xx_get_ex_new_index functions:
8064
 *  - wolfSSL_CRYPTO_get_ex_new_index
8065
 *  - wolfSSL_CTX_get_ex_new_index
8066
 *  - wolfSSL_get_ex_new_index
8067
 * Issues a unique index number for the specified class-index.
8068
 * Returns an index number greater or equal to zero on success,
8069
 * -1 on failure.
8070
 */
8071
int wolfssl_local_get_ex_new_index(int class_index, long ctx_l, void* ctx_ptr,
8072
        WOLFSSL_CRYPTO_EX_new* new_func, WOLFSSL_CRYPTO_EX_dup* dup_func,
8073
        WOLFSSL_CRYPTO_EX_free* free_func)
8074
{
8075
    /* index counter for each class index*/
8076
    static int ctx_idx = 0;
8077
    static int ssl_idx = 0;
8078
    static int ssl_session_idx = 0;
8079
    static int x509_idx = 0;
8080
8081
    int idx = -1;
8082
8083
    switch(class_index) {
8084
        case WOLF_CRYPTO_EX_INDEX_SSL:
8085
            WOLFSSL_CRYPTO_EX_DATA_IGNORE_PARAMS(ctx_l, ctx_ptr, new_func,
8086
                    dup_func, free_func);
8087
            idx = ssl_idx++;
8088
            break;
8089
        case WOLF_CRYPTO_EX_INDEX_SSL_CTX:
8090
            WOLFSSL_CRYPTO_EX_DATA_IGNORE_PARAMS(ctx_l, ctx_ptr, new_func,
8091
                    dup_func, free_func);
8092
            idx = ctx_idx++;
8093
            break;
8094
        case WOLF_CRYPTO_EX_INDEX_X509:
8095
            WOLFSSL_CRYPTO_EX_DATA_IGNORE_PARAMS(ctx_l, ctx_ptr, new_func,
8096
                    dup_func, free_func);
8097
            idx = x509_idx++;
8098
            break;
8099
        case WOLF_CRYPTO_EX_INDEX_SSL_SESSION:
8100
            if (crypto_ex_cb_new(&crypto_ex_cb_ctx_session, ctx_l, ctx_ptr,
8101
                    new_func, dup_func, free_func) != 0)
8102
                return WOLFSSL_FATAL_ERROR;
8103
            idx = ssl_session_idx++;
8104
            break;
8105
        /* following class indexes are not supoprted */
8106
        case WOLF_CRYPTO_EX_INDEX_X509_STORE:
8107
        case WOLF_CRYPTO_EX_INDEX_X509_STORE_CTX:
8108
        case WOLF_CRYPTO_EX_INDEX_DH:
8109
        case WOLF_CRYPTO_EX_INDEX_DSA:
8110
        case WOLF_CRYPTO_EX_INDEX_EC_KEY:
8111
        case WOLF_CRYPTO_EX_INDEX_RSA:
8112
        case WOLF_CRYPTO_EX_INDEX_ENGINE:
8113
        case WOLF_CRYPTO_EX_INDEX_UI:
8114
        case WOLF_CRYPTO_EX_INDEX_BIO:
8115
        case WOLF_CRYPTO_EX_INDEX_APP:
8116
        case WOLF_CRYPTO_EX_INDEX_UI_METHOD:
8117
        case WOLF_CRYPTO_EX_INDEX_DRBG:
8118
        default:
8119
            break;
8120
    }
8121
    if (idx >= MAX_EX_DATA)
8122
        return WOLFSSL_FATAL_ERROR;
8123
    return idx;
8124
}
8125
#endif /* HAVE_EX_DATA_CRYPTO */
8126
8127
#ifdef HAVE_EX_DATA_CRYPTO
8128
int wolfSSL_CTX_get_ex_new_index(long idx, void* arg,
8129
                                 WOLFSSL_CRYPTO_EX_new* new_func,
8130
                                 WOLFSSL_CRYPTO_EX_dup* dup_func,
8131
                                 WOLFSSL_CRYPTO_EX_free* free_func)
8132
{
8133
8134
    WOLFSSL_ENTER("wolfSSL_CTX_get_ex_new_index");
8135
8136
    return wolfssl_local_get_ex_new_index(WOLF_CRYPTO_EX_INDEX_SSL_CTX, idx,
8137
                                    arg, new_func, dup_func, free_func);
8138
}
8139
8140
/* Return the index that can be used for the WOLFSSL structure to store
8141
 * application data.
8142
 *
8143
 */
8144
int wolfSSL_get_ex_new_index(long argValue, void* arg,
8145
        WOLFSSL_CRYPTO_EX_new* cb1, WOLFSSL_CRYPTO_EX_dup* cb2,
8146
        WOLFSSL_CRYPTO_EX_free* cb3)
8147
{
8148
    WOLFSSL_ENTER("wolfSSL_get_ex_new_index");
8149
8150
    return wolfssl_local_get_ex_new_index(WOLF_CRYPTO_EX_INDEX_SSL, argValue,
8151
            arg, cb1, cb2, cb3);
8152
}
8153
#endif /* HAVE_EX_DATA_CRYPTO */
8154
8155
#ifdef OPENSSL_EXTRA
8156
void* wolfSSL_CTX_get_ex_data(const WOLFSSL_CTX* ctx, int idx)
8157
{
8158
    WOLFSSL_ENTER("wolfSSL_CTX_get_ex_data");
8159
#ifdef HAVE_EX_DATA
8160
    if (ctx != NULL) {
8161
        return wolfSSL_CRYPTO_get_ex_data(&ctx->ex_data, idx);
8162
    }
8163
#else
8164
    (void)ctx;
8165
    (void)idx;
8166
#endif
8167
    return NULL;
8168
}
8169
8170
int wolfSSL_CTX_set_ex_data(WOLFSSL_CTX* ctx, int idx, void* data)
8171
{
8172
    WOLFSSL_ENTER("wolfSSL_CTX_set_ex_data");
8173
#ifdef HAVE_EX_DATA
8174
    if (ctx != NULL) {
8175
        return wolfSSL_CRYPTO_set_ex_data(&ctx->ex_data, idx, data);
8176
    }
8177
#else
8178
    (void)ctx;
8179
    (void)idx;
8180
    (void)data;
8181
#endif
8182
    return WOLFSSL_FAILURE;
8183
}
8184
8185
#ifdef HAVE_EX_DATA_CLEANUP_HOOKS
8186
int wolfSSL_CTX_set_ex_data_with_cleanup(
8187
    WOLFSSL_CTX* ctx,
8188
    int idx,
8189
    void* data,
8190
    wolfSSL_ex_data_cleanup_routine_t cleanup_routine)
8191
{
8192
    WOLFSSL_ENTER("wolfSSL_CTX_set_ex_data_with_cleanup");
8193
    if (ctx != NULL) {
8194
        return wolfSSL_CRYPTO_set_ex_data_with_cleanup(&ctx->ex_data, idx, data,
8195
                                                       cleanup_routine);
8196
    }
8197
    return WOLFSSL_FAILURE;
8198
}
8199
#endif /* HAVE_EX_DATA_CLEANUP_HOOKS */
8200
#endif /* OPENSSL_EXTRA */
8201
8202
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
8203
8204
/* Returns char* to app data stored in ex[0].
8205
 *
8206
 * ssl WOLFSSL structure to get app data from
8207
 */
8208
void* wolfSSL_get_app_data(const WOLFSSL *ssl)
8209
{
8210
    /* checkout exdata stuff... */
8211
    WOLFSSL_ENTER("wolfSSL_get_app_data");
8212
8213
    return wolfSSL_get_ex_data(ssl, 0);
8214
}
8215
8216
8217
/* Set ex array 0 to have app data
8218
 *
8219
 * ssl WOLFSSL struct to set app data in
8220
 * arg data to be stored
8221
 *
8222
 * Returns WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on failure
8223
 */
8224
int wolfSSL_set_app_data(WOLFSSL *ssl, void* arg) {
8225
    WOLFSSL_ENTER("wolfSSL_set_app_data");
8226
8227
    return wolfSSL_set_ex_data(ssl, 0, arg);
8228
}
8229
8230
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
8231
8232
int wolfSSL_set_ex_data(WOLFSSL* ssl, int idx, void* data)
8233
0
{
8234
0
    WOLFSSL_ENTER("wolfSSL_set_ex_data");
8235
#ifdef HAVE_EX_DATA
8236
    if (ssl != NULL) {
8237
        return wolfSSL_CRYPTO_set_ex_data(&ssl->ex_data, idx, data);
8238
    }
8239
#else
8240
0
    WOLFSSL_MSG("HAVE_EX_DATA macro is not defined");
8241
0
    (void)ssl;
8242
0
    (void)idx;
8243
0
    (void)data;
8244
0
#endif
8245
0
    return WOLFSSL_FAILURE;
8246
0
}
8247
8248
#ifdef HAVE_EX_DATA_CLEANUP_HOOKS
8249
int wolfSSL_set_ex_data_with_cleanup(
8250
    WOLFSSL* ssl,
8251
    int idx,
8252
    void* data,
8253
    wolfSSL_ex_data_cleanup_routine_t cleanup_routine)
8254
{
8255
    WOLFSSL_ENTER("wolfSSL_set_ex_data_with_cleanup");
8256
    if (ssl != NULL)
8257
    {
8258
        return wolfSSL_CRYPTO_set_ex_data_with_cleanup(&ssl->ex_data, idx, data,
8259
                                                       cleanup_routine);
8260
    }
8261
    return WOLFSSL_FAILURE;
8262
}
8263
#endif /* HAVE_EX_DATA_CLEANUP_HOOKS */
8264
8265
void* wolfSSL_get_ex_data(const WOLFSSL* ssl, int idx)
8266
0
{
8267
0
    WOLFSSL_ENTER("wolfSSL_get_ex_data");
8268
#ifdef HAVE_EX_DATA
8269
    if (ssl != NULL) {
8270
        return wolfSSL_CRYPTO_get_ex_data(&ssl->ex_data, idx);
8271
    }
8272
#else
8273
0
    WOLFSSL_MSG("HAVE_EX_DATA macro is not defined");
8274
0
    (void)ssl;
8275
0
    (void)idx;
8276
0
#endif
8277
0
    return 0;
8278
0
}
8279
8280
#if defined(HAVE_LIGHTY) || defined(HAVE_STUNNEL) \
8281
    || defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(OPENSSL_EXTRA)
8282
8283
#ifdef WOLFSSL_TLS_ST_OK
8284
/* The OpenSSL compat TLS_ST_OK/SSL_ST_OK constants (wolfssl/openssl/ssl.h)
8285
 * duplicate HANDSHAKE_DONE from the internal 'enum states' returned below;
8286
 * fail the build if the enum ever drifts. */
8287
wc_static_assert(WOLFSSL_TLS_ST_OK == HANDSHAKE_DONE);
8288
#endif
8289
8290
/* returns the enum value associated with handshake state
8291
 *
8292
 * ssl the WOLFSSL structure to get state of
8293
 */
8294
int wolfSSL_get_state(const WOLFSSL* ssl)
8295
{
8296
    WOLFSSL_ENTER("wolfSSL_get_state");
8297
8298
    if (ssl == NULL) {
8299
        WOLFSSL_MSG("Null argument passed in");
8300
        return WOLFSSL_FAILURE;
8301
    }
8302
8303
    return ssl->options.handShakeState;
8304
}
8305
#endif /* HAVE_LIGHTY || HAVE_STUNNEL || WOLFSSL_MYSQL_COMPATIBLE */
8306
8307
#ifdef OPENSSL_EXTRA
8308
void wolfSSL_certs_clear(WOLFSSL* ssl)
8309
{
8310
    WOLFSSL_ENTER("wolfSSL_certs_clear");
8311
8312
    if (ssl == NULL)
8313
        return;
8314
8315
    /* ctx still owns certificate, certChain, key, dh, and cm */
8316
    if (ssl->buffers.weOwnCert) {
8317
        FreeDer(&ssl->buffers.certificate);
8318
        ssl->buffers.weOwnCert = 0;
8319
    }
8320
    ssl->buffers.certificate = NULL;
8321
    if (ssl->buffers.weOwnCertChain) {
8322
        FreeDer(&ssl->buffers.certChain);
8323
        ssl->buffers.weOwnCertChain = 0;
8324
    }
8325
    ssl->buffers.certChain = NULL;
8326
#ifdef WOLFSSL_TLS13
8327
    ssl->buffers.certChainCnt = 0;
8328
#endif
8329
    if (ssl->buffers.weOwnKey) {
8330
        FreeDer(&ssl->buffers.key);
8331
    #ifdef WOLFSSL_BLIND_PRIVATE_KEY
8332
        FreeDer(&ssl->buffers.keyMask);
8333
    #endif
8334
        ssl->buffers.weOwnKey = 0;
8335
    }
8336
    ssl->buffers.key      = NULL;
8337
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
8338
    ssl->buffers.keyMask  = NULL;
8339
#endif
8340
    ssl->buffers.keyType  = 0;
8341
    ssl->buffers.keyId    = 0;
8342
    ssl->buffers.keyLabel = 0;
8343
    ssl->buffers.keySz    = 0;
8344
    ssl->buffers.keyDevId = 0;
8345
#ifdef WOLFSSL_DUAL_ALG_CERTS
8346
    if (ssl->buffers.weOwnAltKey) {
8347
        FreeDer(&ssl->buffers.altKey);
8348
    #ifdef WOLFSSL_BLIND_PRIVATE_KEY
8349
        FreeDer(&ssl->buffers.altKeyMask);
8350
    #endif
8351
        ssl->buffers.weOwnAltKey = 0;
8352
    }
8353
    ssl->buffers.altKey     = NULL;
8354
#ifdef WOLFSSL_BLIND_PRIVATE_KEY
8355
    ssl->buffers.altKeyMask = NULL;
8356
#endif
8357
#endif /* WOLFSSL_DUAL_ALG_CERTS */
8358
}
8359
#endif
8360
8361
#if defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || defined(WOLFSSL_HAPROXY) \
8362
    || defined(WOLFSSL_NGINX) || defined(WOLFSSL_QT)
8363
8364
long wolfSSL_ctrl(WOLFSSL* ssl, int cmd, long opt, void* pt)
8365
{
8366
    WOLFSSL_ENTER("wolfSSL_ctrl");
8367
    if (ssl == NULL)
8368
        return BAD_FUNC_ARG;
8369
8370
    switch (cmd) {
8371
        #if defined(WOLFSSL_NGINX) || defined(WOLFSSL_QT) || \
8372
            defined(OPENSSL_ALL)
8373
        #ifdef HAVE_SNI
8374
        case SSL_CTRL_SET_TLSEXT_HOSTNAME:
8375
            WOLFSSL_MSG("Entering Case: SSL_CTRL_SET_TLSEXT_HOSTNAME.");
8376
            if (pt == NULL) {
8377
                WOLFSSL_MSG("Passed in NULL Host Name.");
8378
                break;
8379
            }
8380
            return wolfSSL_set_tlsext_host_name(ssl, (const char*) pt);
8381
        #endif /* HAVE_SNI */
8382
        #endif /* WOLFSSL_NGINX || WOLFSSL_QT || OPENSSL_ALL */
8383
        default:
8384
            WOLFSSL_MSG("Case not implemented.");
8385
    }
8386
    (void)opt;
8387
    (void)pt;
8388
    return WOLFSSL_FAILURE;
8389
}
8390
8391
long wolfSSL_CTX_ctrl(WOLFSSL_CTX* ctx, int cmd, long opt, void* pt)
8392
{
8393
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
8394
    long ctrl_opt;
8395
#endif
8396
    long ret = WOLFSSL_SUCCESS;
8397
8398
    WOLFSSL_ENTER("wolfSSL_CTX_ctrl");
8399
    if (ctx == NULL)
8400
        return WOLFSSL_FAILURE;
8401
8402
    switch (cmd) {
8403
    case SSL_CTRL_CHAIN:
8404
#ifdef SESSION_CERTS
8405
    {
8406
        /*
8407
         * We don't care about opt here because a copy of the certificate is
8408
         * stored anyway so increasing the reference counter is not necessary.
8409
         * Just check to make sure that it is set to one of the correct values.
8410
         */
8411
        WOLF_STACK_OF(WOLFSSL_X509)* sk = (WOLF_STACK_OF(WOLFSSL_X509)*) pt;
8412
        WOLFSSL_X509* x509;
8413
        int i;
8414
        if (opt != 0 && opt != 1) {
8415
            ret = WOLFSSL_FAILURE;
8416
            break;
8417
        }
8418
        /* Clear certificate chain */
8419
        FreeDer(&ctx->certChain);
8420
        if (sk) {
8421
            for (i = 0; i < wolfSSL_sk_X509_num(sk); i++) {
8422
                x509 = wolfSSL_sk_X509_value(sk, i);
8423
                /* Prevent wolfSSL_CTX_add_extra_chain_cert from freeing cert */
8424
                if (wolfSSL_X509_up_ref(x509) != 1) {
8425
                    WOLFSSL_MSG("Error increasing reference count");
8426
                    continue;
8427
                }
8428
                if (wolfSSL_CTX_add_extra_chain_cert(ctx, x509) !=
8429
                        WOLFSSL_SUCCESS) {
8430
                    WOLFSSL_MSG("Error adding certificate to context");
8431
                    /* Decrease reference count on failure */
8432
                    wolfSSL_X509_free(x509);
8433
                    x509 = NULL;
8434
                }
8435
            }
8436
        }
8437
        /* Free previous chain */
8438
        wolfSSL_sk_X509_pop_free(ctx->x509Chain, NULL);
8439
        ctx->x509Chain = sk;
8440
        if (sk && opt == 1) {
8441
            /* up all refs when opt == 1 */
8442
            for (i = 0; i < wolfSSL_sk_X509_num(sk); i++) {
8443
                x509 = wolfSSL_sk_X509_value(sk, i);
8444
                if (wolfSSL_X509_up_ref(x509) != 1) {
8445
                    WOLFSSL_MSG("Error increasing reference count");
8446
                    continue;
8447
                }
8448
            }
8449
        }
8450
    }
8451
#else
8452
        WOLFSSL_MSG("Session certificates not compiled in");
8453
        ret = WOLFSSL_FAILURE;
8454
#endif
8455
        break;
8456
8457
#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
8458
    case SSL_CTRL_OPTIONS:
8459
        WOLFSSL_MSG("Entering Case: SSL_CTRL_OPTIONS.");
8460
        ctrl_opt = wolfSSL_CTX_set_options(ctx, opt);
8461
8462
        #ifdef WOLFSSL_QT
8463
        /* Set whether to use client or server cipher preference */
8464
        if ((ctrl_opt & WOLFSSL_OP_CIPHER_SERVER_PREFERENCE)
8465
                     == WOLFSSL_OP_CIPHER_SERVER_PREFERENCE) {
8466
            WOLFSSL_MSG("Using Server's Cipher Preference.");
8467
            ctx->useClientOrder = 0;
8468
        } else {
8469
            WOLFSSL_MSG("Using Client's Cipher Preference.");
8470
            ctx->useClientOrder = 1;
8471
        }
8472
        #endif /* WOLFSSL_QT */
8473
8474
        return ctrl_opt;
8475
#endif /* OPENSSL_EXTRA || HAVE_WEBSERVER */
8476
    case SSL_CTRL_EXTRA_CHAIN_CERT:
8477
        WOLFSSL_MSG("Entering Case: SSL_CTRL_EXTRA_CHAIN_CERT.");
8478
        if (pt == NULL) {
8479
            WOLFSSL_MSG("Passed in x509 pointer NULL.");
8480
            ret = WOLFSSL_FAILURE;
8481
            break;
8482
        }
8483
        return wolfSSL_CTX_add_extra_chain_cert(ctx, (WOLFSSL_X509*)pt);
8484
8485
#ifndef NO_DH
8486
    case SSL_CTRL_SET_TMP_DH:
8487
        WOLFSSL_MSG("Entering Case: SSL_CTRL_SET_TMP_DH.");
8488
        if (pt == NULL) {
8489
            WOLFSSL_MSG("Passed in DH pointer NULL.");
8490
            ret = WOLFSSL_FAILURE;
8491
            break;
8492
        }
8493
        return wolfSSL_CTX_set_tmp_dh(ctx, (WOLFSSL_DH*)pt);
8494
#endif
8495
8496
#ifdef HAVE_ECC
8497
    case SSL_CTRL_SET_TMP_ECDH:
8498
        WOLFSSL_MSG("Entering Case: SSL_CTRL_SET_TMP_ECDH.");
8499
        if (pt == NULL) {
8500
            WOLFSSL_MSG("Passed in ECDH pointer NULL.");
8501
            ret = WOLFSSL_FAILURE;
8502
            break;
8503
        }
8504
        return wolfSSL_SSL_CTX_set_tmp_ecdh(ctx, (WOLFSSL_EC_KEY*)pt);
8505
#endif
8506
    case SSL_CTRL_MODE:
8507
        wolfSSL_CTX_set_mode(ctx,opt);
8508
        break;
8509
    case SSL_CTRL_SET_MIN_PROTO_VERSION:
8510
        WOLFSSL_MSG("set min proto version");
8511
        return wolfSSL_CTX_set_min_proto_version(ctx, (int)opt);
8512
    case SSL_CTRL_SET_MAX_PROTO_VERSION:
8513
        WOLFSSL_MSG("set max proto version");
8514
        return wolfSSL_CTX_set_max_proto_version(ctx, (int)opt);
8515
    case SSL_CTRL_GET_MIN_PROTO_VERSION:
8516
        WOLFSSL_MSG("get min proto version");
8517
        return wolfSSL_CTX_get_min_proto_version(ctx);
8518
    case SSL_CTRL_GET_MAX_PROTO_VERSION:
8519
        WOLFSSL_MSG("get max proto version");
8520
        return wolfSSL_CTX_get_max_proto_version(ctx);
8521
    default:
8522
        WOLFSSL_MSG("CTX_ctrl cmd not implemented");
8523
        ret = WOLFSSL_FAILURE;
8524
        break;
8525
    }
8526
8527
    (void)ctx;
8528
    (void)cmd;
8529
    (void)opt;
8530
    (void)pt;
8531
    WOLFSSL_LEAVE("wolfSSL_CTX_ctrl", (int)ret);
8532
    return ret;
8533
}
8534
8535
#ifndef NO_WOLFSSL_STUB
8536
long wolfSSL_CTX_callback_ctrl(WOLFSSL_CTX* ctx, int cmd, void (*fp)(void))
8537
{
8538
    (void) ctx;
8539
    (void) cmd;
8540
    (void) fp;
8541
    WOLFSSL_STUB("wolfSSL_CTX_callback_ctrl");
8542
    return WOLFSSL_FAILURE;
8543
8544
}
8545
#endif /* NO_WOLFSSL_STUB */
8546
8547
8548
#endif /* OPENSSL_ALL || WOLFSSL_ASIO || WOLFSSL_HAPROXY || WOLFSSL_QT */
8549
8550
8551
/* stunnel compatibility functions*/
8552
#if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && \
8553
    (defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \
8554
     defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \
8555
     defined(WOLFSSL_OPENSSH)))
8556
8557
#ifndef NO_FILESYSTEM
8558
/***TBD ***/
8559
void wolfSSL_print_all_errors_fp(XFILE fp)
8560
{
8561
    (void)fp;
8562
}
8563
#endif /* !NO_FILESYSTEM */
8564
8565
#endif /* OPENSSL_ALL || OPENSSL_EXTRA || HAVE_STUNNEL || WOLFSSL_NGINX ||
8566
    HAVE_LIGHTY || WOLFSSL_HAPROXY || WOLFSSL_OPENSSH */
8567
8568
/* Note: This is a huge section of API's - through
8569
 *       wolfSSL_X509_OBJECT_get0_X509_CRL */
8570
#if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA)
8571
8572
#if defined(USE_WOLFSSL_MEMORY) && !defined(WOLFSSL_DEBUG_MEMORY) && \
8573
    !defined(WOLFSSL_STATIC_MEMORY)
8574
static wolfSSL_OSSL_Malloc_cb  ossl_malloc  = NULL;
8575
static wolfSSL_OSSL_Free_cb    ossl_free    = NULL;
8576
static wolfSSL_OSSL_Realloc_cb ossl_realloc = NULL;
8577
8578
static void* OSSL_Malloc(size_t size)
8579
{
8580
    if (ossl_malloc != NULL)
8581
        return ossl_malloc(size, NULL, 0);
8582
    else
8583
        return NULL;
8584
}
8585
8586
static void  OSSL_Free(void *ptr)
8587
{
8588
    if (ossl_free != NULL)
8589
        ossl_free(ptr, NULL, 0);
8590
}
8591
8592
static void* OSSL_Realloc(void *ptr, size_t size)
8593
{
8594
    if (ossl_realloc != NULL)
8595
        return ossl_realloc(ptr, size, NULL, 0);
8596
    else
8597
        return NULL;
8598
}
8599
#endif /* USE_WOLFSSL_MEMORY && !WOLFSSL_DEBUG_MEMORY &&
8600
        * !WOLFSSL_STATIC_MEMORY */
8601
8602
int wolfSSL_CRYPTO_set_mem_functions(
8603
        wolfSSL_OSSL_Malloc_cb  m,
8604
        wolfSSL_OSSL_Realloc_cb r,
8605
        wolfSSL_OSSL_Free_cb    f)
8606
{
8607
#if defined(USE_WOLFSSL_MEMORY) && !defined(WOLFSSL_STATIC_MEMORY)
8608
#ifdef WOLFSSL_DEBUG_MEMORY
8609
    WOLFSSL_MSG("mem functions will receive function name instead of "
8610
                "file name");
8611
    if (wolfSSL_SetAllocators((wolfSSL_Malloc_cb)m, (wolfSSL_Free_cb)f,
8612
            (wolfSSL_Realloc_cb)r) == 0)
8613
        return WOLFSSL_SUCCESS;
8614
#else
8615
    WOLFSSL_MSG("wolfSSL was compiled without WOLFSSL_DEBUG_MEMORY mem "
8616
                "functions will receive a NULL file name and 0 for the "
8617
                "line number.");
8618
    if (wolfSSL_SetAllocators((wolfSSL_Malloc_cb)OSSL_Malloc,
8619
           (wolfSSL_Free_cb)OSSL_Free, (wolfSSL_Realloc_cb)OSSL_Realloc) == 0) {
8620
        ossl_malloc = m;
8621
        ossl_free = f;
8622
        ossl_realloc = r;
8623
        return WOLFSSL_SUCCESS;
8624
    }
8625
#endif
8626
    else
8627
        return WOLFSSL_FAILURE;
8628
#else
8629
    (void)m;
8630
    (void)r;
8631
    (void)f;
8632
    WOLFSSL_MSG("wolfSSL allocator callback functions not compiled in");
8633
    return WOLFSSL_FAILURE;
8634
#endif
8635
}
8636
8637
int wolfSSL_FIPS_mode(void)
8638
{
8639
#ifdef HAVE_FIPS
8640
    return 1;
8641
#else
8642
    return 0;
8643
#endif
8644
}
8645
8646
int wolfSSL_FIPS_mode_set(int r)
8647
{
8648
#ifdef HAVE_FIPS
8649
    if (r == 0) {
8650
        WOLFSSL_MSG("Cannot disable FIPS at runtime.");
8651
        return WOLFSSL_FAILURE;
8652
    }
8653
    return WOLFSSL_SUCCESS;
8654
#else
8655
    if (r == 0) {
8656
        return WOLFSSL_SUCCESS;
8657
    }
8658
    WOLFSSL_MSG("Cannot enable FIPS. This isn't the wolfSSL FIPS code.");
8659
    return WOLFSSL_FAILURE;
8660
#endif
8661
}
8662
8663
int wolfSSL_CIPHER_get_bits(const WOLFSSL_CIPHER *c, int *alg_bits)
8664
{
8665
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
8666
    WOLFSSL_ENTER("wolfSSL_CIPHER_get_bits");
8667
8668
    #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL)
8669
    (void)alg_bits;
8670
    if (c!= NULL)
8671
        ret = c->bits;
8672
    #else
8673
    if (c != NULL && c->ssl != NULL) {
8674
        ret = 8 * c->ssl->specs.key_size;
8675
        if (alg_bits != NULL) {
8676
            *alg_bits = ret;
8677
        }
8678
    }
8679
    #endif
8680
    return ret;
8681
}
8682
8683
8684
WOLFSSL_CTX* wolfSSL_set_SSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx)
8685
{
8686
    int ret;
8687
    /* This method requires some explanation. Its sibling is
8688
     *   int SetSSL_CTX(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup)
8689
     * which re-inits the WOLFSSL* with all settings in the new CTX.
8690
     * That one is the right one to use *before* a handshake is started.
8691
     *
8692
     * This method was added by OpenSSL to be used *during* the handshake, e.g.
8693
     * when a server inspects the SNI in a ClientHello callback and
8694
     * decides which set of certificates to use.
8695
     *
8696
     * Since, at the time the SNI callback is run, some decisions on
8697
     * Extensions or the ServerHello might already have been taken, this
8698
     * method is very restricted in what it does:
8699
     * - changing the server certificate(s)
8700
     * - changing the server id for session handling
8701
     * and everything else in WOLFSSL* needs to remain untouched.
8702
     *
8703
     * SECURITY: swapping ssl->ctx switches cm-resolved settings (CA store,
8704
     * CRL, OCSP) to the new CTX but leaves ssl-cached ones (verify mode and
8705
     * callback, minDowngrade, key-size minimums, suites, version bounds)
8706
     * pinned to the original. SNI callbacks must re-apply those ssl-level
8707
     * settings explicitly; CRL/OCSP isolation requires an SSL-local store.
8708
     */
8709
    WOLFSSL_ENTER("wolfSSL_set_SSL_CTX");
8710
    if (ssl == NULL || ctx == NULL)
8711
        return NULL;
8712
    if (ssl->ctx == ctx)
8713
        return ssl->ctx;
8714
8715
    if (ctx->suites == NULL) {
8716
        /* suites */
8717
        if (AllocateCtxSuites(ctx) != 0)
8718
            return NULL;
8719
        InitSSL_CTX_Suites(ctx);
8720
    }
8721
8722
    wolfSSL_RefWithMutexInc(&ctx->ref, &ret);
8723
#ifdef WOLFSSL_REFCNT_ERROR_RETURN
8724
    if (ret != 0) {
8725
        /* can only fail on serious stuff, like mutex not working
8726
         * or ctx refcount out of whack. */
8727
        return NULL;
8728
    }
8729
#else
8730
    (void)ret;
8731
#endif
8732
    if (ssl->ctx != NULL)
8733
        wolfSSL_CTX_free(ssl->ctx);
8734
    ssl->ctx = ctx;
8735
8736
#ifndef NO_CERTS
8737
#ifdef WOLFSSL_COPY_CERT
8738
    /* If WOLFSSL_COPY_CERT defined, always make new copy of cert from ctx */
8739
    if (ctx->certificate != NULL) {
8740
        if (ssl->buffers.certificate != NULL) {
8741
            FreeDer(&ssl->buffers.certificate);
8742
            ssl->buffers.certificate = NULL;
8743
        }
8744
        ret = AllocCopyDer(&ssl->buffers.certificate, ctx->certificate->buffer,
8745
            ctx->certificate->length, ctx->certificate->type,
8746
            ctx->certificate->heap);
8747
        if (ret != 0) {
8748
            ssl->buffers.weOwnCert = 0;
8749
            return NULL;
8750
        }
8751
8752
        ssl->buffers.weOwnCert = 1;
8753
    }
8754
    if (ctx->certChain != NULL) {
8755
        if (ssl->buffers.certChain != NULL) {
8756
            FreeDer(&ssl->buffers.certChain);
8757
            ssl->buffers.certChain = NULL;
8758
        }
8759
        ret = AllocCopyDer(&ssl->buffers.certChain, ctx->certChain->buffer,
8760
            ctx->certChain->length, ctx->certChain->type,
8761
            ctx->certChain->heap);
8762
        if (ret != 0) {
8763
            ssl->buffers.weOwnCertChain = 0;
8764
            return NULL;
8765
        }
8766
8767
        ssl->buffers.weOwnCertChain = 1;
8768
    }
8769
#else
8770
    /* ctx owns certificate, certChain and key */
8771
    ssl->buffers.certificate = ctx->certificate;
8772
    ssl->buffers.certChain = ctx->certChain;
8773
#endif
8774
#ifdef WOLFSSL_TLS13
8775
    ssl->buffers.certChainCnt = ctx->certChainCnt;
8776
#endif
8777
#ifndef WOLFSSL_BLIND_PRIVATE_KEY
8778
#ifdef WOLFSSL_COPY_KEY
8779
    if (ssl->buffers.key != NULL && ssl->buffers.weOwnKey) {
8780
        FreeDer(&ssl->buffers.key);
8781
    }
8782
    if (ctx->privateKey != NULL) {
8783
        ret = AllocCopyDer(&ssl->buffers.key, ctx->privateKey->buffer,
8784
            ctx->privateKey->length, ctx->privateKey->type,
8785
            ctx->privateKey->heap);
8786
        if (ret != 0) {
8787
            ssl->buffers.weOwnKey = 0;
8788
            return NULL;
8789
        }
8790
        ssl->buffers.weOwnKey = 1;
8791
    }
8792
    else {
8793
        ssl->buffers.key      = ctx->privateKey;
8794
    }
8795
#else
8796
    ssl->buffers.key      = ctx->privateKey;
8797
#endif
8798
#else
8799
    if (ctx->privateKey != NULL) {
8800
        if (ssl->buffers.key != NULL && ssl->buffers.weOwnKey) {
8801
            FreeDer(&ssl->buffers.key);
8802
        }
8803
        ret = AllocCopyDer(&ssl->buffers.key, ctx->privateKey->buffer,
8804
            ctx->privateKey->length, ctx->privateKey->type,
8805
            ctx->privateKey->heap);
8806
        if (ret != 0) {
8807
            return NULL;
8808
        }
8809
        /* Blind the private key for the SSL with new random mask. */
8810
        wolfssl_priv_der_blind_toggle(ssl->buffers.key, ctx->privateKeyMask);
8811
        ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.key,
8812
            &ssl->buffers.keyMask);
8813
        if (ret != 0) {
8814
            return NULL;
8815
        }
8816
    }
8817
#endif
8818
    ssl->buffers.keyType  = ctx->privateKeyType;
8819
    ssl->buffers.keyId    = ctx->privateKeyId;
8820
    ssl->buffers.keyLabel = ctx->privateKeyLabel;
8821
    ssl->buffers.keySz    = ctx->privateKeySz;
8822
    ssl->buffers.keyDevId = ctx->privateKeyDevId;
8823
    /* flags indicating what certs/keys are available */
8824
    ssl->options.haveRSA          = ctx->haveRSA;
8825
    ssl->options.haveDH           = ctx->haveDH;
8826
    ssl->options.haveECDSAsig     = ctx->haveECDSAsig;
8827
    ssl->options.haveECC          = ctx->haveECC;
8828
    ssl->options.haveStaticECC    = ctx->haveStaticECC;
8829
    ssl->options.haveFalconSig    = ctx->haveFalconSig;
8830
    ssl->options.haveMlDsaSig     = ctx->haveMlDsaSig;
8831
    ssl->options.haveSlhDsaSig    = ctx->haveSlhDsaSig;
8832
#ifdef WOLFSSL_DUAL_ALG_CERTS
8833
#ifndef WOLFSSL_BLIND_PRIVATE_KEY
8834
    ssl->buffers.altKey   = ctx->altPrivateKey;
8835
#else
8836
    if (ctx->altPrivateKey != NULL) {
8837
        ret = AllocCopyDer(&ssl->buffers.altKey, ctx->altPrivateKey->buffer,
8838
            ctx->altPrivateKey->length, ctx->altPrivateKey->type,
8839
            ctx->altPrivateKey->heap);
8840
        if (ret != 0) {
8841
            return NULL;
8842
        }
8843
        /* Blind the private key for the SSL with new random mask. */
8844
        wolfssl_priv_der_blind_toggle(ssl->buffers.altKey,
8845
                                      ctx->altPrivateKeyMask);
8846
        ret = wolfssl_priv_der_blind(ssl->rng, ssl->buffers.altKey,
8847
            &ssl->buffers.altKeyMask);
8848
        if (ret != 0) {
8849
            return NULL;
8850
        }
8851
    }
8852
#endif
8853
    ssl->buffers.altKeySz   = ctx->altPrivateKeySz;
8854
    ssl->buffers.altKeyType = ctx->altPrivateKeyType;
8855
#endif /* WOLFSSL_DUAL_ALG_CERTS */
8856
#endif
8857
8858
#ifdef WOLFSSL_SESSION_ID_CTX
8859
    /* copy over application session context ID */
8860
    ssl->sessionCtxSz = ctx->sessionCtxSz;
8861
    XMEMCPY(ssl->sessionCtx, ctx->sessionCtx, ctx->sessionCtxSz);
8862
#endif
8863
8864
    return ssl->ctx;
8865
}
8866
8867
8868
#ifndef NO_BIO
8869
#endif
8870
8871
#ifndef NO_WOLFSSL_STUB
8872
/* Set THREADID callback, return 1 on success, 0 on error */
8873
int wolfSSL_THREADID_set_callback(
8874
        void(*threadid_func)(WOLFSSL_CRYPTO_THREADID*))
8875
{
8876
    WOLFSSL_ENTER("wolfSSL_THREADID_set_callback");
8877
    WOLFSSL_STUB("CRYPTO_THREADID_set_callback");
8878
    (void)threadid_func;
8879
    return 1;
8880
}
8881
#endif
8882
8883
#ifndef NO_WOLFSSL_STUB
8884
void wolfSSL_THREADID_set_numeric(void* id, unsigned long val)
8885
{
8886
    WOLFSSL_ENTER("wolfSSL_THREADID_set_numeric");
8887
    WOLFSSL_STUB("CRYPTO_THREADID_set_numeric");
8888
    (void)id;
8889
    (void)val;
8890
    return;
8891
}
8892
#endif
8893
8894
#endif /* OPENSSL_ALL || OPENSSL_EXTRA */
8895
8896
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
8897
/* Map a signature-algorithm NID to its digest and public-key NIDs, like
8898
 * OpenSSL's OBJ_find_sigid_algs(). */
8899
int wolfSSL_OBJ_find_sigid_algs(int sigid, int *pdig, int *ppkey)
8900
{
8901
    int dig  = 0;
8902
    int pkey = 0;
8903
    int ret  = 1;
8904
8905
    WOLFSSL_ENTER("wolfSSL_OBJ_find_sigid_algs");
8906
8907
    switch (sigid) {
8908
#ifndef NO_RSA
8909
    #ifndef NO_MD5
8910
        case WC_NID_md5WithRSAEncryption:
8911
            dig = WC_NID_md5;    pkey = WC_NID_rsaEncryption; break;
8912
    #endif
8913
        case WC_NID_sha1WithRSAEncryption:
8914
            dig = WC_NID_sha1;   pkey = WC_NID_rsaEncryption; break;
8915
        case WC_NID_sha224WithRSAEncryption:
8916
            dig = WC_NID_sha224; pkey = WC_NID_rsaEncryption; break;
8917
        case WC_NID_sha256WithRSAEncryption:
8918
            dig = WC_NID_sha256; pkey = WC_NID_rsaEncryption; break;
8919
        case WC_NID_sha384WithRSAEncryption:
8920
            dig = WC_NID_sha384; pkey = WC_NID_rsaEncryption; break;
8921
        case WC_NID_sha512WithRSAEncryption:
8922
            dig = WC_NID_sha512; pkey = WC_NID_rsaEncryption; break;
8923
    #ifdef WC_RSA_PSS
8924
        case WC_NID_rsassaPss:
8925
            dig = WC_NID_undef;  pkey = WC_NID_rsassaPss; break;
8926
    #endif
8927
#endif /* !NO_RSA */
8928
#ifdef HAVE_ECC
8929
        case WC_NID_ecdsa_with_SHA1:
8930
            dig = WC_NID_sha1;   pkey = WC_NID_X9_62_id_ecPublicKey; break;
8931
        case WC_NID_ecdsa_with_SHA224:
8932
            dig = WC_NID_sha224; pkey = WC_NID_X9_62_id_ecPublicKey; break;
8933
        case WC_NID_ecdsa_with_SHA256:
8934
            dig = WC_NID_sha256; pkey = WC_NID_X9_62_id_ecPublicKey; break;
8935
        case WC_NID_ecdsa_with_SHA384:
8936
            dig = WC_NID_sha384; pkey = WC_NID_X9_62_id_ecPublicKey; break;
8937
        case WC_NID_ecdsa_with_SHA512:
8938
            dig = WC_NID_sha512; pkey = WC_NID_X9_62_id_ecPublicKey; break;
8939
#endif /* HAVE_ECC */
8940
#ifdef HAVE_ED25519
8941
        case WC_NID_ED25519:
8942
            dig = WC_NID_undef;  pkey = WC_NID_ED25519; break;
8943
#endif
8944
#ifdef HAVE_ED448
8945
        case WC_NID_ED448:
8946
            dig = WC_NID_undef;  pkey = WC_NID_ED448; break;
8947
#endif
8948
        default:
8949
            ret = 0; break;
8950
    }
8951
8952
    if (ret == 1) {
8953
        if (pdig  != NULL) *pdig  = dig;
8954
        if (ppkey != NULL) *ppkey = pkey;
8955
    }
8956
8957
    WOLFSSL_LEAVE("wolfSSL_OBJ_find_sigid_algs", ret);
8958
    return ret;
8959
}
8960
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
8961
8962
8963
#if defined(OPENSSL_EXTRA)
8964
8965
int wolfSSL_CRYPTO_memcmp(const void *a, const void *b, size_t size)
8966
{
8967
    int ret = 0;
8968
    int chunk;
8969
    const byte* pa = (const byte*)a;
8970
    const byte* pb = (const byte*)b;
8971
8972
    if (!a || !b)
8973
        return -1;
8974
    /* ConstantCompare takes an int length. Compare in chunks of at most
8975
     * INT_MAX so a size that does not fit in an int is not narrowed into a
8976
     * negative or truncated length, which could wrongly report equality. */
8977
    while (size > 0) {
8978
        chunk = (size > (size_t)INT_MAX) ? INT_MAX : (int)size;
8979
        ret |= ConstantCompare(pa, pb, chunk);
8980
        pa += chunk;
8981
        pb += chunk;
8982
        size -= (size_t)chunk;
8983
    }
8984
    return ret;
8985
}
8986
8987
8988
#endif /* OPENSSL_EXTRA */
8989
8990
int wolfSSL_version(WOLFSSL* ssl)
8991
0
{
8992
0
    WOLFSSL_ENTER("wolfSSL_version");
8993
0
    if (ssl->version.major == SSLv3_MAJOR) {
8994
0
        switch (ssl->version.minor) {
8995
0
            case SSLv3_MINOR :
8996
0
                return SSL3_VERSION;
8997
0
            case TLSv1_MINOR :
8998
0
                return TLS1_VERSION;
8999
0
            case TLSv1_1_MINOR :
9000
0
                return TLS1_1_VERSION;
9001
0
            case TLSv1_2_MINOR :
9002
0
                return TLS1_2_VERSION;
9003
0
            case TLSv1_3_MINOR :
9004
0
                return TLS1_3_VERSION;
9005
0
            default:
9006
0
                return WOLFSSL_FAILURE;
9007
0
        }
9008
0
    }
9009
0
    else if (ssl->version.major == DTLS_MAJOR) {
9010
0
        switch (ssl->version.minor) {
9011
0
            case DTLS_MINOR :
9012
0
                return DTLS1_VERSION;
9013
0
            case DTLSv1_2_MINOR :
9014
0
                return DTLS1_2_VERSION;
9015
0
            case DTLSv1_3_MINOR:
9016
0
                return DTLS1_3_VERSION;
9017
0
            default:
9018
0
                return WOLFSSL_FAILURE;
9019
0
        }
9020
0
    }
9021
0
    return WOLFSSL_FAILURE;
9022
0
}
9023
9024
WOLFSSL_CTX* wolfSSL_get_SSL_CTX(const WOLFSSL* ssl)
9025
0
{
9026
0
    WOLFSSL_ENTER("wolfSSL_get_SSL_CTX");
9027
0
    return ssl->ctx;
9028
0
}
9029
9030
9031
#ifdef WOLFSSL_JNI
9032
9033
int wolfSSL_set_jobject(WOLFSSL* ssl, void* objPtr)
9034
{
9035
    WOLFSSL_ENTER("wolfSSL_set_jobject");
9036
    if (ssl != NULL)
9037
    {
9038
        ssl->jObjectRef = objPtr;
9039
        return WOLFSSL_SUCCESS;
9040
    }
9041
    return WOLFSSL_FAILURE;
9042
}
9043
9044
void* wolfSSL_get_jobject(WOLFSSL* ssl)
9045
{
9046
    WOLFSSL_ENTER("wolfSSL_get_jobject");
9047
    if (ssl != NULL)
9048
        return ssl->jObjectRef;
9049
    return NULL;
9050
}
9051
9052
#endif /* WOLFSSL_JNI */
9053
9054
9055
#ifdef WOLFSSL_ASYNC_CRYPT
9056
int wolfSSL_CTX_AsyncPoll(WOLFSSL_CTX* ctx, WOLF_EVENT** events, int maxEvents,
9057
    WOLF_EVENT_FLAG flags, int* eventCount)
9058
{
9059
    if (ctx == NULL) {
9060
        return BAD_FUNC_ARG;
9061
    }
9062
9063
    return wolfAsync_EventQueuePoll(&ctx->event_queue, NULL,
9064
                                        events, maxEvents, flags, eventCount);
9065
}
9066
9067
int wolfSSL_AsyncPoll(WOLFSSL* ssl, WOLF_EVENT_FLAG flags)
9068
{
9069
    int ret, eventCount = 0;
9070
    WOLF_EVENT* events[1];
9071
9072
    if (ssl == NULL) {
9073
        return BAD_FUNC_ARG;
9074
    }
9075
9076
    ret = wolfAsync_EventQueuePoll(&ssl->ctx->event_queue, ssl,
9077
        events, sizeof(events)/sizeof(events[0]), flags, &eventCount);
9078
    if (ret == 0) {
9079
        ret = eventCount;
9080
    }
9081
9082
    return ret;
9083
}
9084
#endif /* WOLFSSL_ASYNC_CRYPT */
9085
9086
#ifdef OPENSSL_EXTRA
9087
9088
#endif
9089
9090
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL) || \
9091
    defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
9092
9093
#if !defined(WOLFSSL_USER_IO)
9094
/* converts an IPv6 or IPv4 address into an octet string for use with rfc3280
9095
 * example input would be "127.0.0.1" and the returned value would be 7F000001
9096
 */
9097
WOLFSSL_ASN1_STRING* wolfSSL_a2i_IPADDRESS(const char* ipa)
9098
{
9099
    int ipaSz = WOLFSSL_IP4_ADDR_LEN;
9100
    char buf[WOLFSSL_IP6_ADDR_LEN + 1]; /* plus 1 for terminator */
9101
    int  af = WOLFSSL_IP4;
9102
    WOLFSSL_ASN1_STRING *ret = NULL;
9103
9104
    if (ipa == NULL)
9105
        return NULL;
9106
9107
    if (XSTRSTR(ipa, ":") != NULL) {
9108
        af = WOLFSSL_IP6;
9109
        ipaSz = WOLFSSL_IP6_ADDR_LEN;
9110
    }
9111
9112
    buf[WOLFSSL_IP6_ADDR_LEN] = '\0';
9113
#ifdef FREESCALE_MQX
9114
    if (XINET_PTON(af, ipa, (void*)buf, sizeof(buf)) != RTCS_OK) {
9115
#else
9116
    if (XINET_PTON(af, ipa, (void*)buf) != 1) {
9117
#endif
9118
        WOLFSSL_MSG("Error parsing IP address");
9119
        return NULL;
9120
    }
9121
9122
    ret = wolfSSL_ASN1_STRING_new();
9123
    if (ret != NULL) {
9124
        if (wolfSSL_ASN1_STRING_set(ret, buf, ipaSz) != WOLFSSL_SUCCESS) {
9125
            WOLFSSL_MSG("Error setting the string");
9126
            wolfSSL_ASN1_STRING_free(ret);
9127
            ret = NULL;
9128
        }
9129
    }
9130
9131
    return ret;
9132
}
9133
#endif /* !WOLFSSL_USER_IO */
9134
9135
/* Is the specified cipher suite a fake one used an an extension proxy? */
9136
static WC_INLINE int SCSV_Check(byte suite0, byte suite)
9137
{
9138
    (void)suite0;
9139
    (void)suite;
9140
#ifdef HAVE_RENEGOTIATION_INDICATION
9141
    if (suite0 == CIPHER_BYTE && suite == TLS_EMPTY_RENEGOTIATION_INFO_SCSV)
9142
        return 1;
9143
#endif
9144
    return 0;
9145
}
9146
9147
static WC_INLINE int sslCipherMinMaxCheck(const WOLFSSL *ssl, byte suite0,
9148
        byte suite)
9149
{
9150
    const CipherSuiteInfo* cipher_names = GetCipherNames();
9151
    int cipherSz = GetCipherNamesSize();
9152
    int i;
9153
    for (i = 0; i < cipherSz; i++)
9154
        if (cipher_names[i].cipherSuite0 == suite0 &&
9155
                cipher_names[i].cipherSuite == suite)
9156
            break;
9157
    if (i == cipherSz)
9158
        return 1;
9159
    /* Check min version */
9160
    if (cipher_names[i].minor < ssl->options.minDowngrade) {
9161
        if (ssl->options.minDowngrade <= TLSv1_2_MINOR &&
9162
                cipher_names[i].minor >= TLSv1_MINOR)
9163
            /* 1.0 ciphersuites are in general available in 1.1 and
9164
             * 1.1 ciphersuites are in general available in 1.2 */
9165
            return 0;
9166
        return 1;
9167
    }
9168
    /* Check max version */
9169
    switch (cipher_names[i].minor) {
9170
    case SSLv3_MINOR :
9171
        return ssl->options.mask & WOLFSSL_OP_NO_SSLv3;
9172
    case TLSv1_MINOR :
9173
        return ssl->options.mask & WOLFSSL_OP_NO_TLSv1;
9174
    case TLSv1_1_MINOR :
9175
        return ssl->options.mask & WOLFSSL_OP_NO_TLSv1_1;
9176
    case TLSv1_2_MINOR :
9177
        return ssl->options.mask & WOLFSSL_OP_NO_TLSv1_2;
9178
    case TLSv1_3_MINOR :
9179
        return ssl->options.mask & WOLFSSL_OP_NO_TLSv1_3;
9180
    default:
9181
        WOLFSSL_MSG("Unrecognized minor version");
9182
        return 1;
9183
    }
9184
}
9185
9186
/* returns a pointer to internal cipher suite list. Should not be free'd by
9187
 * caller.
9188
 */
9189
WOLF_STACK_OF(WOLFSSL_CIPHER) *wolfSSL_get_ciphers_compat(const WOLFSSL *ssl)
9190
{
9191
    const Suites* suites;
9192
#if defined(OPENSSL_ALL)
9193
    const CipherSuiteInfo* cipher_names = GetCipherNames();
9194
    int cipherSz = GetCipherNamesSize();
9195
#endif
9196
9197
    WOLFSSL_ENTER("wolfSSL_get_ciphers_compat");
9198
    if (ssl == NULL)
9199
        return NULL;
9200
9201
    suites = WOLFSSL_SUITES(ssl);
9202
    if (suites == NULL)
9203
        return NULL;
9204
9205
    /* check if stack needs populated */
9206
    if (ssl->suitesStack == NULL) {
9207
        int i;
9208
9209
        ((WOLFSSL*)ssl)->suitesStack =
9210
                wolfssl_sk_new_type_ex(STACK_TYPE_CIPHER, ssl->heap);
9211
        if (ssl->suitesStack == NULL)
9212
            return NULL;
9213
9214
        /* higher priority of cipher suite will be on top of stack */
9215
#if defined(OPENSSL_ALL)
9216
        for (i = suites->suiteSz - 2; i >=0; i-=2)
9217
#else
9218
        for (i = 0; i < suites->suiteSz; i+=2)
9219
#endif
9220
        {
9221
            struct WOLFSSL_CIPHER cipher;
9222
9223
            /* A couple of suites are placeholders for special options,
9224
             * skip those. */
9225
            if (SCSV_Check(suites->suites[i], suites->suites[i+1])
9226
                    || sslCipherMinMaxCheck(ssl, suites->suites[i],
9227
                                            suites->suites[i+1])) {
9228
                continue;
9229
            }
9230
9231
            XMEMSET(&cipher, 0, sizeof(cipher));
9232
            cipher.cipherSuite0 = suites->suites[i];
9233
            cipher.cipherSuite  = suites->suites[i+1];
9234
            cipher.ssl          = ssl;
9235
#if defined(OPENSSL_ALL)
9236
            cipher.in_stack     = 1;
9237
            {
9238
                int j;
9239
                for (j = 0; j < cipherSz; j++) {
9240
                    if (cipher_names[j].cipherSuite0 == cipher.cipherSuite0 &&
9241
                            cipher_names[j].cipherSuite == cipher.cipherSuite) {
9242
                        cipher.offset = (unsigned long)j;
9243
                        break;
9244
                    }
9245
                }
9246
            }
9247
#endif
9248
            if (wolfSSL_sk_insert(ssl->suitesStack, &cipher, 0) <= 0) {
9249
                WOLFSSL_MSG("Error inserting cipher onto stack");
9250
                wolfSSL_sk_CIPHER_free(ssl->suitesStack);
9251
                ((WOLFSSL*)ssl)->suitesStack = NULL;
9252
                break;
9253
            }
9254
        }
9255
9256
        /* If no ciphers were added, free empty stack and return NULL */
9257
        if (ssl->suitesStack != NULL && wolfSSL_sk_num(ssl->suitesStack) == 0) {
9258
            wolfSSL_sk_CIPHER_free(ssl->suitesStack);
9259
            ((WOLFSSL*)ssl)->suitesStack = NULL;
9260
        }
9261
    }
9262
    return ssl->suitesStack;
9263
}
9264
#endif /* OPENSSL_EXTRA || OPENSSL_ALL || WOLFSSL_NGINX || WOLFSSL_HAPROXY */
9265
#ifdef OPENSSL_ALL
9266
/* returned pointer is to an internal element in WOLFSSL struct and should not
9267
 * be free'd. It gets free'd when the WOLFSSL struct is free'd. */
9268
WOLF_STACK_OF(WOLFSSL_CIPHER)*  wolfSSL_get_client_ciphers(WOLFSSL* ssl)
9269
{
9270
    WOLF_STACK_OF(WOLFSSL_CIPHER)* ret = NULL;
9271
    const CipherSuiteInfo* cipher_names = GetCipherNames();
9272
    int cipherSz = GetCipherNamesSize();
9273
    const Suites* suites;
9274
9275
    WOLFSSL_ENTER("wolfSSL_get_client_ciphers");
9276
9277
    if (ssl == NULL) {
9278
        return NULL;
9279
    }
9280
9281
    /* return NULL if is client side */
9282
    if (wolfSSL_is_server(ssl) == 0) {
9283
        return NULL;
9284
    }
9285
9286
    suites = ssl->clSuites;
9287
    if (suites == NULL) {
9288
        WOLFSSL_MSG("No client suites stored");
9289
    }
9290
    else if (ssl->clSuitesStack != NULL) {
9291
        ret = ssl->clSuitesStack;
9292
    }
9293
    else { /* generate cipher suites stack if not already done */
9294
        int i;
9295
        int j;
9296
9297
        ret = wolfSSL_sk_new_node(ssl->heap);
9298
        if (ret != NULL) {
9299
            ret->type = STACK_TYPE_CIPHER;
9300
9301
            /* higher priority of cipher suite will be on top of stack */
9302
            for (i = suites->suiteSz - 2; i >= 0; i -= 2) {
9303
                WOLFSSL_CIPHER cipher;
9304
9305
                /* A couple of suites are placeholders for special options,
9306
                 * skip those. */
9307
                if (SCSV_Check(suites->suites[i], suites->suites[i+1])
9308
                        || sslCipherMinMaxCheck(ssl, suites->suites[i],
9309
                                                suites->suites[i+1])) {
9310
                    continue;
9311
                }
9312
9313
                cipher.cipherSuite0 = suites->suites[i];
9314
                cipher.cipherSuite  = suites->suites[i+1];
9315
                cipher.ssl          = ssl;
9316
                for (j = 0; j < cipherSz; j++) {
9317
                    if (cipher_names[j].cipherSuite0 ==
9318
                            cipher.cipherSuite0 &&
9319
                            cipher_names[j].cipherSuite ==
9320
                                    cipher.cipherSuite) {
9321
                        cipher.offset = (unsigned long)j;
9322
                        break;
9323
                    }
9324
                }
9325
9326
                /* in_stack is checked in wolfSSL_CIPHER_description */
9327
                cipher.in_stack     = 1;
9328
9329
                if (wolfSSL_sk_CIPHER_push(ret, &cipher) <= 0) {
9330
                    WOLFSSL_MSG("Error pushing client cipher onto stack");
9331
                    wolfSSL_sk_CIPHER_free(ret);
9332
                    ret = NULL;
9333
                    break;
9334
                }
9335
            }
9336
        }
9337
        ssl->clSuitesStack = ret;
9338
    }
9339
    return ret;
9340
}
9341
#endif /* OPENSSL_ALL */
9342
9343
#if defined(OPENSSL_EXTRA) || defined(HAVE_SECRET_CALLBACK)
9344
long wolfSSL_SSL_CTX_get_timeout(const WOLFSSL_CTX *ctx)
9345
{
9346
    WOLFSSL_ENTER("wolfSSL_SSL_CTX_get_timeout");
9347
9348
    if (ctx == NULL)
9349
        return 0;
9350
9351
    return ctx->timeout;
9352
}
9353
9354
9355
/* returns the time in seconds of the current timeout */
9356
long wolfSSL_get_timeout(WOLFSSL* ssl)
9357
{
9358
    WOLFSSL_ENTER("wolfSSL_get_timeout");
9359
9360
    if (ssl == NULL)
9361
        return 0;
9362
    return ssl->timeout;
9363
}
9364
#endif
9365
9366
#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) \
9367
    || defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY)
9368
9369
#ifndef NO_BIO
9370
WOLFSSL_BIO *wolfSSL_SSL_get_rbio(const WOLFSSL *s)
9371
{
9372
    WOLFSSL_ENTER("wolfSSL_SSL_get_rbio");
9373
    /* Nginx sets the buffer size if the read BIO is different to write BIO.
9374
     * The setting buffer size doesn't do anything so return NULL for both.
9375
     */
9376
    if (s == NULL)
9377
        return NULL;
9378
9379
    return s->biord;
9380
}
9381
WOLFSSL_BIO *wolfSSL_SSL_get_wbio(const WOLFSSL *s)
9382
{
9383
    WOLFSSL_ENTER("wolfSSL_SSL_get_wbio");
9384
    (void)s;
9385
    /* Nginx sets the buffer size if the read BIO is different to write BIO.
9386
     * The setting buffer size doesn't do anything so return NULL for both.
9387
     */
9388
    if (s == NULL)
9389
        return NULL;
9390
9391
    return s->biowr;
9392
}
9393
#endif /* !NO_BIO */
9394
9395
9396
9397
#endif /* OPENSSL_ALL || WOLFSSL_NGINX || WOLFSSL_HAPROXY ||
9398
    OPENSSL_EXTRA || HAVE_LIGHTY */
9399
9400
9401
#if defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) || \
9402
    defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)
9403
9404
9405
void wolfSSL_WOLFSSL_STRING_free(WOLFSSL_STRING s)
9406
{
9407
    WOLFSSL_ENTER("wolfSSL_WOLFSSL_STRING_free");
9408
9409
    XFREE(s, NULL, DYNAMIC_TYPE_OPENSSL);
9410
}
9411
9412
#endif /* WOLFSSL_NGINX || WOLFSSL_HAPROXY || OPENSSL_EXTRA || OPENSSL_ALL */
9413
9414
9415
#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL)
9416
9417
#if (defined(HAVE_ECC) || \
9418
    defined(HAVE_CURVE25519) || defined(HAVE_CURVE448))
9419
#define CURVE_NAME(c) XSTR_SIZEOF((c)), (c)
9420
9421
const WOLF_EC_NIST_NAME kNistCurves[] = {
9422
#ifdef HAVE_ECC
9423
    {CURVE_NAME("P-160"),   WC_NID_secp160r1, WOLFSSL_ECC_SECP160R1},
9424
    {CURVE_NAME("P-160-2"), WC_NID_secp160r2, WOLFSSL_ECC_SECP160R2},
9425
    {CURVE_NAME("P-192"),   WC_NID_X9_62_prime192v1, WOLFSSL_ECC_SECP192R1},
9426
    {CURVE_NAME("P-224"),   WC_NID_secp224r1, WOLFSSL_ECC_SECP224R1},
9427
    {CURVE_NAME("P-256"),   WC_NID_X9_62_prime256v1, WOLFSSL_ECC_SECP256R1},
9428
    {CURVE_NAME("P-384"),   WC_NID_secp384r1, WOLFSSL_ECC_SECP384R1},
9429
    {CURVE_NAME("P-521"),   WC_NID_secp521r1, WOLFSSL_ECC_SECP521R1},
9430
    {CURVE_NAME("K-160"),   WC_NID_secp160k1, WOLFSSL_ECC_SECP160K1},
9431
    {CURVE_NAME("K-192"),   WC_NID_secp192k1, WOLFSSL_ECC_SECP192K1},
9432
    {CURVE_NAME("K-224"),   WC_NID_secp224k1, WOLFSSL_ECC_SECP224K1},
9433
    {CURVE_NAME("K-256"),   WC_NID_secp256k1, WOLFSSL_ECC_SECP256K1},
9434
    {CURVE_NAME("B-256"),   WC_NID_brainpoolP256r1,
9435
     WOLFSSL_ECC_BRAINPOOLP256R1},
9436
    {CURVE_NAME("B-384"),   WC_NID_brainpoolP384r1,
9437
     WOLFSSL_ECC_BRAINPOOLP384R1},
9438
    {CURVE_NAME("B-512"),   WC_NID_brainpoolP512r1,
9439
     WOLFSSL_ECC_BRAINPOOLP512R1},
9440
#endif
9441
#ifdef HAVE_CURVE25519
9442
    {CURVE_NAME("X25519"),  WC_NID_X25519, WOLFSSL_ECC_X25519},
9443
#endif
9444
#ifdef HAVE_CURVE448
9445
    {CURVE_NAME("X448"),    WC_NID_X448, WOLFSSL_ECC_X448},
9446
#endif
9447
#ifdef WOLFSSL_HAVE_MLKEM
9448
#ifndef WOLFSSL_NO_ML_KEM
9449
    {CURVE_NAME("ML_KEM_512"), WOLFSSL_ML_KEM_512, WOLFSSL_ML_KEM_512},
9450
    {CURVE_NAME("ML_KEM_768"), WOLFSSL_ML_KEM_768, WOLFSSL_ML_KEM_768},
9451
    {CURVE_NAME("ML_KEM_1024"), WOLFSSL_ML_KEM_1024, WOLFSSL_ML_KEM_1024},
9452
    /* Aliases accepting the OpenSSL/IANA spelling without underscores. */
9453
    {CURVE_NAME("MLKEM512"), WOLFSSL_ML_KEM_512, WOLFSSL_ML_KEM_512},
9454
    {CURVE_NAME("MLKEM768"), WOLFSSL_ML_KEM_768, WOLFSSL_ML_KEM_768},
9455
    {CURVE_NAME("MLKEM1024"), WOLFSSL_ML_KEM_1024, WOLFSSL_ML_KEM_1024},
9456
#if defined(HAVE_ECC)
9457
    #ifdef WOLFSSL_PQC_HYBRIDS
9458
    {CURVE_NAME("SecP256r1MLKEM768"), WOLFSSL_SECP256R1MLKEM768,
9459
     WOLFSSL_SECP256R1MLKEM768},
9460
    {CURVE_NAME("SecP384r1MLKEM1024"), WOLFSSL_SECP384R1MLKEM1024,
9461
     WOLFSSL_SECP384R1MLKEM1024},
9462
    {CURVE_NAME("X25519MLKEM768"), WOLFSSL_X25519MLKEM768,
9463
     WOLFSSL_X25519MLKEM768},
9464
    #endif /* WOLFSSL_PQC_HYBRIDS */
9465
    #ifdef WOLFSSL_EXTRA_PQC_HYBRIDS
9466
    {CURVE_NAME("SecP256r1MLKEM512"), WOLFSSL_SECP256R1MLKEM512,
9467
     WOLFSSL_SECP256R1MLKEM512},
9468
    {CURVE_NAME("SecP384r1MLKEM768"), WOLFSSL_SECP384R1MLKEM768,
9469
     WOLFSSL_SECP384R1MLKEM768},
9470
    {CURVE_NAME("SecP521r1MLKEM1024"), WOLFSSL_SECP521R1MLKEM1024,
9471
     WOLFSSL_SECP521R1MLKEM1024},
9472
    {CURVE_NAME("X25519MLKEM512"), WOLFSSL_X25519MLKEM512,
9473
     WOLFSSL_X25519MLKEM512},
9474
    {CURVE_NAME("X448MLKEM768"), WOLFSSL_X448MLKEM768,
9475
     WOLFSSL_X448MLKEM768},
9476
    #endif /* WOLFSSL_EXTRA_PQC_HYBRIDS */
9477
#endif
9478
#endif /* !WOLFSSL_NO_ML_KEM */
9479
#ifdef WOLFSSL_MLKEM_KYBER
9480
    {CURVE_NAME("KYBER_LEVEL1"), WOLFSSL_KYBER_LEVEL1, WOLFSSL_KYBER_LEVEL1},
9481
    {CURVE_NAME("KYBER_LEVEL3"), WOLFSSL_KYBER_LEVEL3, WOLFSSL_KYBER_LEVEL3},
9482
    {CURVE_NAME("KYBER_LEVEL5"), WOLFSSL_KYBER_LEVEL5, WOLFSSL_KYBER_LEVEL5},
9483
#if defined(HAVE_ECC)
9484
    {CURVE_NAME("P256_KYBER_LEVEL1"), WOLFSSL_P256_KYBER_LEVEL1,
9485
     WOLFSSL_P256_KYBER_LEVEL1},
9486
    {CURVE_NAME("P384_KYBER_LEVEL3"), WOLFSSL_P384_KYBER_LEVEL3,
9487
     WOLFSSL_P384_KYBER_LEVEL3},
9488
    {CURVE_NAME("P256_KYBER_LEVEL3"), WOLFSSL_P256_KYBER_LEVEL3,
9489
     WOLFSSL_P256_KYBER_LEVEL3},
9490
    {CURVE_NAME("P521_KYBER_LEVEL5"), WOLFSSL_P521_KYBER_LEVEL5,
9491
     WOLFSSL_P521_KYBER_LEVEL5},
9492
    {CURVE_NAME("X25519_KYBER_LEVEL1"), WOLFSSL_X25519_KYBER_LEVEL1,
9493
     WOLFSSL_X25519_KYBER_LEVEL1},
9494
    {CURVE_NAME("X448_KYBER_LEVEL3"), WOLFSSL_X448_KYBER_LEVEL3,
9495
     WOLFSSL_X448_KYBER_LEVEL3},
9496
    {CURVE_NAME("X25519_KYBER_LEVEL3"), WOLFSSL_X25519_KYBER_LEVEL3,
9497
     WOLFSSL_X25519_KYBER_LEVEL3},
9498
#endif
9499
#endif /* WOLFSSL_MLKEM_KYBER */
9500
#endif /* WOLFSSL_HAVE_MLKEM */
9501
#ifdef WOLFSSL_SM2
9502
    {CURVE_NAME("SM2"),     WC_NID_sm2, WOLFSSL_ECC_SM2P256V1},
9503
#endif
9504
#ifdef HAVE_ECC
9505
    /* Alternative curve names */
9506
    {CURVE_NAME("prime256v1"), WC_NID_X9_62_prime256v1, WOLFSSL_ECC_SECP256R1},
9507
    {CURVE_NAME("secp256r1"),  WC_NID_X9_62_prime256v1, WOLFSSL_ECC_SECP256R1},
9508
    {CURVE_NAME("secp384r1"),  WC_NID_secp384r1, WOLFSSL_ECC_SECP384R1},
9509
    {CURVE_NAME("secp521r1"),  WC_NID_secp521r1, WOLFSSL_ECC_SECP521R1},
9510
#endif
9511
#ifdef WOLFSSL_SM2
9512
    {CURVE_NAME("sm2p256v1"),  WC_NID_sm2, WOLFSSL_ECC_SM2P256V1},
9513
#endif
9514
    {0, NULL, 0, 0},
9515
};
9516
9517
int set_curves_list(WOLFSSL* ssl, WOLFSSL_CTX *ctx, const char* names,
9518
        byte curves_only)
9519
{
9520
    int idx, start = 0, len, i, ret = WOLFSSL_FAILURE;
9521
    word16 curve;
9522
    word32 disabled;
9523
    char name[MAX_CURVE_NAME_SZ];
9524
    byte groups_len = 0;
9525
#ifdef WOLFSSL_SMALL_STACK
9526
    void *heap = ssl? ssl->heap : ctx ? ctx->heap : NULL;
9527
    int *groups;
9528
#else
9529
    int groups[WOLFSSL_MAX_GROUP_COUNT];
9530
#endif
9531
    const WOLF_EC_NIST_NAME* nist_name;
9532
9533
    WC_ALLOC_VAR_EX(groups, int, WOLFSSL_MAX_GROUP_COUNT, heap,
9534
        DYNAMIC_TYPE_TMP_BUFFER,
9535
    {
9536
        ret=MEMORY_E;
9537
        goto leave;
9538
    });
9539
9540
    for (idx = 1; names[idx-1] != '\0'; idx++) {
9541
        if (names[idx] != ':' && names[idx] != '\0')
9542
            continue;
9543
9544
        len = idx - start;
9545
        if (len > MAX_CURVE_NAME_SZ - 1)
9546
            goto leave;
9547
9548
        XMEMCPY(name, names + start, (size_t)len);
9549
        name[len] = 0;
9550
        curve = WOLFSSL_NAMED_GROUP_INVALID;
9551
9552
        for (nist_name = kNistCurves; nist_name->name != NULL; nist_name++) {
9553
            if (len == nist_name->name_len &&
9554
                    XSTRNCASECMP(name, nist_name->name, (size_t)len) == 0) {
9555
                curve = nist_name->curve;
9556
                break;
9557
            }
9558
        }
9559
9560
        if (curve == WOLFSSL_NAMED_GROUP_INVALID) {
9561
        #if !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) && defined(HAVE_ECC)
9562
            int   nret;
9563
            const ecc_set_type *eccSet;
9564
9565
            nret = wc_ecc_get_curve_idx_from_name(name);
9566
            if (nret < 0) {
9567
                WOLFSSL_MSG("Could not find name in set");
9568
                goto leave;
9569
            }
9570
9571
            eccSet = wc_ecc_get_curve_params(nret);
9572
            if (eccSet == NULL) {
9573
                WOLFSSL_MSG("NULL set returned");
9574
                goto leave;
9575
            }
9576
9577
            curve = GetCurveByOID((int)eccSet->oidSum);
9578
        #else
9579
            WOLFSSL_MSG("API not present to search farther using name");
9580
            goto leave;
9581
        #endif
9582
        }
9583
9584
        if ((curves_only && curve >= WOLFSSL_ECC_MAX_AVAIL) ||
9585
                curve == WOLFSSL_NAMED_GROUP_INVALID) {
9586
            WOLFSSL_MSG("curve value is not supported");
9587
            goto leave;
9588
        }
9589
9590
        for (i = 0; i < groups_len; ++i) {
9591
            if (groups[i] == curve) {
9592
                /* silently drop duplicates */
9593
                break;
9594
            }
9595
        }
9596
        if (i >= groups_len) {
9597
            if (groups_len >= WOLFSSL_MAX_GROUP_COUNT) {
9598
                WOLFSSL_MSG_EX("setting %d or more supported "
9599
                               "curves is not permitted", groups_len);
9600
                goto leave;
9601
            }
9602
            groups[groups_len++] = (int)curve;
9603
        }
9604
9605
        start = idx + 1;
9606
    }
9607
9608
    /* Disable all curves so that only the ones the user wants are enabled. */
9609
    disabled = 0xFFFFFFFFUL;
9610
    for (i = 0; i < groups_len; ++i) {
9611
        /* Switch the bit to off and therefore is enabled. */
9612
        curve = (word16)groups[i];
9613
        if (curve >= 64) {
9614
            WC_DO_NOTHING;
9615
        }
9616
        else if (curve >= 32) {
9617
            /* 0 is for invalid and 1-14 aren't used otherwise. */
9618
            disabled &= ~(1U << (curve - 32));
9619
        }
9620
        else {
9621
            disabled &= ~(1U << curve);
9622
        }
9623
    #if defined(HAVE_SUPPORTED_CURVES) && !defined(NO_TLS)
9624
    #if !defined(WOLFSSL_OLD_SET_CURVES_LIST)
9625
        /* using the wolfSSL API to set the groups, this will populate
9626
         * (ssl|ctx)->groups and reset any TLSX_SUPPORTED_GROUPS.
9627
         * The order in (ssl|ctx)->groups will then be respected
9628
         * when TLSX_KEY_SHARE needs to be established */
9629
        if ((ssl && wolfSSL_set_groups(ssl, groups, groups_len)
9630
                        != WOLFSSL_SUCCESS)
9631
            || (ctx && wolfSSL_CTX_set_groups(ctx, groups, groups_len)
9632
                           != WOLFSSL_SUCCESS)) {
9633
            WOLFSSL_MSG("Unable to set supported curve");
9634
            goto leave;
9635
        }
9636
    #elif !defined(NO_WOLFSSL_CLIENT)
9637
        /* set the supported curve so client TLS extension contains only the
9638
         * desired curves */
9639
        if ((ssl && wolfSSL_UseSupportedCurve(ssl, curve) != WOLFSSL_SUCCESS)
9640
            || (ctx && wolfSSL_CTX_UseSupportedCurve(ctx, curve)
9641
                           != WOLFSSL_SUCCESS)) {
9642
            WOLFSSL_MSG("Unable to set supported curve");
9643
            goto leave;
9644
        }
9645
    #endif
9646
    #endif /* HAVE_SUPPORTED_CURVES && !NO_TLS */
9647
    }
9648
9649
    if (ssl != NULL)
9650
        ssl->disabledCurves = disabled;
9651
    else if (ctx != NULL)
9652
        ctx->disabledCurves = disabled;
9653
    ret = WOLFSSL_SUCCESS;
9654
9655
leave:
9656
#ifdef WOLFSSL_SMALL_STACK
9657
    if (groups)
9658
        XFREE((void*)groups, heap, DYNAMIC_TYPE_TMP_BUFFER);
9659
#endif
9660
    return ret;
9661
}
9662
9663
#endif /* (HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448) */
9664
#endif /* OPENSSL_EXTRA || HAVE_CURL */
9665
9666
9667
#ifdef OPENSSL_EXTRA
9668
/* Sets a callback for when sending and receiving protocol messages.
9669
 * This callback is copied to all WOLFSSL objects created from the ctx.
9670
 *
9671
 * ctx WOLFSSL_CTX structure to set callback in
9672
 * cb  callback to use
9673
 *
9674
 * return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE with error case
9675
 */
9676
int wolfSSL_CTX_set_msg_callback(WOLFSSL_CTX *ctx, SSL_Msg_Cb cb)
9677
{
9678
    WOLFSSL_ENTER("wolfSSL_CTX_set_msg_callback");
9679
    if (ctx == NULL) {
9680
        WOLFSSL_MSG("Null ctx passed in");
9681
        return WOLFSSL_FAILURE;
9682
    }
9683
9684
    ctx->protoMsgCb = cb;
9685
    return WOLFSSL_SUCCESS;
9686
}
9687
9688
9689
/* Sets a callback for when sending and receiving protocol messages.
9690
 *
9691
 * ssl WOLFSSL structure to set callback in
9692
 * cb  callback to use
9693
 *
9694
 * return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE with error case
9695
 */
9696
int wolfSSL_set_msg_callback(WOLFSSL *ssl, SSL_Msg_Cb cb)
9697
{
9698
    WOLFSSL_ENTER("wolfSSL_set_msg_callback");
9699
9700
    if (ssl == NULL) {
9701
        return WOLFSSL_FAILURE;
9702
    }
9703
9704
    if (cb != NULL) {
9705
        ssl->toInfoOn = 1;
9706
    }
9707
9708
    ssl->protoMsgCb = cb;
9709
    return WOLFSSL_SUCCESS;
9710
}
9711
9712
9713
/* set the user argument to pass to the msg callback when called
9714
 * return WOLFSSL_SUCCESS on success */
9715
int wolfSSL_CTX_set_msg_callback_arg(WOLFSSL_CTX *ctx, void* arg)
9716
{
9717
    WOLFSSL_ENTER("wolfSSL_CTX_set_msg_callback_arg");
9718
    if (ctx == NULL) {
9719
        WOLFSSL_MSG("Null WOLFSSL_CTX passed in");
9720
        return WOLFSSL_FAILURE;
9721
    }
9722
9723
    ctx->protoMsgCtx = arg;
9724
    return WOLFSSL_SUCCESS;
9725
}
9726
9727
9728
int wolfSSL_set_msg_callback_arg(WOLFSSL *ssl, void* arg)
9729
{
9730
    WOLFSSL_ENTER("wolfSSL_set_msg_callback_arg");
9731
    if (ssl == NULL)
9732
        return WOLFSSL_FAILURE;
9733
9734
    ssl->protoMsgCtx = arg;
9735
    return WOLFSSL_SUCCESS;
9736
}
9737
9738
void *wolfSSL_OPENSSL_memdup(const void *data, size_t siz, const char* file,
9739
    int line)
9740
{
9741
    void *ret;
9742
    (void)file;
9743
    (void)line;
9744
9745
    if (data == NULL || siz >= INT_MAX)
9746
        return NULL;
9747
9748
    ret = wolfSSL_OPENSSL_malloc(siz);
9749
    if (ret == NULL) {
9750
        return NULL;
9751
    }
9752
    return XMEMCPY(ret, data, siz);
9753
}
9754
9755
void wolfSSL_OPENSSL_cleanse(void *ptr, size_t len)
9756
{
9757
    if (ptr)
9758
        ForceZero(ptr, (word32)len);
9759
}
9760
9761
#endif /* OPENSSL_EXTRA */
9762
9763
#define WOLFSSL_SSL_API_EXT_INCLUDED
9764
#include "src/ssl_api_ext.c"
9765
9766
#if defined(OPENSSL_EXTRA)
9767
9768
#ifndef NO_BIO
9769
#define WOLFSSL_BIO_INCLUDED
9770
#include "src/bio.c"
9771
#endif
9772
9773
#endif /* OPENSSL_EXTRA */
9774
9775
9776
#if defined(OPENSSL_EXTRA)
9777
9778
/* frees all nodes in the current threads error queue
9779
 *
9780
 * id  thread id. ERR_remove_state is depreciated and id is ignored. The
9781
 *     current threads queue will be free'd.
9782
 */
9783
9784
#endif /* OPENSSL_EXTRA */
9785
9786
9787
#if defined(OPENSSL_EXTRA)
9788
/* wolfSSL_THREADID_current is provided as a compat API with
9789
 * CRYPTO_THREADID_current to register current thread id into given id object.
9790
 * However, CRYPTO_THREADID_current API has been deprecated and no longer
9791
 * exists in the OpenSSL 1.0.0 or later.This API only works as a stub
9792
 * like as existing wolfSSL_THREADID_set_numeric.
9793
 */
9794
void wolfSSL_THREADID_current(WOLFSSL_CRYPTO_THREADID* id)
9795
{
9796
    (void)id;
9797
    return;
9798
}
9799
/* wolfSSL_THREADID_hash is provided as a compatible API with
9800
 * CRYPTO_THREADID_hash which returns a hash value calculated from the
9801
 * specified thread id. However, CRYPTO_THREADID_hash API has been
9802
 * deprecated and no longer exists in the OpenSSL 1.0.0 or later.
9803
 * This API only works as a stub to returns 0. This behavior is
9804
 * equivalent to the latest OpenSSL CRYPTO_THREADID_hash.
9805
 */
9806
unsigned long wolfSSL_THREADID_hash(const WOLFSSL_CRYPTO_THREADID* id)
9807
{
9808
    (void)id;
9809
    return 0UL;
9810
}
9811
9812
/**
9813
 * Set security level (wolfSSL doesn't support setting the security level).
9814
 *
9815
 * The security level can only be set through a system wide crypto-policy
9816
 * with wolfSSL_crypto_policy_enable().
9817
 *
9818
 * @param ctx  a pointer to WOLFSSL_CTX structure
9819
 * @param level security level
9820
 */
9821
void wolfSSL_CTX_set_security_level(WOLFSSL_CTX* ctx, int level)
9822
{
9823
    WOLFSSL_ENTER("wolfSSL_CTX_set_security_level");
9824
    (void)ctx;
9825
    (void)level;
9826
}
9827
9828
int wolfSSL_CTX_get_security_level(const WOLFSSL_CTX * ctx)
9829
{
9830
    WOLFSSL_ENTER("wolfSSL_CTX_get_security_level");
9831
    #if defined(WOLFSSL_SYS_CRYPTO_POLICY)
9832
    if (ctx == NULL) {
9833
        return BAD_FUNC_ARG;
9834
    }
9835
9836
    return ctx->secLevel;
9837
    #else
9838
    (void)ctx;
9839
    return 0;
9840
    #endif /* WOLFSSL_SYS_CRYPTO_POLICY */
9841
}
9842
9843
#if defined(OPENSSL_EXTRA) && defined(HAVE_SECRET_CALLBACK)
9844
/*
9845
 * This API accepts a user callback which puts key-log records into
9846
 * a KEY LOGFILE. The callback is stored into a CTX and propagated to
9847
 * each SSL object on its creation timing.
9848
 */
9849
void wolfSSL_CTX_set_keylog_callback(WOLFSSL_CTX* ctx,
9850
    wolfSSL_CTX_keylog_cb_func cb)
9851
{
9852
    WOLFSSL_ENTER("wolfSSL_CTX_set_keylog_callback");
9853
    /* stores the callback into WOLFSSL_CTX */
9854
    if (ctx != NULL) {
9855
        ctx->keyLogCb = cb;
9856
    }
9857
}
9858
wolfSSL_CTX_keylog_cb_func wolfSSL_CTX_get_keylog_callback(
9859
    const WOLFSSL_CTX* ctx)
9860
{
9861
    WOLFSSL_ENTER("wolfSSL_CTX_get_keylog_callback");
9862
    if (ctx != NULL)
9863
        return ctx->keyLogCb;
9864
    return NULL;
9865
}
9866
#endif /* OPENSSL_EXTRA && HAVE_SECRET_CALLBACK */
9867
9868
#endif /* OPENSSL_EXTRA */
9869
9870
#ifdef WOLFSSL_THREADED_CRYPT
9871
int wolfSSL_AsyncEncryptReady(WOLFSSL* ssl, int idx)
9872
{
9873
    ThreadCrypt* encrypt;
9874
9875
    if (ssl == NULL) {
9876
        return 0;
9877
    }
9878
9879
    encrypt = &ssl->buffers.encrypt[idx];
9880
    return (encrypt->avail == 0) && (encrypt->done == 0);
9881
}
9882
9883
int wolfSSL_AsyncEncryptStop(WOLFSSL* ssl, int idx)
9884
{
9885
    ThreadCrypt* encrypt;
9886
9887
    if (ssl == NULL) {
9888
        return 1;
9889
    }
9890
9891
    encrypt = &ssl->buffers.encrypt[idx];
9892
    return encrypt->stop;
9893
}
9894
9895
int wolfSSL_AsyncEncrypt(WOLFSSL* ssl, int idx)
9896
{
9897
    int ret = WC_NO_ERR_TRACE(NOT_COMPILED_IN);
9898
    ThreadCrypt* encrypt = &ssl->buffers.encrypt[idx];
9899
9900
    if (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm) {
9901
        unsigned char* out = encrypt->buffer.buffer + encrypt->offset;
9902
        unsigned char* input = encrypt->buffer.buffer + encrypt->offset;
9903
        word32 encSz = encrypt->buffer.length - encrypt->offset;
9904
9905
        ret =
9906
#if !defined(NO_GCM_ENCRYPT_EXTRA) && \
9907
    ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \
9908
    (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)))
9909
              wc_AesGcmEncrypt_ex
9910
#else
9911
              wc_AesGcmEncrypt
9912
#endif
9913
              (encrypt->encrypt.aes,
9914
               out + AESGCM_EXP_IV_SZ, input + AESGCM_EXP_IV_SZ,
9915
               encSz - AESGCM_EXP_IV_SZ - ssl->specs.aead_mac_size,
9916
               encrypt->nonce, AESGCM_NONCE_SZ,
9917
               out + encSz - ssl->specs.aead_mac_size,
9918
               ssl->specs.aead_mac_size,
9919
               encrypt->additional, AEAD_AUTH_DATA_SZ);
9920
#if !defined(NO_PUBLIC_GCM_SET_IV) && \
9921
    ((!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \
9922
    (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)))
9923
        XMEMCPY(out, encrypt->nonce + AESGCM_IMP_IV_SZ, AESGCM_EXP_IV_SZ);
9924
#endif
9925
        encrypt->done = 1;
9926
    }
9927
9928
    return ret;
9929
}
9930
9931
int wolfSSL_AsyncEncryptSetSignal(WOLFSSL* ssl, int idx,
9932
    WOLFSSL_THREAD_SIGNAL signal, void* ctx)
9933
{
9934
    int ret = 0;
9935
9936
    if (ssl == NULL) {
9937
        ret = BAD_FUNC_ARG;
9938
    }
9939
    else {
9940
        ssl->buffers.encrypt[idx].signal = signal;
9941
        ssl->buffers.encrypt[idx].signalCtx = ctx;
9942
    }
9943
9944
    return ret;
9945
}
9946
#endif
9947
9948
9949
#ifndef NO_CERT
9950
#define WOLFSSL_X509_INCLUDED
9951
#include "src/x509.c"
9952
#endif
9953
9954
/*******************************************************************************
9955
 * START OF standard C library wrapping APIs
9956
 ******************************************************************************/
9957
#if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && \
9958
    (defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \
9959
     defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \
9960
     defined(WOLFSSL_OPENSSH)))
9961
#ifndef NO_WOLFSSL_STUB
9962
int wolfSSL_CRYPTO_set_mem_ex_functions(void *(*m) (size_t, const char *, int),
9963
                                void *(*r) (void *, size_t, const char *,
9964
                                            int), void (*f) (void *))
9965
{
9966
    (void) m;
9967
    (void) r;
9968
    (void) f;
9969
    WOLFSSL_ENTER("wolfSSL_CRYPTO_set_mem_ex_functions");
9970
    WOLFSSL_STUB("CRYPTO_set_mem_ex_functions");
9971
9972
    return WOLFSSL_FAILURE;
9973
}
9974
#endif
9975
#endif
9976
9977
#if defined(OPENSSL_EXTRA)
9978
9979
/**
9980
 * free allocated memory resource
9981
 * @param str  a pointer to resource to be freed
9982
 * @param file dummy argument
9983
 * @param line dummy argument
9984
 */
9985
void wolfSSL_CRYPTO_free(void *str, const char *file, int line)
9986
{
9987
    (void)file;
9988
    (void)line;
9989
    XFREE(str, 0, DYNAMIC_TYPE_TMP_BUFFER);
9990
}
9991
/**
9992
 * allocate memory with size of num
9993
 * @param num  size of memory allocation to be malloced
9994
 * @param file dummy argument
9995
 * @param line dummy argument
9996
 * @return a pointer to allocated memory on succssesful, otherwise NULL
9997
 */
9998
void *wolfSSL_CRYPTO_malloc(size_t num, const char *file, int line)
9999
{
10000
    (void)file;
10001
    (void)line;
10002
    return XMALLOC(num, 0, DYNAMIC_TYPE_TMP_BUFFER);
10003
}
10004
10005
#endif
10006
10007
/*******************************************************************************
10008
 * END OF standard C library wrapping APIs
10009
 ******************************************************************************/
10010
10011
/*******************************************************************************
10012
 * START OF EX_DATA APIs
10013
 ******************************************************************************/
10014
#ifdef HAVE_EX_DATA
10015
void wolfSSL_CRYPTO_cleanup_all_ex_data(void)
10016
{
10017
    WOLFSSL_ENTER("wolfSSL_CRYPTO_cleanup_all_ex_data");
10018
}
10019
10020
void* wolfSSL_CRYPTO_get_ex_data(const WOLFSSL_CRYPTO_EX_DATA* ex_data, int idx)
10021
{
10022
    WOLFSSL_ENTER("wolfSSL_CRYPTO_get_ex_data");
10023
#ifdef MAX_EX_DATA
10024
    if (ex_data && idx < MAX_EX_DATA && idx >= 0) {
10025
        return ex_data->ex_data[idx];
10026
    }
10027
#else
10028
    (void)ex_data;
10029
    (void)idx;
10030
#endif
10031
    return NULL;
10032
}
10033
10034
int wolfSSL_CRYPTO_set_ex_data(WOLFSSL_CRYPTO_EX_DATA* ex_data, int idx,
10035
    void *data)
10036
{
10037
    WOLFSSL_ENTER("wolfSSL_CRYPTO_set_ex_data");
10038
#ifdef MAX_EX_DATA
10039
    if (ex_data && idx < MAX_EX_DATA && idx >= 0) {
10040
#ifdef HAVE_EX_DATA_CLEANUP_HOOKS
10041
        if (ex_data->ex_data_cleanup_routines[idx]) {
10042
            /* call cleanup then remove cleanup callback,
10043
             * since different value is being set */
10044
            if (ex_data->ex_data[idx])
10045
                ex_data->ex_data_cleanup_routines[idx](ex_data->ex_data[idx]);
10046
            ex_data->ex_data_cleanup_routines[idx] = NULL;
10047
        }
10048
#endif
10049
        ex_data->ex_data[idx] = data;
10050
        return WOLFSSL_SUCCESS;
10051
    }
10052
#else
10053
    (void)ex_data;
10054
    (void)idx;
10055
    (void)data;
10056
#endif
10057
    return WOLFSSL_FAILURE;
10058
}
10059
10060
#ifdef HAVE_EX_DATA_CLEANUP_HOOKS
10061
int wolfSSL_CRYPTO_set_ex_data_with_cleanup(
10062
    WOLFSSL_CRYPTO_EX_DATA* ex_data,
10063
    int idx,
10064
    void *data,
10065
    wolfSSL_ex_data_cleanup_routine_t cleanup_routine)
10066
{
10067
    WOLFSSL_ENTER("wolfSSL_CRYPTO_set_ex_data_with_cleanup");
10068
    if (ex_data && idx < MAX_EX_DATA && idx >= 0) {
10069
        if (ex_data->ex_data_cleanup_routines[idx] && ex_data->ex_data[idx])
10070
            ex_data->ex_data_cleanup_routines[idx](ex_data->ex_data[idx]);
10071
        ex_data->ex_data[idx] = data;
10072
        ex_data->ex_data_cleanup_routines[idx] = cleanup_routine;
10073
        return WOLFSSL_SUCCESS;
10074
    }
10075
    return WOLFSSL_FAILURE;
10076
}
10077
#endif /* HAVE_EX_DATA_CLEANUP_HOOKS */
10078
#endif /* HAVE_EX_DATA */
10079
10080
#ifdef HAVE_EX_DATA_CRYPTO
10081
/**
10082
 * Issues unique index for the class specified by class_index.
10083
 * Other parameter except class_index are ignored.
10084
 * Currently, following class_index are accepted:
10085
 *  - WOLF_CRYPTO_EX_INDEX_SSL
10086
 *  - WOLF_CRYPTO_EX_INDEX_SSL_CTX
10087
 *  - WOLF_CRYPTO_EX_INDEX_X509
10088
 * @param class_index index one of CRYPTO_EX_INDEX_xxx
10089
 * @param argp  parameters to be saved
10090
 * @param argl  parameters to be saved
10091
 * @param new_func a pointer to WOLFSSL_CRYPTO_EX_new
10092
 * @param dup_func a pointer to WOLFSSL_CRYPTO_EX_dup
10093
 * @param free_func a pointer to WOLFSSL_CRYPTO_EX_free
10094
 * @return index value grater or equal to zero on success, -1 on failure.
10095
 */
10096
int wolfSSL_CRYPTO_get_ex_new_index(int class_index, long argl, void *argp,
10097
                                           WOLFSSL_CRYPTO_EX_new* new_func,
10098
                                           WOLFSSL_CRYPTO_EX_dup* dup_func,
10099
                                           WOLFSSL_CRYPTO_EX_free* free_func)
10100
{
10101
    WOLFSSL_ENTER("wolfSSL_CRYPTO_get_ex_new_index");
10102
10103
    return wolfssl_local_get_ex_new_index(class_index, argl, argp, new_func,
10104
            dup_func, free_func);
10105
}
10106
#endif /* HAVE_EX_DATA_CRYPTO */
10107
10108
/*******************************************************************************
10109
 * END OF EX_DATA APIs
10110
 ******************************************************************************/
10111
10112
/*******************************************************************************
10113
 * START OF BUF_MEM API
10114
 ******************************************************************************/
10115
10116
#if defined(OPENSSL_EXTRA)
10117
10118
/* Begin functions for openssl/buffer.h */
10119
WOLFSSL_BUF_MEM* wolfSSL_BUF_MEM_new(void)
10120
{
10121
    WOLFSSL_BUF_MEM* buf;
10122
    buf = (WOLFSSL_BUF_MEM*)XMALLOC(sizeof(WOLFSSL_BUF_MEM), NULL,
10123
                                                        DYNAMIC_TYPE_OPENSSL);
10124
    if (buf) {
10125
        XMEMSET(buf, 0, sizeof(WOLFSSL_BUF_MEM));
10126
    }
10127
    return buf;
10128
}
10129
10130
/* non-compat API returns length of buffer on success */
10131
int wolfSSL_BUF_MEM_grow_ex(WOLFSSL_BUF_MEM* buf, size_t len,
10132
        char zeroFill)
10133
{
10134
    size_t mx;
10135
    char* tmp;
10136
10137
    /* verify provided arguments. The return value is an int holding the
10138
     * resulting length, so reject any len that cannot be represented as a
10139
     * non-negative int. This also prevents truncating size_t to int. */
10140
    if (buf == NULL || len > (size_t)WC_MAX_SINT_OF(int)) {
10141
        return 0; /* BAD_FUNC_ARG; */
10142
    }
10143
10144
    /* check to see if fits in existing length */
10145
    if (buf->length > len) {
10146
        buf->length = len;
10147
        return (int)len;
10148
    }
10149
10150
    /* check to see if fits in max buffer */
10151
    if (buf->max >= len) {
10152
        if (buf->data != NULL && zeroFill) {
10153
            XMEMSET(&buf->data[buf->length], 0, len - buf->length);
10154
        }
10155
        buf->length = len;
10156
        return (int)len;
10157
    }
10158
10159
    /* expand size, to handle growth */
10160
    mx = (len + 3) / 3 * 4;
10161
10162
#ifdef WOLFSSL_NO_REALLOC
10163
    tmp = (char*)XMALLOC(mx, NULL, DYNAMIC_TYPE_OPENSSL);
10164
    if (tmp != NULL && buf->data != NULL) {
10165
       /* only the existing content is valid in the old buffer; copying
10166
        * len_int (the new, larger size) would read past buf->max */
10167
       XMEMCPY(tmp, buf->data, buf->length);
10168
       XFREE(buf->data, NULL, DYNAMIC_TYPE_OPENSSL);
10169
       buf->data = NULL;
10170
    }
10171
#else
10172
    /* use realloc */
10173
    tmp = (char*)XREALLOC(buf->data, mx, NULL, DYNAMIC_TYPE_OPENSSL);
10174
#endif
10175
10176
    if (tmp == NULL) {
10177
        return 0; /* ERR_R_MALLOC_FAILURE; */
10178
    }
10179
    buf->data = tmp;
10180
10181
    buf->max = mx;
10182
    if (zeroFill)
10183
        XMEMSET(&buf->data[buf->length], 0, len - buf->length);
10184
    buf->length = len;
10185
10186
    return (int)len;
10187
10188
}
10189
10190
/* returns length of buffer on success */
10191
int wolfSSL_BUF_MEM_grow(WOLFSSL_BUF_MEM* buf, size_t len)
10192
{
10193
    return wolfSSL_BUF_MEM_grow_ex(buf, len, 1);
10194
}
10195
10196
/* non-compat API returns length of buffer on success */
10197
int wolfSSL_BUF_MEM_resize(WOLFSSL_BUF_MEM* buf, size_t len)
10198
{
10199
    char* tmp;
10200
    size_t mx;
10201
10202
    /* verify provided arguments. The return value is an int, so reject any
10203
     * len that cannot be represented as a positive int. */
10204
    if (buf == NULL || len == 0 || len > (size_t)WC_MAX_SINT_OF(int)) {
10205
        return 0; /* BAD_FUNC_ARG; */
10206
    }
10207
10208
    if (len == buf->length)
10209
        return (int)len;
10210
10211
    if (len > buf->length)
10212
        return wolfSSL_BUF_MEM_grow_ex(buf, len, 0);
10213
10214
    /* expand size, to handle growth */
10215
    mx = (len + 3) / 3 * 4;
10216
10217
    /* We want to shrink the internal buffer */
10218
#ifdef WOLFSSL_NO_REALLOC
10219
    tmp = (char*)XMALLOC(mx, NULL, DYNAMIC_TYPE_OPENSSL);
10220
    if (tmp != NULL && buf->data != NULL)
10221
    {
10222
        XMEMCPY(tmp, buf->data, len);
10223
        XFREE(buf->data,NULL,DYNAMIC_TYPE_OPENSSL);
10224
        buf->data = NULL;
10225
    }
10226
#else
10227
    tmp = (char*)XREALLOC(buf->data, mx, NULL, DYNAMIC_TYPE_OPENSSL);
10228
#endif
10229
10230
    if (tmp == NULL)
10231
        return 0;
10232
10233
    buf->data = tmp;
10234
    buf->length = len;
10235
    buf->max = mx;
10236
10237
    return (int)len;
10238
}
10239
10240
void wolfSSL_BUF_MEM_free(WOLFSSL_BUF_MEM* buf)
10241
{
10242
    if (buf) {
10243
        XFREE(buf->data, NULL, DYNAMIC_TYPE_OPENSSL);
10244
        buf->data = NULL;
10245
        buf->max = 0;
10246
        buf->length = 0;
10247
        XFREE(buf, NULL, DYNAMIC_TYPE_OPENSSL);
10248
    }
10249
}
10250
/* End Functions for openssl/buffer.h */
10251
10252
#endif /* OPENSSL_EXTRA */
10253
10254
/*******************************************************************************
10255
 * END OF BUF_MEM API
10256
 ******************************************************************************/
10257
10258
#define WOLFSSL_CONF_INCLUDED
10259
#include <src/conf.c>
10260
10261
/*******************************************************************************
10262
 * START OF EVP_CIPHER API
10263
 ******************************************************************************/
10264
10265
#ifdef OPENSSL_EXTRA
10266
10267
    /* store for external read of iv, WOLFSSL_SUCCESS on success */
10268
    int  wolfSSL_StoreExternalIV(WOLFSSL_EVP_CIPHER_CTX* ctx)
10269
    {
10270
        WOLFSSL_ENTER("wolfSSL_StoreExternalIV");
10271
10272
        if (ctx == NULL) {
10273
            WOLFSSL_MSG("Bad function argument");
10274
            return WOLFSSL_FATAL_ERROR;
10275
        }
10276
10277
        switch (ctx->cipherType) {
10278
#ifndef NO_AES
10279
#if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT)
10280
            case WC_AES_128_CBC_TYPE :
10281
            case WC_AES_192_CBC_TYPE :
10282
            case WC_AES_256_CBC_TYPE :
10283
                WOLFSSL_MSG("AES CBC");
10284
                XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, ctx->ivSz);
10285
                break;
10286
#endif
10287
#ifdef HAVE_AESGCM
10288
            case WC_AES_128_GCM_TYPE :
10289
            case WC_AES_192_GCM_TYPE :
10290
            case WC_AES_256_GCM_TYPE :
10291
                WOLFSSL_MSG("AES GCM");
10292
                XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, ctx->ivSz);
10293
                break;
10294
#endif /* HAVE_AESGCM */
10295
#ifdef HAVE_AESCCM
10296
            case WC_AES_128_CCM_TYPE :
10297
            case WC_AES_192_CCM_TYPE :
10298
            case WC_AES_256_CCM_TYPE :
10299
                WOLFSSL_MSG("AES CCM");
10300
                XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, ctx->ivSz);
10301
                break;
10302
#endif /* HAVE_AESCCM */
10303
#ifdef HAVE_AES_ECB
10304
            case WC_AES_128_ECB_TYPE :
10305
            case WC_AES_192_ECB_TYPE :
10306
            case WC_AES_256_ECB_TYPE :
10307
                WOLFSSL_MSG("AES ECB");
10308
                break;
10309
#endif
10310
#ifdef WOLFSSL_AES_COUNTER
10311
            case WC_AES_128_CTR_TYPE :
10312
            case WC_AES_192_CTR_TYPE :
10313
            case WC_AES_256_CTR_TYPE :
10314
                WOLFSSL_MSG("AES CTR");
10315
                XMEMCPY(ctx->iv, &ctx->cipher.aes.reg, WC_AES_BLOCK_SIZE);
10316
                break;
10317
#endif /* WOLFSSL_AES_COUNTER */
10318
#ifdef WOLFSSL_AES_CFB
10319
#if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS)
10320
            case WC_AES_128_CFB1_TYPE:
10321
            case WC_AES_192_CFB1_TYPE:
10322
            case WC_AES_256_CFB1_TYPE:
10323
                WOLFSSL_MSG("AES CFB1");
10324
                break;
10325
            case WC_AES_128_CFB8_TYPE:
10326
            case WC_AES_192_CFB8_TYPE:
10327
            case WC_AES_256_CFB8_TYPE:
10328
                WOLFSSL_MSG("AES CFB8");
10329
                break;
10330
#endif /* !HAVE_SELFTEST && !HAVE_FIPS */
10331
            case WC_AES_128_CFB128_TYPE:
10332
            case WC_AES_192_CFB128_TYPE:
10333
            case WC_AES_256_CFB128_TYPE:
10334
                WOLFSSL_MSG("AES CFB128");
10335
                break;
10336
#endif /* WOLFSSL_AES_CFB */
10337
#if defined(WOLFSSL_AES_OFB)
10338
            case WC_AES_128_OFB_TYPE:
10339
            case WC_AES_192_OFB_TYPE:
10340
            case WC_AES_256_OFB_TYPE:
10341
                WOLFSSL_MSG("AES OFB");
10342
                break;
10343
#endif /* WOLFSSL_AES_OFB */
10344
#ifdef WOLFSSL_AES_XTS
10345
            case WC_AES_128_XTS_TYPE:
10346
            case WC_AES_256_XTS_TYPE:
10347
                WOLFSSL_MSG("AES XTS");
10348
                break;
10349
#endif /* WOLFSSL_AES_XTS */
10350
#endif /* NO_AES */
10351
10352
#ifdef HAVE_ARIA
10353
            case WC_ARIA_128_GCM_TYPE :
10354
            case WC_ARIA_192_GCM_TYPE :
10355
            case WC_ARIA_256_GCM_TYPE :
10356
                WOLFSSL_MSG("ARIA GCM");
10357
                XMEMCPY(ctx->iv, &ctx->cipher.aria.nonce, ARIA_BLOCK_SIZE);
10358
                break;
10359
#endif /* HAVE_ARIA */
10360
10361
#ifndef NO_DES3
10362
            case WC_DES_CBC_TYPE :
10363
                WOLFSSL_MSG("DES CBC");
10364
                XMEMCPY(ctx->iv, &ctx->cipher.des.reg, DES_BLOCK_SIZE);
10365
                break;
10366
10367
            case WC_DES_EDE3_CBC_TYPE :
10368
                WOLFSSL_MSG("DES EDE3 CBC");
10369
                XMEMCPY(ctx->iv, &ctx->cipher.des3.reg, DES_BLOCK_SIZE);
10370
                break;
10371
#endif
10372
#ifdef WOLFSSL_DES_ECB
10373
            case WC_DES_ECB_TYPE :
10374
                WOLFSSL_MSG("DES ECB");
10375
                break;
10376
            case WC_DES_EDE3_ECB_TYPE :
10377
                WOLFSSL_MSG("DES3 ECB");
10378
                break;
10379
#endif
10380
            case WC_ARC4_TYPE :
10381
                WOLFSSL_MSG("ARC4");
10382
                break;
10383
10384
#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
10385
            case WC_CHACHA20_POLY1305_TYPE:
10386
                break;
10387
#endif
10388
10389
#ifdef HAVE_CHACHA
10390
            case WC_CHACHA20_TYPE:
10391
                break;
10392
#endif
10393
10394
#ifdef WOLFSSL_SM4_ECB
10395
            case WC_SM4_ECB_TYPE:
10396
                break;
10397
#endif
10398
#ifdef WOLFSSL_SM4_CBC
10399
            case WC_SM4_CBC_TYPE:
10400
                WOLFSSL_MSG("SM4 CBC");
10401
                XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE);
10402
                break;
10403
#endif
10404
#ifdef WOLFSSL_SM4_CTR
10405
            case WC_SM4_CTR_TYPE:
10406
                WOLFSSL_MSG("SM4 CTR");
10407
                XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE);
10408
                break;
10409
#endif
10410
#ifdef WOLFSSL_SM4_GCM
10411
            case WC_SM4_GCM_TYPE:
10412
                WOLFSSL_MSG("SM4 GCM");
10413
                XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE);
10414
                break;
10415
#endif
10416
#ifdef WOLFSSL_SM4_CCM
10417
            case WC_SM4_CCM_TYPE:
10418
                WOLFSSL_MSG("SM4 CCM");
10419
                XMEMCPY(&ctx->cipher.sm4.iv, ctx->iv, SM4_BLOCK_SIZE);
10420
                break;
10421
#endif
10422
10423
            case WC_NULL_CIPHER_TYPE :
10424
                WOLFSSL_MSG("NULL");
10425
                break;
10426
10427
            default: {
10428
                WOLFSSL_MSG("bad type");
10429
                return WOLFSSL_FATAL_ERROR;
10430
            }
10431
        }
10432
        return WOLFSSL_SUCCESS;
10433
    }
10434
10435
    /* set internal IV from external, WOLFSSL_SUCCESS on success */
10436
    int  wolfSSL_SetInternalIV(WOLFSSL_EVP_CIPHER_CTX* ctx)
10437
    {
10438
10439
        WOLFSSL_ENTER("wolfSSL_SetInternalIV");
10440
10441
        if (ctx == NULL) {
10442
            WOLFSSL_MSG("Bad function argument");
10443
            return WOLFSSL_FATAL_ERROR;
10444
        }
10445
10446
        switch (ctx->cipherType) {
10447
10448
#ifndef NO_AES
10449
#if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT)
10450
            case WC_AES_128_CBC_TYPE :
10451
            case WC_AES_192_CBC_TYPE :
10452
            case WC_AES_256_CBC_TYPE :
10453
                WOLFSSL_MSG("AES CBC");
10454
                XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, WC_AES_BLOCK_SIZE);
10455
                break;
10456
#endif
10457
#ifdef HAVE_AESGCM
10458
            case WC_AES_128_GCM_TYPE :
10459
            case WC_AES_192_GCM_TYPE :
10460
            case WC_AES_256_GCM_TYPE :
10461
                WOLFSSL_MSG("AES GCM");
10462
                XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, WC_AES_BLOCK_SIZE);
10463
                break;
10464
#endif
10465
#ifdef HAVE_AES_ECB
10466
            case WC_AES_128_ECB_TYPE :
10467
            case WC_AES_192_ECB_TYPE :
10468
            case WC_AES_256_ECB_TYPE :
10469
                WOLFSSL_MSG("AES ECB");
10470
                break;
10471
#endif
10472
#ifdef WOLFSSL_AES_COUNTER
10473
            case WC_AES_128_CTR_TYPE :
10474
            case WC_AES_192_CTR_TYPE :
10475
            case WC_AES_256_CTR_TYPE :
10476
                WOLFSSL_MSG("AES CTR");
10477
                XMEMCPY(&ctx->cipher.aes.reg, ctx->iv, WC_AES_BLOCK_SIZE);
10478
                break;
10479
#endif
10480
10481
#endif /* NO_AES */
10482
10483
#ifdef HAVE_ARIA
10484
            case WC_ARIA_128_GCM_TYPE :
10485
            case WC_ARIA_192_GCM_TYPE :
10486
            case WC_ARIA_256_GCM_TYPE :
10487
                WOLFSSL_MSG("ARIA GCM");
10488
                XMEMCPY(&ctx->cipher.aria.nonce, ctx->iv, ARIA_BLOCK_SIZE);
10489
                break;
10490
#endif /* HAVE_ARIA */
10491
10492
#ifndef NO_DES3
10493
            case WC_DES_CBC_TYPE :
10494
                WOLFSSL_MSG("DES CBC");
10495
                XMEMCPY(&ctx->cipher.des.reg, ctx->iv, DES_BLOCK_SIZE);
10496
                break;
10497
10498
            case WC_DES_EDE3_CBC_TYPE :
10499
                WOLFSSL_MSG("DES EDE3 CBC");
10500
                XMEMCPY(&ctx->cipher.des3.reg, ctx->iv, DES_BLOCK_SIZE);
10501
                break;
10502
#endif
10503
#ifdef WOLFSSL_DES_ECB
10504
            case WC_DES_ECB_TYPE :
10505
                WOLFSSL_MSG("DES ECB");
10506
                break;
10507
            case WC_DES_EDE3_ECB_TYPE :
10508
                WOLFSSL_MSG("DES3 ECB");
10509
                break;
10510
#endif
10511
10512
            case WC_ARC4_TYPE :
10513
                WOLFSSL_MSG("ARC4");
10514
                break;
10515
10516
#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
10517
            case WC_CHACHA20_POLY1305_TYPE:
10518
                break;
10519
#endif
10520
10521
#ifdef HAVE_CHACHA
10522
            case WC_CHACHA20_TYPE:
10523
                break;
10524
#endif
10525
10526
#ifdef WOLFSSL_SM4_ECB
10527
            case WC_SM4_ECB_TYPE:
10528
                break;
10529
#endif
10530
#ifdef WOLFSSL_SM4_CBC
10531
            case WC_SM4_CBC_TYPE:
10532
                WOLFSSL_MSG("SM4 CBC");
10533
                XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz);
10534
                break;
10535
#endif
10536
#ifdef WOLFSSL_SM4_CTR
10537
            case WC_SM4_CTR_TYPE:
10538
                WOLFSSL_MSG("SM4 CTR");
10539
                XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz);
10540
                break;
10541
#endif
10542
#ifdef WOLFSSL_SM4_GCM
10543
            case WC_SM4_GCM_TYPE:
10544
                WOLFSSL_MSG("SM4 GCM");
10545
                XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz);
10546
                break;
10547
#endif
10548
#ifdef WOLFSSL_SM4_CCM
10549
            case WC_SM4_CCM_TYPE:
10550
                WOLFSSL_MSG("SM4 CCM");
10551
                XMEMCPY(ctx->iv, &ctx->cipher.sm4.iv, ctx->ivSz);
10552
                break;
10553
#endif
10554
10555
            case WC_NULL_CIPHER_TYPE :
10556
                WOLFSSL_MSG("NULL");
10557
                break;
10558
10559
            default: {
10560
                WOLFSSL_MSG("bad type");
10561
                return WOLFSSL_FATAL_ERROR;
10562
            }
10563
        }
10564
        return WOLFSSL_SUCCESS;
10565
    }
10566
10567
#ifndef NO_DES3
10568
10569
void wolfSSL_3des_iv(WOLFSSL_EVP_CIPHER_CTX* ctx, int doset,
10570
                            unsigned char* iv, int len)
10571
{
10572
    (void)len;
10573
10574
    WOLFSSL_MSG("wolfSSL_3des_iv");
10575
10576
    if (ctx == NULL || iv == NULL) {
10577
        WOLFSSL_MSG("Bad function argument");
10578
        return;
10579
    }
10580
10581
    if (doset)
10582
        wc_Des3_SetIV(&ctx->cipher.des3, iv);  /* OpenSSL compat, no ret */
10583
    else
10584
        XMEMCPY(iv, &ctx->cipher.des3.reg, DES_BLOCK_SIZE);
10585
}
10586
10587
#endif /* NO_DES3 */
10588
10589
10590
#ifndef NO_AES
10591
10592
void wolfSSL_aes_ctr_iv(WOLFSSL_EVP_CIPHER_CTX* ctx, int doset,
10593
                      unsigned char* iv, int len)
10594
{
10595
    (void)len;
10596
10597
    WOLFSSL_MSG("wolfSSL_aes_ctr_iv");
10598
10599
    if (ctx == NULL || iv == NULL) {
10600
        WOLFSSL_MSG("Bad function argument");
10601
        return;
10602
    }
10603
10604
    if (doset)
10605
       (void)wc_AesSetIV(&ctx->cipher.aes, iv);  /* OpenSSL compat, no ret */
10606
    else
10607
        XMEMCPY(iv, &ctx->cipher.aes.reg, WC_AES_BLOCK_SIZE);
10608
}
10609
10610
#endif /* NO_AES */
10611
10612
#endif /* OPENSSL_EXTRA */
10613
10614
/*******************************************************************************
10615
 * END OF EVP_CIPHER API
10616
 ******************************************************************************/
10617
10618
#ifndef NO_CERTS
10619
10620
#define WOLFSSL_X509_STORE_INCLUDED
10621
#include <src/x509_str.c>
10622
10623
#define WOLFSSL_SSL_P7P12_INCLUDED
10624
#include <src/ssl_p7p12.c>
10625
10626
#endif /* !NO_CERTS */
10627
10628
10629
/*******************************************************************************
10630
 * BEGIN OPENSSL FIPS DRBG APIs
10631
 ******************************************************************************/
10632
#if defined(OPENSSL_EXTRA) && !defined(WC_NO_RNG) && defined(HAVE_HASHDRBG)
10633
int wolfSSL_FIPS_drbg_init(WOLFSSL_DRBG_CTX *ctx, int type, unsigned int flags)
10634
{
10635
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
10636
    if (ctx != NULL) {
10637
        XMEMSET(ctx, 0, sizeof(WOLFSSL_DRBG_CTX));
10638
        ctx->type = type;
10639
        ctx->xflags = (int)flags;
10640
        ctx->status = DRBG_STATUS_UNINITIALISED;
10641
        ret = WOLFSSL_SUCCESS;
10642
    }
10643
    return ret;
10644
}
10645
WOLFSSL_DRBG_CTX* wolfSSL_FIPS_drbg_new(int type, unsigned int flags)
10646
{
10647
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
10648
    WOLFSSL_DRBG_CTX* ctx = (WOLFSSL_DRBG_CTX*)XMALLOC(sizeof(WOLFSSL_DRBG_CTX),
10649
        NULL, DYNAMIC_TYPE_OPENSSL);
10650
    ret = wolfSSL_FIPS_drbg_init(ctx, type, flags);
10651
    if (ret == WOLFSSL_SUCCESS && type != 0) {
10652
        ret = wolfSSL_FIPS_drbg_instantiate(ctx, NULL, 0);
10653
    }
10654
    if (ret != WOLFSSL_SUCCESS) {
10655
        WOLFSSL_ERROR(ret);
10656
        wolfSSL_FIPS_drbg_free(ctx);
10657
        ctx = NULL;
10658
    }
10659
    return ctx;
10660
}
10661
int wolfSSL_FIPS_drbg_instantiate(WOLFSSL_DRBG_CTX* ctx,
10662
    const unsigned char* pers, size_t perslen)
10663
{
10664
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
10665
    if (ctx != NULL && ctx->rng == NULL) {
10666
    #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
10667
        (defined(HAVE_FIPS) && FIPS_VERSION_GE(5,0)))
10668
        ctx->rng = wc_rng_new((byte*)pers, (word32)perslen, NULL);
10669
    #else
10670
        ctx->rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
10671
        if (ctx->rng != NULL) {
10672
        #if defined(HAVE_FIPS) && FIPS_VERSION_GE(2,0)
10673
            ret = wc_InitRngNonce(ctx->rng, (byte*)pers, (word32)perslen);
10674
        #else
10675
            ret = wc_InitRng(ctx->rng);
10676
            (void)pers;
10677
            (void)perslen;
10678
        #endif
10679
            if (ret != 0) {
10680
                WOLFSSL_ERROR(ret);
10681
                XFREE(ctx->rng, NULL, DYNAMIC_TYPE_RNG);
10682
                ctx->rng = NULL;
10683
            }
10684
        }
10685
    #endif
10686
    }
10687
    if (ctx != NULL && ctx->rng != NULL) {
10688
        ctx->status = DRBG_STATUS_READY;
10689
        ret = WOLFSSL_SUCCESS;
10690
    }
10691
    return ret;
10692
}
10693
int wolfSSL_FIPS_drbg_set_callbacks(WOLFSSL_DRBG_CTX* ctx,
10694
    drbg_entropy_get entropy_get, drbg_entropy_clean entropy_clean,
10695
    size_t entropy_blocklen,
10696
    drbg_nonce_get none_get, drbg_nonce_clean nonce_clean)
10697
{
10698
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
10699
    if (ctx != NULL) {
10700
        ctx->entropy_get = entropy_get;
10701
        ctx->entropy_clean = entropy_clean;
10702
        ctx->entropy_blocklen = entropy_blocklen;
10703
        ctx->none_get = none_get;
10704
        ctx->nonce_clean = nonce_clean;
10705
        ret = WOLFSSL_SUCCESS;
10706
    }
10707
    return ret;
10708
}
10709
void wolfSSL_FIPS_rand_add(const void* buf, int num, double entropy)
10710
{
10711
    /* not implemented */
10712
    (void)buf;
10713
    (void)num;
10714
    (void)entropy;
10715
}
10716
int wolfSSL_FIPS_drbg_reseed(WOLFSSL_DRBG_CTX* ctx, const unsigned char* adin,
10717
    size_t adinlen)
10718
{
10719
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
10720
    if (ctx != NULL && ctx->rng != NULL) {
10721
    #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
10722
        (defined(HAVE_FIPS) && FIPS_VERSION_GE(2,0)))
10723
        if (wc_RNG_DRBG_Reseed(ctx->rng, adin, (word32)adinlen) == 0) {
10724
            ret = WOLFSSL_SUCCESS;
10725
        }
10726
    #else
10727
        ret = WOLFSSL_SUCCESS;
10728
        (void)adin;
10729
        (void)adinlen;
10730
    #endif
10731
    }
10732
    return ret;
10733
}
10734
int wolfSSL_FIPS_drbg_generate(WOLFSSL_DRBG_CTX* ctx, unsigned char* out,
10735
    size_t outlen, int prediction_resistance, const unsigned char* adin,
10736
    size_t adinlen)
10737
{
10738
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
10739
    if (ctx != NULL && ctx->rng != NULL) {
10740
        ret = wc_RNG_GenerateBlock(ctx->rng, out, (word32)outlen);
10741
        if (ret == 0) {
10742
            ret = WOLFSSL_SUCCESS;
10743
        }
10744
    }
10745
    (void)prediction_resistance;
10746
    (void)adin;
10747
    (void)adinlen;
10748
    return ret;
10749
}
10750
int wolfSSL_FIPS_drbg_uninstantiate(WOLFSSL_DRBG_CTX *ctx)
10751
{
10752
    if (ctx != NULL && ctx->rng != NULL) {
10753
    #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
10754
        (defined(HAVE_FIPS) && FIPS_VERSION_GE(5,0)))
10755
        wc_rng_free(ctx->rng);
10756
    #else
10757
        wc_FreeRng(ctx->rng);
10758
        XFREE(ctx->rng, NULL, DYNAMIC_TYPE_RNG);
10759
    #endif
10760
        ctx->rng = NULL;
10761
        ctx->status = DRBG_STATUS_UNINITIALISED;
10762
    }
10763
    return WOLFSSL_SUCCESS;
10764
}
10765
void wolfSSL_FIPS_drbg_free(WOLFSSL_DRBG_CTX *ctx)
10766
{
10767
    if (ctx != NULL) {
10768
        /* As safety check if free'ing the default drbg, then mark global NULL.
10769
         * Technically the user should not call free on the default drbg. */
10770
        if (ctx == gDrbgDefCtx) {
10771
            gDrbgDefCtx = NULL;
10772
        }
10773
        wolfSSL_FIPS_drbg_uninstantiate(ctx);
10774
        XFREE(ctx, NULL, DYNAMIC_TYPE_OPENSSL);
10775
    }
10776
}
10777
WOLFSSL_DRBG_CTX* wolfSSL_FIPS_get_default_drbg(void)
10778
{
10779
    if (gDrbgDefCtx == NULL) {
10780
        gDrbgDefCtx = wolfSSL_FIPS_drbg_new(0, 0);
10781
    }
10782
    return gDrbgDefCtx;
10783
}
10784
void wolfSSL_FIPS_get_timevec(unsigned char* buf, unsigned long* pctr)
10785
{
10786
    /* not implemented */
10787
    (void)buf;
10788
    (void)pctr;
10789
}
10790
void* wolfSSL_FIPS_drbg_get_app_data(WOLFSSL_DRBG_CTX *ctx)
10791
{
10792
    if (ctx != NULL) {
10793
        return ctx->app_data;
10794
    }
10795
    return NULL;
10796
}
10797
void wolfSSL_FIPS_drbg_set_app_data(WOLFSSL_DRBG_CTX *ctx, void *app_data)
10798
{
10799
    if (ctx != NULL) {
10800
        ctx->app_data = app_data;
10801
    }
10802
}
10803
#endif
10804
/*******************************************************************************
10805
 * END OF OPENSSL FIPS DRBG APIs
10806
 ******************************************************************************/
10807
10808
10809
#endif /* !WOLFCRYPT_ONLY */